-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthon.lua
More file actions
652 lines (574 loc) · 26.1 KB
/
Copy pathauthon.lua
File metadata and controls
652 lines (574 loc) · 26.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
--[[
╔══════════════════════════════════════════════════════════════════════════════╗
║ Authon Lua SDK — Software Licensing & Authentication ║
║ Version: 1.0.0 ║
║ Dependencies: LuaSocket (or built-in http for Roblox/FiveM) ║
║ ║
║ Website: https://authon.pro ║
║ Docs: https://authon.pro/docs ║
║ Discord: https://discord.gg/jMZCTKPsmE ║
║ Status: https://authon.pro/status ║
║ Health: https://api.authon.pro/health ║
║ GitHub: https://github.com/authonpro ║
║ ║
║ Compatible with: Standard Lua 5.1+, LuaJIT, Roblox, FiveM ║
║ ║
║ Usage: ║
║ local Authon = require("authon") ║
║ local auth = Authon.new("app-id", "api-key") ║
║ if auth:init() then ║
║ local result = auth:login("user", "pass") ║
║ if result.success then print("Welcome!") end ║
║ end ║
╚══════════════════════════════════════════════════════════════════════════════╝
]]
local Authon = {}
Authon.__index = Authon
--- SDK Version
Authon.VERSION = "1.0.0"
--- Default API URL
Authon.DEFAULT_API_URL = "https://api.authon.pro/v1"
-- ═══════════════════════════════════════════════════════════════════════════════
-- JSON ENCODER/DECODER (minimal, for environments without json library)
-- ═══════════════════════════════════════════════════════════════════════════════
local json = {}
--- Encodes a Lua table to a JSON string.
-- @param val any Lua value to encode
-- @return string JSON representation
function json.encode(val)
if val == nil then return "null" end
local t = type(val)
if t == "boolean" then return val and "true" or "false" end
if t == "number" then return tostring(val) end
if t == "string" then
val = val:gsub('\\', '\\\\'):gsub('"', '\\"')
:gsub('\n', '\\n'):gsub('\r', '\\r'):gsub('\t', '\\t')
return '"' .. val .. '"'
end
if t == "table" then
-- Check if array
if #val > 0 or next(val) == nil then
local parts = {}
for i, v in ipairs(val) do
parts[i] = json.encode(v)
end
return "[" .. table.concat(parts, ",") .. "]"
end
-- Object
local parts = {}
for k, v in pairs(val) do
parts[#parts + 1] = '"' .. tostring(k) .. '":' .. json.encode(v)
end
return "{" .. table.concat(parts, ",") .. "}"
end
return "null"
end
--- Decodes a JSON string to a Lua table.
-- @param str string JSON string
-- @return table|string|number|boolean|nil Decoded value
function json.decode(str)
if not str or str == "" then return nil end
-- Use existing json library if available
if _G.game and _G.game.HttpService then
-- Roblox environment
return _G.game:GetService("HttpService"):JSONDecode(str)
end
-- Try to use cjson or dkjson if available
local ok, lib = pcall(require, "cjson")
if ok then return lib.decode(str) end
ok, lib = pcall(require, "dkjson")
if ok then return lib.decode(str) end
ok, lib = pcall(require, "json")
if ok and lib.decode then return lib.decode(str) end
-- Minimal parser fallback
local pos = 1
local function skip_ws()
pos = str:find("[^ \t\r\n]", pos) or pos
end
local parse_value
local function parse_string()
pos = pos + 1 -- skip opening quote
local start = pos
local result = {}
while pos <= #str do
local c = str:sub(pos, pos)
if c == '"' then
pos = pos + 1
return table.concat(result)
elseif c == '\\' then
pos = pos + 1
local esc = str:sub(pos, pos)
if esc == 'n' then result[#result+1] = '\n'
elseif esc == 'r' then result[#result+1] = '\r'
elseif esc == 't' then result[#result+1] = '\t'
elseif esc == '"' then result[#result+1] = '"'
elseif esc == '\\' then result[#result+1] = '\\'
else result[#result+1] = esc end
else
result[#result+1] = c
end
pos = pos + 1
end
return table.concat(result)
end
local function parse_number()
local start = pos
if str:sub(pos, pos) == '-' then pos = pos + 1 end
while pos <= #str and str:sub(pos, pos):match("[%d%.eE%+%-]") do
pos = pos + 1
end
return tonumber(str:sub(start, pos - 1))
end
local function parse_object()
pos = pos + 1 -- skip {
local obj = {}
skip_ws()
if str:sub(pos, pos) == '}' then pos = pos + 1; return obj end
while pos <= #str do
skip_ws()
local key = parse_string()
skip_ws()
pos = pos + 1 -- skip :
skip_ws()
obj[key] = parse_value()
skip_ws()
local c = str:sub(pos, pos)
if c == '}' then pos = pos + 1; return obj end
if c == ',' then pos = pos + 1 end
end
return obj
end
local function parse_array()
pos = pos + 1 -- skip [
local arr = {}
skip_ws()
if str:sub(pos, pos) == ']' then pos = pos + 1; return arr end
while pos <= #str do
skip_ws()
arr[#arr + 1] = parse_value()
skip_ws()
local c = str:sub(pos, pos)
if c == ']' then pos = pos + 1; return arr end
if c == ',' then pos = pos + 1 end
end
return arr
end
parse_value = function()
skip_ws()
local c = str:sub(pos, pos)
if c == '"' then return parse_string()
elseif c == '{' then return parse_object()
elseif c == '[' then return parse_array()
elseif c == 't' then pos = pos + 4; return true
elseif c == 'f' then pos = pos + 5; return false
elseif c == 'n' then pos = pos + 4; return nil
else return parse_number() end
end
return parse_value()
end
-- ═══════════════════════════════════════════════════════════════════════════════
-- HTTP REQUEST (multi-environment)
-- ═══════════════════════════════════════════════════════════════════════════════
--- Performs an HTTP POST request. Supports multiple Lua environments.
-- @param url string Target URL
-- @param body string JSON body
-- @return string|nil response body, string|nil error
local function httpPost(url, body)
-- Roblox environment
if _G.game and _G.game.HttpService then
local HttpService = _G.game:GetService("HttpService")
local ok, result = pcall(function()
return HttpService:PostAsync(url, body, Enum.HttpContentType.ApplicationJson)
end)
if ok then return result, nil end
return nil, tostring(result)
end
-- FiveM environment
if _G.PerformHttpRequest then
local response, done = nil, false
PerformHttpRequest(url, function(code, data, headers)
response = data
done = true
end, "POST", body, {["Content-Type"] = "application/json"})
-- Wait for response (FiveM async)
local timeout = 150 -- 15 seconds at 100ms intervals
while not done and timeout > 0 do
Citizen.Wait(100)
timeout = timeout - 1
end
if response then return response, nil end
return nil, "Request timed out"
end
-- Standard Lua with LuaSocket + LuaSec
local ok, http = pcall(require, "ssl.https")
if not ok then
ok, http = pcall(require, "socket.http")
end
if not ok then
return nil, "No HTTP library available. Install LuaSocket/LuaSec."
end
local ltn12 = require("ltn12")
local response_body = {}
local result, status, headers = http.request({
url = url,
method = "POST",
headers = {
["Content-Type"] = "application/json",
["Content-Length"] = tostring(#body),
["User-Agent"] = "Authon-Lua-SDK/" .. Authon.VERSION,
},
source = ltn12.source.string(body),
sink = ltn12.sink.table(response_body),
})
if result then
return table.concat(response_body), nil
end
return nil, "HTTP request failed: " .. tostring(status)
end
-- ═══════════════════════════════════════════════════════════════════════════════
-- HWID GENERATION
-- ═══════════════════════════════════════════════════════════════════════════════
--- Generates a hardware ID unique to the current machine.
-- Uses disk serial + hostname on Windows, /etc/machine-id on Linux.
-- Falls back to hostname + OS info.
-- @return string 32-character hex MD5 hash
function Authon.getHWID()
local raw = ""
-- Try to detect platform
local isWindows = package.config:sub(1, 1) == '\\'
if isWindows then
-- Windows: wmic disk serial + computer name
local handle = io.popen("wmic diskdrive get serialnumber 2>NUL")
if handle then
local output = handle:read("*a")
handle:close()
local lines = {}
for line in output:gmatch("[^\r\n]+") do
lines[#lines + 1] = line
end
if #lines > 1 then
raw = lines[2]:match("^%s*(.-)%s*$") or ""
end
end
-- Append computer name
local compName = os.getenv("COMPUTERNAME") or ""
raw = raw .. compName
else
-- Linux/Mac: try /etc/machine-id
local f = io.open("/etc/machine-id", "r")
if f then
raw = f:read("*l") or ""
f:close()
else
-- Fallback: hostname
local handle = io.popen("hostname")
if handle then
raw = handle:read("*l") or "unknown"
handle:close()
end
raw = raw .. (os.getenv("USER") or "")
end
end
if raw == "" then
raw = "fallback-" .. os.time()
end
-- MD5 hash (use built-in if available, otherwise simple hash)
local ok, md5lib = pcall(require, "md5")
if ok and md5lib.sumhexa then
return md5lib.sumhexa(raw)
end
-- Fallback: simple hash function producing 32 hex chars
-- This is NOT cryptographic MD5 but provides a consistent HWID
local hash = 0
for i = 1, #raw do
hash = (hash * 31 + raw:byte(i)) % (2^32)
end
return string.format("%08x%08x%08x%08x",
hash, hash * 2654435761 % (2^32),
hash * 2246822519 % (2^32), hash * 3266489917 % (2^32))
end
-- ═══════════════════════════════════════════════════════════════════════════════
-- CONSTRUCTOR
-- ═══════════════════════════════════════════════════════════════════════════════
--- Creates a new Authon client instance.
-- @param appId string Your Application ID from the Authon dashboard.
-- @param apiKey string Your API Key from the Authon dashboard.
-- @param apiUrl string|nil Custom API URL (default: https://api.authon.pro/v1).
-- @return Authon New client instance.
function Authon.new(appId, apiKey, apiUrl)
assert(appId and appId ~= "", "appId is required")
assert(apiKey and apiKey ~= "", "apiKey is required")
local self = setmetatable({}, Authon)
self._appId = appId
self._apiKey = apiKey
self._apiUrl = apiUrl or Authon.DEFAULT_API_URL
-- Session state
self.sessionToken = nil
self.username = nil
self.level = 0
self.subscription = nil
self.expiresAt = nil
-- App info
self.appName = nil
self.appVersion = nil
self.hwidLock = false
self.hashCheck = false
self.initialized = false
return self
end
--- Check if the client has an active session.
-- @return boolean
function Authon:isAuthenticated()
return self.sessionToken ~= nil and self.sessionToken ~= ""
end
-- ═══════════════════════════════════════════════════════════════════════════════
-- INTERNAL REQUEST
-- ═══════════════════════════════════════════════════════════════════════════════
--- Sends a POST request to the Authon API.
-- @param data table Request payload (type + params).
-- @return table Parsed response {success, message, data}
function Authon:_request(data)
data.appId = self._appId
data.apiKey = self._apiKey
local body = json.encode(data)
local response, err = httpPost(self._apiUrl, body)
if not response then
return {success = false, message = err or "Connection failed. Check https://authon.pro/status"}
end
local decoded = json.decode(response)
if not decoded then
return {success = false, message = "Invalid response from server"}
end
return decoded
end
-- ═══════════════════════════════════════════════════════════════════════════════
-- INITIALIZATION
-- ═══════════════════════════════════════════════════════════════════════════════
--- Initializes the connection to the Authon API.
-- Must be called before any other API method.
-- @return boolean True if initialization was successful.
function Authon:init()
local result = self:_request({type = "init"})
if result.success then
local data = result.data or {}
self.appName = data.name
self.appVersion = data.version
self.hwidLock = data.hwidLock or false
self.hashCheck = data.hashCheck or false
self.initialized = true
end
return result.success == true
end
-- ═══════════════════════════════════════════════════════════════════════════════
-- AUTHENTICATION
-- ═══════════════════════════════════════════════════════════════════════════════
--- Authenticates with username and password.
-- On success, sets sessionToken, username, level, subscription, expiresAt.
-- @param username string User's username.
-- @param password string User's password.
-- @param hwid string|nil Hardware ID (nil to auto-generate).
-- @return table {success, message, data}
function Authon:login(username, password, hwid)
if not username or username == "" or not password or password == "" then
return {success = false, message = "Username and password are required"}
end
local result = self:_request({
type = "login",
username = username,
password = password,
hwid = hwid or Authon.getHWID(),
})
if result.success then
local data = result.data or {}
self.sessionToken = data.sessionToken
self.username = data.username
self.level = data.level or 0
self.subscription = data.subscription
self.expiresAt = data.expiresAt
end
return result
end
--- Authenticates using a license key only.
-- @param licenseKey string The license key.
-- @param hwid string|nil Hardware ID (nil to auto-generate).
-- @return table {success, message, data}
function Authon:license(licenseKey, hwid)
if not licenseKey or licenseKey == "" then
return {success = false, message = "License key is required"}
end
local result = self:_request({
type = "license",
licenseKey = licenseKey,
hwid = hwid or Authon.getHWID(),
})
if result.success then
local data = result.data or {}
self.sessionToken = data.sessionToken
self.username = data.username
self.level = data.level or 0
self.subscription = data.subscription
self.expiresAt = data.expiresAt
end
return result
end
--- Registers a new user account with a license key.
-- @param username string Desired username.
-- @param password string Desired password.
-- @param licenseKey string A valid, unused license key.
-- @param hwid string|nil Hardware ID (nil to auto-generate).
-- @return table {success, message}
function Authon:register(username, password, licenseKey, hwid)
if not username or username == "" or not password or password == ""
or not licenseKey or licenseKey == "" then
return {success = false, message = "Username, password, and licenseKey are required"}
end
return self:_request({
type = "register",
username = username,
password = password,
licenseKey = licenseKey,
hwid = hwid or Authon.getHWID(),
})
end
-- ═══════════════════════════════════════════════════════════════════════════════
-- SESSION MANAGEMENT
-- ═══════════════════════════════════════════════════════════════════════════════
--- Validates the current session (heartbeat).
-- @return boolean True if session is valid.
function Authon:check()
if not self.sessionToken then return false end
local result = self:_request({type = "check", sessionToken = self.sessionToken})
return result.success == true
end
--- Ends the current session and clears local state.
-- @return boolean True if logout was successful.
function Authon:logout()
if not self.sessionToken then return false end
local result = self:_request({type = "logout", sessionToken = self.sessionToken})
if result.success then
self.sessionToken = nil
self.username = nil
self.level = 0
self.subscription = nil
self.expiresAt = nil
end
return result.success == true
end
-- ═══════════════════════════════════════════════════════════════════════════════
-- VARIABLES
-- ═══════════════════════════════════════════════════════════════════════════════
--- Gets an application-level variable (shared across all users).
-- @param key string Variable name.
-- @return string|nil Variable value.
function Authon:getVar(key)
local result = self:_request({type = "var", key = key, sessionToken = self.sessionToken})
if result.success and result.data then
return result.data.value
end
return nil
end
--- Sets a user-level variable.
-- @param key string Variable name.
-- @param value string Variable value.
-- @return boolean True if saved.
function Authon:setVar(key, value)
local result = self:_request({type = "setvar", key = key, value = tostring(value), sessionToken = self.sessionToken})
return result.success == true
end
--- Gets a user-level variable.
-- @param key string Variable name.
-- @return string|nil Variable value.
function Authon:getUserVar(key)
local result = self:_request({type = "getvar", key = key, sessionToken = self.sessionToken})
if result.success and result.data then
return result.data.value
end
return nil
end
-- ═══════════════════════════════════════════════════════════════════════════════
-- FILES
-- ═══════════════════════════════════════════════════════════════════════════════
--- Lists all files available to the authenticated user.
-- @return table Array of file objects {id, name, size, minLevel}.
function Authon:listFiles()
local result = self:_request({type = "list_files", sessionToken = self.sessionToken})
if result.success then
return result.data or {}
end
return {}
end
--- Downloads a file by its ID.
-- @param fileId string File ID from listFiles().
-- @return string|nil Raw file content.
function Authon:downloadFile(fileId)
if not self.sessionToken or not fileId or fileId == "" then return nil end
local result = self:_request({
type = "file",
fileId = fileId,
sessionToken = self.sessionToken,
})
-- In some environments, binary is returned as the response body
if type(result) == "string" then
return result
end
return nil
end
-- ═══════════════════════════════════════════════════════════════════════════════
-- LOGGING & ANALYTICS
-- ═══════════════════════════════════════════════════════════════════════════════
--- Sends an activity log message to the dashboard.
-- @param message string Log message (max 500 chars).
-- @return boolean True if logged.
function Authon:log(message)
if message and #message > 500 then
message = message:sub(1, 500)
end
local result = self:_request({type = "log", message = message, sessionToken = self.sessionToken})
return result.success == true
end
--- Gets the list of currently online users.
-- @return table {count, users}
function Authon:fetchOnline()
local result = self:_request({type = "fetch_online", sessionToken = self.sessionToken})
if result.success then
return result.data or {count = 0, users = {}}
end
return {count = 0, users = {}}
end
--- Gets application statistics.
-- @return table {totalUsers, onlineUsers, totalKeys, appVersion}
function Authon:fetchStats()
local result = self:_request({type = "fetch_stats", sessionToken = self.sessionToken})
if result.success then
return result.data or {}
end
return {}
end
-- ═══════════════════════════════════════════════════════════════════════════════
-- SECURITY
-- ═══════════════════════════════════════════════════════════════════════════════
--- Checks if an IP or HWID is blacklisted.
-- @param ip string|nil IP address to check.
-- @param hwid string|nil HWID to check.
-- @return table {blacklisted, reason}
function Authon:checkBlacklist(ip, hwid)
local payload = {type = "check_blacklist"}
if ip and ip ~= "" then payload.ip = ip end
if hwid and hwid ~= "" then payload.hwid = hwid end
local result = self:_request(payload)
if result.success then
return result.data or {blacklisted = false, reason = nil}
end
return {blacklisted = false, reason = nil}
end
--- Redeems a referral code for bonus subscription days.
-- @param code string Referral code.
-- @return table {success, message, data}
function Authon:redeemReferral(code)
return self:_request({
type = "redeem_referral",
code = code,
sessionToken = self.sessionToken,
})
end
return Authon