KDPika Licensing Sign inStart free
API v1
Show all languages
Browse documentation

Choose a page in the navigation drawer.

KDPika Licensing · API v1 Intermediate

Ruby REST client

Build a complete Ruby Sandbox licensing client with verified signatures, persistent identity, private state, offline policy and safe feature gating.

On this page
Updated 2026-10-17 UTCDownload Markdown

Use the real API v1 from a trusted Ruby process with explicit signature and policy checks before enabling features. This REST sample is not an additional official SDK.

What you will learn

  • Activate, validate and deactivate one stable Sandbox installation.
  • Preserve signed bytes and verify the trusted Ed25519 key before policy.
  • Handle cache, offline grace, explicit rejection and safe user messages.

Prerequisites

Runtime and application type

Ruby2.6+, libsodium1.0.20, standard-library Net::HTTP/Fiddle. Trusted Ruby CLI or backend. Install the native libsodium library and set SODIUM_LIBRARY to its absolute platform path when library discovery does not find it. No Rails plugin is implied. The Net::HTTP client disables automatic retries and redirects and verifies TLS peers.

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-ruby-rest-example-1.0.0.zip · 7082 bytes · version 1.0.0

SHA-256: aa018d402159802d6189e7fb9cf21be95581c206acbca80a4a37cf18d6a022f3

<!-- 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/ruby. 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.
bashbash
ruby -c session.rb

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

VariableRequiredMeaning
KDP_APP_IDYesPublic App ID, not internal product ID or developer key
KDP_BASE_URLNoHTTPS API base ending /api/v1; default https://licensing.kdpika.com/api/v1
KDP_STATE_DIRYesAbsolute private application state root; keep it stable
KDP_TRUSTED_KEY_FILEYesAbsolute path to an independently trusted public-key document
KDP_LICENSE_KEYActivationSandbox key beginning TEST; never embedded in distributed source
KDP_CUSTOMER_EMAILOptionalActual matching customer email for email-bound activation
KDP_ALLOW_LOOPBACKLocal testing only1 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

session.rbruby
# Complete Sandbox REST CLI. Ruby2.6+, libsodium1.0.20; stdlib HTTP/TLS.
# Run ruby session.rb status|activate|check|validate|deactivate. Safe decisions.
# Requires unchanged ../../security/ruby/verify.rb and a trusted public key file.
require 'net/http'
require 'uri'
require 'time'
require 'securerandom'
require 'fileutils'
require_relative '../../security/ruby/verify'

class Refusal < StandardError
  attr_reader :code, :request_id
  def initialize(code, id = nil); super(code); @code = code; @request_id = id; end
end
class Unreachable < StandardError; end
class Session
  def required(name)
    value = ENV.fetch(name)
    raise 'Invalid configuration' if value.empty? || value.match?(/[\r\n]/)
    value
  end
  def read(file)
    stat = File.lstat(file)
    raise 'Unsafe file' unless stat.file? && !stat.symlink? && stat.size <= 1_048_576
    File.binread(file)
  end
  def object(raw)
    value = RawJson.new(raw.dup).parse
    raise Refusal.new('INVALID_RESPONSE') unless value.is_a?(Hash)
    value
  end
  def initialize
    @app = required('KDP_APP_ID'); raise 'App ID' unless /\A[A-Za-z0-9_-]{3,160}\z/.match?(@app)
    uri = URI(ENV.fetch('KDP_BASE_URL', 'https://licensing.kdpika.com/api/v1').sub(%r{/+\z}, ''))
    local = uri.scheme == 'http' && ['127.0.0.1', 'localhost'].include?(uri.host) && ENV['KDP_ALLOW_LOOPBACK'] == '1'
    raise 'Unsafe URL' unless uri.host && (uri.scheme == 'https' || local) && !uri.userinfo && !uri.query && !uri.fragment && uri.path == '/api/v1'
    @base = uri.to_s
    root = required('KDP_STATE_DIR'); key = required('KDP_TRUSTED_KEY_FILE')
    raise 'Absolute paths required' unless File.absolute_path(root) == root && File.absolute_path(key) == key
    @trusted = read(key); public_key = object(@trusted)
    raise 'Trusted key' unless public_key['algorithm'] == 'Ed25519' && public_key['encoding'] == 'base64url'
    FileUtils.mkdir_p(root, mode: 0o700); raise 'Root symlink' if File.symlink?(root)
    @dir = File.join(root, Digest::SHA256.hexdigest([@base, @app, 'SANDBOX', 'ruby-rest-v1'].join('|'))[0, 20])
    FileUtils.mkdir_p(@dir, mode: 0o700); raise 'Namespace symlink' if File.symlink?(@dir)
    File.chmod(0o700, @dir)
    @lock = File.open(File.join(@dir, '.lock'), File::WRONLY | File::CREAT | File::EXCL, 0o600)
    begin
      identity = File.join(@dir, 'installation.json')
      write('installation.json', {'installation_id' => 'lmp-install-' + SecureRandom.uuid}) unless File.exist?(identity) || File.symlink?(identity)
      @installation = object(read(identity)).fetch('installation_id')
      raise 'Invalid identity; do not reset automatically' unless /\Almp-install-[a-f0-9-]{36}\z/.match?(@installation)
    rescue StandardError
      close; raise
    end
  end
  def close
    return unless @lock
    @lock.close; File.unlink(File.join(@dir, '.lock')); @lock = nil
  end
  def write(name, value)
    temporary = File.join(@dir, 'write-' + SecureRandom.hex(12))
    File.open(temporary, File::WRONLY | File::CREAT | File::EXCL, 0o600) { |file| file.write(JSON.generate(value)); file.flush; file.fsync }
    File.rename(temporary, File.join(@dir, name))
  end
  def state
    file = File.join(@dir, 'session.json'); return nil unless File.exist?(file) || File.symlink?(file)
    raw = read(file); object(raw); value = JSON.parse(raw)
    raise 'Invalid state' unless value['token'].is_a?(String) && /\Aact_[A-Za-z0-9_-]+\z/.match?(value['token']) &&
      (value['envelope'].nil? || value['envelope'].is_a?(String)) && value['checkpoint'].is_a?(String)
    timestamp(value['checkpoint']); value
  end
  def clear
    file = File.join(@dir, 'session.json'); File.unlink(file) if File.exist?(file) || File.symlink?(file)
  end
  def timestamp(value)
    raise Refusal.new('INVALID_TIME') unless value.is_a?(String) && /\A\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)\z/.match?(value)
    Time.iso8601(value)
  rescue ArgumentError
    raise Refusal.new('INVALID_TIME')
  end
  def request(endpoint, body, token = nil)
    uri = URI(@base + endpoint); request = Net::HTTP::Post.new(uri.request_uri)
    request['Accept'] = 'application/json'; request['Content-Type'] = 'application/json'; request['User-Agent'] = 'KDPika-REST-Ruby-example/1.0'
    if token
      request['Authorization'] = 'Bearer ' + token; request['X-Installation-ID'] = @installation
    else
      request['X-App-ID'] = @app; request['X-Environment'] = 'SANDBOX'
    end
    request.body = JSON.generate(body); raw = ''.b; response = nil
    begin
      # Explicit nil proxy prevents accidental forwarding through environment proxies.
      http = Net::HTTP.new(uri.host, uri.port, nil); http.use_ssl = uri.scheme == 'https'; http.verify_mode = OpenSSL::SSL::VERIFY_PEER
      http.open_timeout = 5; http.read_timeout = 15; http.max_retries = 0
      http.start { |connection| connection.request(request) { |reply| response = reply; reply.read_body { |part| raw << part; raise Refusal.new('INVALID_RESPONSE') if raw.bytesize > 1_048_576 } } }
    rescue Refusal
      raise
    rescue StandardError
      raise Unreachable
    end
    begin; value = object(raw); rescue StandardError; raise Refusal.new('INVALID_RESPONSE'); end
    id = value['request_id']; id = nil unless id.is_a?(String) && /\Areq_[A-Za-z0-9_-]{1,120}\z/.match?(id)
    unless response.code.to_i.between?(200, 299) && value['success'] == true
      code = value.dig('error', 'code') rescue nil
      code = 'HTTP_ERROR' unless code.is_a?(String) && /\A[A-Z0-9_]{1,64}\z/.match?(code)
      raise Refusal.new(code, id)
    end
    [value, id]
  end
  def accepted(source, id = nil)
    {'valid' => true, 'source' => source, 'signature_valid' => false, 'error_code' => nil, 'request_id' => id,
     'pdf_export_allowed' => false, 'seat_count' => nil, 'message' => 'Your license is ready.'}
  end
  def verify(envelope, source, checkpoint, id = nil)
    raise Refusal.new('SIGNATURE_INVALID', id) unless verify_envelope(@trusted.dup, envelope.dup)
    payload = JSON.parse(envelope).fetch('payload'); now = Time.now
    unless payload['product_id'] == @app && payload['environment'] == 'sandbox' &&
      payload.dig('device', 'installation_hash') == Digest::SHA256.hexdigest(@installation)
      raise Refusal.new('BINDING_MISMATCH', id)
    end
    server = timestamp(payload['server_time']); next_time = timestamp(payload['next_validation_at']); grace = timestamp(payload['offline_grace_until'])
    raise Refusal.new('INVALID_TIME', id) if next_time < server || grace < server
    latest = checkpoint ? [server, timestamp(checkpoint)].max : server
    raise Refusal.new('CLOCK_ROLLBACK_DETECTED', id) if now + 300 < latest
    raise Refusal.new('LICENSE_NOT_ACTIVE', id) unless payload['status'] == 'active'
    raise Refusal.new('LICENSE_NOT_STARTED', id) if payload['starts_at'] && now < timestamp(payload['starts_at'])
    raise Refusal.new('LICENSE_EXPIRED', id) if payload['expires_at'] && now >= timestamp(payload['expires_at'])
    raise Refusal.new('OFFLINE_GRACE_EXPIRED', id) if source != 'online' && now > grace
    features = payload.fetch('features'); raise Refusal.new('INVALID_RESPONSE') unless features.is_a?(Hash)
    value = accepted(source, id); value['signature_valid'] = true; value['pdf_export_allowed'] = features['pdf_export'] == true
    seat = features['seat_count']; value['seat_count'] = seat if seat.is_a?(Integer) && seat.between?(0, 9_007_199_254_740_991)
    value
  end
  def run(action)
    saved = state
    return {'activated' => !saved.nil?, 'installation_hash' => Digest::SHA256.hexdigest(@installation), 'storage_security' => 'permission-protected-file'} if action == 'status'
    if action == 'activate'
      license = required('KDP_LICENSE_KEY'); raise 'Sandbox key required' unless license.start_with?('TEST')
      raise Refusal.new('ALREADY_ACTIVATED') if saved
      body = {'license_key' => license, 'device_id' => @installation, 'device_name' => 'Ruby REST example', 'platform' => RUBY_PLATFORM, 'app_version' => '1.0.0'}
      body['email'] = required('KDP_CUSTOMER_EMAIL') if ENV['KDP_CUSTOMER_EMAIL'] && !ENV['KDP_CUSTOMER_EMAIL'].empty?
      reply, id = request('/licenses/activate', body); token = reply['activation_token']
      raise Refusal.new('INVALID_RESPONSE', id) unless token.is_a?(String) && /\Aact_[A-Za-z0-9_-]+\z/.match?(token)
      begin
        envelope = canonical(reply.fetch('license')); result = verify(envelope, 'online', nil, id)
        write('session.json', {'token' => token, 'envelope' => envelope, 'checkpoint' => Time.now.utc.iso8601(6)}); return result
      rescue StandardError
        begin; request('/licenses/deactivate', {}, token); rescue StandardError; end
        raise
      end
    end
    raise Refusal.new('NOT_ACTIVATED') unless saved
    if action == 'deactivate'
      reply, id = request('/licenses/deactivate', {}, saved['token']); raise Refusal.new('INVALID_RESPONSE', id) unless reply['deactivated'] == true
      clear; value = accepted('online', id); value['message'] = 'This installation has been deactivated.'; return value
    end
    if action == 'check' && saved['envelope']
      begin
        value = verify(saved['envelope'], 'cache', saved['checkpoint'])
        if Time.now < timestamp(JSON.parse(saved['envelope']).dig('payload', 'next_validation_at'))
          saved['checkpoint'] = Time.now.utc.iso8601(6); write('session.json', saved); return value
        end
      rescue Refusal
        saved['envelope'] = nil; write('session.json', saved)
      end
    end
    begin
      reply, id = request('/licenses/validate', {}, saved['token']); envelope = canonical(reply.fetch('license'))
      value = verify(envelope, 'online', saved['checkpoint'], id); saved['envelope'] = envelope
    rescue Unreachable
      raise Refusal.new('OFFLINE_CACHE_MISSING') unless saved['envelope']
      value = verify(saved['envelope'], 'offline', saved['checkpoint'])
    rescue Refusal => error
      if ['INVALID_TOKEN', 'DEVICE_MISMATCH', 'LICENSE_REVOKED', 'LICENSE_EXPIRED', 'LICENSE_CANCELLED'].include?(error.code)
        clear
      else
        saved['envelope'] = nil; write('session.json', saved)
      end
      raise
    end
    saved['checkpoint'] = Time.now.utc.iso8601(6); write('session.json', saved); value
  end
end

if $PROGRAM_NAME == __FILE__
  client = nil; code = 2
  begin
    raise 'Choose an action' unless ARGV.length == 1 && ['status', 'activate', 'check', 'validate', 'deactivate'].include?(ARGV[0])
    client = Session.new
    begin
      puts JSON.generate(client.run(ARGV[0])); code = 0
    rescue Refusal, Unreachable => error
      value = client.accepted('local', error.is_a?(Refusal) ? error.request_id : nil)
      value['valid'] = false; value['error_code'] = error.is_a?(Refusal) ? error.code : 'NETWORK_ERROR'
      value['message'] = 'Your license could not be confirmed. Connect and try again, or contact your software provider.'
      puts JSON.generate(value); code = 1
    end
  rescue StandardError
    warn 'Check application settings and private storage. Contact your software provider if the problem continues.'
  ensure
    client.close if client
  end
  exit code
end

The complete project also contains the exact verification helper. Its source and all positive/negative vectors are available in the security verifier archive. 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 ruby session.rb 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 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/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 is random, persistent and independent of MAC/serial/hardware fingerprints. A namespaced private session stores the activation token, lossless 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 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. 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

Trusted Ruby CLI or backend. Install the native libsodium library and set SODIUM_LIBRARY to its absolute platform path when library discovery does not find it. No Rails plugin is implied. The Net::HTTP client disables automatic retries and redirects and verifies TLS peers.

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

SymptomCauseAction
Exit2 at startupUnsafe URL, missing private path, bad identity or busy lockCorrect trusted configuration; do not expose raw diagnostics to users
INVALID_LICENSEKey/email/App ID/environment mismatchUse the actual matching Sandbox values
SIGNATURE_INVALIDWrong key, modified state or changed canonical bytesDeny access and run the published vectors
OFFLINE_CACHE_MISSINGNo accepted signed state remainsReconnect and validate; never manufacture a cache
CLOCK_ROLLBACK_DETECTEDSystem time behind trusted timeCorrect the device clock and reconnect
Release uncertainLost response or network/server refusalPreserve identity and reconcile the seat with your software provider

Next steps

Review offline mode, signed responses and API errors.

Was this page helpful?

Choose an answer

Do not include personal data, license keys or credentials. Retained for up to 30 days. This is not a support inbox.

Search documentation

Arrow keys to move, Enter to open, Escape to close. Search stays in your browser.

Cookie settings