Skip to main content

🌙 Lua Code Examples

local http = require("socket.http")
local json = require("json")
local socket = require("socket")
local crypto = require("crypto")

local API_KEY = "your-api-key-here"
local API_URL = "http://your-domain.com/api/license/auth"
local PRODUCT = "MyLuaApp"
local VERSION = "1.0.0"

local TKIAuth = {}

function TKIAuth.getHWID()
-- Generate HWID based on available system info
local hostname = os.getenv("HOSTNAME") or os.getenv("COMPUTERNAME") or "unknown"
local user = os.getenv("USER") or os.getenv("USERNAME") or "unknown"
local hw_string = hostname .. "-" .. user .. "-" .. os.time()

-- Simple hash function (replace with proper crypto if available)
local hash = 0
for i = 1, #hw_string do
hash = hash + string.byte(hw_string, i)
end

return "LUA-" .. string.format("%x", hash):sub(1, 16)
end

function TKIAuth.getLocalIP()
-- Try to get local IP (fallback to localhost)
local s = socket.tcp()
if s then
s:connect("8.8.8.8", 80)
local ip = s:getsockname()
s:close()
return ip or "127.0.0.1"
end
return "127.0.0.1"
end

function TKIAuth.authenticate(license_key)
local payload = {
data = {
product = PRODUCT,
version = VERSION,
licensekey = license_key,
ip = TKIAuth.getLocalIP(),
hwid = TKIAuth.getHWID()
}
}

local json_data = json.encode(payload)
local headers = {
["Content-Type"] = "application/json",
["Authorization"] = API_KEY,
["Content-Length"] = tostring(#json_data)
}

local response_body = {}

local result, status_code = http.request{
url = API_URL,
method = "POST",
headers = headers,
source = ltn12.source.string(json_data),
sink = ltn12.sink.table(response_body)
}

if result and status_code == 200 then
local response_text = table.concat(response_body)
local response_data = json.decode(response_text)

if response_data and response_data.status_overview == "success" then
print("✓ License authenticated!")
print("User: " .. (response_data.discord_username or "Unknown"))
print("Expires: " .. (response_data.expire_date or "Unknown"))
print("Staff License: " .. tostring(response_data.staff_license or false))
return true, response_data
else
print("✗ Authentication failed: " .. (response_data.message or "Unknown error"))
return false, response_data.message
end
else
print("✗ Network error: " .. tostring(status_code))
return false, "Network error"
end
end

-- Main execution
function main()
print("Enter license key:")
local license_key = io.read()

if license_key and license_key ~= "" then
local success, result = TKIAuth.authenticate(license_key:gsub("%s+", ""))

if success then
print("Starting application...")
-- Your application logic here
return 0
else
print("Authentication failed!")
return 1
end
else
print("No license key provided!")
return 1
end
end

-- Run the application
if not pcall(main) then
print("Application error occurred!")
os.exit(1)
end

Advanced Lua Implementation​

local http = require("socket.http")
local ltn12 = require("ltn12")
local json = require("json")
local socket = require("socket")

local API_KEY = "your-api-key-here"
local API_URL = "http://your-domain.com/api/license/auth"
local PRODUCT = "MyAdvancedLuaApp"
local VERSION = "1.0.0"

-- TKI Auth Class
local TKIAuth = {}
TKIAuth.__index = TKIAuth

function TKIAuth:new()
local instance = {
timeout = 30,
max_retries = 3,
user_agent = "TKI-Auth-Lua/1.0"
}
setmetatable(instance, TKIAuth)
return instance
end

function TKIAuth:getHWID()
local hwid_sources = {
os.getenv("HOSTNAME") or "",
os.getenv("COMPUTERNAME") or "",
os.getenv("USER") or "",
os.getenv("USERNAME") or "",
tostring(os.time())
}

local hw_string = table.concat(hwid_sources, "-")

-- Simple hash function
local hash = 0
for i = 1, #hw_string do
hash = ((hash << 5) - hash) + string.byte(hw_string, i)
hash = hash & 0xFFFFFFFF
end

return "LUA-" .. string.format("%08x", hash):sub(1, 16)
end

function TKIAuth:getLocalIP()
local s = socket.tcp()
if s then
local success = s:connect("1.1.1.1", 80)
if success then
local ip = s:getsockname()
s:close()
return ip or "127.0.0.1"
end
s:close()
end
return "127.0.0.1"
end

function TKIAuth:makeRequest(payload)
local json_data = json.encode(payload)
local response_body = {}

local headers = {
["Content-Type"] = "application/json",
["Authorization"] = API_KEY,
["User-Agent"] = self.user_agent,
["Content-Length"] = tostring(#json_data)
}

local result, status_code, response_headers = http.request{
url = API_URL,
method = "POST",
headers = headers,
source = ltn12.source.string(json_data),
sink = ltn12.sink.table(response_body)
}

local response_text = table.concat(response_body)

return {
success = result ~= nil,
status_code = status_code,
body = response_text,
headers = response_headers
}
end

function TKIAuth:authenticate(license_key, ip, hwid)
local payload = {
data = {
product = PRODUCT,
version = VERSION,
licensekey = license_key,
ip = ip or self:getLocalIP(),
hwid = hwid or self:getHWID()
}
}

local response = self:makeRequest(payload)

if not response.success then
return false, "Network error", nil
end

local response_data
if response.body and response.body ~= "" then
local success, decoded = pcall(json.decode, response.body)
if success then
response_data = decoded
else
return false, "Invalid response format", nil
end
end

if response.status_code == 200 and response_data.status_overview == "success" then
return true, "Success", response_data
else
local error_msg = response_data and response_data.message or ("HTTP " .. tostring(response.status_code))
return false, error_msg, response_data
end
end

function TKIAuth:authenticateWithRetry(license_key, ip, hwid)
local last_error = "Unknown error"

for attempt = 1, self.max_retries do
local success, error_msg, data = self:authenticate(license_key, ip, hwid)

if success then
return true, error_msg, data
end

last_error = error_msg

if attempt < self.max_retries then
local wait_time = attempt * 2
print(string.format("Attempt %d failed, retrying in %d seconds...", attempt, wait_time))
socket.sleep(wait_time)
end
end

return false, last_error, nil
end

-- Licensed Application Class
local LicensedApp = {}
LicensedApp.__index = LicensedApp

function LicensedApp:new()
local instance = {
auth = TKIAuth:new(),
is_authenticated = false,
license_info = nil,
validation_interval = 1800, -- 30 minutes
running = false
}
setmetatable(instance, LicensedApp)
return instance
end

function LicensedApp:authenticate(license_key)
print("Authenticating license...")

local success, error_msg, data = self.auth:authenticateWithRetry(license_key)

if success then
self.is_authenticated = true
self.license_info = data

print("✓ Authentication successful!")
print(" User: " .. (data.discord_username or "Unknown"))
print(" Tag: " .. (data.discord_tag or "Unknown"))
print(" Expires: " .. (data.expire_date or "Unknown"))
print(" Staff License: " .. tostring(data.staff_license or false))

return true
else
print("✗ Authentication failed: " .. error_msg)
return false
end
end

function LicensedApp:startPeriodicValidation(license_key)
-- Simple periodic validation (in a real app, you'd use proper threading)
local last_validation = os.time()

self.validate_license = function()
local current_time = os.time()
if current_time - last_validation >= self.validation_interval then
local success, error_msg = self.auth:authenticate(license_key)

if success then
print("✓ Periodic validation successful")
last_validation = current_time
else
print("⚠ Periodic validation failed: " .. error_msg)
self:onLicenseExpired()
return false
end
end
return true
end

return true
end

function LicensedApp:onLicenseExpired()
print("License expired or validation failed!")
self.is_authenticated = false
self.running = false
-- Implement your logic here
end

function LicensedApp:run()
-- Get license key from user
print("Enter license key:")
local license_key = io.read()

if not license_key or license_key == "" then
print("No license key provided!")
return false
end

license_key = license_key:gsub("%s+", "") -- Remove whitespace

-- Authenticate
if not self:authenticate(license_key) then
return false
end

-- Start periodic validation
self:startPeriodicValidation(license_key)

print("Starting application...")
self.running = true

-- Main application loop
local loop_count = 0
while self.running and self.is_authenticated do
-- Your application logic here
print("Application is running... (loop " .. loop_count .. ")")

-- Check license periodically
if self.validate_license and not self.validate_license() then
break
end

socket.sleep(5) -- Wait 5 seconds
loop_count = loop_count + 1

-- Stop after 10 loops for demo
if loop_count >= 10 then
print("Demo completed successfully!")
break
end
end

print("Application stopped.")
return true
end

-- Utility functions
local function getUserInput(prompt)
print(prompt)
return io.read()
end

local function handleError(error_msg)
print("Error: " .. error_msg)
os.exit(1)
end

-- Main execution
local function main()
local app = LicensedApp:new()

local success, error_msg = pcall(function()
return app:run()
end)

if not success then
handleError(error_msg or "Unknown application error")
end

return app:run() and 0 or 1
end

-- Example usage functions
local function example_simple()
print("=== Simple TKI Auth Example ===")
local auth = TKIAuth:new()

local license_key = getUserInput("Enter license key:")
license_key = license_key:gsub("%s+", "")

local success, error_msg, data = auth:authenticate(license_key)

if success then
print("✓ License valid!")
print("User: " .. (data.discord_username or "Unknown"))
else
print("✗ License invalid: " .. error_msg)
end
end

local function example_advanced()
print("=== Advanced TKI Auth Example ===")
return main()
end

-- Run examples
if arg and arg[1] == "simple" then
example_simple()
elseif arg and arg[1] == "advanced" then
os.exit(example_advanced())
else
print("Usage: lua script.lua [simple|advanced]")
print("Running advanced example by default...")
os.exit(example_advanced())
end

Dependencies​

For LuaRocks package manager:

luarocks install luasocket
luarocks install lua-cjson

Usage Examples​

# Run simple example
lua tkiauth.lua simple

# Run advanced example
lua tkiauth.lua advanced

# Default (advanced)
lua tkiauth.lua