Sponsorkit 1.0.0
dotnet add package Sponsorkit --version 1.0.0
NuGet\Install-Package Sponsorkit -Version 1.0.0
<PackageReference Include="Sponsorkit" Version="1.0.0" />
<PackageVersion Include="Sponsorkit" Version="1.0.0" />
<PackageReference Include="Sponsorkit" />
paket add Sponsorkit --version 1.0.0
#r "nuget: Sponsorkit, 1.0.0"
#:package Sponsorkit@1.0.0
#addin nuget:?package=Sponsorkit&version=1.0.0
#tool nuget:?package=Sponsorkit&version=1.0.0
Sponsorkit for .NET
Build financial contributions into your .NET app or CLI. Sponsorkit tells you what the current user has contributed to your GitHub Sponsors and Open Collective accounts and sends them to contribute. You decide what to do with that: show a thank-you, nag every N runs, or unlock a feature.
- Zero setup. There is no Sponsorkit account, API key, dashboard or webhook. You name the accounts you receive money on.
- Facts, not policy. Contributions come back per provider as raw data. Sponsorkit never sums or converts currencies.
- Never breaks your app. Network errors, outages and rate limits never throw from
GetFinancialContributionAsync. - Targets
netstandard2.0andnet8.0. The only dependency isSystem.Text.Json, and only on netstandard2.0.
Install
dotnet add package Sponsorkit
Quickstart
using Sponsorkit;
var sk = new SponsorkitClient(new SponsorkitOptions
{
GitHub = "mathiaslorenzen", // GitHub Sponsors login (user or org)
OpenCollective = "sponsorkit", // Open Collective slug (optional)
AppName = "my-cli", // shown on the consent page as "says it is"
});
var fc = await sk.GetFinancialContributionAsync();
if (fc.SignedIn && !fc.Active().Any(c => c.Amount.Currency == "USD" && c.Amount.Value >= 500))
{
Console.WriteLine("Consider sponsoring my-cli!");
}
// Somewhere in your UI or CLI, for example `my-cli sponsor`:
var result = await sk.OpenCheckoutAsync(new CheckoutOptions { Frequency = Frequencies.Monthly, Amount = 500 });
if (result.Status == CheckoutStatus.Contributed) Console.WriteLine("Thank you! ❤");
When the user is not signed in, GetFinancialContributionAsync returns SignedIn == false without any network
call. Call SignInAsync() when the user asks for it, for example from a my-cli login command.
API reference
SponsorkitClient
| Member | Description |
|---|---|
new SponsorkitClient(SponsorkitOptions) |
Validates the configuration and performs no I/O. It throws SponsorkitError("invalid_config") when there are no targets, a target is malformed, ApiBaseUrl, SiteBaseUrl or AppName is invalid, or the mock preset is unknown. |
Task<ContributionResult> GetFinancialContributionAsync(CancellationToken) |
Returns the supporter's contributions to your targets. The result comes from the local cache while it is younger than CacheTtl. |
Task<ContributionResult> GetFinancialContributionAsync(TimeSpan cacheTtl, CancellationToken) |
The same with a per-call cache TTL. TimeSpan.Zero always asks the API, unless a Retry-After backoff is in force. |
Task<ContributionResult> SignInAsync(SignInOptions?, CancellationToken) |
Signs in via loopback (system browser) or paste-back. While already signed in, new SignInOptions { Provider = "open-collective" } adds a second identity to the session. If the stored session has died, it starts a fresh session with the new identity. Cancelling the token throws cancelled. |
bool IsSignedIn() |
Whether a session token is stored. No network access. |
Task<CheckoutResult> OpenCheckoutAsync(CheckoutOptions?, CancellationToken) |
Signs in first if needed, opens the checkout page, then polls until a new or changed contribution appears. It resolves Unknown when polling times out (Timeout, default 10 minutes) or on cancellation in either phase. The sign-in phase is bounded by SignInTimeout and throws timeout when it runs out. |
string CheckoutUrl(CheckoutUrlOptions?) |
Returns an anonymous checkout link, <SiteBaseUrl>/checkout/?…. It is synchronous and offline, so it suits nags, --help text and READMEs. It throws invalid_config for an unconfigured provider or an invalid frequency, amount or currency. |
Task SignOutAsync(CancellationToken) |
Deletes the session token and cache locally and keeps nag state. |
SponsorkitNag Nag(NagOptions) |
The nag helper (see below). |
static void ResetProcessState() |
Forgets per-process memo state: counted nag runs, the dev-time check and Retry-After backoff. Intended for tests. |
Targets, TargetsHash, IsDisabled, IsMock, ApiBaseUrl, SiteBaseUrl |
Read-only information about the instance. |
SponsorkitOptions
| Option | Default | Meaning |
|---|---|---|
GitHub, OpenCollective |
— | Your accounts. At least one is required. They are trimmed and lowercased. |
AppName |
null |
Shown on the consent page as "says it is". 1–64 characters. |
CacheTtl |
1 hour | How long results are served from the local cache. Values below 60 s are raised to 60 s. A per-call TTL may be any value ≥ 0. |
Mock |
null |
Mock mode (see below). |
StorageDirectory |
per-user config dir | $XDG_CONFIG_HOME/sponsorkit, ~/Library/Application Support/sponsorkit or %APPDATA%\sponsorkit. If no per-user config directory can be determined (for example HOME is unset), state is kept in memory for the life of the client. The SDK never writes to the working directory and construction never fails over it. |
Storage |
null |
A custom ISponsorkitStorage backend, for example a keychain. |
ApiBaseUrl |
https://api.sponsorkit.io |
The API origin, used for every API call (/api/v1/…). For self-hosting and tests. |
SiteBaseUrl |
https://ffmathy.github.io/sponsorkit, or ApiBaseUrl when that is set and this isn't |
The site base URL (origin plus optional base path), used for every page URL: <SiteBaseUrl>/connect/, <SiteBaseUrl>/checkout/, CheckoutUrl() and the loopback redirect after a checkout sign-in. Setting only ApiBaseUrl serves both from one origin (single-origin self-hosting). Trailing slashes are trimmed from both, and an empty string counts as unset. |
SignInMethod |
Auto |
Auto uses loopback, and falls back to paste-back over SSH, without a display, when 127.0.0.1 can't be bound, or when the browser cannot open. Loopback and Paste force one flow (a forced Loopback that can't bind throws network_error). |
OpenBrowser |
system browser | Func<string, CancellationToken, Task>. Throwing counts as "the browser could not open". The callback is accepted while it is still running. The system launcher (open/xdg-open) counts as failed when it exits non-zero, and as opened when it is still running after about 1.5 s. |
PromptForCode |
reads stdin | Func<string url, CancellationToken, Task<string>>, used by paste-back sign-in. An empty answer throws cancelled. See the stdin limitation. |
SignInTimeout |
5 minutes | How long to wait for a loopback or paste-back sign-in before throwing timeout. |
Interactive |
TTY detection | Overrides the stdout/stderr terminal check used by the nag helper. |
Environment |
process env | Replaces the process environment for SPONSORKIT_DISABLE, SPONSORKIT_MOCK, SPONSORKIT_NO_NAG, SPONSORKIT_DEV_CHECKS and CI for this instance. It is not merged: a variable missing from the dictionary counts as unset. |
DevChecks |
SPONSORKIT_DEV_CHECKS |
Checks once per process that your targets exist (invalid_config if not). Without this option the check is on only when SPONSORKIT_DEV_CHECKS is set; .NET has no implicit development signal. |
CheckoutPollInterval |
60 s | How often OpenCheckoutAsync polls. |
Clock |
DateTimeOffset.UtcNow |
Injectable time for cache-expiry and nag tests. |
HttpClient |
shared client | Bring your own HttpClient. |
RequestTimeout |
30 s | Timeout of each HTTP request. TimeSpan.Zero disables it; negative values throw invalid_config. A timeout is a network error: GetFinancialContributionAsync serves the stale cache, SignInAsync throws network_error. VerifySessionOptions.RequestTimeout does the same for VerifySessionAsync. |
ContributionResult
The result serializes with System.Text.Json to the protocol JSON shape. That is handy for forwarding it to a backend.
| Property | Meaning |
|---|---|
SignedIn, Disabled, Mock |
The mode the SDK is in. |
Targets |
The canonical targets, for example github:mathiaslorenzen. |
Supporter |
Id (a pairwise sup_…, stable per person and target set) and Identities. Each identity has NeedsReconnect. |
Contributions |
Each contribution has Provider, Target, Sponsor, Via (direct/organization), Kind, Frequency, Status, Amount (minor units), Tier, Flags, IsPrivate, the dates and TotalContributed. |
FetchedAt, Stale, FromCache |
Freshness. Stale means some data could not be refreshed. |
The helpers filter Contributions. They never aggregate: Active(), Recurring(), OneTime(),
ByProvider("github") and Direct(), which excludes organization sponsorships.
Errors
Every exception is a SponsorkitError with a stable Code (SponsorkitErrorCodes):
| Code | When |
|---|---|
invalid_config |
Bad configuration (including a negative RequestTimeout), invalid CheckoutUrl options, an unknown mock preset, (dev-time) a target that doesn't exist, or a storage write failure in SignInAsync (persisting the session) or SignOutAsync (clearing it). |
disabled |
SignInAsync or OpenCheckoutAsync while SPONSORKIT_DISABLE is set. |
popup_blocked |
Browser only; never thrown by the .NET SDK. |
access_denied, invalid_state, provider_error |
The provider sign-in failed (delivered to the loopback callback). |
invalid_code |
The API rejected the code exchange (400 invalid_code). Any other 400 from /auth/token is network_error. |
cancelled |
Sign-in was cancelled through its CancellationToken, or no paste-back code was entered. |
timeout |
Sign-in did not finish within SignInTimeout (default 5 minutes). |
network_error |
During sign-in or VerifySessionAsync, Sponsorkit could not be reached, timed out (RequestTimeout), or answered 5xx, 429, a 400 other than invalid_code, or an unexpected response. RetryAfter carries the API's Retry-After delay when it sent one; values that aren't valid are ignored and delays are capped at 24 hours. |
session_invalid, targets_mismatch |
Only from SponsorkitServer.VerifySessionAsync. |
GetFinancialContributionAsync does not throw for network errors, 5xx responses or rate limits:
- With a cache, it returns the cached result with
FromCache = true, Stale = true. - Without a cache, it returns a signed-in empty result with
Stale = true. - On
session_invalid, it clears the stored token and returns the signed-out result.
Cancelling SignInAsync throws SponsorkitError("cancelled"), and cancelling OpenCheckoutAsync returns Unknown.
Cancelling GetFinancialContributionAsync or VerifySessionAsync raises OperationCanceledException in the usual .NET way.
Sign-in flows
- Loopback (desktop):
- The SDK listens on
http://127.0.0.1:<random>/callback. - It opens the system browser on the Sponsorkit consent page,
<SiteBaseUrl>/connect/?…. - It receives the code and exchanges it with its PKCE verifier.
- The SDK listens on
- Paste-back (SSH, containers, no display):
- The SDK prints a
<SiteBaseUrl>/connect/?…URL to stderr. - The user opens it on any device.
- The user pastes the displayed code back into the terminal.
- The SDK prints a
The session token, the cache and the nag counters are stored in <StorageDirectory>/<targets_hash>.json:
- The directory is
0700and the files are0600. - Writes are atomic.
- The file format is shared with the other Sponsorkit SDKs.
- Reading never throws. An unparseable document (including invalid UTF-8) reads as absent, and so does any malformed part of one (an unexpected type, a bad date, a
nulllist, a token that isn'tsks_plus printable ASCII), without losing the rest. - A background refresh writes back its cache and any renewed token only if the stored token is still the one it used, and a
401clears only that token, so a concurrent sign-in or sign-out is never undone.
Paste-back and stdin
The default paste-back prompt reads a line from standard input. A blocking console read can't be cancelled, so after a
cancelled or timed-out paste-back sign-in the read stays pending: the next line typed goes to the next Sponsorkit paste
prompt, or is discarded if none follows. If your app reads standard input itself after an abandoned sign-in, supply
PromptForCode.
Nag helper
var nag = sk.Nag(new NagOptions("my-cli") { Every = 10, OrEvery = TimeSpan.FromDays(7) });
if (await nag.DueAsync(fc => fc.Active().Count == 0))
{
Console.Error.WriteLine($"❤ Enjoying my-cli? Support it: {sk.CheckoutUrl(new CheckoutUrlOptions { Frequency = Frequencies.Monthly })}");
nag.Shown();
}
- Counting runs. Each process counts one run per nag id, on its first
DueAsynccall. The run counts even when your predicate is false. - When it is due.
DueAsyncreturnspredicate && (runs >= Every || sinceLastShown >= OrEvery). Before the firstShown(), theOrEveryclause is false. - Resetting.
Shown()resets both the counter and the timer. - When it never fires.
DueAsyncalways returnsfalsewhenSPONSORKIT_DISABLE,SPONSORKIT_NO_NAGorCIis set, or when stdout or stderr is not a terminal (override the terminal check with theInteractiveoption).DueAsync(predicate, force: true)bypasses every check exceptSPONSORKIT_DISABLE. - Durations.
OrEverytakes aTimeSpan. UseNagOptions.ParseDuration("P7D")for ISO-8601 durations. - No implicit sign-in. The nag helper never signs the user in.
Mock mode and testing
var sk = new SponsorkitClient(new SponsorkitOptions { GitHub = "octocat", Mock = "active-monthly" });
// Presets: signed-out | none | active-monthly | one-time | cancelled | org
var custom = new SponsorkitClient(new SponsorkitOptions
{
GitHub = "octocat",
Mock = SponsorkitMock.WithContributions(new[] { new Contribution { Id = "con_x", Provider = "github", Status = "active" } }),
});
- Mock mode makes no network or disk access, and results carry
Mock = true. Nag state lives in memory, per client instance. SignInAsync()andSignOutAsync()resolve immediately.OpenCheckoutAsync()simulates a new contribution.SPONSORKIT_MOCK=active-monthlyselects a preset from the environment. TheMockoption wins over it.SPONSORKIT_DISABLE=1turns the SDK into a no-op and wins over mock mode.
For integration tests, use these options:
ApiBaseUrlpoints the SDK at a fake server. WithoutSiteBaseUrl, the pages (/connect/,/checkout/) are on the same origin too.OpenBrowserandPromptForCodedrive sign-in.StorageDirectoryshould be a temp directory.Environmentsets the environment variables for one instance.Clockcontrols time.SponsorkitClient.ResetProcessState()simulates a new process.
Backend verification
Your app sends the supporter's session token (sks_…) to your backend. The backend verifies it without any key:
using Sponsorkit;
try
{
var fc = await SponsorkitServer.VerifySessionAsync(token, new VerifySessionOptions { GitHub = "mathiaslorenzen" });
var isSupporter = fc.Active().Count > 0;
var userKey = fc.Supporter?.Id; // stable per person for your target set
}
catch (SponsorkitError e) when (e.Code is SponsorkitErrorCodes.SessionInvalid or SponsorkitErrorCodes.TargetsMismatch)
{
return Results.Unauthorized();
}
VerifySessionAsync calls the API live, checks that the session is bound to exactly your targets, and uses no local storage.
When Sponsorkit is unreachable or answers 5xx or 429 it throws network_error, with RetryAfter set for rate limits.
Development
dotnet test sdks/dotnet # unit tests + the full conformance suite (needs `bun` on PATH)
dotnet format sdks/dotnet/Sponsorkit.slnx --verify-no-changes
dotnet pack sdks/dotnet -c Release
bash sdks/dotnet/scripts/gen-docs.sh /tmp/dotnet-ref # API reference Markdown (see scripts/docgen)
The conformance tests run every scenario in sdks/conformance/scenarios.json against the fake server (bun sdks/conformance/server.ts).
License
MIT
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- System.Text.Json (>= 10.0.15)
-
net8.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.