Naar de inhoud

Handleiding licentie-integratie voor de desktopclient

1. Het grote geheel

  1. De gebruiker betaalt op de website (Stripe/PayPal). De server geeft een licentie uit (plan Pro, idempotent per bestelling) met sleutel GRAV-XXXXX-XXXXX-XXXXX-XXXXX. De sleutel in leesbare vorm wordt één keer getoond op de downloadpagina; de server bewaart alleen de SHA-256-hash en kan hem nooit opnieuw tonen.
  2. De gebruiker plakt de sleutel in de desktopapp → de app roept /api/license/verify aan bij elke start. De eerste controle registreert de computer als activering (maximaal 3 computers per licentie).
  3. De app logt ook in met de websitegegevens → krijgt een Bearer-sessietoken van 30 dagen.
  4. De app stuurt regelmatig heartbeats met dat token; een verlopen/ingetrokken sessie of licentie moet Pro-functies vergrendelen.

Twee inloggegevens: haal ze nooit door elkaar

GegevenBronDoelGeldigheid
Licentiesleutel GRAV-...Downloadpagina (eenmalig)Activering van de computer + controle365 dagen
SessietokenPOST /api/auth/loginBearer-header voor heartbeat/uitloggen30 dagen

2. Conventies

  • Basis-URL voor ontwikkeling: http://localhost:5243 (https-profiel: https://localhost:7130). Productie: https://iamgravity.eu
  • Alle endpoints: POST, Content-Type: application/json, JSON-antwoorden (camelCase)
  • Geen cookies/CSRF — de licentie-API's zijn anoniem; authenticatie gaat via velden in de body of Authorization: Bearer <token>
  • Alle tijdstempels zijn UTC ISO-8601; lees ze als UTC, toon ze in lokale tijd
  • Licentieweigeringen geven HTTP 200 terug met valid:false — baseer je logica altijd op de JSON-body, nooit op de statuscode

3. Endpoints

3.1 POST /api/license/verify — Activeringscontrole bij het opstarten

Verzoek:

{
  "licenseKey": "GRAV-XXXXX-XXXXX-XXXXX-XXXXX",
  "machineId": "<stable id>",
  "machineName": "DESKTOP-ABC123",
  "appVersion": "1.0.0"
}

Gelukt (200):

{
  "valid": true,
  "reason": "ok",
  "license": {
    "orderNumber": "PYPL-8XK4321",
    "plan": "Pro",
    "expiresAt": "2027-10-07T09:26:21Z",
    "activations": 1,
    "maxActivations": 3
  }
}

Failure (also HTTP 200):

{
  "valid": false,
  "reason": "license_expired",
  "message": "Your license has expired. Renew at iamgravity.eu/#pricing."
}

3.2 POST /api/auth/login — Account Login, Returns Session Token

Verzoek:

{
  "email": "[email protected]",
  "password": "...",
  "machineId": "<stable id>",
  "machineName": "DESKTOP-ABC123",
  "appVersion": "1.0.0"
}

3.3 POST /api/license/heartbeat — Session Keep-Alive

Header: Authorization: Bearer <sessionToken>

{ "machineId": "<stable id>" }

3.4 POST /api/auth/logout — Revoke Session Token

Header: Authorization: Bearer <sessionToken>, empty body → 200 { "success": true }

4. Formaat en levensduur van de licentiesleutel

Format: GRAV- + 4 groups of 5 chars (--separated, 23 chars total). Alphabet: ABCDEFGHJKLMNPQRSTUVWXYZ23456789 — no I, O, 0, 1 (anti-confusion).

Client-side validation regex:

^GRAV-[A-HJ-NP-Z2-9]{5}-[A-HJ-NP-Z2-9]{5}-[A-HJ-NP-Z2-9]{5}-[A-HJ-NP-Z2-9]{5}$

Lifecycle: Issued on payment success, plan "Pro", valid 365 dagen. Status Active(0) → Expired(2) (auto-flipped) or Revoked(1) (manual). MaxActivations = 3 machines.

5. Eisen aan de machine-ID

machineId is a client-generated, opaque, stable string. Rules:

  1. Deterministic — same machine, same ID, across restarts/updates/reinstalls
  2. Unique per machine — two PCs must never collide
  3. Recommended recipe (Windows): hex SHA-256 of the registry MachineGuid (HKLM\\SOFTWARE\\Microsoft\\Cryptography\\MachineGuid)
  4. Do NOT use values that change with hardware dongles, VPNs, MAC randomization, or current username
  5. Always send machineName (Environment.MachineName) and appVersion

6. Reason / Error Codes → Required Client Behavior

CodeWhereBetekenisClient Action
ok (valid:true)verifyLicensedUnlock Pro features, cache license info
license_not_foundverifyKey unknownRe-prompt; link to Download page
license_revokedverifyLicense revoked by staffLock; show [email protected]
license_expiredverifyPast ExpiresAtLock; deep-link /pricing to renew
activation_limit_reachedverifyMore than 3 machinesLock; deep-link account page to revoke a device
machine_revokedverifyThis device was revokedLock; user must re-activate from account page
session_invalid_or_expired (401)HeartbeatSession dead or machine not activatedSilent re-login; if still failing → re-verify, then lock
no_active_license (402)InloggenNo active license on accountLock; deep-link /pricing

7. Aanbevolen opstartverloop

App start
 ├─ No stored license key → Activation screen (paste key) ─────────────────────────────────────────────────────────────────────────────────────────────│
 ├─ Stored key:                                             │
 │   1. POST /api/license/verify {key, machineId, ...}  ├──────────────────────────────────────────────────────│
 │        valid:true   → cache license, continue
 │        valid:false   → show message, LOCK Pro features
 │        network error → offline grace
 │   2. POST /api/auth/login {email, password, machineId, ...}
 │        200            → store sessionToken + expiresAt securely
 │        402/401/429    → handle per error codes
 │   3. Start heartbeat timer (every 30–60 min)
 └─ Runtime:
        heartbeat 200   → refresh cached license info, stay unlocked
        heartbeat 401   → silent re-login once; 402 → LOCK
        user sign-out / app exit → POST /api/auth/logout (fire-and-forget)

8. Offline respijtbeleid

If the last successful verify/heartbeat is within N days (recommend 7; max 30 = session lifetime), allow Pro features offline and retry in background with backoff (1h → 6h → 24h). Lock when grace window exceeded or explicit valid:false / 402 arrives.

9. Checklist opslag en beveiliging

  • sessionToken → Windows Credential Manager or DPAPI (ProtectedData). Never plaintext on disk, never in logs/telemetry.
  • Password → Credential Manager only with explicit "remember me"; otherwise memory only.
  • License key → local settings file is acceptable (low sensitivity); display masked in UI.
  • machineId → compute deterministically or cache after first generation; reuse forever.
  • Gate ALL Pro features behind a single IsLicensed service — no scattered booleans.
  • Never embed a default/shared license key in the binary.
  • Log reason codes (not keys/tokens) for support diagnostics.

10. Referentieclient in C#

public sealed class LicenseApiClient
{
    private readonly HttpClient _http;
    public string? SessionToken { get; set; }

    public LicenseApiClient(string baseUrl)
    {
        _http = new HttpClient { BaseAddress = new Uri(baseUrl.TrimEnd('/') + "/") };
        _http.DefaultRequestHeaders.Accept.Add(new("application/json"));
    }

    public static string GetMachineId()
    {
        using var key = Microsoft.Win32.Registry
            .OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine,
                         Microsoft.Win32.RegistryView.Registry64)
            .OpenSubKey("SOFTWARE\\\\Microsoft\\\\Cryptography");
        var guid = (string?)key?.GetValue("MachineGuid")
                   ?? throw new InvalidOperationException("MachineGuid unavailable");
        return Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(
            System.Text.Encoding.UTF8.GetBytes(guid))).ToLowerInvariant();
    }

    public async Task VerifyAsync(string licenseKey) { ... }
    public async Task LoginAsync(string email, string password) { ... }
    public async Task HeartbeatAsync() { ... }
    public async Task LogoutAsync() { ... }
}

11. Integratiechecklist

  • [ ] Settings UI to paste the license key (validate shape locally with regex, then send as-is)
  • [ ] Deterministic machineId + machineName + appVersion on every call
  • [ ] Startup sequence: verify → login → heartbeat timer (30–60 min)
  • [ ] Every reason code mapped to a user message + app state
  • [ ] Offline grace window with authoritative-lock overrides
  • [ ] Silent re-login on 401 session_invalid_or_expired
  • [ ] Secure token/password storage; masked key display
  • [ ] Logout on sign-out/app exit
  • [ ] Single IsLicensed gate for ALL Pro features
  • [ ] Test matrix: wrong key, expired license, 4th machine, revoked machine, revoked license, session expiry, offline start, rate-limited login