# License key API (/docs/license-keys/license-key-api)

Your app checks [generated license keys](/docs/license-keys) with three routes on the usage meter, `https://usage.comecero.com`. They are separate from the Comecero API and take no API token: the customer's license key and your shop's public `account_id` are the credential. The usage meter hashes the key as soon as it arrives and never stores or logs it.

Call them from your app (a desktop app, a plugin) or your server. They send no CORS headers, so a web page can't call them from the browser. All three take a JSON body of at most 1 MiB and answer JSON.

| Route | When your app calls it | Reference |
| --- | --- | --- |
| `POST /v1/licenses/activate` | Once, when the customer enters their key. Save the `instance_id` it returns. | [Activate a license key](/api/license-activation/activate-license) |
| `POST /v1/licenses/validate` | When the app starts, then now and again (once a day is plenty), with the saved `instance_id`. | [Validate a license key](/api/license-activation/validate-license) |
| `POST /v1/licenses/deactivate` | When the customer signs out or moves to another device. It frees the seat. | [Deactivate a device](/api/license-activation/deactivate-license) |

Every field, answer and status code is in the reference pages.

## Errors [#errors]

Errors are `{ "error": "<code>" }`, with more fields for some codes. Validate answers `200` with a `code` instead, for every well-formed request.

| Code | Status | Meaning |
| --- | --- | --- |
| `invalid_request` | `400` | A field is missing or wrong. `field` names it (never its value), and for `fingerprint` `detail` says what to send instead. |
| `invalid_json`, `empty_body` | `400` | The body is not JSON, or is empty. |
| `license_not_found` | `404` | No such key for this `account_id`. |
| `instance_not_found` | `404` | Deactivate only: no such device on this key. |
| `license_expired`, `license_revoked` | `403` | Activate only: the key can't take new devices. |
| `activation_limit_reached` | `403` | Activate only: every seat is taken. `used` and `limit` say how many. |
| `body_too_large` | `413` | The body is over 1 MiB. |
| `too_many_requests` | `429` | Over a rate limit. `retry_after` and the `Retry-After` header say how many seconds to wait. |
| `try_again` | `503` | A temporary problem. Retry shortly. An activation resent with the same `fingerprint` takes no extra seat. |

## Rate limits [#rate-limits]

Checked in this order. Over one, the answer is `429` with `Retry-After`, and nothing changes.

| Limit | Per |
| --- | --- |
| 600 requests, and 20 keys that don't exist | IP address, per minute |
| 10 activations and deactivations, and 60 validations | key, per minute |
| A shared limit for all your customers' requests | account, per second |

Only requests with a real key that passed its own limit count against your account.

## A Mac app in Swift [#a-mac-app-in-swift]

Four rules keep a Mac app's license check simple and fair to the customer.

### Keep the key in the Keychain [#keep-the-key-in-the-keychain]

Save the key and the `instance_id` in the Keychain, not in `UserDefaults` or a file: the Keychain is encrypted and other apps can't read it. Put your shop's `account_id` in the app itself; it is public. Never put a Comecero API token in the app.

```swift title="LicenseStore.swift"
import Foundation
import Security

struct KeychainError: Error { let status: OSStatus }

enum LicenseStore {
    private static let service = "com.example.WidgetPro.license"

    private static func item(_ name: String) -> [String: Any] {
        [kSecClass as String: kSecClassGenericPassword,
         kSecAttrService as String: service,
         kSecAttrAccount as String: name]
    }

    static func save(_ value: String, as name: String) throws {
        let data = Data(value.utf8)
        var status = SecItemUpdate(item(name) as CFDictionary, [kSecValueData as String: data] as CFDictionary)
        if status == errSecItemNotFound {
            var add = item(name)
            add[kSecValueData as String] = data
            add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock
            status = SecItemAdd(add as CFDictionary, nil)
        }
        guard status == errSecSuccess else { throw KeychainError(status: status) }
    }

    // nil only when nothing is saved under this name; any other Keychain failure throws.
    static func read(_ name: String) throws -> String? {
        var query = item(name)
        query[kSecReturnData as String] = true
        var result: AnyObject?
        let status = SecItemCopyMatching(query as CFDictionary, &result)
        if status == errSecItemNotFound { return nil }
        guard status == errSecSuccess, let data = result as? Data else { throw KeychainError(status: status) }
        return String(decoding: data, as: UTF8.self)
    }
}
```

### Use a saved random UUID as the fingerprint [#use-a-saved-random-uuid-as-the-fingerprint]

The same Mac must always send the same `fingerprint`, or each activation takes a new seat. Make a random UUID the first time the app needs one, save it in the Keychain next to the key, and send that same UUID every time. It says nothing about the Mac or the person, and other apps can't match it to theirs. It survives a reinstall of the app only if the Keychain item does. If the Keychain can't save or read it, stop and don't activate: a UUID that isn't kept would take a new seat each time.

```swift title="DeviceFingerprint.swift"
import Foundation
import Security

func deviceFingerprint() throws -> String {
    if let saved = try LicenseStore.read("fingerprint") { return saved }
    try LicenseStore.save(UUID().uuidString, as: "fingerprint")
    // Send the UUID the Keychain really kept, never one it may not have.
    guard let saved = try LicenseStore.read("fingerprint") else { throw KeychainError(status: errSecItemNotFound) }
    return saved
}
```

### Validate with the saved instance_id [#validate-with-the-saved-instance_id]

Activate once, when the customer enters the key, and save the `instance_id` it returns. After that, validate with the saved key and `instance_id`; don't activate again on every launch.

```swift title="LicenseClient.swift"
import Foundation

struct LicenseAnswer: Decodable {
    let valid: Bool?
    let code: String?
    let instanceId: String?
    let error: String?
}

func callUsageMeter(_ route: String, _ body: [String: String]) async throws -> LicenseAnswer {
    var request = URLRequest(url: URL(string: "https://usage.comecero.com/v1/licenses/\(route)")!)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = try JSONEncoder().encode(body)
    let (data, _) = try await URLSession.shared.data(for: request)
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    return try decoder.decode(LicenseAnswer.self, from: data)
}

let accountId = "AB1234"

// When the customer enters their key.
func activate(key: String) async throws -> Bool {
    let fingerprint = try deviceFingerprint() // saved before activating, or this throws and nothing is sent
    let answer = try await callUsageMeter("activate", ["account_id": accountId, "license_key": key,
                                                       "fingerprint": fingerprint,
                                                       "instance_name": Host.current().localizedName ?? "Mac"])
    guard let instanceId = answer.instanceId else { return false } // answer.error says why
    try LicenseStore.save(key, as: "license_key")
    try LicenseStore.save(instanceId, as: "instance_id")
    return true
}

// At launch, and about once a day.
func validate() async throws -> String? {
    guard let key = try LicenseStore.read("license_key"), let instanceId = try LicenseStore.read("instance_id") else { return nil }
    let answer = try await callUsageMeter("validate", ["account_id": accountId, "license_key": key, "instance_id": instanceId])
    return answer.code
}
```

If the usage meter can't be reached (no network, a `503`), keep the app working on its last `VALID` answer for a few days rather than locking out a paying customer.

### Never activate again on your own after INSTANCE_DEACTIVATED [#never-activate-again-on-your-own-after-instance_deactivated]

`INSTANCE_DEACTIVATED` means the customer, or your support team, freed this Mac's seat, usually to use the key on another Mac. If the app activated again by itself, it would take the seat back from that other Mac, and two Macs could keep taking it from each other. Lock the app and ask instead:

| `code` | What the app does |
| --- | --- |
| `VALID` | Works. |
| `INSTANCE_DEACTIVATED` | Shows "This Mac was removed from your license" with an "Activate on this Mac" button. Activates only when the customer clicks it. |
| `INSTANCE_NOT_FOUND` | The key was replaced, so this device is not one of its devices any more. Asks the customer to enter the key again. |
| `REVOKED`, `EXPIRED`, `NOT_FOUND` | Locks, says why, and links to the customer's account to renew or buy. |

When the customer signs out in your app, call deactivate with the saved `instance_id` and remove the key and the `instance_id` from the Keychain. Keep the fingerprint, so this Mac stays the same device if it activates again.
