-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathun.cr
More file actions
2080 lines (1905 loc) · 68.9 KB
/
Copy pathun.cr
File metadata and controls
2080 lines (1905 loc) · 68.9 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
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
# PUBLIC DOMAIN - NO LICENSE, NO WARRANTY
#
# This is free public domain software for the public good of a permacomputer hosted
# at permacomputer.com - an always-on computer by the people, for the people. One
# which is durable, easy to repair, and distributed like tap water for machine
# learning intelligence.
#
# The permacomputer is community-owned infrastructure optimized around four values:
#
# TRUTH - First principles, math & science, open source code freely distributed
# FREEDOM - Voluntary partnerships, freedom from tyranny & corporate control
# HARMONY - Minimal waste, self-renewing systems with diverse thriving connections
# LOVE - Be yourself without hurting others, cooperation through natural law
#
# This software contributes to that vision by enabling code execution across 42+
# programming languages through a unified interface, accessible to all. Code is
# seeds to sprout on any abandoned technology.
#
# Learn more: https://www.permacomputer.com
#
# Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
# software, either in source code form or as a compiled binary, for any purpose,
# commercial or non-commercial, and by any means.
#
# NO WARRANTY. THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND.
#
# That said, our permacomputer's digital membrane stratum continuously runs unit,
# integration, and functional tests on all of it's own software - with our
# permacomputer monitoring itself, repairing itself, with minimal human in the
# loop guidance. Our agents do their best.
#
# Copyright 2025 TimeHexOn & foxhop & russell@unturf
# https://www.timehexon.com
# https://www.foxhop.net
# https://www.unturf.com/software
#!/usr/bin/env crystal
require "http/client"
require "json"
require "base64"
require "option_parser"
require "openssl/hmac"
# Extension to language mapping
EXT_MAP = {
".jl" => "julia", ".r" => "r", ".cr" => "crystal",
".f90" => "fortran", ".cob" => "cobol", ".pro" => "prolog",
".forth" => "forth", ".4th" => "forth", ".py" => "python",
".js" => "javascript", ".ts" => "typescript", ".rb" => "ruby",
".php" => "php", ".pl" => "perl", ".lua" => "lua", ".sh" => "bash",
".go" => "go", ".rs" => "rust", ".c" => "c", ".cpp" => "cpp",
".cc" => "cpp", ".cxx" => "cpp", ".java" => "java", ".kt" => "kotlin",
".cs" => "csharp", ".fs" => "fsharp", ".hs" => "haskell",
".ml" => "ocaml", ".clj" => "clojure", ".scm" => "scheme",
".lisp" => "commonlisp", ".erl" => "erlang", ".ex" => "elixir",
".exs" => "elixir", ".d" => "d", ".nim" => "nim", ".zig" => "zig",
".v" => "v", ".dart" => "dart", ".groovy" => "groovy",
".scala" => "scala", ".tcl" => "tcl", ".raku" => "raku", ".m" => "objc"
}
# ANSI color codes
BLUE = "\033[34m"
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
RESET = "\033[0m"
API_BASE = "https://api.unsandbox.com"
PORTAL_BASE = "https://unsandbox.com"
MAX_ENV_CONTENT_SIZE = 65536
LANGUAGES_CACHE_TTL = 3600 # 1 hour in seconds
def detect_language(filename : String) : String
ext = File.extname(filename).downcase
EXT_MAP.fetch(ext, "unknown")
end
def get_languages_cache_path : String?
home = ENV["HOME"]?
return nil if home.nil? || home.empty?
File.join(home, ".unsandbox", "languages.json")
end
def load_languages_cache : String?
cache_path = get_languages_cache_path
return nil if cache_path.nil? || !File.exists?(cache_path)
begin
content = File.read(cache_path)
# Parse timestamp from JSON
parsed = JSON.parse(content)
cached_time = parsed["timestamp"]?.try(&.as_i64?)
return nil if cached_time.nil?
current_time = Time.utc.to_unix
# Check if cache is still valid (within TTL)
if current_time - cached_time < LANGUAGES_CACHE_TTL
return content
end
rescue
# Cache read failed, return nil to fetch fresh
end
nil
end
def save_languages_cache(response : JSON::Any)
cache_path = get_languages_cache_path
return if cache_path.nil?
begin
# Ensure directory exists
cache_dir = File.dirname(cache_path)
Dir.mkdir_p(cache_dir) unless Dir.exists?(cache_dir)
# Extract languages array from response
languages = response["languages"]?
return if languages.nil?
# Build cache JSON with timestamp
timestamp = Time.utc.to_unix
cache_data = {
"languages" => languages,
"timestamp" => timestamp
}
File.write(cache_path, cache_data.to_json)
rescue
# Cache write failed, ignore
end
end
def load_accounts_csv(path : String, index : Int32) : {String, String}?
return nil unless File.exists?(path)
begin
lines = File.read(path).split('\n').select do |l|
t = l.strip
!t.empty? && !t.starts_with?('#')
end
return nil if index < 0 || index >= lines.size
parts = lines[index].split(',')
return nil if parts.size < 2
pk = parts[0].strip
sk = parts[1].strip
return nil if pk.empty? || sk.empty?
{pk, sk}
rescue
nil
end
end
def get_api_keys(args_key : String?, args_public_key : String? = nil, account : Int32? = nil) : {String, String?}
# Tier 1: explicit -p/-k flags
if args_public_key && !args_public_key.empty? && args_key && !args_key.empty?
return {args_public_key, args_key}
end
# Tier 2: --account N → accounts.csv row N (bypasses env vars)
if !account.nil?
idx = account.not_nil!
home = ENV["HOME"]?
if home && !home.empty?
result = load_accounts_csv(File.join(home, ".unsandbox", "accounts.csv"), idx)
return {result[0], result[1]} if result
end
result = load_accounts_csv("accounts.csv", idx)
return {result[0], result[1]} if result
STDERR.puts "#{RED}Error: --account #{idx} not found in accounts.csv#{RESET}"
exit 1
end
# Tier 3: env vars
env_pk = ENV["UNSANDBOX_PUBLIC_KEY"]?
env_sk = ENV["UNSANDBOX_SECRET_KEY"]?
if env_pk && !env_pk.empty? && env_sk && !env_sk.empty?
return {env_pk, env_sk}
end
# Tier 4: ~/.unsandbox/accounts.csv row 0 (or UNSANDBOX_ACCOUNT env var)
home = ENV["HOME"]?
def_index = (ENV["UNSANDBOX_ACCOUNT"]?.try(&.to_i?) || 0).to_i32
if home && !home.empty?
result = load_accounts_csv(File.join(home, ".unsandbox", "accounts.csv"), def_index)
return {result[0], result[1]} if result
end
# Tier 5: ./accounts.csv row 0
result = load_accounts_csv("accounts.csv", def_index)
return {result[0], result[1]} if result
# Legacy UNSANDBOX_API_KEY fallback
legacy_key = args_key || ENV["UNSANDBOX_API_KEY"]?
if legacy_key && !legacy_key.empty?
return {legacy_key, nil}
end
STDERR.puts "#{RED}Error: UNSANDBOX_PUBLIC_KEY and UNSANDBOX_SECRET_KEY not set#{RESET}"
exit 1
end
def extract_challenge_id(response_body : String) : String?
begin
parsed = JSON.parse(response_body)
parsed["challenge_id"]?.try(&.as_s?)
rescue
nil
end
end
def handle_sudo_challenge(response_body : String, public_key : String, secret_key : String?, method : String, endpoint : String, body : String?) : JSON::Any
challenge_id = extract_challenge_id(response_body)
STDERR.puts "#{YELLOW}Confirmation required. Check your email for a one-time code.#{RESET}"
STDERR.print "Enter OTP: "
otp = STDIN.gets
if otp.nil? || otp.strip.empty?
STDERR.puts "#{RED}Error: Operation cancelled#{RESET}"
exit 1
end
otp = otp.strip
url = URI.parse(API_BASE + endpoint)
headers = HTTP::Headers{
"Content-Type" => "application/json"
}
request_body = body || ""
# Add HMAC authentication headers
if secret_key && !secret_key.empty?
timestamp = Time.utc.to_unix.to_s
message = "#{timestamp}:#{method}:#{endpoint}:#{request_body}"
signature = OpenSSL::HMAC.hexdigest(:sha256, secret_key, message)
headers["Authorization"] = "Bearer #{public_key}"
headers["X-Timestamp"] = timestamp
headers["X-Signature"] = signature
else
headers["Authorization"] = "Bearer #{public_key}"
end
# Add sudo headers
headers["X-Sudo-OTP"] = otp
if challenge_id
headers["X-Sudo-Challenge"] = challenge_id
end
begin
response = case method
when "GET"
HTTP::Client.get(url, headers: headers)
when "POST"
HTTP::Client.post(url, headers: headers, body: request_body)
when "PATCH"
HTTP::Client.patch(url, headers: headers, body: request_body)
when "DELETE"
HTTP::Client.delete(url, headers: headers)
else
STDERR.puts "#{RED}Error: Unsupported method: #{method}#{RESET}"
exit 1
end
if response.status_code >= 200 && response.status_code < 300
STDERR.puts "#{GREEN}Operation completed successfully#{RESET}"
JSON.parse(response.body)
else
STDERR.puts "#{RED}Error: HTTP #{response.status_code}#{RESET}"
begin
error_json = JSON.parse(response.body)
if error_msg = error_json["error"]?.try(&.as_s?)
STDERR.puts error_msg
else
STDERR.puts response.body
end
rescue
STDERR.puts response.body
end
exit 1
end
rescue ex
STDERR.puts "#{RED}Error: #{ex.message}#{RESET}"
exit 1
end
end
def api_request_with_sudo(endpoint : String, public_key : String, secret_key : String?, method = "GET", data : JSON::Any? = nil) : {Int32, JSON::Any}
url = URI.parse(API_BASE + endpoint)
headers = HTTP::Headers{
"Content-Type" => "application/json"
}
body = data ? data.to_json : ""
# Add HMAC authentication headers if secret_key is provided
if secret_key && !secret_key.empty?
timestamp = Time.utc.to_unix.to_s
message = "#{timestamp}:#{method}:#{endpoint}:#{body}"
signature = OpenSSL::HMAC.hexdigest(:sha256, secret_key, message)
headers["Authorization"] = "Bearer #{public_key}"
headers["X-Timestamp"] = timestamp
headers["X-Signature"] = signature
else
# Legacy API key authentication
headers["Authorization"] = "Bearer #{public_key}"
end
begin
response = case method
when "GET"
HTTP::Client.get(url, headers: headers)
when "POST"
HTTP::Client.post(url, headers: headers, body: body)
when "PATCH"
HTTP::Client.patch(url, headers: headers, body: body)
when "DELETE"
HTTP::Client.delete(url, headers: headers)
else
STDERR.puts "#{RED}Error: Unsupported method: #{method}#{RESET}"
exit 1
end
{response.status_code, JSON.parse(response.body)}
rescue ex
error_msg = ex.message || ""
if error_msg.downcase.includes?("timestamp")
STDERR.puts "#{RED}Error: Request timestamp expired (must be within 5 minutes of server time)#{RESET}"
STDERR.puts "#{YELLOW}Your computer's clock may have drifted.#{RESET}"
STDERR.puts "Check your system time and sync with NTP if needed:"
STDERR.puts " Linux: sudo ntpdate -s time.nist.gov"
STDERR.puts " macOS: sudo sntp -sS time.apple.com"
STDERR.puts " Windows: w32tm /resync"
else
STDERR.puts "#{RED}Error: Request failed: #{ex.message}#{RESET}"
end
exit 1
end
end
def api_request(endpoint : String, public_key : String, secret_key : String?, method = "GET", data : JSON::Any? = nil)
url = URI.parse(API_BASE + endpoint)
headers = HTTP::Headers{
"Content-Type" => "application/json"
}
body = data ? data.to_json : ""
# Add HMAC authentication headers if secret_key is provided
if secret_key && !secret_key.empty?
timestamp = Time.utc.to_unix.to_s
message = "#{timestamp}:#{method}:#{endpoint}:#{body}"
signature = OpenSSL::HMAC.hexdigest(:sha256, secret_key, message)
headers["Authorization"] = "Bearer #{public_key}"
headers["X-Timestamp"] = timestamp
headers["X-Signature"] = signature
else
# Legacy API key authentication
headers["Authorization"] = "Bearer #{public_key}"
end
begin
response = case method
when "GET"
HTTP::Client.get(url, headers: headers)
when "POST"
HTTP::Client.post(url, headers: headers, body: body)
when "PATCH"
HTTP::Client.patch(url, headers: headers, body: body)
when "DELETE"
HTTP::Client.delete(url, headers: headers)
else
STDERR.puts "#{RED}Error: Unsupported method: #{method}#{RESET}"
exit 1
end
JSON.parse(response.body)
rescue ex
error_msg = ex.message || ""
if error_msg.downcase.includes?("timestamp") || (response && response.status_code == 401 && response.body.downcase.includes?("timestamp"))
STDERR.puts "#{RED}Error: Request timestamp expired (must be within 5 minutes of server time)#{RESET}"
STDERR.puts "#{YELLOW}Your computer's clock may have drifted.#{RESET}"
STDERR.puts "Check your system time and sync with NTP if needed:"
STDERR.puts " Linux: sudo ntpdate -s time.nist.gov"
STDERR.puts " macOS: sudo sntp -sS time.apple.com"
STDERR.puts " Windows: w32tm /resync"
else
STDERR.puts "#{RED}Error: Request failed: #{ex.message}#{RESET}"
end
exit 1
end
end
def api_request_text(endpoint : String, public_key : String, secret_key : String?, body : String) : Bool
url = URI.parse(API_BASE + endpoint)
headers = HTTP::Headers{
"Content-Type" => "text/plain"
}
# Add HMAC authentication headers if secret_key is provided
if secret_key && !secret_key.empty?
timestamp = Time.utc.to_unix.to_s
message = "#{timestamp}:PUT:#{endpoint}:#{body}"
signature = OpenSSL::HMAC.hexdigest(:sha256, secret_key, message)
headers["Authorization"] = "Bearer #{public_key}"
headers["X-Timestamp"] = timestamp
headers["X-Signature"] = signature
else
headers["Authorization"] = "Bearer #{public_key}"
end
begin
response = HTTP::Client.put(url, headers: headers, body: body)
return response.status_code >= 200 && response.status_code < 300
rescue
return false
end
end
def read_env_file(path : String) : String
unless File.exists?(path)
STDERR.puts "#{RED}Error: Env file not found: #{path}#{RESET}"
exit 1
end
File.read(path)
end
def build_env_content(envs : Array(String), env_file : String?) : String
lines = envs.dup
if env_file && !env_file.empty?
content = read_env_file(env_file)
content.split('\n').each do |line|
trimmed = line.strip
if !trimmed.empty? && !trimmed.starts_with?('#')
lines << trimmed
end
end
end
lines.join('\n')
end
def cmd_service_env(args)
public_key, secret_key = get_api_keys(args[:api_key]?.as?(String), args_public_key: args[:public_key]?.as?(String), account: args[:account]?.as?(Int32))
action = args[:env_action]?.as?(String) || ""
target = args[:env_target]?.as?(String) || ""
case action
when "status"
if target.empty?
STDERR.puts "#{RED}Error: service env status requires service ID#{RESET}"
exit 1
end
result = api_request("/services/#{target}/env", public_key, secret_key)
if result["has_vault"]?.try(&.as_bool?) == true
puts "#{GREEN}Vault: configured#{RESET}"
if env_count = result["env_count"]?
puts "Variables: #{env_count}"
end
if updated_at = result["updated_at"]?.try(&.as_s?)
puts "Updated: #{updated_at}"
end
else
puts "#{YELLOW}Vault: not configured#{RESET}"
end
when "set"
if target.empty?
STDERR.puts "#{RED}Error: service env set requires service ID#{RESET}"
exit 1
end
svc_envs = args[:svc_envs]?.as?(Array(String)) || [] of String
svc_env_file = args[:svc_env_file]?.as?(String)
if svc_envs.empty? && (svc_env_file.nil? || svc_env_file.empty?)
STDERR.puts "#{RED}Error: service env set requires -e or --env-file#{RESET}"
exit 1
end
env_content = build_env_content(svc_envs, svc_env_file)
if env_content.size > MAX_ENV_CONTENT_SIZE
STDERR.puts "#{RED}Error: Env content exceeds maximum size of 64KB#{RESET}"
exit 1
end
if api_request_text("/services/#{target}/env", public_key, secret_key, env_content)
puts "#{GREEN}Vault updated for service #{target}#{RESET}"
else
STDERR.puts "#{RED}Error: Failed to update vault#{RESET}"
exit 1
end
when "export"
if target.empty?
STDERR.puts "#{RED}Error: service env export requires service ID#{RESET}"
exit 1
end
result = api_request("/services/#{target}/env/export", public_key, secret_key, method: "POST", data: JSON.parse("{}"))
if content = result["content"]?.try(&.as_s?)
print content
end
when "delete"
if target.empty?
STDERR.puts "#{RED}Error: service env delete requires service ID#{RESET}"
exit 1
end
api_request("/services/#{target}/env", public_key, secret_key, method: "DELETE")
puts "#{GREEN}Vault deleted for service #{target}#{RESET}"
else
STDERR.puts "#{RED}Error: Unknown env action: #{action}#{RESET}"
STDERR.puts "Usage: un.cr service env <status|set|export|delete> <service_id>"
exit 1
end
end
def cmd_execute(args)
public_key, secret_key = get_api_keys(args[:api_key]?.as?(String), args_public_key: args[:public_key]?.as?(String), account: args[:account]?.as?(Int32))
filename = args[:source_file].as(String)
unless File.exists?(filename)
STDERR.puts "#{RED}Error: File not found: #{filename}#{RESET}"
exit 1
end
language = detect_language(filename)
if language == "unknown"
STDERR.puts "#{RED}Error: Cannot detect language for #{filename}#{RESET}"
exit 1
end
code = File.read(filename)
# Build request payload
payload = JSON.parse({language: language, code: code}.to_json)
# Add environment variables
if env_vars = args[:env]?.as?(Array(String))
env_hash = {} of String => String
env_vars.each do |e|
if e.includes?('=')
k, v = e.split('=', 2)
env_hash[k] = v
end
end
unless env_hash.empty?
payload.as_h["env"] = JSON.parse(env_hash.to_json)
end
end
# Add input files
if files = args[:files]?.as?(Array(String))
input_files = [] of JSON::Any
files.each do |filepath|
unless File.exists?(filepath)
STDERR.puts "#{RED}Error: Input file not found: #{filepath}#{RESET}"
exit 1
end
content = Base64.strict_encode(File.read(filepath))
input_files << JSON.parse({
filename: File.basename(filepath),
content_base64: content
}.to_json)
end
unless input_files.empty?
payload.as_h["input_files"] = JSON.parse(input_files.to_json)
end
end
# Add options
if args[:artifacts]?.as?(Bool)
payload.as_h["return_artifacts"] = JSON::Any.new(true)
end
if network = args[:network]?.as?(String)
payload.as_h["network"] = JSON::Any.new(network)
end
# Execute
result = api_request("/execute", public_key, secret_key, method: "POST", data: payload)
# Print output
if stdout = result["stdout"]?.try(&.as_s?)
print BLUE, stdout, RESET
end
if stderr = result["stderr"]?.try(&.as_s?)
print RED, stderr, RESET
end
# Save artifacts
if args[:artifacts]?.as?(Bool) && (artifacts = result["artifacts"]?.try(&.as_a?))
out_dir = args[:output_dir]?.as?(String) || "."
Dir.mkdir_p(out_dir)
artifacts.each do |artifact|
filename = artifact["filename"]?.try(&.as_s?) || "artifact"
content = Base64.decode(artifact["content_base64"].as_s)
path = File.join(out_dir, filename)
File.write(path, content)
File.chmod(path, 0o755)
STDERR.puts "#{GREEN}Saved: #{path}#{RESET}"
end
end
exit_code = result["exit_code"]?.try(&.as_i?) || 0
exit exit_code
end
def cmd_session(args)
public_key, secret_key = get_api_keys(args[:api_key]?.as?(String), args_public_key: args[:public_key]?.as?(String), account: args[:account]?.as?(Int32))
if args[:list]?.as?(Bool)
result = api_request("/sessions", public_key, secret_key)
sessions = result["sessions"]?.try(&.as_a?) || [] of JSON::Any
if sessions.empty?
puts "No active sessions"
else
printf "%-40s %-10s %-10s %s\n", "ID", "Shell", "Status", "Created"
sessions.each do |s|
printf "%-40s %-10s %-10s %s\n",
s["id"]?.try(&.as_s?) || "N/A",
s["shell"]?.try(&.as_s?) || "N/A",
s["status"]?.try(&.as_s?) || "N/A",
s["created_at"]?.try(&.as_s?) || "N/A"
end
end
return
end
if info_id = args[:session_info]?.as?(String)
result = api_request("/sessions/#{info_id}", public_key, secret_key)
puts result.to_pretty_json
return
end
if kill_id = args[:kill]?.as?(String)
api_request("/sessions/#{kill_id}", public_key, secret_key, method: "DELETE")
puts "#{GREEN}Session terminated: #{kill_id}#{RESET}"
return
end
if freeze_id = args[:session_freeze]?.as?(String)
api_request("/sessions/#{freeze_id}/freeze", public_key, secret_key, method: "POST")
puts "#{GREEN}Session frozen: #{freeze_id}#{RESET}"
return
end
if unfreeze_id = args[:session_unfreeze]?.as?(String)
api_request("/sessions/#{unfreeze_id}/unfreeze", public_key, secret_key, method: "POST")
puts "#{GREEN}Session unfreezing: #{unfreeze_id}#{RESET}"
return
end
if boost_id = args[:session_boost]?.as?(String)
vcpu = args[:vcpu]?.as?(Int32) || 2
payload = JSON.parse({vcpu: vcpu}.to_json)
api_request("/sessions/#{boost_id}/boost", public_key, secret_key, method: "POST", data: payload)
puts "#{GREEN}Session boosted to #{vcpu} vCPU: #{boost_id}#{RESET}"
return
end
if unboost_id = args[:session_unboost]?.as?(String)
api_request("/sessions/#{unboost_id}/unboost", public_key, secret_key, method: "POST")
puts "#{GREEN}Session unboosted: #{unboost_id}#{RESET}"
return
end
if execute_id = args[:session_execute]?.as?(String)
command = args[:command]?.as?(String) || ""
payload = JSON.parse({command: command}.to_json)
result = api_request("/sessions/#{execute_id}/execute", public_key, secret_key, method: "POST", data: payload)
if stdout = result["stdout"]?.try(&.as_s?)
print BLUE, stdout, RESET
end
if stderr = result["stderr"]?.try(&.as_s?)
print RED, stderr, RESET
end
return
end
# Create new session
payload = JSON.parse({shell: "bash"}.to_json)
if network = args[:network]?.as?(String)
payload.as_h["network"] = JSON::Any.new(network)
end
if shell = args[:shell]?.as?(String)
payload.as_h["shell"] = JSON::Any.new(shell)
end
# Add input files
if files = args[:files]?.as?(Array(String))
input_files = [] of JSON::Any
files.each do |filepath|
unless File.exists?(filepath)
STDERR.puts "#{RED}Error: Input file not found: #{filepath}#{RESET}"
exit 1
end
content = Base64.strict_encode(File.read(filepath))
input_files << JSON.parse({
filename: File.basename(filepath),
content_base64: content
}.to_json)
end
unless input_files.empty?
payload.as_h["input_files"] = JSON.parse(input_files.to_json)
end
end
puts "#{YELLOW}Creating session...#{RESET}"
result = api_request("/sessions", public_key, secret_key, method: "POST", data: payload)
puts "#{GREEN}Session created: #{result["id"]?.try(&.as_s?) || "N/A"}#{RESET}"
puts "#{YELLOW}(Interactive sessions require WebSocket - use un2 for full support)#{RESET}"
end
def cmd_languages(args)
public_key, secret_key = get_api_keys(args[:api_key]?.as?(String), args_public_key: args[:public_key]?.as?(String), account: args[:account]?.as?(Int32))
# Try to load from cache first
cached_response = load_languages_cache
result : JSON::Any
if cached_response
result = JSON.parse(cached_response)
else
# Fetch from API
result = api_request("/languages", public_key, secret_key)
# Save to cache
save_languages_cache(result)
end
languages = result["languages"]?.try(&.as_a?) || [] of JSON::Any
if args[:json]?.as?(Bool)
# Output as JSON array of language names
names = languages.map { |l| l["name"]?.try(&.as_s?) || "" }.reject(&.empty?)
puts names.to_json
else
# Output one language per line
languages.each do |lang|
if name = lang["name"]?.try(&.as_s?)
puts name
end
end
end
end
def cmd_key(args)
public_key, secret_key = get_api_keys(args[:api_key]?.as?(String), args_public_key: args[:public_key]?.as?(String), account: args[:account]?.as?(Int32))
# Validate key
url = URI.parse(PORTAL_BASE + "/keys/validate")
headers = HTTP::Headers{
"Content-Type" => "application/json"
}
body = "{}"
# Add HMAC authentication headers if secret_key is provided
if secret_key && !secret_key.empty?
timestamp = Time.utc.to_unix.to_s
message = "#{timestamp}:POST:/keys/validate:#{body}"
signature = OpenSSL::HMAC.hexdigest(:sha256, secret_key, message)
headers["Authorization"] = "Bearer #{public_key}"
headers["X-Timestamp"] = timestamp
headers["X-Signature"] = signature
else
# Legacy API key authentication
headers["Authorization"] = "Bearer #{public_key}"
end
begin
response = HTTP::Client.post(url, headers: headers, body: body)
result = JSON.parse(response.body)
status = result["status"]?.try(&.as_s?) || "unknown"
public_key = result["public_key"]?.try(&.as_s?) || "N/A"
tier = result["tier"]?.try(&.as_s?) || "N/A"
case status
when "valid"
puts "#{GREEN}Valid#{RESET}"
puts "Public Key: #{public_key}"
puts "Tier: #{tier}"
if expires_at = result["expires_at"]?.try(&.as_s?)
puts "Expires: #{expires_at}"
end
# Handle --extend flag
if args[:extend]?.as?(Bool)
extend_url = "#{PORTAL_BASE}/keys/extend?pk=#{public_key}"
puts "\n#{BLUE}Opening browser to extend key...#{RESET}"
# Try common browser commands
["xdg-open", "open", "firefox", "chromium", "google-chrome"].each do |browser|
if system("which #{browser} > /dev/null 2>&1")
system("#{browser} '#{extend_url}' > /dev/null 2>&1 &")
break
end
end
puts extend_url
end
when "expired"
puts "#{RED}Expired#{RESET}"
puts "Public Key: #{public_key}"
puts "Tier: #{tier}"
if expired_at = result["expires_at"]?.try(&.as_s?)
puts "Expired: #{expired_at}"
end
puts "#{YELLOW}To renew: Visit #{PORTAL_BASE}/keys/extend#{RESET}"
# Handle --extend flag for expired keys
if args[:extend]?.as?(Bool)
extend_url = "#{PORTAL_BASE}/keys/extend?pk=#{public_key}"
puts "\n#{BLUE}Opening browser to renew key...#{RESET}"
["xdg-open", "open", "firefox", "chromium", "google-chrome"].each do |browser|
if system("which #{browser} > /dev/null 2>&1")
system("#{browser} '#{extend_url}' > /dev/null 2>&1 &")
break
end
end
puts extend_url
end
when "invalid"
puts "#{RED}Invalid#{RESET}"
STDERR.puts "#{RED}Error: API key is not valid#{RESET}"
exit 1
else
puts "#{YELLOW}Unknown status: #{status}#{RESET}"
end
rescue ex
STDERR.puts "#{RED}Error: Failed to validate key: #{ex.message}#{RESET}"
exit 1
end
end
def cmd_image(args)
public_key, secret_key = get_api_keys(args[:api_key]?.as?(String), args_public_key: args[:public_key]?.as?(String), account: args[:account]?.as?(Int32))
if args[:list]?.as?(Bool)
result = api_request("/images", public_key, secret_key)
puts result.to_pretty_json
return
end
if info_id = args[:image_info]?.as?(String)
result = api_request("/images/#{info_id}", public_key, secret_key)
puts result.to_pretty_json
return
end
if del_id = args[:image_delete]?.as?(String)
status_code, response = api_request_with_sudo("/images/#{del_id}", public_key, secret_key, method: "DELETE")
if status_code == 428
handle_sudo_challenge(response.to_json, public_key, secret_key, "DELETE", "/images/#{del_id}", nil)
elsif status_code >= 200 && status_code < 300
puts "#{GREEN}Image deleted: #{del_id}#{RESET}"
else
STDERR.puts "#{RED}Error: HTTP #{status_code}#{RESET}"
STDERR.puts response.to_json
exit 1
end
return
end
if lock_id = args[:image_lock]?.as?(String)
payload = JSON.parse({}.to_json)
api_request("/images/#{lock_id}/lock", public_key, secret_key, method: "POST", data: payload)
puts "#{GREEN}Image locked: #{lock_id}#{RESET}"
return
end
if unlock_id = args[:image_unlock]?.as?(String)
payload = JSON.parse({}.to_json)
body = "{}"
status_code, response = api_request_with_sudo("/images/#{unlock_id}/unlock", public_key, secret_key, method: "POST", data: payload)
if status_code == 428
handle_sudo_challenge(response.to_json, public_key, secret_key, "POST", "/images/#{unlock_id}/unlock", body)
elsif status_code >= 200 && status_code < 300
puts "#{GREEN}Image unlocked: #{unlock_id}#{RESET}"
else
STDERR.puts "#{RED}Error: HTTP #{status_code}#{RESET}"
STDERR.puts response.to_json
exit 1
end
return
end
if publish_id = args[:image_publish]?.as?(String)
source_type = args[:image_source_type]?.as?(String)
if source_type.nil? || source_type.empty?
STDERR.puts "#{RED}Error: --publish requires --source-type (service or snapshot)#{RESET}"
exit 1
end
payload = JSON.parse({source_type: source_type, source_id: publish_id}.to_json)
if name = args[:image_name]?.as?(String)
payload.as_h["name"] = JSON::Any.new(name)
end
result = api_request("/images/publish", public_key, secret_key, method: "POST", data: payload)
puts "#{GREEN}Image published#{RESET}"
puts result.to_pretty_json
return
end
if visibility_id = args[:image_visibility_id]?.as?(String)
visibility = args[:image_visibility]?.as?(String)
if visibility.nil? || visibility.empty?
STDERR.puts "#{RED}Error: --visibility requires visibility mode (private, unlisted, public)#{RESET}"
exit 1
end
payload = JSON.parse({visibility: visibility}.to_json)
api_request("/images/#{visibility_id}/visibility", public_key, secret_key, method: "POST", data: payload)
puts "#{GREEN}Image visibility set to: #{visibility}#{RESET}"
return
end
if spawn_id = args[:image_spawn]?.as?(String)
payload = JSON.parse({}.to_json)
if name = args[:image_name]?.as?(String)
payload.as_h["name"] = JSON::Any.new(name)
end
if ports_str = args[:image_ports]?.as?(String)
ports = ports_str.split(',').map(&.to_i)
payload.as_h["ports"] = JSON.parse(ports.to_json)
end
result = api_request("/images/#{spawn_id}/spawn", public_key, secret_key, method: "POST", data: payload)
puts "#{GREEN}Service spawned from image#{RESET}"
puts result.to_pretty_json
return
end
if clone_id = args[:image_clone]?.as?(String)
payload = JSON.parse({}.to_json)
if name = args[:image_name]?.as?(String)
payload.as_h["name"] = JSON::Any.new(name)
end
result = api_request("/images/#{clone_id}/clone", public_key, secret_key, method: "POST", data: payload)
puts "#{GREEN}Image cloned#{RESET}"
puts result.to_pretty_json
return
end
if grant_id = args[:image_grant]?.as?(String)
trusted_key = args[:image_trusted_key]?.as?(String)
if trusted_key.nil? || trusted_key.empty?
STDERR.puts "#{RED}Error: --grant requires --trusted-key#{RESET}"
exit 1
end
payload = JSON.parse({trusted_api_key: trusted_key}.to_json)
api_request("/images/#{grant_id}/grant", public_key, secret_key, method: "POST", data: payload)
puts "#{GREEN}Access granted to #{trusted_key}#{RESET}"
return
end
if revoke_id = args[:image_revoke]?.as?(String)
trusted_key = args[:image_trusted_key]?.as?(String)
if trusted_key.nil? || trusted_key.empty?
STDERR.puts "#{RED}Error: --revoke requires --trusted-key#{RESET}"
exit 1
end
payload = JSON.parse({trusted_api_key: trusted_key}.to_json)
api_request("/images/#{revoke_id}/revoke", public_key, secret_key, method: "POST", data: payload)
puts "#{GREEN}Access revoked from #{trusted_key}#{RESET}"
return
end
if trusted_id = args[:image_trusted]?.as?(String)
result = api_request("/images/#{trusted_id}/trusted", public_key, secret_key)
puts result.to_pretty_json
return
end
if transfer_id = args[:image_transfer]?.as?(String)
to_key = args[:image_to_key]?.as?(String)
if to_key.nil? || to_key.empty?
STDERR.puts "#{RED}Error: --transfer requires --to-key#{RESET}"
exit 1
end
payload = JSON.parse({to_api_key: to_key}.to_json)
status_code, response = api_request_with_sudo("/images/#{transfer_id}/transfer", public_key, secret_key, method: "POST", data: payload)
if status_code == 428
handle_sudo_challenge(response.to_json, public_key, secret_key, "POST", "/images/#{transfer_id}/transfer", payload.to_json)
elsif status_code >= 200 && status_code < 300
puts "#{GREEN}Image transferred to #{to_key}#{RESET}"
else
STDERR.puts "#{RED}Error: HTTP #{status_code}#{RESET}"
STDERR.puts response.to_json
exit 1
end
return
end
# Default: list images
result = api_request("/images", public_key, secret_key)
puts result.to_pretty_json
end