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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
local ALLOW_EXEC = false
local ALLOW_FILE = false
local ALLOW_REGISTRY = false
local ALLOW_LUA_EXEC = false
local PROTOCOL_VERSION = "1.2.0"
local cfg = UI.Schema({
port = UI.Slider(19561, { min = 1024, max = 65535, label = "WS port" }),
auth_token = UI.Text("", {
label = "Auth token",
placeholder = "blank = open (lan-exposed!)",
tooltip = 'when set, clients must send { t="auth", token="..." } first. redacted from ui.get.',
}),
})
local GATES = {
exec = ALLOW_EXEC,
file = ALLOW_FILE,
registry = ALLOW_REGISTRY,
lua = ALLOW_LUA_EXEC,
}
local REDACTED = { auth_token = true }
local function auth_token()
return cfg.auth_token or ""
end
local function token_ok(given)
local expected = auth_token()
if expected == "" then
return true
end
return Hash.SHA256(given or "") == Hash.SHA256(expected)
end
local function server_banner()
return {
protocol = PROTOCOL_VERSION,
auth_required = auth_token() ~= "",
gates = {
exec = ALLOW_EXEC,
file = ALLOW_FILE,
registry = ALLOW_REGISTRY,
lua = ALLOW_LUA_EXEC,
},
}
end
local server = nil
local clients = {}
local authed = {}
local subscribers = {}
local timers = {}
local sounds = {}
local next_id = 0
local last_mouse_x, last_mouse_y, last_window_title = nil, nil, nil
local ESCAPES = {
['"'] = '\\"',
["\\"] = "\\\\",
["\n"] = "\\n",
["\r"] = "\\r",
["\t"] = "\\t",
["\b"] = "\\b",
["\f"] = "\\f",
}
local function encode_str(s)
return '"'
.. s:gsub('[%z\1-\31\\"]', function(c)
return ESCAPES[c] or string.format("\\u%04x", c:byte())
end)
.. '"'
end
local function encode(v)
local t = type(v)
if v == nil then
return "null"
elseif t == "boolean" then
return v and "true" or "false"
elseif t == "number" then
if v ~= v or v == math.huge or v == -math.huge then
return "null"
end
if v == math.floor(v) and math.abs(v) < 1e15 then
return string.format("%.0f", v)
end
return string.format("%.14g", v)
elseif t == "string" then
return encode_str(v)
elseif t == "table" then
local n = #v
local count = 0
for _ in pairs(v) do
count += 1
end
if count == n then
local parts = {}
for i = 1, n do
parts[i] = encode(v[i])
end
return "[" .. table.concat(parts, ",") .. "]"
end
local parts = {}
for k, val in pairs(v) do
parts[#parts + 1] = encode_str(tostring(k)) .. ":" .. encode(val)
end
return "{" .. table.concat(parts, ",") .. "}"
end
return "null"
end
local function send(client, obj)
client:Send(encode(obj))
end
local function reply(client, req, payload)
if req.id == nil then
return
end
payload.id = req.id
send(client, payload)
end
local function err(client, req, code, message)
if req.id == nil then
Log.Warn(`remote: client {client.id} error ({code}): {message}`)
return
end
send(client, { id = req.id, error = { code = code, message = message } })
end
local function hex_rgb(hex)
return tonumber(hex:sub(1, 2), 16) or 0,
tonumber(hex:sub(3, 4), 16) or 0,
tonumber(hex:sub(5, 6), 16) or 0
end
local function alloc_id()
next_id += 1
return next_id
end
local api = {}
local function def(name, fn, opts)
opts = opts or {}
opts.fn = fn
api[name] = opts
end
def("hello", function()
return server_banner()
end, { open = true })
def("ping", function()
return { pong = true, time_ms = System.Time() }
end, { open = true })
def("auth", function(client, req)
if auth_token() == "" then
authed[client.id] = true
return { ok = true, note = "no token required" }
end
if token_ok(req.token) then
authed[client.id] = true
return { ok = true }
end
return nil, "bad_token", "token does not match"
end, { open = true })
def("commands", function()
local names = {}
for name in pairs(api) do
names[#names + 1] = name
end
table.sort(names)
return { commands = names, protocol = PROTOCOL_VERSION }
end)
def("hid.down", function(_, req)
HID.Down(req.code)
end)
def("hid.up", function(_, req)
HID.Up(req.code)
end)
def("hid.combo", function(_, req)
HID.Combo(req.code)
end)
def("hid.type", function(_, req)
HID.Type(req.text or "")
end)
def("hid.move", function(_, req)
HID.Move(req.dx or 0, req.dy or 0)
end)
def("hid.move_to", function(_, req)
HID.MoveTo(req.x or 0, req.y or 0)
end)
def("hid.scroll", function(_, req)
HID.Scroll(req.delta or 0)
end)
def("hid.set_mouse_mode", function(_, req)
HID.SetMouseMode(req.mode or "relative")
return { mode = HID.GetMouseMode() }
end)
def("hid.get_mouse_mode", function()
return { mode = HID.GetMouseMode() }
end)
def("hid.press", function(_, req)
HID.Press(req.code, req.hold_ms or 20)
end, { async = true })
def("hid.typewriter", function(_, req)
HID.Typewriter(req.text or "", req.delay_ms)
end, { async = true })
def("hid.move_smooth", function(_, req)
local tx, ty = req.x or 0, req.y or 0
local steps = math.max(1, req.steps or 60)
local duration_ms = req.duration_ms or 250
local sx, sy = System.Mouse()
local ax, ay = 0, 0
for i = 1, steps do
local t = i / steps
t = t < 0.5 and 2 * t * t or 1 - (-2 * t + 2) ^ 2 / 2
local wx, wy = sx + (tx - sx) * t, sy + (ty - sy) * t
local cx, cy = System.Mouse()
local dx, dy = wx - cx + ax, wy - cy + ay
local mdx, mdy = math.floor(dx), math.floor(dy)
ax, ay = dx - mdx, dy - mdy
if mdx ~= 0 or mdy ~= 0 then
HID.Move(mdx, mdy)
end
Sleep(duration_ms / steps)
end
HID.MoveTo(tx, ty)
local fx, fy = System.Mouse()
return { x = fx, y = fy }
end, { async = true })
def("system.mouse", function()
local x, y = System.Mouse()
return { x = x, y = y }
end)
def("system.window", function()
return { window = System.Window() }
end)
def("system.time", function()
return { time_ms = System.Time() }
end)
def("system.screen", function()
local w, h = System.Screen()
return { width = w, height = h }
end)
def("system.exec", function(_, req)
return System.Exec(req.cmd or "", { timeout = req.timeout, cwd = req.cwd })
end, { gate = "exec" })
def("system.exec_detached", function(_, req)
return {
pid = System.ExecDetached(req.cmd or "", req.args, { cwd = req.cwd }),
}
end, { gate = "exec" })
def("screen.pixel", function(_, req)
local r, g, b = hex_rgb(Screen.GetPixelColor(req.x, req.y))
return { r = r, g = g, b = b }
end)
def("screen.pixel_hex", function(_, req)
return { hex = Screen.GetPixelColor(req.x, req.y) }
end)
def("screen.resolution", function()
local w, h = System.Screen()
return { width = w, height = h }
end)
def("screen.displays", function()
return { displays = Screen.List() }
end)
def("screen.list", function()
return { displays = Screen.List() }
end)
def("screen.capture", function(_, req)
return Screen.Capture({
display = req.display,
region = req.region,
max_edge = req.max_edge or 1280,
})
end, { async = true })
def("screen.capture_window", function(_, req)
local handle = req.handle or Window.Find(req.title or "")
if not handle then
return nil, "not_found", "no window matches"
end
local pos = Window.GetPos(handle)
local target = nil
for _, d in ipairs(Screen.List()) do
if
pos.x >= d.x
and pos.x < d.x + d.width
and pos.y >= d.y
and pos.y < d.y + d.height
then
target = d
break
end
if d.primary then
target = target or d
end
end
if not target then
return nil, "no_display", "no displays available"
end
local rx = math.max(0, pos.x - target.x)
local ry = math.max(0, pos.y - target.y)
local rw = math.min(pos.width, target.width - rx)
local rh = math.min(pos.height, target.height - ry)
return Screen.Capture({
display = target.index,
region = { x = rx, y = ry, w = rw, h = rh },
max_edge = req.max_edge or 1280,
})
end, { async = true })
def("screen.search_color", function(_, req)
local hit = Screen.SearchForColor(req.region, req.color, req.tolerance)
return { match = hit }
end, { async = true })
def("input.keys", function()
return { keys = Input.GetActiveKeys() }
end)
def("input.is_down", function(_, req)
return { down = Input.IsDown(req.code) }
end)
def("input.duration", function(_, req)
return { ms = Input.GetDuration(req.code) }
end)
def("input.modifiers", function()
return { modifiers = Input.GetModifiers() }
end)
def("input.mouse_pos", function()
return { pos = Input.GetMousePos() }
end)
def("clipboard.get", function()
return { text = Clipboard.Get() or "" }
end)
def("clipboard.set", function(_, req)
Clipboard.Set(req.text or "")
end)
def("window.list", function(_, req)
return { windows = Window.List(req.filter) }
end)
def("window.find", function(_, req)
return { handle = Window.Find(req.title or "") }
end)
def("window.get_title", function(_, req)
return { title = Window.GetTitle(req.handle) }
end)
def("window.get_class", function(_, req)
return { class = Window.GetClass(req.handle) }
end)
def("window.get_pos", function(_, req)
return { pos = Window.GetPos(req.handle) }
end)
def("window.get_pid", function(_, req)
return { pid = Window.GetPID(req.handle) }
end)
def("window.is_visible", function(_, req)
return { visible = Window.IsVisible(req.handle) }
end)
def("window.is_active", function(_, req)
return { active = Window.IsActive(req.handle) }
end)
def("window.activate", function(_, req)
Window.Activate(req.handle)
end)
def("window.move", function(_, req)
Window.Move(req.handle, req.x, req.y, req.width, req.height)
end)
def("window.minimize", function(_, req)
Window.Minimize(req.handle)
end)
def("window.maximize", function(_, req)
Window.Maximize(req.handle)
end)
def("window.restore", function(_, req)
Window.Restore(req.handle)
end)
def("window.hide", function(_, req)
Window.Hide(req.handle)
end)
def("window.show", function(_, req)
Window.Show(req.handle)
end)
def("window.set_title", function(_, req)
Window.SetTitle(req.handle, req.title or "")
end)
def("window.set_always_on_top", function(_, req)
Window.SetAlwaysOnTop(req.handle, req.enabled and true or false)
end)
def("window.set_transparency", function(_, req)
Window.SetTransparency(req.handle, req.alpha or 255)
end)
def("window.close", function(_, req)
Window.Close(req.handle)
end)
def("window.kill", function(_, req)
Window.Kill(req.handle)
end)
def("window.wait", function(_, req)
return { handle = Window.Wait(req.title or "", req.timeout) }
end, { async = true })
def("window.wait_active", function(_, req)
return { activated = Window.WaitActive(req.title or "", req.timeout) }
end, { async = true })
def("window.wait_close", function(_, req)
return { closed = Window.WaitClose(req.title or "", req.timeout) }
end, { async = true })
def("app.front", function()
return { app = App.Front() }
end)
def("app.is_front", function(_, req)
return { result = App.IsFront(req.name or "") }
end)
def("app.is_running", function(_, req)
return { result = App.IsRunning(req.name or "") }
end)
def("app.is_hidden", function(_, req)
return { result = App.IsHidden(req.name or "") }
end)
def("app.activate", function(_, req)
App.Activate(req.name or "")
end)
def("app.hide", function(_, req)
App.Hide(req.name or "")
end)
def("app.quit", function(_, req)
App.Quit(req.name or "")
end)
def("process.exists", function(_, req)
return { pid = Process.Exists(req.name or "") }
end)
def("process.list", function(_, req)
return { processes = Process.List(req.name) }
end)
def("process.kill", function(_, req)
return { killed = Process.Kill(req.pid) }
end, { gate = "exec" })
def("env.get", function(_, req)
return { value = Env.Get(req.name or "") }
end)
def("env.set", function(_, req)
Env.Set(req.name or "", req.value or "")
end)
for _, dir in ipairs({
"Home",
"Config",
"Data",
"Desktop",
"Documents",
"Downloads",
"AppData",
"Temp",
}) do
def("env." .. dir:lower(), function()
return { path = Env[dir]() }
end)
end
for _, algo in ipairs({ "MD5", "SHA1", "SHA256", "SHA512", "CRC32" }) do
def("hash." .. algo:lower(), function(_, req)
return { digest = Hash[algo](req.data or "") }
end)
end
def("hash.hmac", function(_, req)
return {
digest = Hash.HMAC(req.algo or "sha256", req.key or "", req.data or ""),
}
end)
def("codec.base64", function(_, req)
return { result = Codec.Base64(req.data or "") }
end)
def("codec.base64_decode", function(_, req)
return { result = Codec.Base64Decode(req.data or "") }
end)
def("codec.hex", function(_, req)
return { result = Codec.Hex(req.data or "") }
end)
def("codec.hex_decode", function(_, req)
return { result = Codec.HexDecode(req.data or "") }
end)
def("regex.is_match", function(_, req)
return { result = Regex.IsMatch(req.text or "", req.pattern or "") }
end)
def("regex.find", function(_, req)
return { match = Regex.Find(req.text or "", req.pattern or "") }
end)
def("regex.find_all", function(_, req)
return { matches = Regex.FindAll(req.text or "", req.pattern or "") }
end)
def("regex.replace", function(_, req)
return {
result = Regex.Replace(req.text or "", req.pattern or "", req.rep or ""),
}
end)
def("regex.replace_all", function(_, req)
return {
result = Regex.ReplaceAll(req.text or "", req.pattern or "", req.rep or ""),
}
end)
def("regex.split", function(_, req)
return { parts = Regex.Split(req.text or "", req.pattern or "") }
end)
def("config.parse_toml", function(_, req)
return { table = Config.ParseTOML(req.text or "") }
end)
def("config.to_toml", function(_, req)
return { text = Config.ToTOML(req.table or {}) }
end)
def("config.read_toml", function(_, req)
return { table = Config.ReadTOML(req.path or "") }
end, { gate = "file" })
def("config.write_toml", function(_, req)
Config.WriteTOML(req.path or "", req.table or {})
end, { gate = "file" })
def("file.read", function(_, req)
return { content = File.Read(req.path or "") }
end, { gate = "file" })
def("file.read_bytes", function(_, req)
return { bytes = File.ReadBytes(req.path or "") }
end, { gate = "file" })
def("file.write", function(_, req)
File.Write(req.path or "", req.content or "")
end, { gate = "file" })
def("file.append", function(_, req)
File.Append(req.path or "", req.content or "")
end, { gate = "file" })
def("file.exists", function(_, req)
return { exists = File.Exists(req.path or "") }
end, { gate = "file" })
def("file.delete", function(_, req)
return { deleted = File.Delete(req.path or "") }
end, { gate = "file" })
def("file.list", function(_, req)
return { entries = File.List(req.path) }
end, { gate = "file" })
def("file.mkdir", function(_, req)
return { created = File.MkDir(req.path or "") }
end, { gate = "file" })
def("file.rmdir", function(_, req)
File.RmDir(req.path or "")
end, { gate = "file" })
def("file.is_dir", function(_, req)
return { result = File.IsDir(req.path or "") }
end, { gate = "file" })
def("file.is_file", function(_, req)
return { result = File.IsFile(req.path or "") }
end, { gate = "file" })
def("file.size", function(_, req)
return { bytes = File.GetSize(req.path or "") }
end, { gate = "file" })
def("file.time", function(_, req)
return { mtime = File.GetTime(req.path or "") }
end, { gate = "file" })
def("file.copy", function(_, req)
File.Copy(req.src or "", req.dst or "")
end, { gate = "file" })
def("file.move", function(_, req)
File.Move(req.src or "", req.dst or "")
end, { gate = "file" })
def("file.read_json", function(_, req)
return { value = File.ReadJSON(req.path or "") }
end, { gate = "file" })
def("file.write_json", function(_, req)
File.WriteJSON(req.path or "", req.value or {})
end, { gate = "file" })
def("file.script_dir", function()
return { path = File.GetScriptDir() }
end, { gate = "file" })
def("net.get", function(_, req)
return {
response = Net.Get(req.url or "", req.headers, { timeout = req.timeout }),
}
end, { async = true })
def("net.post", function(_, req)
return {
response = Net.Post(
req.url or "",
req.body or "",
req.headers,
{ timeout = req.timeout }
),
}
end, { async = true })
def("net.put", function(_, req)
return {
response = Net.Put(
req.url or "",
req.body or "",
req.headers,
{ timeout = req.timeout }
),
}
end, { async = true })
def("net.patch", function(_, req)
return {
response = Net.Patch(
req.url or "",
req.body or "",
req.headers,
{ timeout = req.timeout }
),
}
end, { async = true })
def("net.delete", function(_, req)
return {
response = Net.Delete(
req.url or "",
req.headers,
{ timeout = req.timeout }
),
}
end, { async = true })
def("net.head", function(_, req)
return {
response = Net.Head(req.url or "", req.headers, { timeout = req.timeout }),
}
end, { async = true })
def("net.request", function(_, req)
return { response = Net.Request(req.options or {}) }
end, { async = true })
def("dialog.message", function(_, req)
Dialog.Message(req.text or "", req.options)
end, { async = true })
def("dialog.confirm", function(_, req)
return { confirmed = Dialog.Confirm(req.text or "", req.options) }
end, { async = true })
def("dialog.open_file", function(_, req)
return { path = Dialog.OpenFile(req.options) }
end, { async = true })
def("dialog.save_file", function(_, req)
return { path = Dialog.SaveFile(req.options) }
end, { async = true })
def("dialog.open_dir", function(_, req)
return { path = Dialog.OpenDir(req.options) }
end, { async = true })
def("math.random", function(_, req)
return { value = Math.Random(req.min or 0, req.max or 1) }
end)
def("math.gaussian", function(_, req)
return { value = Math.Gaussian(req.mean or 0, req.std_dev or 1) }
end)
def("math.scale", function(_, req)
return {
macro = Math.Scale(req.macro or {}, req.x_factor or 1, req.y_factor or 1),
}
end)
def("math.spline", function(_, req)
return { macro = Math.Spline(req.macro or {}, req.tension or 0.5) }
end)
def("math.resample", function(_, req)
return { macro = Math.Resample(req.macro or {}, req.interval_ms or 10) }
end)
def("math.interpolate", function(_, req)
return {
macro = Math.Interpolate(req.macro or {}, req.interval_ms or 10, req.mode),
}
end)
def("math.time_comp", function(_, req)
return { macro = Math.TimeComp(req.macro or {}, req.target_ms or 1000) }
end)
def("macro.record", function(_, req)
Macro.Record(req.options)
end)
def("macro.finish", function()
return { macro = Macro.Finish() }
end)
def("macro.play", function(_, req)
Macro.Play(req.macro or {}, req.speed, req.mode)
end)
def("macro.stream", function(_, req)
Macro.Stream(req.macro or {})
end)
def("macro.abort", function()
Macro.Abort()
end)
def("macro.stop_all", function()
Macro.StopAll()
end)
def("audio.beep", function()
Audio.Beep()
end)
def("audio.play", function(_, req)
local handle = Audio.Play(req.path or "", req.options)
local id = alloc_id()
sounds[id] = handle
return { sound = id }
end)
def("audio.stop", function(_, req)
local h = sounds[req.sound]
if h then
h:Stop()
sounds[req.sound] = nil
end
end)
def("audio.pause", function(_, req)
local h = sounds[req.sound]
if h then
h:Pause()
end
end)
def("audio.resume", function(_, req)
local h = sounds[req.sound]
if h then
h:Resume()
end
end)
def("audio.is_playing", function(_, req)
local h = sounds[req.sound]
return { playing = h ~= nil and h:IsPlaying() or false }
end)
def("audio.set_volume", function(_, req)
local h = sounds[req.sound]
if h then
h:SetVolume(req.volume or 1.0)
end
end)
def("audio.get_volume", function(_, req)
local h = sounds[req.sound]
return { volume = h and h:GetVolume() or 0 }
end)
def("audio.stop_all", function()
Audio.StopAll()
sounds = {}
end)
def("audio.set_master_volume", function(_, req)
Audio.SetMasterVolume(req.volume or 1.0)
end)
def("audio.get_master_volume", function()
return { volume = Audio.GetMasterVolume() }
end)
def("timer.after", function(client, req)
local id = alloc_id()
local cid = client.id
local handle = Timer.After(req.ms or 1000, function()
local c = clients[cid]
if c then
c:Send(encode({ t = "timer", handle = id, kind = "after" }))
end
if timers[cid] then
timers[cid][id] = nil
end
end)
timers[cid] = timers[cid] or {}
timers[cid][id] = handle
return { handle = id }
end)
def("timer.every", function(client, req)
local id = alloc_id()
local cid = client.id
local handle = Timer.Every(req.ms or 1000, function()
local c = clients[cid]
if c then
c:Send(encode({ t = "timer", handle = id, kind = "every" }))
end
end)
timers[cid] = timers[cid] or {}
timers[cid][id] = handle
return { handle = id }
end)
def("timer.cancel", function(client, req)
local set = timers[client.id]
local handle = set and set[req.handle]
if handle then
handle:Cancel()
set[req.handle] = nil
end
end)
def("timer.cancel_all", function(client)
local set = timers[client.id]
if set then
for _, handle in pairs(set) do
handle:Cancel()
end
timers[client.id] = {}
end
end)
for _, level in ipairs({ "Info", "Warn", "Error", "Debug" }) do
def("log." .. level:lower(), function(_, req)
Log[level](req.message or "")
end)
end
def("ui.notify", function(_, req)
UI.Notify(req.message or "", req.variant or "info")
end)
def("ui.get", function(_, req)
if REDACTED[req.id] then
return nil, "redacted", "that value is not readable over the wire"
end
return { value = UI.Get(req.id or "") }
end)
def("ui.get_all", function()
local all = UI.GetAll()
for k in pairs(REDACTED) do
all[k] = nil
end
return { values = all }
end)
def("ui.schema", function()
return { schema = UI.GetSchema() }
end)
if Registry then
def("registry.read", function(_, req)
return { value = Registry.Read(req.key or "", req.name or "") }
end)
def("registry.write", function(_, req)
Registry.Write(
req.key or "",
req.type or "string",
req.name or "",
req.value
)
end, { gate = "registry" })
def("registry.delete_value", function(_, req)
Registry.DeleteValue(req.key or "", req.name or "")
end, { gate = "registry" })
def("registry.delete_key", function(_, req)
Registry.DeleteKey(req.key or "")
end, { gate = "registry" })
def("registry.create_key", function(_, req)
Registry.CreateKey(req.key or "")
end, { gate = "registry" })
end
def("script.reload", function()
Script.Reload()
end)
def("script.exit", function(_, req)
Script.Exit(req.reason)
end)
def("subscribe", function(client, req)
local events = req.events or {}
subscribers[client.id] = subscribers[client.id] or { client = client }
subscribers[client.id].client = client
for _, name in ipairs(events) do
subscribers[client.id][name] = true
end
return { ok = true, subscribed = events }
end)
def("unsubscribe", function(client, req)
local subs = subscribers[client.id]
if subs then
for _, name in ipairs(req.events or {}) do
subs[name] = nil
end
end
return { ok = true }
end)
def("lua.exec", function(_, req)
if type(loadstring) ~= "function" then
return nil, "unavailable", "loadstring is not available in this sandbox"
end
local source = req.source or ""
local fn, parse_err = loadstring(source)
if not fn then
return nil, "parse_error", tostring(parse_err)
end
local ok, result = pcall(fn)
if ok then
return { result = result }
end
local msg = tostring(result)
local line = msg:match(":(%d+):")
if line then
local n, excerpt = tonumber(line), nil
local i = 0
for l in (source .. "\n"):gmatch("(.-)\n") do
i = i + 1
if i == n then
excerpt = l
break
end
end
if excerpt then
msg = msg .. " | line " .. line .. ": " .. excerpt:sub(1, 160)
end
end
return nil, "runtime_error", msg
end, { gate = "lua", async = true })
local function invoke(client, req, spec)
local res, code, msg = spec.fn(client, req)
if code then
err(client, req, code, msg or code)
else
reply(client, req, res or { ok = true })
end
end
local function dispatch(client, req)
local spec = api[req.t or ""]
if not spec then
err(client, req, "unknown_command", `unknown command '{tostring(req.t)}'`)
return
end
if auth_token() ~= "" and not spec.open and not authed[client.id] then
err(
client,
req,
"unauthenticated",
'send { t = "auth", token = "..." } first'
)
return
end
if spec.gate and not GATES[spec.gate] then
err(
client,
req,
"disabled",
`'{req.t}' is disabled in config (ALLOW_{spec.gate:upper()})`
)
return
end
if spec.async then
Run(function()
local ok, res, code, msg = pcall(spec.fn, client, req)
if not ok then
err(client, req, "handler_error", tostring(res))
elseif code then
err(client, req, code, msg or code)
else
reply(client, req, res or { ok = true })
end
end)
return
end
local ok, e = pcall(invoke, client, req, spec)
if not ok then
err(client, req, "handler_error", tostring(e))
end
end
function OnStart()
server = Net.WSListen(cfg.port, {
OnConnect = function(client)
Log.Info(`Remote: client {client.id} connected`)
clients[client.id] = client
local banner = server_banner()
banner.t = "hello"
send(client, banner)
end,
OnMessage = function(client, payload, is_binary)
if is_binary then
err(
client,
{ id = nil },
"no_binary",
"binary frames are not supported"
)
return
end
local ok, req = pcall(JSON.Parse, payload)
if not ok or type(req) ~= "table" then
err(client, { id = nil }, "bad_json", "could not parse JSON object")
return
end
dispatch(client, req)
end,
OnClose = function(client)
Log.Info(`Remote: client {client.id} disconnected`)
local set = timers[client.id]
if set then
for _, handle in pairs(set) do
handle:Cancel()
end
end
timers[client.id] = nil
subscribers[client.id] = nil
authed[client.id] = nil
clients[client.id] = nil
end,
})
Log.Info(
`Remote server listening on ws://0.0.0.0:{cfg.port} (auth={auth_token() ~= "" and "required" or "open"})`
)
UI.Notify(`Remote: ws://0.0.0.0:{cfg.port}`, "success")
end
function OnStop()
if server then
server:Stop()
server = nil
end
for _, set in pairs(timers) do
for _, handle in pairs(set) do
handle:Cancel()
end
end
Audio.StopAll()
clients = {}
subscribers = {}
authed = {}
timers = {}
sounds = {}
end
function OnTick()
if not server or next(subscribers) == nil then
return
end
local mouse_msg, window_msg, input_msg = nil, nil, nil
local x, y = System.Mouse()
if x ~= last_mouse_x or y ~= last_mouse_y then
last_mouse_x, last_mouse_y = x, y
mouse_msg = encode({ t = "mouse", x = x, y = y })
end
local win = System.Window()
if win.title ~= last_window_title then
last_window_title = win.title
window_msg = encode({ t = "window", window = win })
end
local any_input = false
for _, subs in pairs(subscribers) do
if subs.input then
any_input = true
break
end
end
if any_input then
input_msg = encode({
t = "input",
keys = Input.GetActiveKeys(),
modifiers = Input.GetModifiers(),
})
end
for _, subs in pairs(subscribers) do
if mouse_msg and subs.mouse then
subs.client:Send(mouse_msg)
end
if window_msg and subs.window then
subs.client:Send(window_msg)
end
if input_msg and subs.input then
subs.client:Send(input_msg)
end
end
end