-
Notifications
You must be signed in to change notification settings - Fork 2
/
runtime_lua_nakama.go
5262 lines (4692 loc) · 139 KB
/
runtime_lua_nakama.go
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 The Nakama Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"bytes"
"crypto"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/md5"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"database/sql"
"encoding/base64"
"encoding/gob"
"encoding/hex"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"sync"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/golang/protobuf/jsonpb"
"github.com/gofrs/uuid"
"github.com/golang/protobuf/ptypes/timestamp"
"github.com/golang/protobuf/ptypes/wrappers"
"github.com/heroiclabs/nakama/api"
"github.com/heroiclabs/nakama/cronexpr"
"github.com/heroiclabs/nakama/rtapi"
"github.com/heroiclabs/nakama/social"
"github.com/yuin/gopher-lua"
"go.uber.org/zap"
"golang.org/x/crypto/bcrypt"
)
type RuntimeLuaNakamaModule struct {
logger *zap.Logger
db *sql.DB
jsonpbUnmarshaler *jsonpb.Unmarshaler
config Config
socialClient *social.Client
leaderboardCache LeaderboardCache
rankCache LeaderboardRankCache
leaderboardScheduler LeaderboardScheduler
sessionRegistry SessionRegistry
matchRegistry MatchRegistry
tracker Tracker
streamManager StreamManager
router MessageRouter
once *sync.Once
localCache *RuntimeLuaLocalCache
registerCallbackFn func(RuntimeExecutionMode, string, *lua.LFunction)
announceCallbackFn func(RuntimeExecutionMode, string)
client *http.Client
node string
matchCreateFn RuntimeMatchCreateFunction
}
func NewRuntimeLuaNakamaModule(logger *zap.Logger, db *sql.DB, jsonpbUnmarshaler *jsonpb.Unmarshaler, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, rankCache LeaderboardRankCache, leaderboardScheduler LeaderboardScheduler, sessionRegistry SessionRegistry, matchRegistry MatchRegistry, tracker Tracker, streamManager StreamManager, router MessageRouter, once *sync.Once, localCache *RuntimeLuaLocalCache, matchCreateFn RuntimeMatchCreateFunction, registerCallbackFn func(RuntimeExecutionMode, string, *lua.LFunction), announceCallbackFn func(RuntimeExecutionMode, string)) *RuntimeLuaNakamaModule {
return &RuntimeLuaNakamaModule{
logger: logger,
db: db,
jsonpbUnmarshaler: jsonpbUnmarshaler,
config: config,
socialClient: socialClient,
leaderboardCache: leaderboardCache,
rankCache: rankCache,
leaderboardScheduler: leaderboardScheduler,
sessionRegistry: sessionRegistry,
matchRegistry: matchRegistry,
tracker: tracker,
streamManager: streamManager,
router: router,
once: once,
localCache: localCache,
registerCallbackFn: registerCallbackFn,
announceCallbackFn: announceCallbackFn,
client: &http.Client{
Timeout: 5 * time.Second,
},
node: config.GetName(),
matchCreateFn: matchCreateFn,
}
}
func (n *RuntimeLuaNakamaModule) Loader(l *lua.LState) int {
functions := map[string]lua.LGFunction{
"register_rpc": n.registerRPC,
"register_req_before": n.registerReqBefore,
"register_req_after": n.registerReqAfter,
"register_rt_before": n.registerRTBefore,
"register_rt_after": n.registerRTAfter,
"register_matchmaker_matched": n.registerMatchmakerMatched,
"register_tournament_end": n.registerTournamentEnd,
"register_tournament_reset": n.registerTournamentReset,
"register_leaderboard_reset": n.registerLeaderboardReset,
"run_once": n.runOnce,
"get_context": n.getContext,
"localcache_get": n.localcacheGet,
"localcache_put": n.localcachePut,
"localcache_delete": n.localcacheDelete,
"time": n.time,
"cron_next": n.cronNext,
"sql_exec": n.sqlExec,
"sql_query": n.sqlQuery,
"uuid_v4": n.uuidV4,
"uuid_bytes_to_string": n.uuidBytesToString,
"uuid_string_to_bytes": n.uuidStringToBytes,
"http_request": n.httpRequest,
"jwt_generate": n.jwtGenerate,
"json_encode": n.jsonEncode,
"json_decode": n.jsonDecode,
"base64_encode": n.base64Encode,
"base64_decode": n.base64Decode,
"base64url_encode": n.base64URLEncode,
"base64url_decode": n.base64URLDecode,
"base16_encode": n.base16Encode,
"base16_decode": n.base16Decode,
"aes128_encrypt": n.aes128Encrypt,
"aes128_decrypt": n.aes128Decrypt,
"aes256_encrypt": n.aes256Encrypt,
"aes256_decrypt": n.aes256Decrypt,
"md5_hash": n.md5Hash,
"sha256_hash": n.sha256Hash,
"hmac_sha256_hash": n.hmacSHA256Hash,
"rsa_sha256_hash": n.rsaSHA256Hash,
"bcrypt_hash": n.bcryptHash,
"bcrypt_compare": n.bcryptCompare,
"authenticate_custom": n.authenticateCustom,
"authenticate_device": n.authenticateDevice,
"authenticate_email": n.authenticateEmail,
"authenticate_facebook": n.authenticateFacebook,
"authenticate_gamecenter": n.authenticateGameCenter,
"authenticate_google": n.authenticateGoogle,
"authenticate_steam": n.authenticateSteam,
"authenticate_token_generate": n.authenticateTokenGenerate,
"logger_info": n.loggerInfo,
"logger_warn": n.loggerWarn,
"logger_error": n.loggerError,
"account_get_id": n.accountGetId,
"accounts_get_id": n.accountsGetId,
"account_update_id": n.accountUpdateId,
"account_delete_id": n.accountDeleteId,
"users_get_id": n.usersGetId,
"users_get_username": n.usersGetUsername,
"users_ban_id": n.usersBanId,
"users_unban_id": n.usersUnbanId,
"stream_user_list": n.streamUserList,
"stream_user_get": n.streamUserGet,
"stream_user_join": n.streamUserJoin,
"stream_user_update": n.streamUserUpdate,
"stream_user_leave": n.streamUserLeave,
"stream_user_kick": n.streamUserKick,
"stream_count": n.streamCount,
"stream_close": n.streamClose,
"stream_send": n.streamSend,
"stream_send_raw": n.streamSendRaw,
"session_disconnect": n.sessionDisconnect,
"match_create": n.matchCreate,
"match_list": n.matchList,
"notification_send": n.notificationSend,
"notifications_send": n.notificationsSend,
"wallet_update": n.walletUpdate,
"wallets_update": n.walletsUpdate,
"wallet_ledger_update": n.walletLedgerUpdate,
"wallet_ledger_list": n.walletLedgerList,
"storage_list": n.storageList,
"storage_read": n.storageRead,
"storage_write": n.storageWrite,
"storage_delete": n.storageDelete,
"leaderboard_create": n.leaderboardCreate,
"leaderboard_delete": n.leaderboardDelete,
"leaderboard_records_list": n.leaderboardRecordsList,
"leaderboard_record_write": n.leaderboardRecordWrite,
"leaderboard_record_delete": n.leaderboardRecordDelete,
"tournament_create": n.tournamentCreate,
"tournament_delete": n.tournamentDelete,
"tournament_add_attempt": n.tournamentAddAttempt,
"tournament_join": n.tournamentJoin,
"tournament_list": n.tournamentList,
"tournament_record_write": n.tournamentRecordWrite,
"tournament_records_haystack": n.tournamentRecordsHaystack,
"groups_get_id": n.groupsGetId,
"group_create": n.groupCreate,
"group_update": n.groupUpdate,
"group_delete": n.groupDelete,
"group_users_list": n.groupUsersList,
"user_groups_list": n.userGroupsList,
}
mod := l.SetFuncs(l.CreateTable(0, len(functions)), functions)
l.Push(mod)
return 1
}
func (n *RuntimeLuaNakamaModule) registerRPC(l *lua.LState) int {
fn := l.CheckFunction(1)
id := l.CheckString(2)
if id == "" {
l.ArgError(2, "expects rpc id")
return 0
}
id = strings.ToLower(id)
if n.registerCallbackFn != nil {
n.registerCallbackFn(RuntimeExecutionModeRPC, id, fn)
}
if n.announceCallbackFn != nil {
n.announceCallbackFn(RuntimeExecutionModeRPC, id)
}
return 0
}
func (n *RuntimeLuaNakamaModule) registerReqBefore(l *lua.LState) int {
fn := l.CheckFunction(1)
id := l.CheckString(2)
if id == "" {
l.ArgError(2, "expects method name")
return 0
}
id = strings.ToLower(API_PREFIX + id)
if n.registerCallbackFn != nil {
n.registerCallbackFn(RuntimeExecutionModeBefore, id, fn)
}
if n.announceCallbackFn != nil {
n.announceCallbackFn(RuntimeExecutionModeBefore, id)
}
return 0
}
func (n *RuntimeLuaNakamaModule) registerReqAfter(l *lua.LState) int {
fn := l.CheckFunction(1)
id := l.CheckString(2)
if id == "" {
l.ArgError(2, "expects method name")
return 0
}
id = strings.ToLower(API_PREFIX + id)
if n.registerCallbackFn != nil {
n.registerCallbackFn(RuntimeExecutionModeAfter, id, fn)
}
if n.announceCallbackFn != nil {
n.announceCallbackFn(RuntimeExecutionModeAfter, id)
}
return 0
}
func (n *RuntimeLuaNakamaModule) registerRTBefore(l *lua.LState) int {
fn := l.CheckFunction(1)
id := l.CheckString(2)
if id == "" {
l.ArgError(2, "expects message name")
return 0
}
id = strings.ToLower(RTAPI_PREFIX + id)
if n.registerCallbackFn != nil {
n.registerCallbackFn(RuntimeExecutionModeBefore, id, fn)
}
if n.announceCallbackFn != nil {
n.announceCallbackFn(RuntimeExecutionModeBefore, id)
}
return 0
}
func (n *RuntimeLuaNakamaModule) registerRTAfter(l *lua.LState) int {
fn := l.CheckFunction(1)
id := l.CheckString(2)
if id == "" {
l.ArgError(2, "expects message name")
return 0
}
id = strings.ToLower(RTAPI_PREFIX + id)
if n.registerCallbackFn != nil {
n.registerCallbackFn(RuntimeExecutionModeAfter, id, fn)
}
if n.announceCallbackFn != nil {
n.announceCallbackFn(RuntimeExecutionModeAfter, id)
}
return 0
}
func (n *RuntimeLuaNakamaModule) registerMatchmakerMatched(l *lua.LState) int {
fn := l.CheckFunction(1)
if n.registerCallbackFn != nil {
n.registerCallbackFn(RuntimeExecutionModeMatchmaker, "", fn)
}
if n.announceCallbackFn != nil {
n.announceCallbackFn(RuntimeExecutionModeMatchmaker, "")
}
return 0
}
func (n *RuntimeLuaNakamaModule) registerTournamentEnd(l *lua.LState) int {
fn := l.CheckFunction(1)
if n.registerCallbackFn != nil {
n.registerCallbackFn(RuntimeExecutionModeTournamentEnd, "", fn)
}
if n.announceCallbackFn != nil {
n.announceCallbackFn(RuntimeExecutionModeTournamentEnd, "")
}
return 0
}
func (n *RuntimeLuaNakamaModule) registerTournamentReset(l *lua.LState) int {
fn := l.CheckFunction(1)
if n.registerCallbackFn != nil {
n.registerCallbackFn(RuntimeExecutionModeTournamentReset, "", fn)
}
if n.announceCallbackFn != nil {
n.announceCallbackFn(RuntimeExecutionModeTournamentReset, "")
}
return 0
}
func (n *RuntimeLuaNakamaModule) registerLeaderboardReset(l *lua.LState) int {
fn := l.CheckFunction(1)
if n.registerCallbackFn != nil {
n.registerCallbackFn(RuntimeExecutionModeLeaderboardReset, "", fn)
}
if n.announceCallbackFn != nil {
n.announceCallbackFn(RuntimeExecutionModeLeaderboardReset, "")
}
return 0
}
func (n *RuntimeLuaNakamaModule) runOnce(l *lua.LState) int {
n.once.Do(func() {
fn := l.CheckFunction(1)
if fn == nil {
l.ArgError(1, "expects a function")
return
}
ctx := NewRuntimeLuaContext(l, RuntimeLuaConvertMapString(l, n.config.GetRuntime().Environment), RuntimeExecutionModeRunOnce, nil, 0, "", "", "", "", "")
l.Push(LSentinel)
l.Push(fn)
l.Push(ctx)
if err := l.PCall(1, lua.MultRet, nil); err != nil {
l.RaiseError("error in run_once function: %v", err.Error())
return
}
// Unwind the stack up to and including our sentinel value, effectively discarding any returned parameters.
for {
v := l.Get(-1)
l.Pop(1)
if v.Type() == LTSentinel {
break
}
}
})
return 0
}
func (n *RuntimeLuaNakamaModule) getContext(l *lua.LState) int {
ctx := NewRuntimeLuaContext(l, RuntimeLuaConvertMapString(l, n.config.GetRuntime().Environment), RuntimeExecutionModeRunOnce, nil, 0, "", "", "", "", "")
l.Push(ctx)
return 1
}
func (n *RuntimeLuaNakamaModule) localcacheGet(l *lua.LState) int {
key := l.CheckString(1)
if key == "" {
l.ArgError(1, "expects key string")
return 0
}
defaultValue := l.Get(2)
if t := defaultValue.Type(); t != lua.LTNil && t != lua.LTString {
l.ArgError(2, "expects default value string or nil")
return 0
}
value, found := n.localCache.Get(key)
if found {
l.Push(lua.LString(value))
} else {
l.Push(defaultValue)
}
return 1
}
func (n *RuntimeLuaNakamaModule) localcachePut(l *lua.LState) int {
key := l.CheckString(1)
if key == "" {
l.ArgError(1, "expects key string")
return 0
}
value := l.CheckString(2)
if value == "" {
l.ArgError(2, "expects value string")
return 0
}
n.localCache.Put(key, value)
return 0
}
func (n *RuntimeLuaNakamaModule) localcacheDelete(l *lua.LState) int {
key := l.CheckString(1)
if key == "" {
l.ArgError(1, "expects key string")
return 0
}
n.localCache.Delete(key)
return 0
}
func (n *RuntimeLuaNakamaModule) time(l *lua.LState) int {
if l.GetTop() == 0 {
l.Push(lua.LNumber(time.Now().UTC().UnixNano() / int64(time.Millisecond)))
} else {
tbl := l.CheckTable(1)
msec := getIntField(l, tbl, "msec", 0)
sec := getIntField(l, tbl, "sec", 0)
min := getIntField(l, tbl, "min", 0)
hour := getIntField(l, tbl, "hour", 12)
day := getIntField(l, tbl, "day", -1)
month := getIntField(l, tbl, "month", -1)
year := getIntField(l, tbl, "year", -1)
isdst := getBoolField(l, tbl, "isdst", false)
t := time.Date(year, time.Month(month), day, hour, min, sec, msec*int(time.Millisecond), time.UTC)
// TODO dst
if false {
print(isdst)
}
l.Push(lua.LNumber(t.UTC().UnixNano() / int64(time.Millisecond)))
}
return 1
}
func (n *RuntimeLuaNakamaModule) cronNext(l *lua.LState) int {
cron := l.CheckString(1)
if cron == "" {
l.ArgError(1, "expects cron string")
return 0
}
ts := l.CheckInt64(2)
if ts == 0 {
l.ArgError(1, "expects timestamp in seconds")
return 0
}
expr, err := cronexpr.Parse(cron)
if err != nil {
l.ArgError(1, "expects a valid cron string")
return 0
}
t := time.Unix(ts, 0).UTC()
next := expr.Next(t)
nextTs := next.UTC().Unix()
l.Push(lua.LNumber(nextTs))
return 1
}
func (n *RuntimeLuaNakamaModule) sqlExec(l *lua.LState) int {
query := l.CheckString(1)
if query == "" {
l.ArgError(1, "expects query string")
return 0
}
paramsTable := l.OptTable(2, nil)
var params []interface{}
if paramsTable != nil && paramsTable.Len() != 0 {
var ok bool
params, ok = RuntimeLuaConvertLuaValue(paramsTable).([]interface{})
if !ok {
l.ArgError(2, "expects a list of params as a table")
return 0
}
}
var result sql.Result
var err error
err = ExecuteRetryable(func() error {
result, err = n.db.ExecContext(l.Context(), query, params...)
return err
})
if err != nil {
l.RaiseError("sql exec error: %v", err.Error())
return 0
}
count, err := result.RowsAffected()
if err != nil {
l.RaiseError("sql exec rows affected error: %v", err.Error())
return 0
}
l.Push(lua.LNumber(count))
return 1
}
func (n *RuntimeLuaNakamaModule) sqlQuery(l *lua.LState) int {
query := l.CheckString(1)
if query == "" {
l.ArgError(1, "expects query string")
return 0
}
paramsTable := l.OptTable(2, nil)
var params []interface{}
if paramsTable != nil && paramsTable.Len() != 0 {
var ok bool
params, ok = RuntimeLuaConvertLuaValue(paramsTable).([]interface{})
if !ok {
l.ArgError(2, "expects a list of params as a table")
return 0
}
}
var rows *sql.Rows
var err error
err = ExecuteRetryable(func() error {
rows, err = n.db.QueryContext(l.Context(), query, params...)
return err
})
if err != nil {
l.RaiseError("sql query error: %v", err.Error())
return 0
}
defer rows.Close()
resultColumns, err := rows.Columns()
if err != nil {
l.RaiseError("sql query column lookup error: %v", err.Error())
return 0
}
resultColumnCount := len(resultColumns)
resultRows := make([][]interface{}, 0)
for rows.Next() {
resultRowValues := make([]interface{}, resultColumnCount)
resultRowPointers := make([]interface{}, resultColumnCount)
for i, _ := range resultRowValues {
resultRowPointers[i] = &resultRowValues[i]
}
if err = rows.Scan(resultRowPointers...); err != nil {
l.RaiseError("sql query scan error: %v", err.Error())
return 0
}
resultRows = append(resultRows, resultRowValues)
}
if err = rows.Err(); err != nil {
l.RaiseError("sql query row scan error: %v", err.Error())
return 0
}
rt := l.CreateTable(len(resultRows), 0)
for i, r := range resultRows {
rowTable := l.CreateTable(0, resultColumnCount)
for j, col := range resultColumns {
rowTable.RawSetString(col, RuntimeLuaConvertValue(l, r[j]))
}
rt.RawSetInt(i+1, rowTable)
}
l.Push(rt)
return 1
}
func (n *RuntimeLuaNakamaModule) uuidV4(l *lua.LState) int {
l.Push(lua.LString(uuid.Must(uuid.NewV4()).String()))
return 1
}
func (n *RuntimeLuaNakamaModule) uuidBytesToString(l *lua.LState) int {
uuidBytes := l.CheckString(1)
if uuidBytes == "" {
l.ArgError(1, "expects a UUID byte string")
return 0
}
u, err := uuid.FromBytes([]byte(uuidBytes))
if err != nil {
l.ArgError(1, "not a valid UUID byte string")
return 0
}
l.Push(lua.LString(u.String()))
return 1
}
func (n *RuntimeLuaNakamaModule) uuidStringToBytes(l *lua.LState) int {
uuidString := l.CheckString(1)
if uuidString == "" {
l.ArgError(1, "expects a UUID string")
return 0
}
u, err := uuid.FromString(uuidString)
if err != nil {
l.ArgError(1, "not a valid UUID string")
return 0
}
l.Push(lua.LString(u.Bytes()))
return 1
}
func (n *RuntimeLuaNakamaModule) httpRequest(l *lua.LState) int {
url := l.CheckString(1)
method := l.CheckString(2)
headers := l.CheckTable(3)
body := l.OptString(4, "")
if url == "" {
l.ArgError(1, "expects URL string")
return 0
}
if method == "" {
l.ArgError(2, "expects method string")
return 0
}
// Set a custom timeout if one is provided, or use the default.
timeoutMs := l.OptInt64(5, 5000)
n.client.Timeout = time.Duration(timeoutMs) * time.Millisecond
// Prepare request body, if any.
var requestBody io.Reader
if body != "" {
requestBody = strings.NewReader(body)
}
// Prepare the request.
req, err := http.NewRequest(method, url, requestBody)
if err != nil {
l.RaiseError("HTTP request error: %v", err.Error())
return 0
}
// Apply any request headers.
httpHeaders := RuntimeLuaConvertLuaTable(headers)
for k, v := range httpHeaders {
if vs, ok := v.(string); !ok {
l.RaiseError("HTTP header values must be strings")
return 0
} else {
req.Header.Add(k, vs)
}
}
// Execute the request.
resp, err := n.client.Do(req)
if err != nil {
l.RaiseError("HTTP request error: %v", err.Error())
return 0
}
// Read the response body.
responseBody, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
l.RaiseError("HTTP response body error: %v", err.Error())
return 0
}
// Read the response headers.
responseHeaders := make(map[string]interface{}, len(resp.Header))
for k, vs := range resp.Header {
// TODO accept multiple values per header
for _, v := range vs {
responseHeaders[k] = v
break
}
}
l.Push(lua.LNumber(resp.StatusCode))
l.Push(RuntimeLuaConvertMap(l, responseHeaders))
l.Push(lua.LString(string(responseBody)))
return 3
}
func (n *RuntimeLuaNakamaModule) jwtGenerate(l *lua.LState) int {
algoType := l.CheckString(1)
if algoType == "" {
l.ArgError(1, "expects string")
return 0
}
var signingMethod jwt.SigningMethod
switch algoType {
case "HS256":
signingMethod = jwt.SigningMethodHS256
case "RS256":
signingMethod = jwt.SigningMethodRS256
default:
l.ArgError(3, "unsupported algo type - only allowed 'HS256', 'RS256'.")
}
signingKey := l.CheckString(2)
if signingKey == "" {
l.ArgError(2, "expects string")
return 0
}
claimsetTable := l.CheckTable(3)
if claimsetTable == nil {
l.ArgError(3, "expects nil")
return 0
}
claimset := RuntimeLuaConvertLuaValue(claimsetTable).(map[string]interface{})
jwtClaims := jwt.MapClaims{}
for k, v := range claimset {
jwtClaims[k] = v
}
block, _ := pem.Decode([]byte(signingKey))
if block == nil {
l.RaiseError("could not parse private key: no valid blocks found")
return 0
}
pk, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
l.RaiseError("could not parse private key: %v", err.Error())
return 0
}
token := jwt.NewWithClaims(signingMethod, jwtClaims)
signedToken, err := token.SignedString(pk)
if err != nil {
l.RaiseError("failed to sign token: %v", err.Error())
return 0
}
l.Push(lua.LString(signedToken))
return 1
}
func (n *RuntimeLuaNakamaModule) jsonEncode(l *lua.LState) int {
value := l.Get(1)
if value == nil {
l.ArgError(1, "expects a non-nil value to encode")
return 0
}
jsonData := RuntimeLuaConvertLuaValue(value)
jsonBytes, err := json.Marshal(jsonData)
if err != nil {
l.RaiseError("error encoding to JSON: %v", err.Error())
return 0
}
l.Push(lua.LString(string(jsonBytes)))
return 1
}
func (n *RuntimeLuaNakamaModule) jsonDecode(l *lua.LState) int {
jsonString := l.CheckString(1)
if jsonString == "" {
l.ArgError(1, "expects JSON string")
return 0
}
var jsonData interface{}
if err := json.Unmarshal([]byte(jsonString), &jsonData); err != nil {
l.RaiseError("not a valid JSON string: %v", err.Error())
return 0
}
l.Push(RuntimeLuaConvertValue(l, jsonData))
return 1
}
func (n *RuntimeLuaNakamaModule) base64Encode(l *lua.LState) int {
input := l.CheckString(1)
if input == "" {
l.ArgError(1, "expects string")
return 0
}
padding := l.OptBool(2, true)
e := base64.StdEncoding
if !padding {
e = base64.RawStdEncoding
}
output := e.EncodeToString([]byte(input))
l.Push(lua.LString(output))
return 1
}
func (n *RuntimeLuaNakamaModule) base64Decode(l *lua.LState) int {
input := l.CheckString(1)
if input == "" {
l.ArgError(1, "expects string")
return 0
}
padding := l.OptBool(2, false)
if !padding {
// Pad string up to length multiple of 4 if needed to effectively make padding optional.
if maybePad := len(input) % 4; maybePad != 0 {
input += strings.Repeat("=", 4-maybePad)
}
}
output, err := base64.StdEncoding.DecodeString(input)
if err != nil {
l.RaiseError("not a valid base64 string: %v", err.Error())
return 0
}
l.Push(lua.LString(output))
return 1
}
func (n *RuntimeLuaNakamaModule) base64URLEncode(l *lua.LState) int {
input := l.CheckString(1)
if input == "" {
l.ArgError(1, "expects string")
return 0
}
padding := l.OptBool(2, true)
e := base64.URLEncoding
if !padding {
e = base64.RawURLEncoding
}
output := e.EncodeToString([]byte(input))
l.Push(lua.LString(output))
return 1
}
func (n *RuntimeLuaNakamaModule) base64URLDecode(l *lua.LState) int {
input := l.CheckString(1)
if input == "" {
l.ArgError(1, "expects string")
return 0
}
padding := l.OptBool(2, false)
if !padding {
// Pad string up to length multiple of 4 if needed to effectively make padding optional.
if maybePad := len(input) % 4; maybePad != 0 {
input += strings.Repeat("=", 4-maybePad)
}
}
output, err := base64.URLEncoding.DecodeString(input)
if err != nil {
l.RaiseError("not a valid base64 url string: %v", err.Error())
return 0
}
l.Push(lua.LString(output))
return 1
}
func (n *RuntimeLuaNakamaModule) base16Encode(l *lua.LState) int {
input := l.CheckString(1)
if input == "" {
l.ArgError(1, "expects string")
return 0
}
output := hex.EncodeToString([]byte(input))
l.Push(lua.LString(output))
return 1
}
func (n *RuntimeLuaNakamaModule) base16Decode(l *lua.LState) int {
input := l.CheckString(1)
if input == "" {
l.ArgError(1, "expects string")
return 0
}
output, err := hex.DecodeString(input)
if err != nil {
l.RaiseError("not a valid base16 string: %v", err.Error())
return 0
}
l.Push(lua.LString(output))
return 1
}
func aesEncrypt(l *lua.LState, keySize int) int {
input := l.CheckString(1)
if input == "" {
l.ArgError(1, "expects string")
return 0
}
key := l.CheckString(2)
if len(key) != keySize {
l.ArgError(2, fmt.Sprintf("expects key %v bytes long", keySize))
return 0
}
// Pad string up to length multiple of 4 if needed.
if maybePad := len(input) % 4; maybePad != 0 {
input += strings.Repeat(" ", 4-maybePad)
}
block, err := aes.NewCipher([]byte(key))
if err != nil {
l.RaiseError("error creating cipher block: %v", err.Error())
return 0
}
cipherText := make([]byte, aes.BlockSize+len(input))
iv := cipherText[:aes.BlockSize]
if _, err = io.ReadFull(rand.Reader, iv); err != nil {
l.RaiseError("error getting iv: %v", err.Error())
return 0
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(cipherText[aes.BlockSize:], []byte(input))
l.Push(lua.LString(cipherText))
return 1
}
func aesDecrypt(l *lua.LState, keySize int) int {
input := l.CheckString(1)
if input == "" {
l.ArgError(1, "expects string")
return 0
}
key := l.CheckString(2)
if len(key) != keySize {
l.ArgError(2, fmt.Sprintf("expects key %v bytes long", keySize))
return 0
}
if len(input) < aes.BlockSize {
l.RaiseError("input too short")
return 0
}
block, err := aes.NewCipher([]byte(key))
if err != nil {
l.RaiseError("error creating cipher block: %v", err.Error())
return 0
}
cipherText := []byte(input)
iv := cipherText[:aes.BlockSize]
cipherText = cipherText[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
stream.XORKeyStream(cipherText, cipherText)
l.Push(lua.LString(cipherText))
return 1
}
func (n *RuntimeLuaNakamaModule) aes128Encrypt(l *lua.LState) int {
return aesEncrypt(l, 16)
}
func (n *RuntimeLuaNakamaModule) aes128Decrypt(l *lua.LState) int {
return aesDecrypt(l, 16)
}
func (n *RuntimeLuaNakamaModule) aes256Encrypt(l *lua.LState) int {
return aesEncrypt(l, 32)
}