-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.lua
More file actions
521 lines (433 loc) · 14.5 KB
/
server.lua
File metadata and controls
521 lines (433 loc) · 14.5 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
local ESX = exports['es_extended']:getSharedObject()
-- Anti-spam / sessions
local cooldown = {} -- src -> last timer
local sessions = {} -- src -> { token, issuedAt }
local nonceSeen = {} -- src -> map nonce -> time
local failCount = {} -- src -> { n, lastReset }
-- ========== CONFIG SECURITE ==========
local SESSION_TTL_SECONDS = 600 -- 10 min
local FAIL_RESET_SECONDS = 30
local FAIL_MAX_IN_WINDOW = 8 -- si trop d'échecs -> flag/log
local MAX_CART_ITEMS = 20
-- ========== DB HELPERS (oxmysql) ==========
local function dbScalar(query, params)
local p = promise.new()
exports.oxmysql:scalar(query, params, function(result) p:resolve(result) end)
return Citizen.Await(p)
end
local function dbUpdate(query, params)
local p = promise.new()
exports.oxmysql:update(query, params, function(affected) p:resolve(affected) end)
return Citizen.Await(p)
end
-- ========== IDENTIFIER ==========
local function getIdentifier(src)
local xPlayer = ESX.GetPlayerFromId(src)
return xPlayer and xPlayer.identifier or nil
end
-- ========== COINS DB ==========
local function ensureCoinsRow(identifier)
dbUpdate(
"INSERT IGNORE INTO growthcodedev_webstore_coins (identifier, coins) VALUES (?, 0)",
{ identifier }
)
end
local function getCoins(identifier)
ensureCoinsRow(identifier)
local c = dbScalar(
"SELECT coins FROM growthcodedev_webstore_coins WHERE identifier = ?",
{ identifier }
)
return tonumber(c) or 0
end
local function addCoins(identifier, amount)
ensureCoinsRow(identifier)
amount = math.floor(tonumber(amount) or 0)
if amount <= 0 then return end
dbUpdate(
"UPDATE growthcodedev_webstore_coins SET coins = coins + ? WHERE identifier = ?",
{ amount, identifier }
)
end
local function removeCoins(identifier, amount)
ensureCoinsRow(identifier)
amount = math.floor(tonumber(amount) or 0)
if amount <= 0 then return end
dbUpdate(
"UPDATE growthcodedev_webstore_coins SET coins = GREATEST(coins - ?, 0) WHERE identifier = ?",
{ amount, identifier }
)
end
local function insertTx(tx)
dbUpdate([[
INSERT INTO growthcodedev_webstore_transactions
(identifier, src, cart, promoCode, subtotal, discount, total, payMethod, balance_after)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
]], {
tx.identifier,
tx.src,
json.encode(tx.cart),
(tx.promoCode ~= "" and tx.promoCode or nil),
tx.subtotal,
tx.discount,
tx.total,
tx.payMethod,
tx.newBalance
})
end
-- ========== SESSIONS / TOKEN / NONCE ==========
local function newToken()
return ("%d:%d:%d"):format(GetGameTimer(), math.random(100000, 999999), math.random(100000, 999999))
end
local function startSession(src)
sessions[src] = { token = newToken(), issuedAt = os.time() }
nonceSeen[src] = {}
return sessions[src].token
end
local function endSession(src)
sessions[src] = nil
nonceSeen[src] = nil
end
local function isValidSession(src, token)
local s = sessions[src]
if not s or not token or token ~= s.token then return false end
if (os.time() - (s.issuedAt or 0)) > SESSION_TTL_SECONDS then
endSession(src)
return false
end
return true
end
local function nonceOk(src, nonce)
if type(nonce) ~= "string" then return false end
local n = nonce
if #n < 6 or #n > 64 then return false end
local map = nonceSeen[src]
if not map then return false end
if map[n] then return false end
map[n] = os.time()
return true
end
-- ========== FAIL TRACKER ==========
local function registerFail(src, reason)
local now = os.time()
failCount[src] = failCount[src] or { n = 0, lastReset = now }
if (now - failCount[src].lastReset) > FAIL_RESET_SECONDS then
failCount[src].n = 0
failCount[src].lastReset = now
end
failCount[src].n = failCount[src].n + 1
if failCount[src].n >= FAIL_MAX_IN_WINDOW then
TriggerEvent('growthcodedev:webstore:suspicious', src, reason or "too_many_fails")
print(("[growthcodedev_webstore] Suspicious src=%d reason=%s"):format(src, reason or "too_many_fails"))
end
end
-- ========== PRICING / PROMOS (SERVER TRUTH) ==========
local function calcSubtotal(cart)
local subtotal = 0
for _, it in ipairs(cart) do
local id = tostring(it.id or "")
local qty = tonumber(it.qty) or 0
if qty < 1 or qty > Config.MaxQtyPerPack then
return nil, "Quantité invalide."
end
local pack = Config.Packs[id]
if not pack then
return nil, ("Pack invalide: %s"):format(id)
end
subtotal = subtotal + (pack.price * qty)
end
return subtotal, nil
end
local function calcDiscount(subtotal, promoCode)
if not promoCode or promoCode == "" then return 0 end
local promo = Config.Promos[string.upper(promoCode)]
if not promo then return 0 end
if promo.type == "percent" then
return math.floor(subtotal * (promo.value / 100))
elseif promo.type == "flat" then
return math.min(subtotal, promo.value)
end
return 0
end
-- ========== APPLY PACK ACTIONS (ESX) ==========
local function notify(src, msg)
TriggerClientEvent('growthcodedev:webstore:notify', src, msg)
end
local function giveItemESX(src, name, count)
local xPlayer = ESX.GetPlayerFromId(src)
if not xPlayer then return end
count = math.floor(tonumber(count) or 1)
if count <= 0 then return end
xPlayer.addInventoryItem(name, count)
end
local function giveMoneyESX(src, account, amount)
local xPlayer = ESX.GetPlayerFromId(src)
if not xPlayer then return end
amount = math.floor(tonumber(amount) or 0)
if amount <= 0 then return end
if account == "bank" then
xPlayer.addAccountMoney('bank', amount)
else
xPlayer.addMoney(amount)
end
end
-- ESX Vehicle insert
local function randomPlate()
local chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
local nums = "0123456789"
local function pick(str) return str:sub(math.random(#str), math.random(#str)) end
return (pick(chars)..pick(chars)..pick(chars).." "..pick(nums)..pick(nums)..pick(nums))
end
local function plateExists(plate)
local q = ("SELECT %s FROM %s WHERE %s = ? LIMIT 1"):format(
Config.Vehicle.PlateColumn,
Config.Vehicle.OwnedVehiclesTable,
Config.Vehicle.PlateColumn
)
local r = dbScalar(q, { plate })
return r ~= nil
end
local function generateUniquePlate()
for _ = 1, 30 do
local plate = randomPlate()
if not plateExists(plate) then return plate end
end
return ("GC%05d"):format(math.random(0, 99999))
end
local function insertOwnedVehicle(identifier, model)
local plate = generateUniquePlate()
local vehProps = {
model = joaat(model),
plate = plate
}
local tableName = Config.Vehicle.OwnedVehiclesTable
local ownerCol = Config.Vehicle.OwnerColumn
local plateCol = Config.Vehicle.PlateColumn
local vehCol = Config.Vehicle.VehicleColumn
local typeCol = Config.Vehicle.TypeColumn
local storedCol = Config.Vehicle.StoredColumn
local cols = { ownerCol, plateCol, vehCol }
local vals = { identifier, plate, json.encode(vehProps) }
local qs = { "?", "?", "?" }
if typeCol and typeCol ~= "" then
cols[#cols+1] = typeCol
vals[#vals+1] = Config.Vehicle.DefaultType
qs[#qs+1] = "?"
end
if storedCol and storedCol ~= "" then
cols[#cols+1] = storedCol
vals[#vals+1] = Config.Vehicle.DefaultStoredValue
qs[#qs+1] = "?"
end
local query = ("INSERT INTO %s (%s) VALUES (%s)"):format(
tableName,
table.concat(cols, ", "),
table.concat(qs, ", ")
)
dbUpdate(query, vals)
return plate
end
local function applyAction(src, action, qty)
local t = action.type
if t == "item" then
giveItemESX(src, action.name, (action.count or 1) * qty)
return
end
if t == "money" then
giveMoneyESX(src, action.account or "cash", (action.amount or 0) * qty)
return
end
if t == "vehicle" then
local identifier = getIdentifier(src)
if not identifier then return end
for _ = 1, qty do
local plate = insertOwnedVehicle(identifier, action.model)
TriggerEvent('growthcodedev:webstore:grantVehicle', src, action.model, plate)
notify(src, ("Véhicule ajouté: ~b~%s~s~ (~y~%s~s~)"):format(action.model, plate))
end
return
end
if t == "vip" then
TriggerEvent('growthcodedev:webstore:grantVip', src, action.level)
notify(src, ("VIP activé: ~b~%s~s~"):format(action.level))
return
end
if t == "event" then
for _ = 1, qty do
TriggerEvent(action.name, src, action.data or {})
end
return
end
end
local function applyPack(src, packId, qty)
local pack = Config.Packs[packId]
if not pack then return end
-- Hook externe principal
TriggerEvent('growthcodedev:webstore:applyPack', src, packId, qty, pack)
if pack.actions then
for _, action in ipairs(pack.actions) do
applyAction(src, action, qty)
end
end
end
-- ========== EVENTS ==========
AddEventHandler('playerDropped', function()
local src = source
endSession(src)
cooldown[src] = nil
failCount[src] = nil
end)
RegisterNetEvent('growthcodedev:webstore:close', function()
local src = source
endSession(src)
end)
RegisterNetEvent('growthcodedev:webstore:requestCatalog', function()
local src = source
local packsArr = {}
for id, p in pairs(Config.Packs) do
packsArr[#packsArr+1] = {
id = id,
label = p.label,
description = p.description,
category = p.category,
tags = p.tags or {},
price = p.price
}
end
local token = startSession(src)
-- IMPORTANT: on n’envoie PAS les promos (moins d’infos à scrap)
TriggerClientEvent('growthcodedev:webstore:catalog', src, {
packs = packsArr,
currency = Config.CurrencyName,
serverName = Config.ServerName,
token = token
})
end)
RegisterNetEvent('growthcodedev:webstore:requestBalance', function()
local src = source
local identifier = getIdentifier(src)
if not identifier then return end
TriggerClientEvent('growthcodedev:webstore:balance', src, getCoins(identifier))
end)
-- ✅ addCoins sécurisé par ACE
local function canAddCoins(src)
return IsPlayerAceAllowed(src, "growthcodedev.webstore.addcoins")
end
RegisterNetEvent('growthcodedev:webstore:addCoins', function(targetSrc, amount)
local src = source
if not canAddCoins(src) then
print(("[growthcodedev_webstore] addCoins denied src=%d"):format(src))
return
end
local t = tonumber(targetSrc)
local a = tonumber(amount) or 0
if not t or a <= 0 then return end
local identifier = getIdentifier(t)
if not identifier then return end
addCoins(identifier, a)
TriggerClientEvent('growthcodedev:webstore:balance', t, getCoins(identifier))
TriggerClientEvent('growthcodedev:webstore:notify', t, ("+%d %s"):format(a, Config.CurrencyName))
end)
RegisterNetEvent('growthcodedev:webstore:checkout', function(data)
local src = source
-- Rate limit
if cooldown[src] and (GetGameTimer() - cooldown[src] < Config.CheckoutCooldownMs) then
TriggerClientEvent('growthcodedev:webstore:checkoutResult', src, { ok=false, message="Trop rapide." })
registerFail(src, "rate_limit")
return
end
cooldown[src] = GetGameTimer()
if type(data) ~= "table" then
TriggerClientEvent('growthcodedev:webstore:checkoutResult', src, { ok=false, message="Données invalides." })
registerFail(src, "invalid_payload")
return
end
-- Session token + nonce anti-replay
local token = tostring(data.token or "")
local nonce = tostring(data.nonce or "")
if not isValidSession(src, token) then
TriggerClientEvent('growthcodedev:webstore:checkoutResult', src, { ok=false, message="Session invalide." })
registerFail(src, "bad_session")
return
end
if not nonceOk(src, nonce) then
TriggerClientEvent('growthcodedev:webstore:checkoutResult', src, { ok=false, message="Requête refusée (replay)." })
registerFail(src, "replay_nonce")
return
end
if type(data.cart) ~= "table" then
TriggerClientEvent('growthcodedev:webstore:checkoutResult', src, { ok=false, message="Panier invalide." })
registerFail(src, "invalid_cart")
return
end
if #data.cart > MAX_CART_ITEMS then
TriggerClientEvent('growthcodedev:webstore:checkoutResult', src, { ok=false, message="Panier trop grand." })
registerFail(src, "cart_too_big")
return
end
local payMethod = tostring(data.payMethod or "coins")
if not Config.AllowedPayMethods[payMethod] then
TriggerClientEvent('growthcodedev:webstore:checkoutResult', src, { ok=false, message="Paiement non autorisé." })
registerFail(src, "bad_paymethod")
return
end
-- SERVER ONLY pricing (ignore tout ce que le client pourrait envoyer)
local subtotal, err = calcSubtotal(data.cart)
if not subtotal then
TriggerClientEvent('growthcodedev:webstore:checkoutResult', src, { ok=false, message=err or "Panier invalide." })
registerFail(src, "calc_subtotal_fail")
return
end
local promoCode = tostring(data.promoCode or "")
local discount = calcDiscount(subtotal, promoCode)
local total = math.max(0, subtotal - discount)
local identifier = getIdentifier(src)
if not identifier then
TriggerClientEvent('growthcodedev:webstore:checkoutResult', src, { ok=false, message="Joueur introuvable." })
registerFail(src, "no_identifier")
return
end
local coins = getCoins(identifier)
if coins < total then
TriggerClientEvent('growthcodedev:webstore:checkoutResult', src, { ok=false, message="Solde coins insuffisant." })
registerFail(src, "insufficient_coins")
return
end
-- Deduct coins
removeCoins(identifier, total)
local newBalance = getCoins(identifier)
-- Log tx DB + hook externe
local tx = {
src = src,
identifier = identifier,
cart = data.cart,
promoCode = promoCode,
subtotal = subtotal,
discount = discount,
total = total,
payMethod = payMethod,
newBalance = newBalance
}
insertTx(tx)
TriggerEvent('growthcodedev:webstore:transaction', tx)
-- Apply packs
for _, it in ipairs(data.cart) do
applyPack(src, tostring(it.id or ""), tonumber(it.qty) or 1)
end
-- Rotate token (anti replay même si quelqu’un “voit” le token)
startSession(src)
TriggerClientEvent('growthcodedev:webstore:checkoutResult', src, {
ok = true,
message = "Achat validé ✅",
balance = newBalance
})
end)
-- Exemple notif ESX côté client
RegisterNetEvent('growthcodedev:webstore:notify', function(msg) end)
-- Hooks externes (tu peux les mettre ailleurs)
AddEventHandler('growthcodedev:webstore:grantVip', function(src, level)
print(("[growthcodedev_webstore] VIP grant src=%d level=%s"):format(src, level))
end)
AddEventHandler('growthcodedev:webstore:grantVehicle', function(src, model, plate)
print(("[growthcodedev_webstore] Vehicle grant src=%d model=%s plate=%s"):format(src, model, plate))
end)