---
title: "Swift REST client"
description: "Build a complete Swift Sandbox licensing client with verified signatures, persistent identity, private state, offline policy and safe feature gating."
slug: "/docs/v1/sdks/swift"
section: "SDKs and languages"
order: 54
audience: "all"
level: "intermediate"
last_updated: "2026-10-17"
version: "v1"
related: ["/docs/v1/api/activate", "/docs/v1/security/offline-mode"]
draft: false
---
Use the real API v1 from a trusted Swift process with explicit signature and policy checks before enabling [features](/docs/v1/start/glossary#feature). This REST sample is not an additional [official SDK](/docs/v1/start/glossary#official-sdk).

## What you will learn
- Activate, validate and deactivate one stable [Sandbox](/docs/v1/start/glossary#sandbox) installation.
- Preserve signed bytes and verify the trusted Ed25519 key before policy.
- Handle cache, [offline grace](/docs/v1/start/glossary#offline-grace), explicit rejection and safe user messages.

## Prerequisites
- Complete [the Sandbox quickstart](/docs/v1/start/quickstart).
- Read [authentication](/docs/v1/start/authentication) and [signed responses](/docs/v1/security/signed-responses).
- Have the [product](/docs/v1/start/glossary#product) App ID, a Sandbox [license](/docs/v1/start/glossary#license) and its matching [customer](/docs/v1/start/glossary#customer) email when supplied.
- Obtain the actual [public-key document](/docs/v1/api/public-key) over independently trusted HTTPS and distribute/pin it through controlled application configuration, not from an untrusted envelope.

## Runtime and application type
Swift6+, macOS13+, Foundation and CryptoKit. Native macOS CLI or application service. This concrete project imports Darwin and CryptoKit; Windows/Linux compilation is not claimed. A mobile app needs its actual platform lifecycle and secure-storage adaptation. The generated Signature.swift contains the complete published verifier without its CLI tail.

## Complete project and integrity
<!-- P7-PROJECT-PACKAGE:START -->
The complete project archive contains every client/verifier source and the exact build/dependency metadata needed by this language. Extract it with its original directory layout. Dependencies/locks are included where this runtime uses them; no hidden helper or test-only clock is required.

[kdpika-swift-rest-example-1.0.0.zip](/docs/downloads/kdpika-swift-rest-example-1.0.0.zip) · 8789 bytes · version 1.0.0

SHA-256: ccd6c4302e9664efd1853be40a87282d0fe3baf05e8df86a562c8072d8007315
<!-- P7-PROJECT-PACKAGE:END -->
Extract the entire project, preserving its samples/sdks and samples/security layout. The archive includes all first-party client/verifier sources and pinned manifests/locks; dependency downloads are development-time restoration, never extra services needed by the PHP host. Do not flatten the tree or replace the verification helper with a generic JSON reserializer.

## Install and build
1. Verify the archive SHA-256 against the current table. Expected: exact digest match; otherwise stop.
2. Extract into a clean private development directory. Expected: complete samples tree with the language project.
3. Enter samples/sdks/swift. Expected: the main client and build/dependency files are present.
4. Install the stated runtime/native libraries, then run the full build command below. Expected: successful syntax check or native executable, not a registry SDK download.
```bash
sh build.sh
```
The source scripts compile the exact files and validate third-party download checksums where applicable. Compiler toolchains are development dependencies, not tools to install on KDPika shared hosting. macOS is the actual tested runtime; other targets require their own build/permission/TLS-root checks.

## Application configuration
| Variable | Required | Meaning |
| --- | --- | --- |
| KDP_APP_ID | Yes | [Public App ID](/docs/v1/start/glossary#public-app-id), not internal product ID or [developer](/docs/v1/start/glossary#developer) key |
| KDP_BASE_URL | No | HTTPS API base ending /api/v1; default https://licensing.kdpika.com/api/v1 |
| KDP_STATE_DIR | Yes | Absolute private application state root; keep it stable |
| KDP_TRUSTED_KEY_FILE | Yes | Absolute path to an independently trusted public-key document |
| KDP_LICENSE_KEY | [Activation](/docs/v1/start/glossary#activation) | Sandbox key beginning TEST; never embedded in distributed source |
| KDP_CUSTOMER_EMAIL | Optional | Actual matching customer email for email-bound activation |
| KDP_ALLOW_LOOPBACK | Local testing only | 1 permits explicit localhost/127.0.0.1 HTTP, not arbitrary HTTP hosts |

Environment is fixed to SANDBOX in this example. Unsafe URL credentials/query/fragment and nonlocal HTTP are rejected. Official SDK constructors expect the site origin; these REST programs expect /api/v1. Store state and trusted keys outside public web roots. Do not ship lmp_ developer management keys.

## Complete runnable client
```swift
// Complete Sandbox session CLI. Swift6+, macOS13+, Foundation/CryptoKit.
// Build with Signature.swift derived from the published P5 verifier, no CLI tail.
// Run session status|activate|check|validate|deactivate; safe JSON decisions.
import Foundation
import CryptoKit
import Darwin

enum ClientError: Error {case setup, network, denied(String, String?)}
final class NoRedirect: NSObject, URLSessionTaskDelegate, @unchecked Sendable {
    func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
                    newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {completionHandler(nil)}
}
func required(_ name: String) throws -> String {
    guard let value=ProcessInfo.processInfo.environment[name], !value.isEmpty, !value.contains("\r"), !value.contains("\n") else {throw ClientError.setup};return value
}
func sha(_ text: String) -> String {SHA256.hash(data:Data(text.utf8)).map{String(format:"%02x",$0)}.joined()}
func matches(_ text:String,_ pattern:String)->Bool{text.range(of:pattern,options:.regularExpression) != nil}
func object(_ raw:Data)throws->[String:Any] {
    var parser=try Parser(raw);guard case .object=try parser.parse(), let value=try JSONSerialization.jsonObject(with:raw) as? [String:Any] else {throw ClientError.denied("INVALID_RESPONSE",nil)};return value
}
func instant(_ value:Any?)throws->Date {
    guard let value=value as? String,matches(value,#"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$"#) else {throw ClientError.denied("INVALID_TIME",nil)}
    let fractional=ISO8601DateFormatter();fractional.formatOptions=[.withInternetDateTime,.withFractionalSeconds]
    guard let result=fractional.date(from:value) ?? ISO8601DateFormatter().date(from:value) else {throw ClientError.denied("INVALID_TIME",nil)};return result
}
func iso()->String{let formatter=ISO8601DateFormatter();formatter.formatOptions=[.withInternetDateTime,.withFractionalSeconds];return formatter.string(from:Date())}
func isTrue(_ value:Any?)->Bool{guard let value=value as? NSNumber else{return false};return CFGetTypeID(value)==CFBooleanGetTypeID() && value.boolValue}
import CoreFoundation
struct Stored:Codable {var token:String;var envelope:String?;var checkpoint:String}
final class Session {
    let app:String,base:String,dir:URL,installation:String,key:Data
    let lock:Int32
    var connection:URLSession?
    static func read(_ url:URL)throws->Data {
        let attributes=try FileManager.default.attributesOfItem(atPath:url.path)
        guard attributes[.type] as? FileAttributeType == .typeRegular, let size=attributes[.size] as? NSNumber,size.intValue<=1048576 else {throw ClientError.setup};return try Data(contentsOf:url)
    }
    init()throws {
        app=try required("KDP_APP_ID");guard matches(app,#"^[A-Za-z0-9_-]{3,160}$"#) else {throw ClientError.setup}
        let env=ProcessInfo.processInfo.environment;let raw=(env["KDP_BASE_URL"] ?? "https://licensing.kdpika.com/api/v1").replacingOccurrences(of:"/+$",with:"",options:.regularExpression)
        guard let uri=URLComponents(string:raw),let host=uri.host else {throw ClientError.setup}
        let local=uri.scheme=="http" && ["127.0.0.1","localhost"].contains(host) && env["KDP_ALLOW_LOOPBACK"]=="1"
        guard (uri.scheme=="https" || local),uri.user==nil,uri.password==nil,uri.query==nil,uri.fragment==nil,uri.path=="/api/v1" else {throw ClientError.setup};base=raw
        let root=try required("KDP_STATE_DIR"),keyfile=try required("KDP_TRUSTED_KEY_FILE");guard root.hasPrefix("/"),keyfile.hasPrefix("/") else {throw ClientError.setup}
        key=try Self.read(URL(fileURLWithPath:keyfile));let publicKey=try object(key);guard publicKey["algorithm"] as? String == "Ed25519",publicKey["encoding"] as? String == "base64url" else {throw ClientError.setup}
        let manager=FileManager.default;try manager.createDirectory(atPath:root,withIntermediateDirectories:true,attributes:[.posixPermissions:0o700])
        guard try manager.attributesOfItem(atPath:root)[.type] as? FileAttributeType == .typeDirectory else {throw ClientError.setup}
        dir=URL(fileURLWithPath:root).appendingPathComponent(String(sha(base+"|"+app+"|SANDBOX|swift-rest-v1").prefix(20)))
        try manager.createDirectory(at:dir,withIntermediateDirectories:true,attributes:[.posixPermissions:0o700])
        guard try manager.attributesOfItem(atPath:dir.path)[.type] as? FileAttributeType == .typeDirectory else {throw ClientError.setup};try manager.setAttributes([.posixPermissions:0o700],ofItemAtPath:dir.path)
        lock=Darwin.open(dir.appendingPathComponent(".lock").path,O_CREAT|O_EXCL|O_WRONLY|O_NOFOLLOW,0o600);guard lock>=0 else {throw ClientError.setup}
        do {
            let identity=dir.appendingPathComponent("installation.json")
            if !manager.fileExists(atPath:identity.path) {let raw=try JSONSerialization.data(withJSONObject:["installation_id":"lmp-install-"+UUID().uuidString.lowercased()]);try Self.atomic(dir,"installation.json",raw)}
            guard let value=try object(Self.read(identity))["installation_id"] as? String,matches(value,#"^lmp-install-[a-f0-9-]{36}$"#) else {throw ClientError.setup};installation=value
        } catch {Darwin.close(lock);unlink(dir.appendingPathComponent(".lock").path);throw error}
    }
    func close(){connection?.invalidateAndCancel();Darwin.close(lock);unlink(dir.appendingPathComponent(".lock").path)}
    static func atomic(_ directory:URL,_ name:String,_ data:Data)throws {
        let temporary=directory.appendingPathComponent("write-"+UUID().uuidString);let descriptor=Darwin.open(temporary.path,O_CREAT|O_EXCL|O_WRONLY|O_NOFOLLOW,0o600)
        guard descriptor>=0 else {throw ClientError.setup};let handle=FileHandle(fileDescriptor:descriptor,closeOnDealloc:true)
        try handle.write(contentsOf:data);try handle.synchronize();try handle.close()
        guard rename(temporary.path,directory.appendingPathComponent(name).path)==0 else {throw ClientError.setup}
    }
    func save(_ state:Stored)throws{try Self.atomic(dir,"session.json",JSONEncoder().encode(state))}
    func state()throws->Stored? {
        let url=dir.appendingPathComponent("session.json");guard FileManager.default.fileExists(atPath:url.path) else{return nil}
        let raw=try Self.read(url);_=try object(raw);let state=try JSONDecoder().decode(Stored.self,from:raw)
        guard matches(state.token,#"^act_[A-Za-z0-9_-]+$"#) else {throw ClientError.setup};_=try instant(state.checkpoint);return state
    }
    func clear()throws{let url=dir.appendingPathComponent("session.json");if FileManager.default.fileExists(atPath:url.path){try FileManager.default.removeItem(at:url)}}
    func request(_ endpoint:String,_ body:[String:Any],_ token:String?=nil)async throws->(JSON,[String:Any],String?) {
        guard let url=URL(string:base+endpoint) else {throw ClientError.setup};var request=URLRequest(url:url);request.httpMethod="POST";request.httpBody=try JSONSerialization.data(withJSONObject:body);request.timeoutInterval=15
        request.setValue("application/json",forHTTPHeaderField:"Accept");request.setValue("application/json",forHTTPHeaderField:"Content-Type");request.setValue("KDPika-REST-Swift-example/1.0",forHTTPHeaderField:"User-Agent")
        if let token=token{request.setValue("Bearer "+token,forHTTPHeaderField:"Authorization");request.setValue(installation,forHTTPHeaderField:"X-Installation-ID")}else{request.setValue(app,forHTTPHeaderField:"X-App-ID");request.setValue("SANDBOX",forHTTPHeaderField:"X-Environment")}
        if connection==nil{let config=URLSessionConfiguration.ephemeral;config.httpCookieStorage=nil;config.urlCache=nil;config.timeoutIntervalForRequest=15;config.timeoutIntervalForResource=15;connection=URLSession(configuration:config,delegate:NoRedirect(),delegateQueue:nil)}
        var raw=Data();var response:URLResponse
        do{let (stream,reply)=try await connection!.bytes(for:request);response=reply;for try await byte in stream{raw.append(byte);if raw.count>1048576{throw ClientError.denied("INVALID_RESPONSE",nil)}}}
        catch let error as ClientError {throw error} catch {throw ClientError.network}
        let value:[String:Any];var tree:JSON
        do{value=try object(raw);var parser=try Parser(raw);tree=try parser.parse()}catch{throw ClientError.denied("INVALID_RESPONSE",nil)}
        var id=value["request_id"] as? String;if let v=id,!matches(v,#"^req_[A-Za-z0-9_-]{1,120}$"#){id=nil}
        guard let http=response as? HTTPURLResponse,(200..<300).contains(http.statusCode),isTrue(value["success"]) else {let error=value["error"] as? [String:Any];let candidate=error?["code"] as? String ?? "HTTP_ERROR";throw ClientError.denied(matches(candidate,#"^[A-Z0-9_]{1,64}$"#) ? candidate:"HTTP_ERROR",id)}
        return(tree,value,id)
    }
    func accepted(_ source:String,_ id:String?=nil)->[String:Any]{["valid":true,"source":source,"signature_valid":false,"error_code":NSNull(),"request_id":id as Any? ?? NSNull(),"pdf_export_allowed":false,"seat_count":NSNull(),"message":"Your license is ready."]}
    func verify(_ envelope:String,_ source:String,_ checkpoint:String?,_ id:String?=nil)throws->[String:Any] {
        guard verifyEnvelope(key,Data(envelope.utf8)) else {throw ClientError.denied("SIGNATURE_INVALID",id)}
        guard let p=try object(Data(envelope.utf8))["payload"] as? [String:Any],let device=p["device"] as? [String:Any],p["product_id"] as? String==app,p["environment"] as? String=="sandbox",device["installation_hash"] as? String==sha(installation) else {throw ClientError.denied("BINDING_MISMATCH",id)}
        let server=try instant(p["server_time"]),next=try instant(p["next_validation_at"]),grace=try instant(p["offline_grace_until"]),now=Date()
        guard next>=server,grace>=server else {throw ClientError.denied("INVALID_TIME",id)};let latest=try checkpoint.map{max(server,try instant($0))} ?? server
        guard now.addingTimeInterval(300)>=latest else {throw ClientError.denied("CLOCK_ROLLBACK_DETECTED",id)}
        guard p["status"] as? String=="active" else {throw ClientError.denied("LICENSE_NOT_ACTIVE",id)}
        if let start=p["starts_at"],!(start is NSNull),now < (try instant(start)){throw ClientError.denied("LICENSE_NOT_STARTED",id)}
        if let expiry=p["expires_at"],!(expiry is NSNull),now >= (try instant(expiry)){throw ClientError.denied("LICENSE_EXPIRED",id)}
        guard source=="online" || now<=grace else {throw ClientError.denied("OFFLINE_GRACE_EXPIRED",id)}
        guard let features=p["features"] as? [String:Any] else {throw ClientError.denied("INVALID_RESPONSE",id)};var value=accepted(source,id);value["signature_valid"]=true;value["pdf_export_allowed"]=isTrue(features["pdf_export"])
        if let count=features["seat_count"] as? NSNumber,CFGetTypeID(count) != CFBooleanGetTypeID(),count.doubleValue.isFinite,count.doubleValue>=0,count.doubleValue<=9007199254740991,count.doubleValue.rounded()==count.doubleValue {value["seat_count"]=count.int64Value};return value
    }
    func run(_ action:String)async throws->[String:Any] {
        let saved=try state();if action=="status"{return ["activated":saved != nil,"installation_hash":sha(installation),"storage_security":"permission-protected-file"]}
        if action=="activate"{let license=try required("KDP_LICENSE_KEY");guard license.hasPrefix("TEST") else {throw ClientError.setup};guard saved==nil else {throw ClientError.denied("ALREADY_ACTIVATED",nil)}
            var body:[String:Any]=["license_key":license,"device_id":installation,"device_name":"Swift REST example","platform":"macos","app_version":"1.0.0"];if let email=ProcessInfo.processInfo.environment["KDP_CUSTOMER_EMAIL"],!email.isEmpty{body["email"]=try required("KDP_CUSTOMER_EMAIL")}
            let(tree,reply,id)=try await request("/licenses/activate",body);guard let token=reply["activation_token"] as? String,matches(token,#"^act_[A-Za-z0-9_-]+$"#) else {throw ClientError.denied("INVALID_RESPONSE",id)}
            do{let envelope=canonical(try tree.get("license"));let value=try verify(envelope,"online",nil,id);try save(Stored(token:token,envelope:envelope,checkpoint:iso()));return value}
            catch{_=try? await request("/licenses/deactivate",[:],token);throw error}}
        guard var state=saved else {throw ClientError.denied("NOT_ACTIVATED",nil)}
        if action=="deactivate"{let(_,reply,id)=try await request("/licenses/deactivate",[:],state.token);guard isTrue(reply["deactivated"]) else {throw ClientError.denied("INVALID_RESPONSE",id)};try clear();var value=accepted("online",id);value["message"]="This installation has been deactivated.";return value}
        if action=="check",let envelope=state.envelope{do{let value=try verify(envelope,"cache",state.checkpoint);let payload=try object(Data(envelope.utf8))["payload"] as? [String:Any];if Date() < (try instant(payload?["next_validation_at"])){state.checkpoint=iso();try save(state);return value}}catch{state.envelope=nil;try save(state)}}
        do{let(tree,_,id)=try await request("/licenses/validate",[:],state.token);let envelope=canonical(try tree.get("license"));let value=try verify(envelope,"online",state.checkpoint,id);state.envelope=envelope;state.checkpoint=iso();try save(state);return value}
        catch ClientError.network{guard let envelope=state.envelope else {throw ClientError.denied("OFFLINE_CACHE_MISSING",nil)};let value=try verify(envelope,"offline",state.checkpoint);state.checkpoint=iso();try save(state);return value}
        catch ClientError.denied(let code,let id){if ["INVALID_TOKEN","DEVICE_MISMATCH","LICENSE_REVOKED","LICENSE_EXPIRED","LICENSE_CANCELLED"].contains(code){try clear()}else{state.envelope=nil;try save(state)};throw ClientError.denied(code,id)}
    }
}
@main struct Application {
    static func main()async{var code:Int32=2
        do{guard CommandLine.arguments.count==2,["status","activate","check","validate","deactivate"].contains(CommandLine.arguments[1]) else {throw ClientError.setup};let session=try Session();defer{session.close()}
            var value:[String:Any];do{value=try await session.run(CommandLine.arguments[1]);code=0}
            catch ClientError.denied(let error,let id){value=session.accepted("local",id);value["valid"]=false;value["error_code"]=error;value["message"]="Your license could not be confirmed. Connect and try again, or contact your software provider.";code=1}
            catch ClientError.network{value=session.accepted("local");value["valid"]=false;value["error_code"]="NETWORK_ERROR";value["message"]="Connect to the internet and try again.";code=1}
            let raw=try JSONSerialization.data(withJSONObject:value,options:[.sortedKeys]);FileHandle.standardOutput.write(raw);FileHandle.standardOutput.write(Data([10]))
        }catch{FileHandle.standardError.write(Data("Check application settings and private storage. Contact your software provider if the problem continues.\n".utf8))};exit(code)
    }
}
```
The complete project also contains the exact verification helper. Its source and all positive/negative vectors are available in the [security verifier archive](/docs/downloads/security-verifiers.zip). Derived reusable files remove only the original standalone CLI entry point/imports that became unused; they do not change the signature algorithm or canonicalization.

## Run the lifecycle
Use ./session followed by exactly one action. Preserve the same App ID, state root and origin across processes.
1. Run status. Expected: activated=false for a new namespace and only an installation hash/storage category. Token presence is not a license validity decision.
2. Set a Sandbox key and matching email, then run activate. Expected: valid=true and signature_valid=true, or a safe refusal. An existing token is not silently replaced.
3. Run check. Expected: eligible authenticated cache before next_validation_at, otherwise an online validation attempt.
4. Run validate. Expected: an online attempt; only transport failure can use an eligible verified offline cache. Explicit HTTP rejection never grants offline permission.
5. Run deactivate. Expected: server-confirmed release, token/cache removal and no feature grant. valid=true here means the release operation succeeded, not permission to run a protected feature.
6. Run status again. Expected: activated=false and the same installation hash. Cumulative activation_count is not reset.
Exit0 means accepted operation/status, exit1 means refusal or connectivity denial, exit2 means unsafe configuration/state or unexpected failure. Output is safe decision metadata: never raw keys, tokens, Authorization headers or signed customer payloads.

## API contract and signature verification
Activation sends X-App-ID and X-Environment: SANDBOX plus license_key/device_id and optional matching email. Validation uses Bearer act_ and X-Installation-ID. Deactivation releases that token. See the [endpoint reference](/docs/v1/api/conventions) for full field/response/error tables.
The response parser preserves numeric lexemes, rejects duplicate/invalid JSON through the shared tested verifier, and authenticates the exact envelope. Only a verified payload enters policy. Key ID is derived from the independently trusted raw public key; wrong algorithm/key/signature is rejected. Never repair a mismatch by stripping signed fields or using JSON.stringify-style numeric normalization.

## Binding, features and fail-closed policy
The client requires its actual product App ID, environment=sandbox, SHA-256 installation binding and active status. It checks starts_at when present, expiry when nonnull, signed validation/grace dates and the last accepted checkpoint. Invalid data, status or policy is a refusal even if the payload carries a true feature.
pdf_export is allowed only for the boolean true on a fully accepted result. seat_count is exposed only as a nonnegative integer bounded by the shared safe-integer policy; otherwise it stays null. These example feature names must match your own product configuration. Constructing a result or reading token presence never authenticates a license.

## Offline grace and time checks
Before next_validation_at, check can return a verified cache. After that instant it validates online. Only a transport failure may use the existing signed state within offline_grace_until and expires_at. An explicit HTTP refusal, bad signature, malformed success or binding mismatch cannot extend access. Selected token/revocation/[device](/docs/v1/start/glossary#device)/expiry/cancellation refusals clear the token; other refusals clear cached authorization.
The last accepted checkpoint and signed server_time bound rollback with300 seconds tolerance. Grace is based on its signed deadline, not added to next_validation_at. Validating online does not promise permission if time/status/binding rules fail. No constructor flag creates an extra offline extension.
These strict sample policies are not changes to existing SDK behavior. A person controlling the host can patch the program or restore full snapshots. Use server-side authorization for high-value online actions and do not promise absolute local anti-tamper protection.

## Private storage, concurrency and recovery
The [installation ID](/docs/v1/start/glossary#installation-id) is random, persistent and independent of MAC/serial/hardware fingerprints. A namespaced private session stores the [activation token](/docs/v1/start/glossary#activation-token), lossless [signed envelope](/docs/v1/start/glossary#signed-envelope) and checkpoint. Writes are atomic and permissions are owner-only where supported; this is not automatic encryption or an OS-vault certification.
The program serializes one namespace. Java/Kotlin, Dart, Rust and the POSIX native core use an OS lock on a stable file; Go/Ruby/Swift use exclusive lock-file ownership and require manual reconciliation after a crash. Never delete an active lock or regenerate identity to avoid a refusal. A new identity can consume another cumulative activation. Keep separate namespaces for unrelated buyers/tenants.
Review [secure token storage](/docs/v1/security/secure-token-storage) for native vault adapters. POSIX modes do not replace Windows ACL review. Do not put state under public_html, bundle a populated cache, or expose raw SDK/client methods to a renderer/browser.

## Errors and uncertain mutations
The client accepts only bounded safe error/request identifiers and shows plain user messages. Unknown errors fail closed. No automatic mutation retry is supplied. A lost activation response may already have consumed a server activation; reconcile before retrying. If a returned new token fails signature/policy acceptance, the client attempts best-effort release, which can itself remain uncertain.
Read [the complete server error table](/docs/v1/api/errors). Local example identifiers such as BINDING_MISMATCH, ALREADY_ACTIVATED, SIGNATURE_INVALID and INVALID_TIME are client policy results, not invented server emissions. Never show raw stack traces, private paths or customer payloads to end users.

## Packaging and framework integration
Native macOS CLI or application service. This concrete project imports Darwin and CryptoKit; Windows/Linux compilation is not claimed. A mobile app needs its actual platform lifecycle and secure-storage adaptation. The generated Signature.swift contains the complete published verifier without its CLI tail.
Keep stable state outside executable extraction/install directories. Include the exact verification modules and required native/runtime libraries; never embed a developer key or populated token/cache. A web route still needs application authentication, tenant authorization and CSRF protection. A desktop renderer gets narrow safe decisions only, not arbitrary file paths or token access.
Re-test real activation, cache reload, offline loss, explicit refusal and release after bundling or updating dependencies. macOS native source execution is not proof that every operating-system package, signing/notarization setup or framework UI has passed.

## Recorded verification and limits
The exact native runtime executes the real isolated Sandbox lifecycle and21 negative/positive checks: wrong email, stable cross-process identity, cache without HTTP, online validation, injected network loss, modified offline cache, rollback, explicit HTTP503, modified signed response, no-follow307, recovery, release and unsafe setup guards. Refusal/outage/redirect injections are an explicit loopback test forwarder, not a claimed production outage.
Build evidence records actual toolchain/dependency hashes. All ten fresh project archives build and the complete native clients execute real Sandbox lifecycles. All23 published signature vectors pass in every REST language. Signature authenticity is separate from current license authorization. Native Windows/Linux/mobile GUI execution is not inferred from this macOS run.

## Expected result
Your application authenticates signed state, applies binding/time/status policy and enables only verified features. A refusal or successful seat release cannot accidentally unlock a feature.

## Common mistakes
- Using the internal product ID instead of the Public App ID.
- Losing numeric tokens before verifying the signature.
- Treating a true feature or HTTP success as a validity proof.
- Sharing one installation cache between unrelated tenants or deleting identity on failure.

## Security notes
Keep HTTPS verification, independent key trust and fail-closed policy. This example does not change the platform contract, process payments or grant universal anti-tamper protection. Preserve real API/SDK boundaries and keep credentials off browser/renderer surfaces.

## Troubleshooting
| Symptom | Cause | Action |
| --- | --- | --- |
| Exit2 at startup | Unsafe URL, missing private path, bad identity or busy lock | Correct trusted configuration; do not expose raw diagnostics to users |
| INVALID_LICENSE | Key/email/App ID/environment mismatch | Use the actual matching Sandbox values |
| SIGNATURE_INVALID | Wrong key, modified state or changed canonical bytes | Deny access and run the published vectors |
| OFFLINE_CACHE_MISSING | No accepted signed state remains | Reconnect and validate; never manufacture a cache |
| CLOCK_ROLLBACK_DETECTED | System time behind trusted time | Correct the device clock and reconnect |
| Release uncertain | Lost response or network/server refusal | Preserve identity and reconcile the seat with your software provider |

## Next steps
Review [offline mode](/docs/v1/security/offline-mode), [signed responses](/docs/v1/security/signed-responses) and [API errors](/docs/v1/api/errors).

## Related
- [Activate](/docs/v1/api/activate)
- [Validate](/docs/v1/api/validate)
- [Deactivate](/docs/v1/api/deactivate)
- [Signature test vectors](/docs/v1/security/test-vectors)
