Overview
Obfuscate Lua scripts with layered VM transformations and runtime integrity checks. Drop a file into the Obfuscator, let the engine run, and download the protected build.
Anti-Tamper
Detects and blocks unauthorized modifications to your scripts.
Intense VM
VM virtualization and randomized instruction mapping increase analysis effort.
Local Exports
Save your generated Lua directly; source and output are not stored in browser history.
Select a .lua, .luau or .txt file containing Lua code (max 5 MiB). Drop it here or choose a file to compile in your browser.
Click to select file
or drag and drop a .lua, .luau or .txt file
Automatic Lua protection: Strong compact VM, Anti-Tamper, Anti-Debug and integrity checks. Luau uses Direct VM when recognized; standard Lua uses Sealed.
Idle
GsXFuscator Developer Documentation
Full API reference, architecture, and end-to-end tutorials to build and test your own Lua obfuscator. Available offline.
Quick start
Save this one-line example as example.lua to try your first build.
print(6 * 7)
- Open Obfuscator and select or drop your file. The panel accepts
.lua,.luau, and.txtfiles containing Lua source code. Drag and drop works for all three extensions. - Press Run to compile the file. The downloaded example prints
42when you run it in Lua. - Save the generated Lua file with Download. Keep your own backups: GsXFuscator does not store build history.
Command line
Open a terminal with the lua interpreter available. Place example.lua beside the project’s v2 directory and run this command from the project root.
lua v2/obfuscator.lua example.lua example.obf.lua --preset strong --strict-verify --stats
This command compares the source with the final packaged output. A successful check prints verified: output matches source and writes example.obf.lua.
Threat-model tradeoff: The browser automatically enables strong protection with sealed transport; the CLI also defaults to sealed output. Luau inputs are automatically emitted as Direct VM so scripts do not require loadstring. CLI --no-seal selects the same delivery. Direct VM exposes VM source text to static analysis. Neither mode keeps executable client-side code secret from a host that controls its runtime.
| Option | Behavior |
|---|---|
--preset | strong is the default. Other explicit CLI presets are normal and fast. |
--seed N | Use an integer from 0 to 4294967295 to reproduce a build with the same version and options. |
--no-seal / --direct-vm | Emit the protected VM directly, without a runtime load/loadstring call. The outer VM runtime becomes visible to static analysis. |
--seal | Use the additional encoded wrapper (default). A host that hooks load can capture the recovered VM text at runtime. |
--version | Prints V0.7 and VM/Seal format identifiers. |
--run | Compares source and output behavior once. |
--vm-size compact | Reduce redundant VM handlers/aliases for smaller output; compact is the default. |
--auto-fix | Tries the next preset after an output mismatch. An integrity failure stops the build immediately. |
--max-steps N--seconds N | Sets instruction and CPU time budgets for verification. |
--stats | Prints output size and VM statistics. |
-o FILE | Sets the output path. Defaults to example.obf.lua for example.lua. |
Exit codes 0 completed · 1 usage or file error · 2 build failed · 3 verification failed. The CLI also reports a warning when verification is inconclusive.
Lua API reference
Call the bundled modules with require from your Lua process. Save this example as build.lua in the project root and run lua build.lua. It writes api-output.lua.
package.path = "./v2/?.lua;" .. package.path
local Obfuscate = require("src.obfuscate")
local Seal = require("src.seal")
local source = "print(6 * 7)"
local result = Obfuscate.run(source, {
filename = "example.lua", preset = "normal", seed = 42
})
if not result.ok then
for _, e in ipairs(result.errors) do
io.stderr:write(string.format("%d:%d %s\n", e.line, e.col, e.msg))
end
os.exit(1)
end
local artifact = assert(Seal.wrap(result.code, result.seed))
local file = assert(io.open("api-output.lua", "wb"))
assert(file:write(artifact))
assert(file:close())
Obfuscate.run(source, opts)
source is Lua source text. The optional opts table accepts preset, seed, and a diagnostic filename. An unknown preset raises a Lua error.
| Return field | Meaning |
|---|---|
ok, stage | true and "done" on success. Failure stages include input, parse, scope, and compile. |
code, stats | Generated VM code and build statistics on success. Both are nil on a build failure. |
errors | Diagnostics contain line, col, and msg. Empty on success. |
seed, preset | The seed and preset used for this build. |
Seal.wrap(code, seed)
Packages the protected VM program as a two-stage transport: SEAL3 diversified fragments over the existing SEAL2 LZSS and checksummed payload. Sealed output includes the GsXFuscator V0.7 protected-by signature and anime ASCII comment header; its executable payload remains token-minified on one line and omits the legacy QT signature. Each fragment has its own derived stream and runtime integrity check. The loader remains recoverable under a hostile Lua host; this is not cryptographic authentication or guaranteed dump prevention. CLI option --no-seal emits direct VM bytecode instead.
Complete developer documentation library
Read the full project docs offline, from a beginner's VM to the actual GsXFuscator V0.7 compiler, bytecode, APIs and defensive test methodology. Choose a chapter below; all content is packaged into the dashboard.
19 chapters available
01V0.7 Zero-Dead compact production and 5 MiB policy
GSX V0.7 — Zero-Dead, Active Metatable Entry & Compact Output
Version: V0.7. This revision deliberately does not introduce V0.8.
What changed
- No 10,000-element dead-string injection.
src.deadstringsis removed from the shipped source and published compiler manifest; it cannot be invoked by CLI or browser output. - No generated decoy opcode handlers (
stats.decoys == 0). Unused ISA handlers are pruned, even in the standard size profile; each live opcode retains a randomized encoding, handler and VM9 operand/slot mapping. - No deliberately inert entry parameter wall in the emitted VM or piecewise-wrapper. No environment-read chaff in the generated runtime.
- Constant-true/false opaque predicate insertion and AST-level generated string decoder scaffolding are disabled. Required source string values are still encoded in VM9 encrypted constant pools; they are not dead strings. Normal bytecode protection, self-modifying blocks, anti-debug and integrity remain available.
- Strong now defaults to no redundant AST flattening (can be explicitly enabled for advanced callers with
flatten=true, without decoy states), no opaque predicates. This avoids slowing down the protected program for cosmetic path inflation. - Both sealed and direct outputs begin with executable
return setmetatable({[122]=function(...)....[122]executes the real protected VM and is invoked via__call; it is not a decorative field. - The V0.7 signature is preserved as an inline Lua comment in that active entry function. Because the file begins with
return setmetatable, the old “banner at byte 1” rule no longer applies. - The old large ASCII-art release prelude is no longer emitted.
File upload limit
5 MiB = 5,242,880 UTF-8 bytes, not 5 million characters. The limit is enforced for the web file selector, browser Worker, Lua driver, HTTP build API, and CLI/programmatic Obfuscate.run. Input over the limit fails without generating a partial artifact. The upload limit is a bound on source input; large inputs can still be rejected when VM output or memory limits are exceeded. Output size is not guaranteed to be <= 5 MiB. The compiler does not process oversized source by silently removing mandatory protections.
Performance measurement (representative small source)
Example: a function computing sum of squares and returning 42; Wasmoon Lua 5.4 in Node.js; strong, compact VM, fixed seed 127731, native Lua os.clock() readings. Results are from one run, not a statistical benchmark:
| Artifact mode | Previous published V0.7 | New V0.7 | Reduction |
|---|---|---|---|
| Direct VM | 493,130 bytes | 72,556 bytes | 85.3% |
| SEAL4 | 505,692 bytes | 62,428 bytes | 87.7% |
The same representative local run measured approximately 1.74 s -> 0.22 s (Direct VM), 2.05 s -> 0.39 s (SEAL4). This is not a guarantee for every machine or source. VM9 with full anti-debug/integrity has a nontrivial fixed runtime and tiny scripts may still emit tens of KB. Smaller output is not itself a proof of stronger protection.
Build and verification
python web/build12.py
node .tools/test_v07_zero_dead.js
node .tools/test_v07_modular_worker.js
python -m unittest web.test_service
lua v2/obfuscator.lua input.lua output.lua --preset strong --vm-size compact --no-seal --strict-verify
The first two JavaScript tests cover protected return values, the live setmetatable prefix, zero decoys, opcode pruning, Direct/SEAL4 delivery, modified fragment fail-closed and no partial output on bad input. The service tests cover routing and source size checks. Native Lua and real Luau compatibility still require environment-specific testing.
Security and functional boundaries
- “Zero-Dead” refers to the explicitly generated filler mechanisms (dead literals, decoy handler bodies, environment chaff, dummy parameter walls, opaque predicates); it is not a mathematical proof that no unreachable branch exists in any runtime or user script.
- A client-controlled Lua interpreter can observe or modify execution. The protections are anti-tamper and analysis-cost controls, not cryptographic authenticity or unbreakable confidentiality.
- The provided example starting with
buffer.readi8is host-specific and cannot be emitted literally for standard Lua 5.1–5.4, which does not definebuffer. GSX uses the real VM entry function instead. - SEAL4 intentionally uses runtime
loadto execute decoded VM source. Direct VM avoids the outer dynamic loader; either mode can be observed in a controlled host. Tampering with verified SEAL4 fragments stops execution withruntime verification failed.
02V0.7 modular web, tamper policy and deployment
Current V0.7 Zero-Dead update: compact runtime / no decoy strings / 5 MiB input / active metatable entry. The historical first-byte banner wording below reflects the previous V0.7 build; current protected output starts with executable
return setmetatable({[122]=function(...)and contains an inline V0.7 signature.
GSX V0.7 — Modular UI, output protection and fail-closed behavior
Release identity: V0.7. VM9 and SEAL4/SEAL2 formats are unchanged.
Why index.html no longer embeds the compiler
The former dashboard packed the Wasmoon JavaScript engine, WebAssembly, Lua VM modules, Lua browser driver and Worker source into one multi-megabyte HTML file. Although compilation normally ran in a Worker, the page also carried a complete Base64 blob-worker fallback.
The V0.7 maintenance build separates presentation from compilation:
| File | Responsibility |
|---|---|
public/index.html / root index.html |
UI markup, navigation, docs, controls; no Lua source or WASM bundle. |
public/assets/gsx-ui-*.js |
Browser UI, input validation, progress, Copy/Download, request to Worker. |
public/assets/gsx-style-*.css |
Dashboard styling. |
public/compiler-worker.js |
Isolated same-origin compilation coordinator. |
public/assets/wasmoon.js, glue.wasm |
Browser Lua runtime. |
public/assets/compiler-modules.json |
Versioned Lua module source manifest (VM9, anti-debug, integrity, etc.). |
public/assets/v2driver.lua |
Browser compilation orchestration and protection assertions. |
v2/src/*.lua |
Canonical engine modules used by native tooling and built assets. |
web/build12.py |
Reproducible static-site assembler that emits these files. |
The same deployment files also appear at the project root for users who
serve the root directory rather than public/. Publish the whole directory;
copying only index.html will not work. The browser requires HTTP(S), not
opening the HTML by double-clicking from file://.
python web/build12.py
python web/service.py
# Alternatively:
python -m http.server 8787 --directory public
web/service.py now serves only known same-origin asset filenames in local
mode. Its private origin build API remains a separate, authenticated service.
Security reality: moving source files out of HTML does not make a browser-side compiler secret. Anyone who can fetch the public assets can retrieve its Lua modules and WASM. For non-public compiler algorithms, deploy a genuine server-side compilation service with authentication and do not publish the compiler modules as static assets. The local static builder does not claim source confidentiality.
Mandatory checks on browser output
web/v2driver.lua always uses the modern strong VM9 pipeline. The old
legacy-compact fallback is not exposed by the browser build, even for
single-line scripts. Successful public output requires:
antidebug=true: host/instrumentation behavior probes and runtime checks.integrity=true: packed payload, VM dispatch, handler/canary checks.selfmod=true: encrypted self-modifying block pipeline.vmLayerVerified=true: VM9 packed-audit completed before code emission.- File header begins
--[[ This, File Protected By GsXFuscator V0.7 ]].
The Worker independently rejects a success frame that reports missing mandatory protections or has the wrong banner. It returns an empty code field on every non-OK result, even if a partial artifact existed in memory. The browser does not release a weaker output if a protection layer fails; compilation fails and an error is reported. This is build-time validation, not a guarantee that an attacker controlling the target Lua runtime cannot alter its behavior.
The CLI supports other profiles and deliberate overrides for testing and
compatibility. For maximum enabled baseline on the CLI use --preset strong
without disabling anti-debug, integrity or selfmod. Browser and CLI policy
are separate by design.
What happens on anti-tamper activation?
- The user's source is transformed and compiled into a protected artifact.
- The protected obfuscated artifact is the only code delivered by the web build; no unprotected source fallback is returned.
- During execution, verified VM/SEAL4 corruption can invoke the runtime's
fail-closed error path (normally
runtime verification failed), stopping the protected program. The anti-debug probe layer is not identical to the SEAL4 integrity layer: selected anti-debug conditions may instead alter the program's value-only string constants and silently diverge, as implemented inv2/src/antidebug.lua. Neither path reveals the author's original source or contacts a bot. - The previously generated obfuscated file is not automatically deleted; errors during its execution do not cause a new unprotected build.
The Web UI cannot see arbitrary runtime events after the output file is copied and executed elsewhere. Reporting those events to a Discord/Telegram bot would require an additional explicit, authenticated reporting protocol. This release deliberately makes no such callback and sends no source code.
Limits and compatibility
- Anti-hook/anti-debug checks are best-effort and can produce false positives on unusual hosts. Existing host hooks may be legitimate.
- An attacker controlling the interpreter can instrument, patch or disable in-process checks. Obfuscation is not a cryptographic trust boundary.
- Sealed output uses a runtime loader. Direct VM avoids that outer loader but does not prevent all runtime observation.
- The UI has a same-origin HTTP(S) dependency. It is not a single-file offline
executable. Offline use is possible by serving
public/on localhost.
Verification and outstanding work
node .tools/test_v07_modular_worker.js: Worker Direct VM and SEAL4 output, protected metadata and runtime results (Wasmoon 5.4).python -m unittest web/test_service.py: local UI/asset routing and API tests.node .tools/test_v07_deep.js: 42 deep engine checks.node .tools/test_v07_hardening.js: V0.7 regression checks.python web/build12.py: regenerated UI/Worker/manifest from canonical sources.- Static lint:
node --check public/compiler-worker.js, and generated UI JS.
The browser smoke test in this execution environment could not navigate to loopback or simulated HTTPS origins due to the browser administrator policy. The Worker was executed directly with Node+Wasmoon instead; this is not a claim of full cross-browser validation. Previously known Module8/11 failures, Module9 timeout and Module12 harness issue are not declared fixed by this architecture change.
03V0.7 deep engine hardening
GSX V0.7 — Derin motor güvenilirliği, VM9 ve teslim denetimi
Revizyon: 24 Kasım 2026 · Yayın imzası değişmedi: GsXFuscator V0.7 · Dosya biçimleri değişmedi: VM9, SEAL4/SEAL2.
Bu bakım güncellemesi GSX'in tüm ana çalışma zincirinin temas ettiği denetimleri güçlendirir: kaynak/AST seçenekleri, opcode üretimi, self-modifying bloklar, VM9 paket denetimi, doğrudan VM ve sealed teslim, auto-fix ve taşıma sınırları. Yeni bir V0.8 sürümü veya kriptografik olarak kırılamaz bir mekanizma iddia edilmez. Değişiklikler, tersine mühendislik maliyetini artırmaya yönelik mevcut gizleme katmanlarını korurken bozuk program dağıtma riskini azaltır.
Motor katmanları ve güncel denetimler
| Katman | Gerçek uygulama | Bu revizyondaki katkı | Güvenlik sınırı |
|---|---|---|---|
| Kaynak / AST / scope | src/parser.lua, ast.lua, scope.lua, obfuscate.lua |
Geçersiz seed/decoy/encoding/scheme seçenekleri sessizce düzeltilmek yerine stage=input döndürür. |
Ayrıştırıcı tüm Lua/Luau uzantılarını kapsamayabilir. |
| Sembol, sabit, akış, string dönüşümleri | src/consts.lua, flatten.lua, opaque.lua, strings.lua |
Geçerli, tekrarsız string şemaları seçilir; kayıpsız seçenek aktarımı korunur. | Dönüşümün semantik eşdeğerliği her program için kanıtlanmaz. |
| Opcode/handler polimorfizmi | src/vmgen.lua |
VM9 audit'inde artık selfmod bloklarından çıkan opcode'ların yaşayan handler eşlemesine dahil olduğu kontrol edilir. | Kontrol build aşamasındadır, tüm host müdahalelerini engellemez. |
| Self-modifying komut blokları | src/selfmod.lua |
Sıkı varint uzunluğu/kanoniklik, sayısal alan sınırları, kalan verinin reddi; blok sınırları. | Çözülen bloklar çalışma anında host tarafından gözlenebilir. |
| VM9 paket/şifreli blob | src/bytecode.lua |
32-bit anahtarın kesin doğrulanması, imkânsız uzunlukların checksum öncesi reddi, blok zinciri ve çözülmüş instruction audit'i, Bytecode.generate kolaylık API'sinde audit zorunluluğu. |
ChaCha20/SipHash kullanımı, çıktıya gömülü 32-bit seed'i gizli yapmaz. |
| SEAL4/SEAL2 dış taşıma | src/seal.lua, src/seal2.lua |
Fragment ayarı paketlemeden önce kontrol edilir; en fazla 16.384 fragment; watermark ASCII sınırı. | Anahtarlar ve decoder dosyada bulunduğundan kriptografik güvenlik garantisi yoktur. |
| Çıktı birleştirme, imza, syntax | src/artifact.lua, src/release.lua |
Tek artefakt üretim yolu ve baştaki V0.7 imza kontrolü sürdürülür. | İmza salt yorum metnidir, köken kanıtı değildir. |
| Auto-fix / yerel doğrulama | src/autofix.lua, src/verifier.lua |
Programatik API de teslim edilen sealed/direct dosyayı üretir ve test eder; bytecode-integrity / branding hatalarında fallback durur; taşıma/host parametreleri korunur. | Bu doğrulayıcı güvenli sandbox değil, sınırlı karşılaştırma mekanizmasıdır. |
| CLI / dashboard | src/cli.lua, web/build12.py |
CLI watermark ASCII sınırlaması ve web derleyicisi yeniden paketleme prosedürü. | Web, host ve kaynak dosya için güvenli çalışma ortamı değildir. |
Sıkılaştırılan kabul koşulları
- VM9 bytecode, şifreli gövdeyi açmadan önce header'daki makul gövde uzunluğunu doğrular. Kaynak dosyadan üretilen paketin anahtarı, tam sayılı unsigned 32-bit olmak zorundadır; string, kesirli, negatif veya sınırsız değerler reddedilir.
- Selfmod kontrolü blokların derleme anındaki zincir hash'ini önceki şifreli blok üzerinden yeniden hesaplar. Her blok gerçek decoder'dan geçirilir; bozuk varint, geçersiz sayı, fazla byte ve handler dışı opcode reddedilir.
Autofix.runartıkopts.engineverilmediyseArtifact.buildkullanır.noSeal=falseistenirken yalın VM'nin yanlışlıkla “sealed” sanılıp dönmesi önlenir. CLI zatenArtifact.buildkullanıyordu; programatik davranış eşitlendi.bytecode-integrityvebrandinghataları daha düşük korumayla yeniden denenecek sıradan semantik farklar değildir; otomatik fallback durdurulur. Geçerli testlerdestrong,normal,fast,minimalmerdiveni vestrict-verifyseçeneği korunur.Seal.wrapfragmentSize=128..16384dışında bir değer görürse SEAL2 oluşturmadan hata döndürür. Fragment sayısı 16.384'ü aşarsa sonuç üretilmez; kullanıcı daha büyük fragment seçmelidir. Bunun amacı aşırı büyük ve kaynak tüketen loader üretimini sınırlamaktır.
Deneyebileceğin komutlar
# En yüksek mevcut handler/alias çeşitliliği (daha büyük ve yavaş olabilir)
lua v2/obfuscator.lua input.lua output.lua --preset strong --vm-size standard --strict-verify
# Aynı V0.7 kimliğiyle dinamik dış load kullanmayan dağıtım
lua v2/obfuscator.lua input.lua direct.lua --preset strong --vm-size standard --no-seal --strict-verify
# Hata olduğunda tamamlanmış artefakt üzerinde deneme ve rapor
lua v2/obfuscator.lua input.lua repaired.lua --preset strong --auto-fix --strict-verify
# Yeni test (repo kökünde)
LUA_PATH='v2/?.lua;v2/?/init.lua;;' lua v2/tests/v07_deep_engine_regression.lua
# Browser/Worker bundle kaynak koddan yeniden üretimi
python web/build12.py
--vm-size standard handler çeşitliliğini artırır, fakat temel VM biçimini değiştirmez. compact varsayılandır ve daha az alias/decoy tutar. Çok büyük çıktılar, performans ve startup sınırları nedeniyle her kullanım için standard önerilmez.
Test ve dürüst sınırlar
tests/v07_deep_engine_regression.lua şu senaryoları hedefler: 10 olumsuz obfuscator ayarı; gerçek selfmod VM9 paket round-trip; anahtar/uzunluk hataları; blok zinciri kayması; Direct VM ve SEAL4 runtime paritesi; V0.7 imzası; yanlış watermark/fragment sınırları; programatik auto-fix'in son dağıtım artefaktını gerçekten doğrulaması; bytecode-integrity hatasında fallback'in durması. Toplam 42 kontrol LuaTeX Lua 5.3 ortamında geçti (ilk çalıştırma). Ek sonuçların doğru tarih ve host bilgisi, dağıtım raporunda tutulur.
Eski monolitik module8, module9, module11, module12 testlerinin tamamı yeşil olarak raporlanmıyor. Bazı testler eski handler şekillerine, imza kalıplarına veya eski SEAL sürümüne bağlı; ayrıca module8 içinde gerçek runtime başarısızlığı gibi ayrıca triage gerektiren bulgular var. Bu yeni kontrol, onları otomatik olarak “düzeltilmiş” saydırmaz. Bir bitiş koşulu için Lua 5.1/5.2/5.3/5.4 ve hedef Luau üzerinde gerçek iş yükü regresyonu gereklidir.
Bu paket için tamamlanan ek doğrulama
- LuaTeX Lua 5.3:
v07_deep_engine_regression.lua42/42 PASS;v07_hardening_regression.luaPASS. - Wasmoon Lua 5.4:
.tools/test_v07_deep.js42/42 PASS;test_v07_hardening.js,test_v07.js,test_v07_negative.js,test_v07_artifact.jsPASS. - Lua 5.3 kabul: Module1–7 ve Module10 PASS. Module11 5048/5075, FAIL; Module12 test yordamında
datanil hatası; Module8 38720/40837, FAIL ve eski mask/decoy beklentileri; Module9 için güncel tam sonuç yok (uzun koşu zaman aşımı). - Lua 5.3 CLI:
--preset strong --vm-size standard --strict-verifyile Direct VM ve SEAL4 PASS;--auto-fix --strict-verifysealed teslim PASS. - Headless Chromium:
v06_seal3_browser_smoke.pygüncel web/Worker paketiyle PASS. - Bağımsız Lua 5.1/5.2 ve gerçek Luau host'unda test koşulmadı. Bu konfigürasyonlar için başarı iddiası yok.
Tehdit modeli
GSX’in amacı bir programı analiz etmeyi, statik olarak çözmeyi veya sıradan biçimde değiştirmeyi daha maliyetli hale getirmektir. V0.7 banner'ı ve SHA-256 dosya listesi dijital imza değildir. FNV-1a/Adler-32 hata yakalayan checksum'lardır. Bir saldırgan Lua host'unu, load/loadstring çağrılarını, debug API'lerini, yürütme durumunu ve belleği yönetiyorsa kodu gözleyebilir veya kontrol mekanizmalarını atlatabilir. Gizli anahtarları veya lisans yetkilendirmesini yalnız istemcide tutma; sunucu tarafında doğrula.
04V0.6 release and verification
GsXFuscator V0.6.0 — SEAL3 / VM9 hardening release
Source: User-provided GgSsXx.zip, based on the earlier SEAL2 build. The core VM9 compiler, ChaCha20/SipHash bytecode format, flow transforms, selfmod, anti-debug, anti-tamper, Graphite UI and strong policy are preserved. The default sealed packaging changes to SEAL3 over SEAL2, so old tests that assert the V0.6 wrapper syntax must be migrated.
Security scope: A standalone Lua file necessarily contains everything required to recover and execute itself. SEAL3 raises automated static extraction effort and adds runtime integrity checks; it does not prevent a determined analyst from observing the decoded program, extracting a runtime key, intercepting load, dumping process memory or patching guard logic. All bundled keys are recoverable. Obfuscation, not tamper-proof DRM or a cryptographic trust boundary.
Original report: 12 direct weaknesses
| # | Reported weakness | V0.6 implementation / remaining limit |
|---|---|---|
| 1 | Fixed return({QT=function(...)}) wrapper |
Removed from externally visible output; new polymorphic return (function(...) SEAL3 envelope. The legacy SEAL2 loader still exists inside encrypted/encoded payload and can be extracted dynamically. |
| 2 | Alphabet plaintext | Outer alphabet emitted as permuted numeric character codes with per-build offset. Still recoverable by analysis. |
| 3/11 | K plaintext after concatenation |
Inner key is no longer directly visible on the file surface. The new outer wrapper has independent seeded fragment transforms. Embedded keys remain extractable. |
| 4/8/10 | G table and only two chunks |
Outer payload is split into hundreds of variable-size fragments, distributed into groups of 40 with different local scopes and shuffled declarations; no visible single G table. The inner SEAL2 representation still decodes normally. |
| 5 | Static EXPECTED / EXPECTED_A |
These are concealed within the inner layer; outer length/checksum/seed fields are stored as masked arithmetic expressions. Recalculating and rewriting checks is still possible under a hostile runtime. |
| 6 | Exposed M/T/N/D |
Old SEAL2 parameters are concealed inside the new envelope; the outer layer has different per-piece parameters. Its own constants remain recoverable. |
| 7 | Fully visible decoder | Both decode stages remain client-side and recoverable, by necessity. SEAL3 additionally builds a small decoder at runtime using load/loadstring; it does not make runtime extraction impossible. |
| 9 | ASCII artwork and Discord link | Not emitted by default in sealed artifacts. Direct VM likewise always omits the banner; the generator always emits compact Lua. Legacy inner strings and optional banner remain after decoding. |
| 12 | Only literal calculations | The outer layer uses per-byte state evolution, per-fragment seed reconstruction, checksum verification and assembled runtime decoder. |
Reported 20 missing features
| # | Requested capability | Status |
|---|---|---|
| 1 | Bytecode VM | Already implemented in VM9: AST compiler, register VM and randomized opcode mapping. |
| 2 | Control-flow flattening | Already implemented in src.flatten, default strong preset. |
| 3 | Anti-debug | Already implemented in VM anti-debug probes, extended with outer hook and pcall/xpcall checks. |
| 4 | Dynamic anti-tamper | Already implemented in VM canaries / handler runtime integrity; outer per-fragment checksum added. |
| 5 | Runtime-generated decoder | Extended to the complete reversible SEAL3 fragment transform (XOR, shift, reverse). The full decoder still exists in client-owned Lua. |
| 6 | Multiple decode layers | Added SEAL3 + existing SEAL2 + encrypted VM bytecode. |
| 7 | Real encryption | Already implemented VM9 ChaCha20 and SipHash. No secrecy guarantee: build key derives from a 32-bit seed shipped with the artifact. Outer layer adds a separate reversible, seed-based stream transformation, not authenticated encryption. |
| 8 | Per-piece keys | Added independently seeded per-fragment outer streams. |
| 9 | Self-modifying code | Already implemented as self-rekeying VM bytecode blocks; not self-editing the source .lua file. |
| 10 | Environment checks | Already implemented in VM and extended with outer getfenv/_ENV/_G consistency checks and runtime type checks. |
| 11 | pcall / xpcall traps |
Added outer exception-behavior validation and an optional controlled sethook/gethook sanity probe; existing VM probes preserved. |
| 12 | Opaque predicates | Already implemented in src.opaque; outer predicate added. |
| 13 | Dead-code injection | Added decoy/predicate in outer transport, existing VM decoys preserved. |
| 14 | Real string splitting | Added variable-length fragments, randomized declaration order and lexical scopes. |
| 15 | Number encoding | Already implemented in VM AST constants; outer parameters are additively masked. |
| 16 | Runtime checksums | Added per-fragment and final Adler-32 validation in SEAL3, existing FNV/Adler SEAL2 and SipHash VM checks preserved. Not an unforgeable signature. |
| 17 | os.clock / os.time checks |
Added monotonicity/baseline sanity checks where available; no aggressive timing threshold (avoids false positives). |
| 18 | Hook detection | Already implemented in VM, outer debug.gethook validation added where available. |
| 19 | Dump protection | Best-effort only through anti-hook, VM transforms and staged loading. Guaranteed protection is impossible against a runtime owner; load interception and memory dumps remain viable. |
| 20 | Watermark/fingerprint | Added per-build hidden watermark as comment inside both sealed layers. Optional CLI --watermark ID; recoverable provenance marker, not cryptographic proof. |
Release verification (22 November 2026)
- Native Lua 5.4: four strong-VM builds, sealed/direct and seeds 111/222, all reproduced original
GSX_TEST_2026 55 18under--strict-verify. - Native Lua 5.4 verifier: seven positive/negative sandbox checks passed.
- Native Lua 5.4 VM runtime guard lab: active hook, invalid branch and opcode mutation tests passed.
- Wasmoon/Lua 5.4: independent SEAL3 correctness, deterministic seed output, tampered blob rejection and live
debug.sethookrejection tests passed. - Chromium/Wasmoon: offline dashboard generated a SEAL3 artifact successfully.
- Not verified: exhaustive Lua 5.1–5.3 native compatibility, full 12-module matrix, formal security strength, memory-dump resistance, performance across workloads.
Build / use
python web/build12.py
lua v2/obfuscator.lua input.lua output.lua --preset strong --strict-verify
lua v2/obfuscator.lua input.lua output.lua --watermark customerA --fragment-size 512
python v2/tests/v06_seal3_release_smoke.py --lua lua5.4
python v2/tests/v06_seal3_browser_smoke.py
Deploy the contents of public/ to Cloudflare Pages. Build seeds diversify artifacts; they are not cryptographic secrets. Output sizes and startup overhead can be larger because SEAL3 wraps SEAL2. Users needing a stronger threat model must keep sensitive logic and keys on a trusted server, not in Lua files distributed to clients.
05Documentation hub
V0.7 güncel ek: Derin motor denetimleri, VM9/selfmod, taşıma ve yeni testler. Aşağıdaki V0.5/V0.6 bölümleri tarihsel arşivdir; yeni sürüm adı üretilmedi.
GsXFuscator V0.7 — Complete Documentation Hub
Audience: people who want to use GsXFuscator, integrate its APIs, audit its security model, or learn enough about compilers to write their own Lua obfuscator.
Version: GsXFuscator V0.6 (Release.version = 0.7) · Documentation revision: 22 November 2026.
Read this first: obfuscation is a transformation, not an encryption guarantee. The runtime must eventually execute the logic, so a host that controls the interpreter can observe the program. Our documentation distinguishes observed behavior, source-code implementation, and security assumptions. It does not promise 10/10 resistance or impossible anti-debug properties.
Upgrade note: This documentation was originally written for V0.5. Read V0.6 release notes first for changes to the verifier, browser seed generation and runtime validation. Historical V0.5 test measurements remain historical.
Choose your learning path
| Your goal | Read in this order | Outcome |
|---|---|---|
| Generate an obfuscated Lua file | Quick start → CLI → API | Build, verify, distribute |
| Integrate a desktop/IDE plugin | API → Integration recipes → Errors | Reproducible build tooling |
| Host the browser compiler | Web and deployment → API | Request/response, security, limits |
| Understand GsXFuscator internals | Compiler/AST → VM/ISA → Transforms | Trace source to emitted VM |
| Build your own obfuscator | From scratch → Toy VM example → VM/ISA → Testing |
Implement and validate a learning prototype |
| Evaluate defenses | Security model → Testing | Measured security assertions |
| Fix a failing project | Troubleshooting → API | Diagnose and reproduce |
| Türkçe başlangıç | TR-START.md | Türkçe rehber ve belge haritası |
Complete documentation index
Fundamentals
- TR-START.md — Türkçe giriş, kavramlar ve eğitim yol haritası.
- BUILD-YOUR-OWN-OBFUSCATOR.md — lexer → AST → binding → bytecode → VM, independent runnable miniature implementation and staged exercises.
- COMPILER-AND-AST.md — token contracts, AST structure, lexical scope, upvalues, evaluation semantics.
- VM-ISA-AND-BYTECODE.md — register VM operations, opcode maps, packaging, self-modifying blocks, dispatch.
- TRANSFORMS-AND-EXTENSIONS.md — pass order, safe transform rules, extension recipes.
Interfaces and running
- API.md — detailed CLI, Lua module, and HTTP build interfaces, values, result objects, examples.
- CLI.md — local command-line flags, exit codes and build patterns.
- WEB-API-AND-DEPLOYMENT.md — dashboard, local compiler, authenticated remote origin, limits and failure cases.
- EXAMPLES-AND-RECIPES.md — tested example programs and integration recipes.
- TROUBLESHOOTING-FAQ.md — diagnosis, frequent errors and compatibility gotchas.
Validation and security
- RUNTIME-INTEGRITY-AND-THREAT-MODEL.md — what checks catch, what they cannot guarantee, practical threat model.
- TESTING-AND-BENCHMARKING.md — differential tests, mutation tests, performance methods, checklists.
- SEAL-FORMAT.md — outer sealed transport byte layout.
TESTING.md,VERIFICATION.md— existing project test inventory and historical results.CHANGELOG.md— historical changes; some historical reports describe earlier output formats.- GSXFUSCATOR-BRANDING.md — V0.5 branding, Discord and ASCII output header.
VERIFICATION-FULL-DOCS.md— test report for this documentation release.ARCHITECTURE.md— historical design notes. For current implementation details, use the source files and the guides above.
Quick start
CLI
# Run from the repository root using your installed Lua binary.
lua v2/obfuscator.lua --help
lua v2/obfuscator.lua sample.lua sample.obf.lua --preset strong --strict-verify --stats
lua sample.obf.lua
The default CLI delivery is sealed, which is not the same as cryptographic secrecy. Use --no-seal to omit the outer runtime dynamic load stage and expose the VM layer directly.
Lua API
package.path = "./v2/?.lua;./v2/src/?.lua;" .. package.path
local Artifact = require("src.artifact")
local r = Artifact.build("print('hello')", {preset="strong", noSeal=false})
assert(r.ok, r.stage)
local f = assert(io.open("out.lua", "wb"))
assert(f:write(r.code))
assert(f:close())
This build API performs a syntax check of the generated Lua output; it does not prove behavior equivalence. Use --strict-verify for the CLI's best-effort sandbox comparison, and test on the actual target interpreter.
Source tree
v2/
obfuscator.lua CLI entry
src/
lexer.lua parser.lua source text → parser tree
ast.lua scope.lua normalized AST → bound names
consts.lua flatten.lua opaque.lua strings.lua AST transforms
compiler.lua register ISA / prototypes
vmgen.lua randomized handler layout / runtime emission
selfmod.lua bytecode.lua runtime bytecode preparation
antidebug.lua integrity.lua tamper.lua runtime guards
seal.lua optional wrapper
obfuscate.lua orchestrator
artifact.lua final output builder
verifier.lua autofix.lua cli.lua
examples/
toy_vm_obfuscator.lua independent learning example, very limited grammar
inspect_ast.lua inspect real parser output
custom_builder.lua public Artifact.build API usage
test_toy_vm.py educational example smoke tests
docs/ this documentation collection
web/
v3template.html dashboard source
build12.py standalone site bundler
v2driver.lua browser-side Lua driver
service.py local/private build endpoint
compile_job.py isolated compiler process
functions/api/build.js hosted proxy route
Concepts in one page
Lexing reads text into tokens and preserves token positions. Parsing builds a syntax tree respecting operator precedence. Binding resolves locals, globals and upvalues; renaming before binding breaks shadowing. Transforms change representations while preserving observable effects. Compilation lowers normalized AST into a register-oriented instruction set. VM generation translates those abstract instructions into build-specific handler IDs and a dispatch loop. Packing serializes the prototype tree and constants; optional self-modifying storage changes when instructions are decoded. Sealing packs the VM text into a reversible outer transport. Verification attempts to show that original and protected code behave the same in a finite set of environments.
Compatibility matrix and caution
- The source is designed for portable Lua constructs and includes Luau-specific handling, but a parser accepting a syntax form is not proof that all runtime behaviors match on all Lua versions.
- Lua 5.1 lacks
_ENV,//, bitwise operators and 5.4 integer semantics. Lua 5.4 adds different integer and GC semantics. Luau has additional syntax and host APIs. - The downloadable toy VM example intentionally handles only
returnof a numeric arithmetic expression and does not pretend to support full Lua. - Some historical architecture documents describe numeric goals or tests that are not current guarantees.
How to contribute to docs
Every new claim should be backed by source lines or a new test. When a public option changes, update API.md, CLI.md and the dashboard snippet if affected. When changing a serialized format, update VM-ISA-AND-BYTECODE.md or SEAL-FORMAT.md, add a golden-vector test and version the format if backward compatibility breaks.
06Türkçe başlangıç
Güncel sürüm V0.7: Derin motor/VM9/SEAL4 sertleştirmesi.
strong + sealed + compactvarsayılandır;standarddaha büyük VM çeşitliliği sağlar. Eski V0.5 notları geçmiş revizyonları anlatır.
GsXFuscator V0.5 — Türkçe başlangıç ve kendi obfuscator'ını geliştirme rehberi
Bu dokümantasyonun amacı yalnız GsXFuscator düğmelerini açıklamak değil; Lua dilini okuyabilen bir lexer, AST üreten bir parser, semantiği koruyan dönüşümler, bytecode derleyicisi ve VM yorumlayıcısı oluşturmak için öğrenme yolu sunmaktır. Büyük teknik bölümler İngilizce hazırlanmıştır; kodlarla eşleşen dosya adları korunur.
Hangi belgeyi okumalıyım?
| İhtiyaç | Başlangıç belgesi |
|---|---|
| Sıfırdan kendim kodlamak istiyorum | BUILD-YOUR-OWN-OBFUSCATOR.md |
| Lexer/Parser/AST mantığını öğrenmek istiyorum | COMPILER-AND-AST.md |
| Bytecode, opcode ve VM yazmak istiyorum | VM-ISA-AND-BYTECODE.md |
| String/constant/flow dönüşümleri yazmak istiyorum | TRANSFORMS-AND-EXTENSIONS.md |
| API fonksiyonlarını uygulamama bağlayacağım | API.md |
| Site ve uzaktan build API'si | WEB-API-AND-DEPLOYMENT.md |
| Test, benchmark, anti-tamper ölçümü | TESTING-AND-BENCHMARKING.md |
| Bütün dökümanların içindekiler tablosu | FULL-DOCUMENTATION.md |
İlk çalışan örnek: öğretici mini VM
Proje kök dizininde expr.lua oluştur:
return (2 + 3) * 4
Sonra:
lua v2/examples/toy_vm_obfuscator.lua expr.lua expr.vm.lua 123
lua v2/examples/toy_vm_obfuscator.lua expr.lua expr2.vm.lua 321
Üretilen dosyalarda PUSH, ADD, MUL gibi mantıksal işlemler build'e özgü sayısal opcode kimliklerine çevrilir. Program 20 değerini döndürür. Bu mini örnek tam Lua obfuscator'ı değildir: yalnız sayısal aritmetik ve return destekler. Yararları: tüm kod tek dosyada, okuyup değiştirmek ve test etmek kolaydır. v2/examples/test_toy_vm.py olumlu/olumsuz senaryoları çalıştırır.
Gerçek Lua koduna geçiş
lua v2/examples/inspect_ast.lua expr.lua
lua v2/examples/custom_builder.lua expr.lua expr.sealed.lua 123
İkinci komut, GsXFuscator'ın mevcut gerçek derleyici hattını kullanır. Önce src.lexer, src.parser, src.ast içini incele; sonra src.scope, src.compiler, src.vmgen ve src.bytecode modüllerinin arayüzlerine geç.
Bir dönüşümün güvenli olup olmadığını nasıl anlarsın?
- Semantik sözleşmesini yaz: aynı dönüş değerleri, hata sırası, yan etkiler,
__index/__addgibi metamethod tetiklenmeleri, upvalue paylaşımı ve global ortam davranışı. - En küçük testi oluştur: bir normal, bir sınır, bir hata, bir gölgelenen değişken testi.
- AST'de çalış: rastgele metin
gsubile Lua isimlerini değiştirme; string, yorum ve kapsam bozulur. - Şeffaf başarısız ol: desteklenmeyen sözdiziminde sessizce farklı kod üretme.
- Sürüm matrisini çalıştır: Lua 5.1 / 5.2 / 5.3 / 5.4 / hedef Luau.
- Çıktıyı tekrar analiz et: yeni Lua kodu derleniyor mu, referans testleri aynı mı?
Sık karıştırılan konular
- FNV/Adler ≠ dijital imza. Yanlışlıkla bozulan veriyi yakalayabilir; aynı dosyadaki beklenen checksum da değiştirilebilir.
- ChaCha20 benzeri ya da ChaCha20 temelli karıştırma ≠ gizli anahtar garantisi. Anahtar/seed istemcideyse analist bunları inceleyebilir.
- Kodun çok büyük olması ≠ sağlam güvenlik. VM'nin davranışını, performansını ve hata oranını ayrı ölç.
__newindex≠rawsetengeli. Standart Lua'da tabloyu değiştirmeyi mutlak önleyen bir metatable yoktur.- Anti-debug ≠ her debugger'ı kapatma. Kontrol edilen host kuralları değiştirebilir; tespit ve yanlış alarm oranlarını ölç.
Lisans ve emniyetli geliştirme
Üçüncü taraf kaynaklarını yalnız yetkin varsa analiz et veya değiştir. Kritik yetkilendirmeleri sunucuda tut; dağıtılmış obfuscation çıktısına gizli API anahtarı koyma. Daha güçlü koruma istiyorsan önce test ve kapsam iyileştirmesi ekle.
07Build your own obfuscator
Build Your Own Lua Obfuscator — A Complete Learning Path
This guide teaches a practical, testable compiler pipeline, not a trick consisting of regex substitutions or stacked encodings. You can develop your own implementation, borrow architectural ideas from GsXFuscator V0.5, and understand exactly where source compatibility can break.
0. Prerequisites and project goals
You should understand Lua tables, closures, lexical scope, functions, loops and metamethods. A minimal build environment needs a native Lua interpreter and a text editor. For a production-quality tool you will eventually need a test matrix across Lua 5.1–5.4 and, separately, your intended Luau runtime.
Define an explicit goal before creating transforms:
- Supported source language/version and extensions.
- Allowed output runtimes; whether
loadis allowed or unavailable. - Correctness model: same observable results, errors, side effects and global behavior.
- Transformation goals: rename symbols, hide literals, reduce string searches, virtualize selected code.
- Security boundary: a client-controlled interpreter can inspect its own state; the objective is analysis friction and tamper detection, not unbreakability.
- Performance and output-size budgets; run measurements rather than guessing.
Project layout to start your own implementation
my-obfuscator/
src/
lexer.lua
parser.lua
ast.lua
scope.lua
transforms.lua
compiler.lua
opcode.lua
vm.lua
pack.lua
cli.lua
tests/
lexer_cases.lua
semantics.lua
vm_roundtrip.lua
tamper_cases.lua
benchmark.lua
samples/
hello.lua
closures.lua
loops.lua
You can develop each file independently; do not start by writing a million-character loader.
1. Lexer: recognize source without changing meaning
The lexer converts source bytes into a sequence of positioned tokens. Typical tokens: keyword (local), name (x), number (1.25), string ("hello"), punctuation ((, )), operators (.., //, ==), and EOF. Record line, column and raw lexeme when helpful.
Critical behavior
- Distinguish
--comments, long comments--[=[...]=], and long strings[==[...]==]. - Handle escaped quotes without terminating early.
- Recognize longest operators first (
...before..before.). - Preserve numeric meaning, including hex floats and integer subtleties.
- Report malformed strings/escapes with positions; never silently merge tokens.
Bad approach:
-- Incorrect: a textual rename can change strings, comments and globals.
source = source:gsub("user", "a")
Preferred approach: lexical name tokens feed a binding-aware AST pass. The actual GsXFuscator lexer is in v2/src/lexer.lua; use v2/examples/inspect_ast.lua to inspect what it recognizes.
2. Parser: grammar and operator precedence
A real parser tracks expressions, statements, blocks, functions, labels and table constructors. Pratt parsing is well-suited for expressions: you parse a left expression and repeatedly consume operators whose binding power permits attachment to that left side.
Important precedences to test: ^ is right-associative; .. is right-associative; multiplication binds more tightly than addition; not does not have the same precedence as a comparison; logical and and or short-circuit. Do not transform an expression as though operations were purely mathematical, because Lua metamethods can observe evaluation order.
Start with return (2+3)*4. Then add locals, function calls, closures and if/while. Every syntax addition should have at least a positive parse case, a bad-input case and a behavior-equivalence case.
Source mapping matters: an error at byte 812 should be reported as a human-readable line/column rather than an opaque crash.
3. AST contract: a stable tree between passes
A normalized AST should separate syntax (node type and children) from analysis metadata (binding IDs, scopes, upvalue flags) and preserve relevant source coordinates. Avoid hidden contracts like “every third child is the condition” unless they are documented.
Example conceptual nodes (not a literal GsXFuscator serialization):
Chunk
└── Return
└── BinaryOp(*)
├── BinaryOp(+)
│ ├── Number(2)
│ └── Number(3)
└── Number(4)
GsXFuscator's actual normalizer (src.ast) produces table nodes carrying type, children, line, col, with type-specific metadata. Public helpers include Ast.normalize, Ast.walk, Ast.find, Ast.count, and Ast.validate. See Compiler and AST.
Golden rule: after every AST transform, run an invariant check and compare behavior.
4. Lexical scope: the first serious correctness barrier
Renaming safely requires a symbol table, a scope stack, lexical declaration rules and captured-variable tracking.
Consider:
local x = 10
local function outer()
local x = 20
return function() return x end
end
return x, outer()()
A correct rename preserves 10, 20 and the inner function's capture. You must also handle:
local x = x(RHS resolves in the outer scope).local function f()(self-reference is visible inside the body).- Function parameters shadowing outer names.
- Closures capturing loop variables and mutable upvalues.
repeat ... untilcondition seeing body locals.gotoand labels not crossing function boundaries.- Explicit globals and
_ENVin Lua 5.2+ versus 5.1 environments.
Use a unique bindingId or equivalent for every declaration; rename references by binding identity, not by spelling. Never blindly rename _G or host API names.
5. Source transformations: keep semantics before disguising syntax
Start with local renaming. Add constant rewriting only when you can prove it preserves number type, overflow behavior, precision, metamethod selection and expression order. For strings, a pool/decoder may complicate static scanning, but its key and code ship with the output and are reversible.
For control-flow flattening, transform a statement block into a state machine. Record how break, continue, return, labels, exceptions, multiple assignment and closure capture map to states. Do not flatten across arbitrary function boundaries, reorder side-effecting calls or change the number of evaluations.
Unit-test transformed code under equivalent environments. An AST that is syntactically valid can still be semantically wrong.
6. Bytecode compiler: explicit intermediate representation
Define an instruction format before VM code generation. A simple educational stack machine has:
| Instruction | Stack effect | Behavior |
|---|---|---|
PUSH n |
+1 |
Push constant n |
NEG |
0 |
Negate top |
ADD/SUB/MUL/DIV |
-1 |
Pop two, push result |
HALT |
no change | Return stack top |
GsXFuscator itself uses a register VM and a larger ISA; see VM and ISA. A starter project should deliberately implement fewer instructions and validate them completely.
Instruction invariants: known opcode; expected operand types; in-bounds register/stack use; well-formed jump target; legal terminal state. Disallow missing fields and nonsensical values before dispatch.
7. The runnable miniature: learn the whole pipeline
File: v2/examples/toy_vm_obfuscator.lua. This code is independent of the GsXFuscator compiler and intentionally easy to study.
Create an input file:
return -(11 - 3) * 2
Compile it:
lua v2/examples/toy_vm_obfuscator.lua expr.lua expr.obf.lua 12345
lua v2/examples/toy_vm_obfuscator.lua expr.lua expr.alt.lua 67890
The program:
- Tokenizes a deliberately small Lua expression subset.
- Parses
return, parentheses, decimal literals, unary minus,+,-,*,/. - Emits postfix stack instructions.
- Assigns numeric opcode IDs from a deterministic seed.
- Emits a self-contained Lua VM and executable instruction table.
- Rejects everything outside its documented grammar.
Test with python v2/examples/test_toy_vm.py. The six positive and four negative cases are part of the teaching materials, not full language conformance. The output returns -16 for the input above.
Exercises in order
- Add source-position reporting for parser errors; track the real cursor on every token.
- Implement exponentiation (
^) with right associativity and test2^3^2. - Add variable declarations and a lexical environment before supporting
Nameexpressions. - Add
JMPandJMPFwith a target validation pass. - Add calls and multiple return values; preserve evaluation order and Lua's nil-return semantics.
- Support closures: bind upvalues to cells shared between closures.
- Add tables, metatables, and metamethod-sensitive operations.
- Introduce function prototypes and a constant pool.
- Add a packer with explicit version, length and checksum; distinguish corruption detection from authentication.
- Run cross-version compatibility tests; only then add alias opcodes or control-flow flattening.
8. Randomized opcode mapping, correctly explained
Opcode polymorphism assigns different numeric IDs to the same logical instruction in different builds. The emitted dispatch must use the same mapping as the compiler. Fix the seed to make failures reproducible; vary it to test build diversity. Never call this key secrecy when the interpreter contains the mapping.
In the mini example, keys are permuted and embedded in both instructions and dispatch branches. The VM can therefore run in any supported Lua process without asking for a secret. This is obfuscation, not encryption.
For production, consider a per-prototype mapping and operand layouts only after your base compiler passes differential tests.
9. Packing and delivery modes
Separating compilation and packaging simplifies testing:
source → AST → compiled prototypes → VM source
├─ direct VM artifact
└─ sealed transport → loader → VM
The sealed wrapper in this project uses reversible Base64-like encoding, rolling XOR/PRNG and optional LZSS; the client must decode it. Runtime loading through load is observable. A direct VM avoids that extra loading point, but reveals the VM source at rest. Neither choice gives a cryptographic trust boundary.
In a fresh implementation, do not add a wrapper until the direct form is correct and independently testable.
10. A realistic test strategy from day one
Correctness
- Tokenizer golden vectors and invalid escapes.
- AST shape snapshots and parser precedence tests.
- Scope/rename tests with shadowing and upvalues.
- Metamethod-sensitive arithmetic, table access and equality.
- String bytes, nulls, Unicode source, long brackets.
- Function varargs, tail calls, multiple return values, error messages.
- Versions: Lua 5.1, 5.2, 5.3, 5.4 and the particular Luau target.
Security assumptions
- Manipulate operand, opcode, prototype length and block checksum separately.
- Verify that protections fail closed on malformed data.
- Test that no unmodified supported program spuriously fails an anti-debug probe.
- State explicitly that the code and decoding secrets in distributed artifacts can be inspected.
Performance
Benchmark a source program and a protected program with identical inputs, recording compilation time, cold start, steady-state work, output bytes and peak memory (where available). Use medians plus dispersion; don't call one unusually fast run a general speedup.
See Testing and Benchmarking for a full acceptance matrix.
11. Turning the learning project into a maintainable tool
Before shipping to users:
- Separate parser, semantic analysis, compiler, VM and packer modules.
- Keep protocol schemas and format versions explicit.
- Add deterministic seeds, input-size limits and stable, human-readable errors.
- Avoid silent fallbacks that remove protection without telling the user.
- Make build artifacts reproducible with an explicit seed.
- Build automated regression tests for each layer and a cross-runtime matrix.
- Write license, support and threat-model documentation.
- Publish measured performance and label experimental protections as experimental.
12. Building on the actual GsXFuscator compiler
The learning example above builds your own limited language pipeline. To build an actual Lua obfuscator using GsXFuscator's existing full pipeline, use v2/examples/custom_builder.lua and read:
src.obfuscate— pass orchestration and presets.src.compiler— register instruction set.src.vmgen— mappings, handlers, code emission.src.bytecode— serialization / encrypted block encoding.src.artifact— final delivery and syntax check.
Internal structures are not a supported plugin ABI. Fork, test, document and version them if you change their representation.
08Lexer, parser, AST & scope
Compiler Front End, AST, Scope and Semantics
Source of truth: v2/src/lexer.lua, parser.lua, ast.lua, scope.lua, compiler.lua. This describes the current V0.5 implementation, not a guaranteed stable plugin ABI.
1. What each component owns
| File | Responsibility | Input → output |
|---|---|---|
lexer.lua |
Lexical scanning and diagnostics | UTF-8 source bytes → token list, errors |
parser.lua |
Grammar (recursive descent / Pratt expressions) | source → parser AST + errors |
ast.lua |
Normalize, walk, count, validate | parser tree → consistent type/children tree |
scope.lua |
Resolve bindings, rename locals without collisions | normalized AST → binding metadata + rewritten names |
compiler.lua |
Lower AST to register IR | bound AST → prototypes, instructions, constants and stats |
The main orchestrator calls these in src/obfuscate.lua, with additional passes in between. Do not call Compiler.compile before the AST has been normalized and scope-analyzed unless you understand the constraints of that particular test.
2. Lexer contract
local Lexer = require('src.lexer')
local tokens, errors = Lexer.lex('local x = "hello"', 'sample.lua')
assert(#errors == 0)
for i, token in ipairs(tokens) do
print(i, token.t, token.v, token.line, token.col)
end
Tokens carry t and source coordinates line, col; some types also carry v and raw. The lexer recognizes Lua keywords, numeric literals, quoted/long strings and long comments, operators, and selected Luau syntax extensions. Lexer.KEYWORDS is exposed, but simply adding a word to it does not implement parsing or code generation for that word.
Escapes and edge cases
- Single- and double-quoted strings, escaped quotes and backslashes.
- Numeric escapes,
\xNN,\u{...}, line continuations, and\zwhitespace skipping. [=[...]=]long strings and--[==[...]==]long comments.- Multi-character operators (longest match).
- Unicode bytes in string contents and position diagnostics.
- Error locations for unfinished strings or illegal token sequences.
Test rule: for each feature, add a valid example and an invalid example. Do not let a lexer silently consume an unexpected character as trivia.
3. Parser contract
local Parser = require('src.parser')
local rawTree, errors = Parser.parse('local x = 3\nreturn x + 1', 'demo.lua')
assert(rawTree and #errors == 0)
The parser creates a tree using its own node tags (t) and records errors rather than normally throwing syntax failures at the caller. Expressions use Parser.BINPRI precedence mappings; unary parsing, statements and scopes use recursive descent. Parse errors contain line, col, msg, and may include filename.
Syntax coverage and uncertainty
The code includes Lua 5.1–5.4 and Luau-oriented parsing. That should not be interpreted as a claim that all host-specific constructs have verified runtime behavior. A build for Lua 5.1 must not casually inject syntax that exists only in 5.4; emitted VM code uses a portable subset for this reason.
4. Normalized AST contract
local Ast = require('src.ast')
local tree = Ast.normalize(rawTree)
local violations = Ast.validate(tree)
assert(#violations == 0)
local metrics = Ast.count(tree)
print(metrics.nodes, metrics.maxDepth, metrics.leaves)
Ast.walk(tree, function(node, depth, parent)
print(depth, node.type, node.line, node.col)
end)
Normalized nodes contain at least type, children, line, col; additional fields depend on the node type. Ast.find(tree, 'BinaryOp') returns matching nodes. Ast.count returns nodes, maxDepth, leaves, and byType counts. The AST is not a plain text rewriter: many transformations consume child positions and metadata. Read ast.lua before mutating nodes.
Representative node types
| Category | Typical nodes | Watch for |
|---|---|---|
| Root | Chunk |
top-level return, varargs |
| Variables | Name, Local, Assign |
local/global identity and shadowing |
| Expressions | Number, String, BinaryOp, UnaryOp, Call |
evaluation order, metamethods |
| Functions | Function, LocalFunction, Return |
closures, varargs and multiple results |
| Tables | Table, TableField, indexed fields |
constructor evaluation order |
| Control flow | If, While, Repeat, numeric/generic For |
scope lifetimes and jumps |
| Other | labels, goto, Luau-oriented variants | runtime-specific compatibility |
Node names/fields above are representative. For extensions, inspect the actual parser and normalizer; don't assume a generic ESTree or Lua AST schema.
5. Scope and binding contract
local Scope = require('src.scope')
local plan = Scope.analyze(tree, {seed=123, prefix='_0x'})
assert(#plan.errors == 0)
Scope.apply(plan)
Scope.analyze annotates names with binding IDs / reference kinds before Scope.apply mutates declarations and references. It reserves existing names to avoid collisions. Globals remain global; _G and _ENV are handled deliberately. A renamed local must keep exactly the same links to its references and upvalues.
Correctness examples
local x = 1
local function f()
local x = 2
return function() return x end
end
return x, f()() -- expect 1, 2
local y = 5
local function g()
local y = y -- the initializer refers to the outer y
return y
end
return g() -- expect 5
local count = 0
local function inc()
count = count + 1
return count
end
return inc(), inc() -- expect 1, 2; same captured storage
When a name is rebound or captured, copying its string spelling is not enough. Binding identity is the invariant.
6. Compiler and prototype format
local Compiler = require('src.compiler')
local compiled = Compiler.compile(tree, {})
assert(#compiled.errors == 0)
local problems = Compiler.validate(compiled)
assert(#problems == 0)
for i, p in ipairs(compiled.protos) do
print('proto', i, '#code', #p.code, '#const', #p.k)
end
Compiler.compile returns {protos = {...}, errors = {...}, stats = {...}}. A proto contains at least:
{
code = { {op='LOADK',a=1,b=0,c=0,d=1}, ... },
k = { ... }, -- constant pool
params = 0,
vararg = true,
maxstack = 1,
updesc = { ... }, -- closure upvalue descriptors
}
Instruction fields are op, a, b, c, and d. Registers are 1-based; register 0 is not a normal allocated register. The full instruction list is Compiler.OPS and the count is Compiler.OPCOUNT. Compiler.validate checks compiler output before VM randomization.
Registers vs stack machine
The teaching example is stack-based because it is easier to learn. The real VM is register-based: LOADK A D loads K[D] into R[A]; MOVE A B copies a register; CALL A B C D needs careful handling of varargs and multiple return values. This is why a realistic Lua compiler is more complex than the toy.
Details people regularly get wrong
- Multiple assignment: Lua computes the RHS expressions before assigning LHS targets; don't rewrite sequentially.
- Multi-return adjustment: last call/vararg in a list expands in some contexts but collapses elsewhere.
- Short-circuit logic:
and/orreturn operands, not arbitrary booleans. - Metamethods: arithmetic, equality, length, indexing, calls and concatenation can run user code.
- Numeric differences:
//, bitwise ops, 64-bit integers, float coercion and overflow vary by runtime. - Tail calls: can affect stack traces and recursion limits.
- Upvalues: a closure must capture the same cell, not a stale value snapshot.
- Error semantics: changing evaluation order changes which error surfaces first.
_ENVandgetfenv: different language versions use different environment rules.- Iteration: don't change hash/table iteration behavior without a clear contract.
7. Extension design: a safe new AST pass
A new transformation should accept and return the normalized AST, have deterministic seed handling, and preserve invariants. A minimal no-op pass looks like:
local Ast = require('src.ast')
local MyPass = {}
function MyPass.run(tree, opts)
assert(Ast.isNode(tree), 'normalized AST required')
opts = opts or {}
-- Inspect nodes, then apply only proven semantic-preserving changes.
Ast.walk(tree, function(node)
if node.type == 'Number' then
-- Intentionally no mutation: changing raw numeric representation
-- without checking integer/float semantics can break programs.
end
end)
assert(#Ast.validate(tree) == 0)
return tree
end
return MyPass
Integrate it into src/obfuscate.lua only after it has a dedicated unit test and an end-to-end behavior test. The sequence of existing passes matters because a later pass may depend on fields created by an earlier pass.
8. Hands-on exercises
- Run
v2/examples/inspect_ast.luaonreturn 2+3and inspect node type counts. - Add one new parser test for a long-bracketed string and one malformed string.
- Trace a captured variable through
Scope.analyzetoCompiler.compile. - Implement a no-op AST pass and verify that the 12 module tests still pass.
- Add a local rename with deterministic seed, then test shadowing and closures.
- Add a new instruction in an isolated VM fork and update
Compiler.OPS, handler definitions, serialization and validator together. - Compare behavior across available Lua 5.x targets using the matrix in Testing.
Further reading in this repo
09VM ISA, bytecode & selfmod
VM, Register ISA, Bytecode Container and Runtime Execution
V0.5 source files: src/compiler.lua, src/vmgen.lua, src/bytecode.lua, src/selfmod.lua, src/integrity.lua, src/antidebug.lua. Audience: implementers building their own VM or extending this compiler's internals.
This file documents the source design. The VM and bytecode internals are not a stable public ABI. In particular, opcode IDs and masks may differ by build seed, and the format should be treated as opaque unless the same version's pack/unpack logic is used.
1. Execution path
Normalized, bound AST
↓ Compiler.compile
Prototype tree: code, constants, parameters, upvalues
↓ VMGen.randomize
Build-specific opcodes, layouts, masks, handler plan
↓ optional Selfmod.apply
Encrypted instruction blocks / lazy decode metadata
↓ Bytecode.pack
Packed prototype stream → encrypted payload → header/trailer
↓ VMGen.emit
Lua source with VM decoder, runtime, handler table, checks
↓ optional Seal.wrap
Reversible outside transport (loader); runtime load() of VM text
Direct VM emits the VM runtime source without wrapping it in the outside loader. The runtime may still decode internal bytecode, but it does not need the seal-stage load of a second VM script.
2. Instruction schema
Compiler.compile emits {op="NAME", a=number, b=number, c=number, d=number}. The exact use of operands depends on op. Abstract opcodes are semantic operations; emitted numeric keys are build-specific.
Value/register movement
| Opcode(s) | Behavior (simplified) |
|---|---|
MOVE A B |
R[A] = R[B] |
LOADK A D |
Load K[D] into R[A] |
LOADINT A D |
Load an immediate integer into R[A] |
LOADBOOL A B |
Load a boolean |
LOADNIL A, LOADNILN A D |
Clear one / a range of registers |
GETUPVAL, SETUPVAL |
Access captured upvalue cells |
NEWCELL, GETCELL, SETCELL |
Support mutable captured locals |
SETTOP A |
Update runtime top marker |
Globals and tables
| Opcode(s) | Behavior (simplified) |
|---|---|
GETGLOBAL, SETGLOBAL |
Host-global reads and writes |
NEWTABLE |
Allocate Lua table |
GETTABLE, SETTABLE |
Indexed read/write |
GETFIELD, SETFIELD |
Constant-key table access |
GETIDXI, SETIDXI |
Immediate numeric-key table access |
SELF |
Prepare method call plus receiver |
SETLIST |
Populate array-style table fields |
Arithmetic, string, comparison and tests
ADD, SUB, MUL, DIV, MOD, POW, IDIV, UNM, CONCAT, LEN, NOT, BOOL; bitwise arithmetic BAND, BOR, BXOR, BNOT, SHL, SHR; comparisons EQ, NE, LT, LE, GT, GE; immediate/constant variants such as ADDK, ADDI, EQK, LTK (see Compiler.OPS for the full inventory).
Control and function operations
| Opcode | Behavior (simplified) |
|---|---|
TEST, TESTSET, TESTNIL |
Conditional evaluation/skip |
JMP, JMPF, JMPT |
Relative jump; target validation matters |
FORPREP, FORLOOP |
Numeric loop setup/advance |
TFORCALL, TFORLOOP |
Generic iterator loop |
CALL, TAILCALL, RETURN |
Call, tail call, return/multiple return handling |
CLOSURE |
Create closure from child prototype |
VARARG |
Read variable argument count |
CLOSE |
Closing/upvalue-related barrier |
NOP |
No-op |
Do not assume all opcodes have the same register usage. Some use constants or an immediate in d, some use b/c as counts, and some have relative jump offsets. The authoritative instruction comments are at the start of src/compiler.lua.
3. Prototypes and closures
A compiled prototype contains code (P.code), constants (P.k), parameters (P.params), vararg flag (P.vararg), maximum register allocation (P.maxstack) and upvalue descriptors (P.updesc). Nested functions become separate prototypes; closure creation refers to those prototypes. Captured locals must share mutable cells with every closure that closes over them.
Conceptual execution frame:
R : register array (1-based)
K : constants belonging to the prototype
U : captured upvalue cells
pc: program counter
S : frame bookkeeping (top, arguments, returns, etc.)
A VM that copies upvalue values instead of sharing cells will silently change program semantics. Test closure mutation and loop captures first.
4. Opcode mappings and polymorphic handlers
VMGen.randomize(compiled, {seed=..., decoys=..., encodings=...}) validates compiled prototypes then creates a plan. In the current source it assigns a shuffled dense slot pool and computes numeric keys from a per-build keyBase plus a slot. Each abstract instruction may have multiple aliases; selected operand positions and masks vary across aliases. Decoy handlers occupy additional keys.
The dispatcher uses a function table, not a single static readable elseif ladder for every canonical opcode. The emitted VM contains a consistent mapping between bytecode keys, masks and handler bodies. This is not a hidden-key scheme: the runtime necessarily has the data needed to execute.
How to extend safely
Adding an abstract opcode requires coordinated changes:
- Update
Compiler.OPSand compiler lowering. - Define the VM handler semantics in
vmgen.lua. - Update operand encoding/decoding if the instruction needs a new operand class.
- Update compiler validation and runtime instruction-shape checks.
- Add positive, negative and metamethod-sensitive tests.
- Verify direct and sealed outputs and all supported Lua runtimes.
Changing numeric IDs alone is easier, but is not equivalent to changing semantic opcode definitions.
5. Packed bytecode format (V0.5 format version 9)
Bytecode.pack(plan, opts) returns a package table containing blob, key, version, plainLength, plainBytes, cipherBytes, blobBytes, checksum and keyTag. Internal Bytecode.VERSION is 9.
Container layout
| Byte offset | Size | Content |
|---|---|---|
| 0–3 | 4 | FNV-1a32 checksum of ciphertext body (little endian) |
| 4–7 | 4 | Plaintext body length (little endian) |
| 8–11 | 4 | Build-key-derived tag (little endian) |
| 12–15 | 4 | Per-build format marker bytes derived from tag |
16 … n-9 |
variable | ChaCha20-processed ciphertext body |
| last 8 | 8 | SipHash-2-4 trailer covering header + ciphertext (little endian words) |
The exact parser is Bytecode.parseHeader; it refuses blobs shorter than 24 bytes and returns structured fields: checksum, plainLength, keyTag, version, magic, body, tag.
Security interpretation: the keyed trailer derives from values reconstructed within distributed code, ultimately a 32-bit build seed; do not present it as independent, secret-key, cryptographic authentication. It does make accidental or naive corruption detection more involved than a lone checksum.
Plaintext body
The packer serializes a prototype count and per-prototype fields: parameter/vararg information, instruction count, numeric opcode/operands, constants and upvalue descriptors. Integers use a variable-length format; signed values use zigzag encoding where applicable. Constants are tagged/length-prefixed. Reading requires strict bounds and exact type handling.
Encryption/mixing
bytecode.lua implements a ChaCha20-compatible 20-round core with portable arithmetic and optionally faster build-host operations. That arithmetic is careful about 32-bit overflow and 5.1 compatibility. The emitted VM decoder mirrors the format; it contains enough information to reconstruct the bytecode. ChaCha20 primitives do not make an embedded client-side build seed secret.
Parsing and validation
A safe decoder must:
- Require correct minimum container size and internal version.
- Check authenticated/checksummed ranges with the exact intended byte order.
- Reject malformed or overlong variable integers and forbidden values.
- Enforce prototype counts and total byte/operation budgets.
- Prevent cursor overruns in every nested section.
- Check operand types, bounds and jumps before execution.
- Fail closed on unknown opcode IDs and corrupted padding.
The project has regression tests for several of these classes; neither the presence of code nor a green unit test proves that every attack is prevented.
6. Lazy block decoding and self-modifying storage
In the strong profile Selfmod.apply(plan, {seed=...}) can rewrite prototype code into block metadata. It records the total instruction count (P.total), encrypted blocks (P.blocks), block chain state, block size and cache cap, and empties P.c as part of representation change. The emitted runtime can decode instructions on demand and may evict/re-encrypt cached blocks.
Two lengths must not be confused:
- Total logical instruction count of the prototype.
- Number of currently decoded instructions in a cache/window.
A preflight that only checks #decoded_cache against the total count will fail for legitimate lazy implementations; a preflight that stores 0 for every expected length fails to check anything. The V0.5 prototype length checks intentionally distinguish total metadata and current cache residency.
Selfmod.replay is a test helper that exercises the decode/evict/re-encrypt lifecycle on copies of the blocks. It is not a public high-level build API.
7. Runtime CFI and integrity checks
Checks in the emitted runtime include validation of handler identities, table/prototype shape, checksummed encoded blocks, bounds/operand forms and some runtime behavior probes. A protected metatable's __newindex does not make existing table slots immutable; independent reference checks detect certain mutations instead. Some hosts provide table.freeze, but standard Lua does not guarantee it.
The VM must validate the next program counter and instruction fields before dispatch. Short programs still need a pre-dispatch check rather than depending solely on periodic checks. See Runtime integrity and threat model.
8. Seal is a different format
Do not conflate internal bytecode with the optional external seal transport:
| Property | Internal VM bytecode | External sealed wrapper |
|---|---|---|
| What it packages | prototypes + instructions + constants | generated VM Lua source text |
| Source | bytecode.lua |
seal.lua |
| Layout | 16-byte header + ciphertext + 8-byte tag | 12-byte per-block metadata, LZSS/raw, XOR, 64-symbol alphabet |
| Runtime | VM interpreter | decode and call load/loadstring on VM text |
| Cryptographic secrecy | no independent trust boundary | no independent trust boundary |
See SEAL-FORMAT.md for block details and decoder limits.
9. Test your own VM rather than trust code size
Suggested development gates:
- A small instruction trace with expected register values after every opcode.
- Out-of-range, fractional and zero program-counter mutation cases.
- Invalid register index, malformed constants and missing operands.
- Inconsistent prototype length or cache size.
- Duplicate/unknown opcode IDs and dispatcher table mutation.
- Nested closures with captured mutable variables.
- Metamethod-sensitive ops and
pcall/xpcallerror behavior. - Differential comparison of original and VM programs under the same target runtime.
Key insight: more handlers, a longer loader or deeper nesting are complexity metrics, not proof of resistance to devirtualization.
10Transforms and extensions
Current GSX V0.7 Zero-Dead revision: see V07-ZERO-DEAD-COMPACT.md. Historic dead-string, synthetic decoder, first-byte banner, alias and decoy descriptions below refer to earlier builds; current production outputs use a live
return setmetatableentry and zero decoy handlers.
Source Transformations, Pass Ordering and Extending GsXFuscator
V0.5 implementation: src/obfuscate.lua orchestrates parsing, name resolution, constant/flow/string passes, register compilation, VM randomization, self-modifying blocks, packed bytecode, and runtime emission. This is a source-architecture guide, not an externally versioned transform plugin API.
1. The exact pass order in the orchestrator
Parser.parse
→ Ast.normalize
→ Scope.analyze / Scope.apply
→ Consts.run
→ Flatten.run (if selected)
→ Opaque.run (if selected)
→ Strings.run
→ Compiler.compile
→ VMGen.randomize
→ Selfmod.apply (if selected)
→ Bytecode.pack
→ VMGen.emit (integrity / anti-debug parameters)
→ Artifact.build: optional Seal.wrap + syntax-load check
This order is meaningful. For instance, name resolution must precede transformations that introduce synthetic locals, and VM randomization works on compiled prototypes, not source text.
2. Presets and override hierarchy
The public default preset is strong (Obfuscate.DEFAULT_PRESET). In src/obfuscate.lua, the current preset table expresses roughly:
| Layer | strong | normal | fast |
|---|---|---|---|
flatten |
enabled | enabled | disabled |
opaque |
enabled | enabled | disabled |
selfmod |
enabled | disabled | disabled |
antidebug |
enabled | enabled | disabled |
integrity |
enabled | enabled | enabled |
schemes |
6 | 6 | 2 |
decoys (nominal maximum) |
896 | 448 | 160 |
Caveat: the build pipeline scales handler aliases and decoy counts with source size, so the actual emitted numbers are not always the nominal preset values. --vm-size compact reduces variation and decoys for output size. When custom flags are explicitly passed, those values can override preset choices. The browser dashboard fixes a strong policy; the CLI and programmatic module expose more controls.
Example:
local Obfuscate = require('src.obfuscate')
local r = Obfuscate.run(source, {
preset = 'strong', seed = 4242, vmSize = 'standard',
flatten = true, opaque = true, selfmod = true,
antidebug = true, integrity = true,
})
assert(r.ok, r.stage)
3. Scoped renaming: a reliable first transform
A binding-aware rename changes the spelling of locals but not their referents. It must protect globals, built-ins, user-defined globals, labels, private function parameters and captured upvalues. A global function lookup, including _G and _ENV behavior, must remain directed at the user's environment.
A minimal reference workflow:
local Parser, Ast, Scope = require('src.parser'), require('src.ast'), require('src.scope')
local parsed, errors = Parser.parse('local a = 7; return a')
assert(parsed and #errors == 0)
local tree = Ast.normalize(parsed)
local plan = Scope.analyze(tree, { seed = 123, prefix = '_0x' })
assert(#plan.errors == 0)
Scope.apply(plan)
assert(#Ast.validate(tree) == 0)
Scope.analyze and Scope.apply are internal stages. This recipe is useful for understanding the pipeline; for end-to-end output use Artifact.build() instead of inventing a new source printer.
4. Constant and string rewriting
Consts.run obscures selected scalar constants through equivalent expressions. Strings.run transforms string occurrences using an encoded pool and emitted decoder. The implementation includes multiple scheme labels such as XOR, shuffled alphabet, Huffman-oriented or other encodings in strings.lua.
Correctness hazards
- Integer vs floating subtype (
1versus1.0on Lua 5.3+). - NaN, infinities, negative zero and unsupported numeric representations.
- Binary strings containing
\0and bytes above 127. - String identity/equality after decoding.
- Source encoding and escape semantics; UTF-8 text is not always a byte-preserving copy of a Lua string literal.
- Decoding a string during a metamethod-sensitive evaluation can change error timing.
Test advice: run byte-level comparisons, not only printable-string comparisons. Treat the pool key as accessible to an attacker when shipped in the output.
5. Control-flow flattening
Flatten.run(ast, opts) rewrites selected source control flow into alternative AST forms, including state-machine-like shapes. This can increase static analysis work but raises correctness risk.
Transform only when you can preserve
- Relative ordering of side effects.
- Correct truthiness (
falseandnilare false, everything else is true). - Multiple return values and the placement of tail calls.
- Short-circuiting and conditional evaluation.
- Label visibility and the scope of
goto. - Loop-scoped captures and repeat/until variable lifetime.
break/continuesemantics and error propagation.- Metamethod calls and their order.
Example conceptual state conversion:
-- Original
if flag then workA() else workB() end
finish()
-- Illustration only; not an AST serialization and not a safe
-- generic textual rewrite of arbitrary Lua:
local state = flag and 1 or 2
while state ~= 0 do
if state == 1 then workA(); state = 3
elseif state == 2 then workB(); state = 3
elseif state == 3 then finish(); state = 0
else error('invalid state') end
end
This example is intentionally simple. Real Lua if may contain returns, nested scopes and calls with observable errors; a safe compiler must operate on AST/CFG, not text.
6. Opaque predicates
An opaque predicate is a condition whose outcome is known to the compiler but intended to be less obvious to a reader. Opaque.run adds selected constructs from predefined templates. A generator must test its mathematical claims for the actual numeric domain and host semantics; integer overflow and float precision can invalidate apparently tautological expressions.
Never let an opaque predicate evaluate a user expression twice. A metamethod or function call may have side effects.
7. Bytecode and runtime modifications
Compiler.compile creates semantic instructions; VMGen.randomize assigns handler keys; Selfmod.apply optionally rewrites instruction storage; Bytecode.pack serializes/encrypts a payload; VMGen.emit writes the VM. These are coupled internals.
Coordinated change checklist
For an added opcode:
- add a compiler lowering rule and opcode name;
- add runtime handler semantics and any variant templates;
- add compiler validation and runtime operand checks;
- update wire encoding for any new operand type;
- test direct and sealed emission, selfmod and non-selfmod paths;
- run regression tests on every supported Lua interpreter.
For a changed serialized field, update packer + loader + test vectors together and document the compatibility break. Failing to do so can yield runnable output with subtly wrong values.
8. Integration extension points
There are three practical levels:
Level A — supported integration: call Artifact.build(source, opts) and inspect result. Recommended for independent tools, editors and GUIs.
Level B — experimental compiler fork: call or modify src.obfuscate and transform modules. Keep a source fork and a test matrix because internal data layouts can change.
Level C — VM/runtime format fork: modify compiler, vmgen, bytecode, selfmod, integrity in tandem. Treat generated artifacts as a new format and create a versioned wire specification.
9. Do not mistake more complexity for more security
Added decoy handlers, bytecode encoding layers, or lengthy opaque predicates can make programs larger without defeating a capable dynamic observer. Use independent measurements:
| Claim | Testable question |
|---|---|
| Hides source text | Does static output reveal plaintext literals and source structure? |
| Prevents tampering | Which exact alterations are detected, and before which side effect? |
| Increases analyst cost | How much work/time does a controlled reconstruction require? |
| Compatible | Does the output match original behavior in each target runtime? |
| Fast enough | What is cold-start/steady-state/peak-memory overhead? |
10. Suggested learning extensions
- Add a metadata-only AST analysis pass (count conditional nodes).
- Add a deterministic local-renaming strategy and test collisions.
- Create a benign source-transformation pass under strict AST invariants.
- Implement one extra logical opcode in an isolated teaching VM.
- Add invalid operand and broken jump-target tests.
- Make a versioned serializer and round-trip parser.
- Benchmark before and after, recording measured size and runtime.
- Document the threat model and compatibility risks.
Further reading: Build your own, Compiler and AST, VM and bytecode, Testing.
11Full CLI, Lua and HTTP API
Current release: GsXFuscator V0.7 (24 Nov 2026). The V0.5 section titles below are historical. The current CLI defaults to
strong,compactVM sizing, and sealed transport;--versionreports V0.7 / VM9 / SEAL4/SEAL2.Obfuscate.runrejects non-finite/negative decoy counts, non-uint32 seeds and invalid/duplicate scheme selections;Bytecode.pack/unpackrequire numeric uint32 keys.Autofix.runnow verifies the final delivered artifact. See deep engine hardening.
GsXFuscator V0.7 — Complete API Documentation
API index: Full documentation hub · Build your own obfuscator · VM bytecode · Deployment.
Scope: This page documents the supported public interfaces of GsXFuscator V0.7: the CLI, the Lua modules intended for programmatic use, and the authenticated/private HTTP build API used by the dashboard.
Stability note: The CLI,
Obfuscate.run,Artifact.build,Seal.wrap, and the explicitly documented HTTP schema are the recommended integration surfaces. Internals, return stats andAutofixdetails may change; API descriptions here are source-derived, not a separate versioned compatibility guarantee. Internals (vmgen,bytecode,flatten,antidebug) are not a public plugin ABI.
1) API surface at a glance
| Surface | Entry point | Best for |
|---|---|---|
| CLI | lua v2/obfuscator.lua ... |
Local builds, CI, repeatable scripting |
| Lua build API | require("src.obfuscate") |
Generate direct VM programmatically |
| Lua artifact API | require("src.artifact") |
Generate sealed or direct distributable output |
| Lua seal API | require("src.seal") |
Wrap direct VM code into the sealed transport |
| Lua verification API | require("src.autofix") / require("src.verifier") |
Run verification and auto-fix ladders |
| Lua CLI API | require("src.cli") |
Embed the CLI parser/runner into host tools |
| Release metadata API | require("src.release") |
Read banner/version/format constants |
| HTTP build API | POST /api/build |
Browser dashboard and remote build service |
2) CLI API
2.1 Syntax
lua v2/obfuscator.lua <input.lua> [output.lua] [options]
2.2 Options
| Option | Type | Default | Meaning |
|---|---|---|---|
<input.lua> |
path | required | Source Lua file to read |
[output.lua] |
path | <input>.obf.lua |
Output file path |
-o PATH, --out PATH |
path | — | Explicit output path; overrides positional output |
--preset strong|normal|fast |
string | strong |
Build profile |
--seed N |
integer | random/fresh | Build seed in 0..4294967295 |
--seal |
flag | on | Emit sealed artifact |
--no-seal |
flag | off | Emit direct VM artifact |
--direct-vm |
flag | off | Alias for --no-seal |
--vm-size standard|compact |
string | compact |
Standard = max variety; compact = smaller output |
--seal-compression auto|raw|lzss |
string | auto |
Transport compression mode |
--seal-block-size N |
integer | 65536 |
Raw bytes per seal block |
--run |
flag | off | Verify built output once against the source |
--strict-verify |
flag | off | Treat inconclusive verification as failure |
--auto-fix |
flag | off | Retry safer combinations when verification fails |
--stats |
flag | off | Print extended statistics |
--max-steps N |
integer | verifier default | Sandbox instruction budget |
--seconds N |
number | verifier default | Sandbox CPU time budget |
--version |
flag | off | Print display and internal format versions |
-h, --help |
flag | off | Print usage |
2.3 Exit codes
| Code | Name | Meaning |
|---|---|---|
0 |
EXIT_OK |
Build succeeded |
1 |
EXIT_USAGE |
Usage, parsing, read, or write error |
2 |
EXIT_FAILED |
Build pipeline failed |
3 |
EXIT_VERIFY |
Verification/integrity failed |
2.4 CLI Lua module
Module: src.cli
Constants
| Field | Value |
|---|---|
Cli.EXIT_OK |
0 |
Cli.EXIT_USAGE |
1 |
Cli.EXIT_FAILED |
2 |
Cli.EXIT_VERIFY |
3 |
Cli.USAGE |
human-readable help string |
Cli.parse(argv) -> opts | nil, err
Parses a command-line argument vector.
local Cli = require("src.cli")
local opts, err = Cli.parse({"input.lua", "out.lua", "--preset", "strong"})
assert(opts, err)
print(opts.input, opts.output, opts.preset)
Successful result fields
| Field | Type | Notes |
|---|---|---|
help |
boolean? | Present when --help requested |
version |
boolean? | Present when --version requested |
input |
string | Input path |
output |
string | Output path or - |
preset |
"strong" | "normal" | "fast" |
Build preset |
seed |
string? | Raw seed argument text |
seedNumber |
integer? | Parsed seed |
run |
boolean | Verification enabled |
autofix |
boolean | Auto-fix enabled |
stats |
boolean | Stats requested |
noSeal |
boolean | Direct VM requested |
strictVerify |
boolean | Fail on inconclusive verification |
vmSize |
"standard" | "compact"? |
Optional VM size override |
sealCompression |
"auto" | "raw" | "lzss"? |
Optional compression override |
sealBlockSize |
integer? | Optional block-size override |
maxSteps |
integer? | Verification budget |
seconds |
number? | Verification CPU budget |
Failure
- Returns
nil, error_message - Error messages are already user-readable (e.g.
unknown option --foo,missing input file)
Cli.main(argv [, sink]) -> exit_code
Runs the complete CLI workflow.
argv: array of argument strings, without the interpreter namesink: optional output hooks
local Cli = require("src.cli")
local code = Cli.main({"sample.lua", "sample.obf.lua", "--run"}, {
out = function(s) io.write("[OUT] ", s) end,
err = function(s) io.stderr:write("[ERR] ", s) end,
})
os.exit(code)
sink shape:
{
out = function(text) ... end, -- defaults to io.write
err = function(text) ... end, -- defaults to io.stderr:write
}
3) Lua build API
Module: src.obfuscate
3.1 Constants
| Field | Type | Meaning |
|---|---|---|
Obfuscate.DEFAULT_PRESET |
string | Default preset name ("strong") |
Obfuscate.PRESETS |
table | Built-in preset table |
Obfuscate.PRESETS currently contains:
strongnormalfast
3.2 Obfuscate.run(source [, opts]) -> result
Runs the V0.5 VM obfuscation pipeline and returns direct VM code (not sealed transport).
package.path = "./v2/?.lua;./v2/src/?.lua;" .. package.path
local Obfuscate = require("src.obfuscate")
local result = Obfuscate.run("print('hello')", {
preset = "strong",
seed = 12345,
filename = "hello.lua",
vmSize = "standard",
})
assert(result.ok, result.stage)
print(result.code)
Supported opts
| Field | Type | Default | Meaning |
|---|---|---|---|
preset |
string | strong |
strong, normal, or fast |
seed |
integer | random/fresh | Build seed |
filename |
string | input.lua |
Filename used for parse diagnostics |
flatten |
boolean | preset-based | Override control-flow flattening |
opaque |
boolean | preset-based | Override opaque predicates |
decoys |
integer | preset-based | Override decoy handler count |
schemes |
integer or {string,...} |
preset-based | String obfuscation scheme count/list |
encodings |
integer | size-based | Override alias/encoding diversity |
vmSize |
standard/compact |
standard |
Size/variety profile |
selfmod |
boolean | preset-based | Override self-modifying bytecode layer |
antidebug |
boolean | preset-based | Override anti-debug layer |
integrity |
boolean | preset-based | Override integrity layer |
executor |
boolean | false |
Extra environment-specific checks if supported by the runtime |
gethui |
boolean | false |
Extra environment-specific checks if supported by the runtime |
antiwebhook |
boolean | false |
Extra environment-specific checks if supported by the runtime |
Result schema
{
ok = true|false,
stage = "done" | "input" | "parse" | "scope" | "compile" | ...,
code = "..." or nil,
seed = 12345,
preset = "strong",
errors = { {line=1, col=2, msg="..."}, ... },
stats = {...} or nil,
vmSize = "standard" | "compact",
integrity = boolean,
selfmod = boolean,
antidebug = boolean,
executor = boolean,
gethui = boolean,
antiwebhook = boolean,
settings = {
flatten = boolean,
opaque = boolean,
decoys = integer,
schemes = integer|table,
vmSize = "standard" | "compact",
}
}
result.stats fields
The exact set may expand, but V0.5 may include:
| Field | Type | Meaning |
|---|---|---|
bytes |
integer? | Final artifact bytes if later filled by callers |
plainBytes |
integer? | Unsealed VM text size |
payloadBytes |
integer? | Packed payload size |
protos |
integer | Prototype count |
instructions |
integer | VM instruction count |
opcodes |
integer | Real opcode handler count |
aliases |
integer | Alias/encoding count |
decoys |
integer | Decoy handler count |
selfmodBytes |
integer? | Self-modifying payload bytes |
selfmodBlocks |
integer? | Self-modifying block count |
selfmodProtos |
integer? | Self-modifying prototype count |
antidebugMask |
integer? | Probe mask/summary |
antidebugProbes |
integer? | Anti-debug probe count |
integrityPeriod |
integer? | Periodic integrity check cadence |
integrityCanaryLen |
integer? | Canary size |
integrityProbe |
integer? | Integrity probe selector |
Failure stages
Typical stage values you may see:
inputparsescopecompiledone
Other internal stages may appear in future V0.5 maintenance builds; callers should treat unknown non-done stages as failure.
4) Lua artifact API
Module: src.artifact
Artifact.build(source [, opts]) -> result
Builds a final distributable artifact.
- If
opts.noSeal ~= true, returns a sealed artifact. - If
opts.noSeal == true, returns a direct VM artifact prefixed with the GsXFuscator banner. - Performs a syntax load check on the produced artifact.
local Artifact = require("src.artifact")
local r = Artifact.build("print('hi')", {
preset = "normal",
seed = 20261122,
noSeal = false,
sealCompression = "auto",
sealBlockSize = 4096,
})
assert(r.ok, r.stage)
print(r.deliveryMode, #r.code)
Additional opts consumed by Artifact.build
Everything accepted by Obfuscate.run, plus:
| Field | Type | Default | Meaning |
|---|---|---|---|
noSeal |
boolean | false |
true = direct VM, false = sealed |
sealCompression |
auto/raw/lzss |
auto |
Compression mode passed to Seal.wrap |
sealBlockSize |
integer | 65536 |
Raw bytes per seal block |
Additional result fields
| Field | Type | Meaning |
|---|---|---|
deliveryMode |
"sealed" | "direct-vm" |
Delivery mode of result.code |
On seal or syntax failure:
ok = falsestage = "seal"orstage = "emit"errors[1].msgcontains the reason
5) Lua seal API
Module: src.seal
Public fields
| Field | Meaning |
|---|---|
Seal.MAX_BYTES |
Maximum raw input size accepted by Seal.wrap |
Seal.wrap(text, seed [, opts]) -> sealed_text | nil, err
Wraps direct VM text in the sealed transport.
local Seal = require("src.seal")
local sealed, err = Seal.wrap("print('vm')", 12345, {
compression = "auto",
blockSize = 4096,
})
assert(sealed, err)
opts
| Field | Type | Default | Meaning |
|---|---|---|---|
compression |
auto/raw/lzss |
auto |
Transport compression strategy |
blockSize |
integer | 65536 |
Raw bytes per block |
maxBytes |
integer | Seal.MAX_BYTES |
Maximum accepted input size |
Errors
Examples include:
- invalid block size
- unsupported compression mode
- input exceeds
maxBytes - empty/invalid source text
Seal.isWrapped(text) -> boolean
Heuristic check for the GsXFuscator sealed wrapper.
Important: this is not a cryptographic or authoritative validation function.
6) Verification and auto-fix API
Module: src.verifier
Module: src.autofix (re-exports verifier functions and adds retry orchestration)
6.1 Autofix.verify(source, code [, opts]) -> check
Runs the verification sandbox against source/output.
local Autofix = require("src.autofix")
local check = Autofix.verify("print(1)", built.code, {
maxSteps = 200000,
seconds = 2,
})
print(check.verified, check.ok, check.reason)
Common result fields used by the CLI:
| Field | Type | Meaning |
|---|---|---|
ok |
boolean | Verification passed |
verified |
boolean | Result was conclusive |
reason |
string? | Failure or inconclusive reason |
note |
string? | Extra note |
candidate |
table | Candidate execution/build context |
6.2 Autofix.run(source [, opts]) -> result
Builds and re-tries with safer combinations if verification fails or is inconclusive.
local Autofix = require("src.autofix")
local result = Autofix.run("print('x')", {
engine = require("src.artifact").build,
preset = "strong",
noSeal = false,
})
assert(result.ok, result.stage)
result extends the normal build result with retry metadata.
Common additional fields:
| Field | Type | Meaning |
|---|---|---|
attempts |
array | Attempt log |
verified |
boolean | Whether the final result was verified |
note |
string? | Extra verification note |
reason |
string? | Failure summary |
Each attempts[i] may contain:
indexlabelokmatchreasonstage
6.3 Autofix.isIntegrityError(reason) -> boolean
Returns whether a verification reason should be treated as integrity failure.
6.4 Autofix.DEFAULTS
Table of verifier/autofix default budgets.
At minimum used by the CLI:
Autofix.DEFAULTS.maxStepsAutofix.DEFAULTS.seconds
7) Release metadata API
Module: src.release
Returns a table with branding/runtime constants.
| Field | Type | Meaning |
|---|---|---|
version |
string | Semantic module version, currently 0.5.0 |
displayVersion |
string | Human-facing version, currently V0.5 |
vmFormat |
string | Internal VM format identifier (VM9) |
sealFormat |
string | Internal seal format identifier (SEAL2) |
banner |
string | Banner prepended to direct artifacts |
integrityError |
string | Standard integrity failure text |
Example:
local Release = require("src.release")
print(Release.displayVersion, Release.vmFormat, Release.sealFormat)
8) HTTP build API
The dashboard and proxy function use a JSON HTTP API at:
POST /api/build
Two server-side implementations exist in the repo:
- local/private Python service:
web/service.py - Cloudflare Pages proxy function:
functions/api/build.js
8.1 Request headers
| Header | Required | Meaning |
|---|---|---|
Content-Type: application/json |
yes | Request format |
Content-Length |
yes (Python service) | Body length |
Authorization: Bearer <token> |
required in origin mode / remote proxy target | Service authentication |
Origin |
browser requests | Must be same-origin for the public proxy |
8.2 Request body schema
{
"source": "print('hello')",
"preset": "strong",
"seed": 12345,
"rules": {
"flatten": true,
"opaque": true,
"selfmod": true,
"antidebug": true,
"integrity": true
}
}
Request fields
| Field | Type | Required | Meaning |
|---|---|---|---|
source |
string | yes | Lua source text |
preset |
strong/normal/fast |
no | Build preset; defaults to strong |
seed |
integer or null |
no | Deterministic build seed |
rules |
object | no | Per-rule boolean overrides |
Allowed rules keys:
flattenopaqueselfmodantidebugintegrity
Request limits
| Limit | Value |
|---|---|
| Max HTTP body | 64 MiB (JSON envelope) |
Max source size |
5 MiB UTF-8 |
| Build timeout | No application-level deadline; host limits may apply |
| Max output size | 32 MiB |
| Max parallel builds (Python service) | 2 |
8.3 Success response schema
Illustrative fixture only: numerical stats and code sizes below vary by source, seed, runtime and profile. The following is a schema example, not a recorded output.
{
"status": "OK",
"data": {
"kind": "build",
"ok": true,
"stage": "done",
"seed": 12345,
"preset": "strong",
"errors": [],
"stats": {
"bytes": 123456,
"protos": 249,
"instructions": 1234,
"opcodes": 1552,
"aliases": 96,
"decoys": 640,
"payload": 45678,
"intPeriod": 24,
"smBlocks": 8,
"smProtos": 12,
"adProbes": 54
},
"selfmod": true,
"antidebug": true,
"integrity": true,
"engine": "vm",
"ms": 812
},
"code": "--[[ This, File Protected By GsXFuscator V0.5 ... ]] ..."
}
Top-level success fields
| Field | Type | Meaning |
|---|---|---|
status |
string | OK, FAIL, or CRASH from the compiler frame |
data |
object | Structured result metadata |
code |
string | Generated artifact text; may be empty when streamed internally |
data fields
| Field | Type | Meaning |
|---|---|---|
kind |
string | Always build for successful compile responses |
ok |
boolean | Build success flag |
stage |
string | Final stage (done, parse, seal, etc.) |
seed |
integer | Effective build seed |
preset |
string | Effective preset |
errors |
array | Diagnostic list, each with line, col, msg |
stats |
object or null |
Build statistics |
selfmod |
boolean | Self-mod layer enabled |
antidebug |
boolean | Anti-debug layer enabled |
integrity |
boolean | Integrity layer enabled |
engine |
string | Usually vm; may be compact in explicit compatibility mode |
ms |
integer | Total compile time in milliseconds |
streamed |
boolean? | Present when the artifact was assembled in streamed mode |
bytes |
integer? | Final bytes in streamed mode |
chunks |
integer? | Number of split-build chunks |
fallback |
boolean? | Present if a fallback engine was used |
8.4 Error responses
Both the Python service and the proxy return JSON error bodies:
{ "error": "message text" }
Common status codes:
| Status | Meaning |
|---|---|
400 |
Invalid JSON or invalid build request |
403 |
Access denied / same-origin violation |
404 |
Unknown path |
405 |
Wrong method |
411 |
Missing content length |
413 |
Request too large |
415 |
Wrong content type |
422 |
Build failed, timed out, or exceeded memory budget |
429 |
All build slots busy |
503 |
Upstream/private compiler unavailable |
8.5 Example: calling the local/private API
curl -X POST http://127.0.0.1:8787/api/build \
-H 'Content-Type: application/json' \
-d '{
"source":"print(2+2)",
"preset":"strong",
"rules":{"flatten":true,"opaque":true,"selfmod":true,"antidebug":true,"integrity":true}
}'
8.6 Example: JavaScript fetch
const response = await fetch('/api/build', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
source: "print('hello')",
preset: 'strong',
rules: {
flatten: true,
opaque: true,
selfmod: true,
antidebug: true,
integrity: true,
},
}),
});
const data = await response.json();
9) Compatibility and guarantees
What the public API does guarantee for V0.5:
- programmatic build entry points exist and are documented here
- sealed and direct delivery are both available
- the build seed can be fixed for repeatable output
- the build service accepts JSON requests with the documented fields
What it does not guarantee:
- that internal modules or VM internals remain stable
- cryptographic secrecy of distributed keys/transport
- resistance to a hostile host with full runtime control
- cross-version binary compatibility of generated artifacts
- exact preservation of undocumented fields in stats/result tables
10) Recommended integration patterns
Local automation / CI
Use the CLI or Artifact.build().
Editor plugin / desktop GUI
Use Artifact.build() locally, or the private HTTP build API when you need sandboxed compilation.
Browser dashboard
Use POST /api/build through the provided local or proxied service.
Post-build verification gate
Use CLI --strict-verify or programmatic Autofix.verify() / Autofix.run().
11) Related documents
- CLI.md
- SEAL-FORMAT.md
TESTING.md- GSXFUSCATOR-BRANDING.md
GSX-V05-VM-RUNTIME-CFI.mdVERIFICATION-RUNTIME.md
12) Developer education and complete manuals
12CLI reference
Current GSX V0.7 Zero-Dead revision: see V07-ZERO-DEAD-COMPACT.md. Historic dead-string, synthetic decoder, first-byte banner, alias and decoy descriptions below refer to earlier builds; current production outputs use a live
return setmetatableentry and zero decoy handlers.
Güncel yayın: V0.7. Bu dosyada aşağıda görülebilen V0.5 başlıklı paragraflar tarihsel nottur. Güncel varsayılanlar
strong + compact + sealed;--versionV0.7/VM9/SEAL4/SEAL2 gösterir. Daha geniş handler çeşitliliği için--vm-size standard; davranış eşleştirmesi için--strict-verify. V0.7 derin motor rehberi.
V0.5 (2026-11-21):
Artifact.buildve CLI varsayılan Sealed VM üretir.--no-sealveya programatiknoSeal=trueile harici seal kapatılır. Çıktı dosyalarının başında yalnızcaGsXFuscator V0.5marka başlığı bulunur;CLAX-V*|SEAL2/CLAX-V*|VM9|DIRECTişaretleri artık üretilmez.--versionjeneratörün iç formatlarını (VM9/SEAL2) gösterir.--vm-size compact, varsayılanstandardprofilinden daha küçük ve daha az çeşitlendirilmiş VM üretir.
CLI ve Lua API — ayrıntılı rehber
Çalıştırma ve örnekler
Komutlar proje kökünde çalıştırılır. Lua yorumlayıcısı lua, lua5.4 veya uygun başka bir isim taşıyabilir.
lua v2/obfuscator.lua --help
lua v2/obfuscator.lua hello.lua hello.obf.lua --preset fast --seed 123 --run
lua v2/obfuscator.lua hello.lua hello.vm.lua --preset strong --no-seal --stats
lua v2/obfuscator.lua hello.lua hello.sealed.lua --preset normal --seal --auto-fix
lua v2/obfuscator.lua hello.lua hello.compact.lua --preset strong --vm-size compact --strict-verify
lua v2/obfuscator.lua hello.lua -o hello.lua.protected --preset normal
lua v2/obfuscator.lua hello.lua hello.strict.lua --strict-verify --preset normal
lua v2/obfuscator.lua hello.lua hello.raw.lua --seal --seal-compression raw --seal-block-size 4096
Parametre tablosu
| Seçenek | Varsayılan | Açıklama |
|---|---|---|
| Girdi dosyası | zorunlu | Okunacak Lua kaynak dosyası. |
| Çıktı dosyası | <girdi>.obf.lua |
Oluşturulacak dosya. - stdout'a yazar, raporu stderr'e aktarır. |
--preset strong/normal/fast |
strong |
Koruma/performans dengesi. |
--vm-size standard/compact |
compact |
compact daha az sahte handler ve alias üretir; runtime anti-tamper/anti-debug katmanlarını devre dışı bırakmaz. |
--seed N |
zaman + rastgele durumdan seçilir | 0–4294967295 arasında deterministik derleme tohumu. Kriptografik anahtar değildir. |
--seal |
açık (varsayılan) | LZSS + kayan XOR + base64 dış taşıyıcı; çalışma anında Lua dinamik derleyicisine geçer. |
--no-seal |
kapalı (isteğe bağlı) | Dış taşıyıcıyı atlar; doğrudan VM kodunu verir. |
--direct-vm |
— | --no-seal eşanlamlısı. |
--run |
kapalı | Aynı doğrulama ortamında girdiyi ve çıktıyı çalıştırıp karşılaştırır. |
--auto-fix |
kapalı | Doğrulayıp daha az karmaşık preset'i tekrar dener. |
--max-steps N |
doğrulayıcı ayarı | Sandbox işlem adımı sınırı. |
--seconds N |
doğrulayıcı ayarı | Sandbox CPU süre sınırı. |
--stats |
kapalı | Katman ve boyut istatistiklerini yazdırır. |
--strict-verify |
kapalı | --run'ı açar; kaynak veya çıktı doğrulaması sonuçsuzsa 3 ile çıkar, dosyayı yazmaz. --auto-fix ile de çalışır. |
--seal-compression auto/raw/lzss |
auto |
auto küçük sonucu seçer; raw LZSS aramasını atlar; lzss boyut büyüse de sıkıştırılmış akışı zorlar. |
--seal-block-size N |
65536 |
Seal ham blok boyutu: 1–8388607. Küçük bloklarda paketleme overhead'i artar. |
-o PATH, --out PATH |
— | İkinci pozisyonel çıktı dosyasını geçersiz kılar. |
-h, --help |
— | Yardım metni. |
--version |
— | V0.7, VM9 ve SEAL4/SEAL2 sürüm/format kimliklerini yazdırır. |
Parametreler soldan sağa okunur: hem --no-seal hem --seal yazılırsa sonuncusu geçerlidir. --run ve --auto-fix aynı şey değildir: --run çıktıyı bir kez doğrular; --auto-fix sorunlarda farklı koruma katmanlarıyla tekrar deneyebilir.
Çıkış kodları
| Kod | Anlamı | Örnek neden |
|---|---|---|
0 |
Derleme tamamlandı | Çıktı doğrulanmış olabilir veya doğrulama çalıştırılmamış olabilir. |
1 |
Kullanım veya dosya hatası | Bilinmeyen parametre, bulunmayan kaynak, çıktı yazma hatası. |
2 |
Derleme hatası | Parse, scope, derleyici, seal veya emit söz dizimi hatası. |
3 |
Doğrulama / bütünlük sorunu | Çıktı çalışmıyor veya beklenen davranıştan farklı. |
--auto-fix bir özelliği kapatıp daha sade bir sonuç üretebilir. Bu nedenle koruma seviyesi için logdaki preset ve stats değerleri kontrol edilmelidir. Bilinen sınırlar: host Lua sürümüne göre tip/metatable davranışı, binary işlemler ve Luau uzantıları farklılık gösterebilir.
Doğrudan mod neden önemli?
Seal'i kullanırken dış decoder çalışır ve VM kodunu load/loadstring ile tekrar derler. Host bu fonksiyonları değiştirdiyse, veriyi görebilir. Direct VM bu ekstra aşamayı kaldırır; ancak birincil VM'nin Lua metnini görünür hale getirir.
Kodun kendi içinde dinamik yükleme bulunuyorsa bu ayrı bir konudur; direct VM, kullanıcı kodunun kullanımını otomatik kaldırmaz.
Gömülü Lua API
v2 yolunu modül arama listesine ekleyin:
package.path = "./v2/?.lua;./v2/src/?.lua;" .. package.path
local Obfuscate = require("src.obfuscate")
local Seal = require("src.seal")
local source = [[print("Merhaba", 6 * 7)]]
local result = Obfuscate.run(source, {
preset = "normal",
seed = 12345,
filename = "hello.lua",
})
assert(result.ok, result.stage)
-- Seçenek A: direct VM; runtime ek load() çağrısı yapmaz.
local vmCode = result.code
-- Seçenek B: seal; runtime önce gövdeyi açar, sonra load() çağırır.
local sealedCode = assert(Seal.wrap(result.code, result.seed))
local file = assert(io.open("hello.sealed.lua", "wb"))
assert(file:write(sealedCode))
assert(file:close())
Not: Obfuscate.run her zaman VM kaynak kodunu döndürür. Seal işlemi yalnız Seal.wrap ile veya CLI varsayılan akışında uygulanır. Bir uygulamanın Lua API kullanması CLI'nin test ve dosya yazma kontrollerini otomatik olarak çalıştırmaz.
Seal API
Seal.wrap(text, seed, opts) metni bir Lua dosyasına dönüştürür. opts.blockSize pozitif tamsayı ve 8388608'den küçük olmalıdır; varsayılan blok 65536 ham bayttır. opts.maxBytes en büyük ham yük boyutunu belirler; varsayılan Seal.MAX_BYTES = 33554432. Limitin aşılması durumunda nil, error_message döner. Art arda aynı metin, seed ve seçenekler ile aynı çıktının üretilmesi hedeflenir.
Seal.isWrapped(text) yalnız dış banner ve beklenen taşıyıcı sentineli için sezgisel bir testtir; güvenli doğrulama işlevi değildir.
Geliştirme / CI tavsiyeleri
Testlerden önce proje kökünde python v2/tests/run.py --module 12 komutunu deneyin. Bu komutun standart çalıştırıcısı lupa gerektirir. Alternatif olarak host Lua yorumlayıcınızdan v2/tests/module12.lua dosyasını çalıştırabilirsiniz; modül import yolu doğru olmalıdır. Ek uçtan uca testler için TESTING.md sayfasına bakın.
Sertleştirilmiş programatik API: tek artifact modülü
package.path = "./v2/?.lua;./v2/src/?.lua;" .. package.path
local Artifact = require("src.artifact")
local r = Artifact.build('print("Hello from VM")', {
preset = "normal", seed = 20261121,
noSeal = false, sealCompression = "auto", sealBlockSize = 4096,
})
assert(r.ok, r.stage)
print(r.deliveryMode, r.seed, #r.code)
Artifact.build() derleme ve üretilmiş metnin sözdizimini kontrol eder; davranış eşdeğerliğini çalıştırmaz. Bunun için CLI --run, kesin doğrulama gerektiren otomasyonda ise --strict-verify kullanılır. Browser dashboard CLI'nin tüm yeni bayraklarını sunmaz.
Seed çeşitliliği ve deterministik build
src/entropy.lua, /dev/urandom varsa 4 bayt alır. Host bu kaynağı sunmuyorsa süreç saati, math.random ve iç sayaçla best-effort fallback kullanır. Fallback kriptografik olarak güvenli değildir. Aynı kaynak/seed/host ile aynı çıktı üretilmesi hedeflenir; karşılaştırmalı testte farklı seed'lerin VM byte çıktılarını değiştirdiği doğrulanır. Seed gizli anahtar değildir.
Kısmi çıktıyı önleme
CLI önce hedefin yanında geçici dosya yazar, ardından close() başarılıysa os.rename() uygular. Hedef zaten varken rename'e izin vermeyen Windows dosya sistemlerinde, eski dosya silinmek yerine hata döner. Bu, her sistemde tam atomiklik/durability garantisi değildir.
13Web API and deployment
Dashboard, JSON Build API, Local Server and Remote Deployment
V0.5 components: web/v3template.html, web/build12.py, web/v2driver.lua, web/build-worker.js, web/service.py, web/compile_job.py, functions/api/build.js.
1. Topology
Browser/dashboard (Graphite Light/Night)
├─ local browser runtime / worker using bundled Lua VM and web/v2driver.lua
└─ optional POST /api/build
├─ Python local/private service
│ └─ isolated compile_job.py subprocess
└─ Cloudflare Pages function (authenticated proxy)
└─ HTTPS private Python origin
The browser's own compiler pipeline and Python origin are two deployment paths. They need not expose identical build flags. The browser UI automatically uses its strong profile; the CLI exposes more options. The website does not promise a general-purpose sandbox for untrusted Lua code.
2. Build the standalone dashboard
From the project root:
python web/build12.py
This assembles web/v3template.html, settings CSS/JS, a bundled worker, a Wasm Lua runtime, modules and images into index.html and public/index.html. The build is self-contained for the main app, though optional display fonts use a network request and have a system fallback. The file output can be large because a Lua runtime and modules are embedded.
The V0.5 interface uses the supplied GSX logo, Graphite colors, Light/Night mode and a Discord Community link. The old History and file-to-link conversion features are removed.
3. Local Python service
python web/service.py --port 8787 --open
- Local mode binds to loopback by default (
127.0.0.1). - Dashboard root routes
/and/index.htmlservepublic/index.html. POST /api/buildcompiles source by launching a Python worker process.- Unknown paths return
404(history and sharing endpoints do not exist). - Origin/Host checks reject cross-origin/invalid local access.
The service requires the Python runtime dependencies listed by web/requirements.txt, including the Lua runtime binding used by compile_job.py. If dependencies are missing, the web API cannot complete builds even if the static dashboard page loads.
4. Request schema
POST /api/build expects JSON, Content-Type: application/json:
{
"source": "print('hello')",
"preset": "strong",
"seed": 12345,
"rules": {
"flatten": true,
"opaque": true,
"selfmod": true,
"antidebug": true,
"integrity": true
}
}
Top-level request fields are only source, preset, seed, rules. Other keys are rejected by Python validation. rules is an object whose allowed keys are those five names and whose values must be booleans; this is a private service contract, not the browser's unlocked public settings. The local server validates syntax/types; the CLI has additional flags not accepted by the HTTP API.
Limits in current implementation
| Constraint | Value | Enforced by |
|---|---|---|
| HTTP request body | 64 MiB (JSON envelope) | web/service.py, proxy |
| Source field UTF-8 length | 5 MiB | web/service.py |
| Build subprocess wall timeout | Not imposed by application | web/service.py |
| Build return artifact | 32 MiB | web/compile_job.py |
| Concurrent build slots | 2 | web/service.py |
| Total connections | 24 | web/service.py |
Some limits are implementation constants, not contractual service-level guarantees. Different hosting layers can impose smaller limits or stricter timeouts.
5. Response contract and error interpretation
A completed HTTP response with status 200 may carry a JSON object containing:
{
"status": "OK",
"data": {
"kind": "build",
"ok": true,
"stage": "done",
"seed": 12345,
"preset": "strong",
"errors": [],
"stats": {"bytes": 10000},
"selfmod": true,
"antidebug": true,
"integrity": true,
"engine": "vm",
"ms": 250
},
"code": "--[[ This, File Protected By GsXFuscator V0.5 ... ]] ..."
}
This is illustrative, not a fixed-size code or stats fixture. The compiler driver returns OK, FAIL or CRASH in its own framed response, and the HTTP wrapper returns a top-level status plus data/code. Client code should check both the HTTP status and the data.ok/status fields, not treat all HTTP 200 responses as valid builds.
web/v2driver.lua internally frames values as status\1jsonLength\1json\1code where JSON values are percent-encoded to maintain its simple ASCII frame convention. The Python worker decode_fields reverses that encoding before emitting the final JSON. Do not send the internal frame directly to public HTTP clients.
Common error codes
| HTTP status | Meaning |
|---|---|
400 |
Invalid source, JSON, seed, preset or rules schema |
403 |
Origin, Host or authorization denied |
404 |
Unknown route |
405 |
Method not allowed |
411 |
Python service requires Content-Length |
413 |
Body too large |
415 |
Wrong Content-Type |
422 |
Failed or memory-limited compiler process |
429 |
Both build slots occupied |
503 |
Remote proxy not configured or private compiler unavailable |
Example error body: { "error": "The build request exceeds 64 MiB." }. Never pass raw traceback paths or secrets back to untrusted clients.
6. Authenticated private origin
Run an origin server only with explicit credentials and controlled hosting:
# Supply a private value of at least 32 characters.
export GSX_BUILD_TOKEN='replace-with-a-random-secret-token-at-least-32-chars'
python web/service.py --origin --host 127.0.0.1 --port 8787
The upstream should be placed behind HTTPS (reverse proxy); the Cloudflare function enforces an HTTPS upstream URL. Configure deployment secrets GSX_BUILD_ORIGIN (upstream base URL) and GSX_BUILD_TOKEN (bearer secret). Legacy CLAX_BUILD_ORIGIN/CLAX_BUILD_TOKEN are accepted as migration fallbacks.
Security requirements
- Never put the bearer token in static HTML or browser JS.
- Do not expose the origin HTTP listener directly to the open internet without TLS and an explicit access policy.
- The function checks same-origin browser requests, request Content-Type and body size.
- The Python compiler subprocess uses restricted environment variables and output capture; this is not proof of full OS-level sandbox isolation.
- Restrict outgoing network access and process permissions in the host deployment.
- Do not log uploaded source or returned artifacts.
- Use request throttling, quotas and abuse monitoring in production beyond the 2-slot semaphore.
7. JavaScript request example
const body = {
source: "print(40 + 2)",
preset: "strong",
seed: 12345,
rules: { flatten: true, opaque: true, selfmod: true,
antidebug: true, integrity: true }
};
const response = await fetch("/api/build", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
});
const message = await response.json();
if (!response.ok) throw new Error(message.error || `HTTP ${response.status}`);
if (message.status !== "OK" || message.data?.ok !== true) {
const detail = message.data?.errors?.[0]?.msg || "Build failed";
throw new Error(detail);
}
console.log(message.data.seed, message.code.length);
The ?. operator here runs in the browser/Node JavaScript environment; it is not Lua syntax.
8. UI accessibility and offline behavior
- Graphite is fixed; Light/Night mode is a retained user preference.
- Decorative Elegant font applies to headings; body/documentation uses readable system fonts with browser zoom support.
prefers-reduced-motionand low-data/low-memory hints reduce nonessential animations where available.- The Discord Community card uses an embedded image and the same Discord invitation URL.
- In-page documentation is compiled into the dashboard and can be read without a live API server.
9. Deployment test checklist
- [ ]
python web/build12.pycompletes and leaves no placeholder strings. - [ ] JavaScript bundles and proxy parse without syntax errors.
- [ ] Static root loads without JS errors on desktop and mobile widths.
- [ ] Light and Night modes render legible labels and forms.
- [ ] Unknown routes return
404, not a sensitive file listing. - [ ] CORS/Origin/Host and bearer-token tests reject disallowed requests.
- [ ] Request size, source limit and concurrency limit are enforced.
- [ ] Successful compiler response contains
status,dataandcode. - [ ] Compiler errors preserve useful diagnostics without leaking traceback paths.
- [ ] The private origin is reachable only via the intended HTTPS proxy.
Related: API, Troubleshooting, Full docs.
14Examples and recipes
Practical Examples and Integration Recipes
These recipes are copyable, but always execute the examples in a controlled environment first. The API is version V0.5; internal VM structures are not a stable plugin surface.
Recipe 1 — Strong sealed file from CLI
lua v2/obfuscator.lua input.lua protected.lua --preset strong --seal --strict-verify --stats
- Sealed output is the default, so
--sealis redundant but explicit. --strict-verifyuses sandbox comparison and refuses to write when inconclusive.--statsprints emitted counts and sizes.- Run
lua protected.luain the actual target interpreter as well.
Recipe 2 — Direct VM (no outer dynamic load)
lua v2/obfuscator.lua input.lua protected-direct.lua --preset strong --no-seal --strict-verify
This skips the external seal wrapper, not the internal VM bytecode decoder. The direct VM code is visible at rest; choose based on your threat model.
Recipe 3 — Fixed seed for regression repro
lua v2/obfuscator.lua input.lua a.lua --preset strong --seed 707
lua v2/obfuscator.lua input.lua b.lua --preset strong --seed 707
Use identical files/options/runtime to reproduce failures. Do not use the seed as an access credential or key.
Recipe 4 — Build from Lua, not a shell
Actual example source: ../examples/custom_builder.lua.
package.path = './v2/?.lua;./v2/src/?.lua;' .. package.path
local Artifact = require('src.artifact')
local result = Artifact.build('return 40+2', {
preset='strong', vmSize='standard', noSeal=false,
sealCompression='auto', seed=12345
})
if not result.ok then
for _,e in ipairs(result.errors or {}) do
io.stderr:write(tostring(e.msg), '\n')
end
error('build failed')
end
local f = assert(io.open('answer.obf.lua','wb'))
assert(f:write(result.code))
assert(f:close())
Artifact.build checks emitted Lua syntax but is not a conclusive behavior equivalence test. Use CLI verification or a separate regression harness.
Recipe 5 — Inspect tokens and the normalized AST
Actual example source: ../examples/inspect_ast.lua.
lua v2/examples/inspect_ast.lua input.lua
Internals:
local Lexer, Parser, Ast = require('src.lexer'), require('src.parser'), require('src.ast')
local tokens, lexErrors = Lexer.lex('local x = 2')
local tree, parseErrors = Parser.parse('local x = 2')
assert(#lexErrors==0 and #parseErrors==0)
local root = Ast.normalize(tree)
print(Ast.count(root).nodes)
Use the parser/AST interfaces for source inspection; do not rename identifiers using gsub.
Recipe 6 — Learn how to compile your own toy VM
printf 'return (2 + 3) * 4\n' > arithmetic.lua
lua v2/examples/toy_vm_obfuscator.lua arithmetic.lua arithmetic.vm.lua 99
Open arithmetic.vm.lua: the custom numeric opcode mapping and all handlers are visible so you can learn how every instruction executes. Test from the repo with:
python v2/examples/test_toy_vm.py
The toy example supports only its documented arithmetic subset. A full Lua program with functions, globals, strings or tables will be rejected rather than silently miscompiled. Follow Build your own to extend the grammar.
Recipe 7 — Seal an already-built VM
local Obfuscate, Seal = require('src.obfuscate'), require('src.seal')
local vm = Obfuscate.run('print("ok")', {preset='normal', seed=12345})
assert(vm.ok, vm.stage)
local sealed, err = Seal.wrap(vm.code, vm.seed,
{compression='auto', blockSize=4096})
assert(sealed, err)
Do not try to seal an arbitrary text artifact without understanding its runtime compatibility; Seal.wrap packages Lua source text and reconstructs it via dynamic load/loadstring.
Recipe 8 — Use a build server
Start local service (after installing required Python packages):
python web/service.py --port 8787
Request:
curl -sS http://127.0.0.1:8787/api/build \
-H 'Content-Type: application/json' \
--data '{"source":"print(42)","preset":"strong"}'
Check the HTTP status and response JSON fields status, data.ok, data.errors; never assume every HTTP 200 means compilation succeeded. See Web API.
Recipe 9 — Compare original vs protected behavior
For pure return-based examples:
local original = assert(loadfile('original.lua'))
local protected = assert(loadfile('protected.lua'))
local a, b = original(), protected()
assert(a == b, 'mismatch')
For real software, compare all return values and observable side effects, not a single scalar. Tests that involve nondeterministic I/O or network calls need injected deterministic host interfaces.
Recipe 10 — Add a custom AST transform safely
Add src/mypass.lua in your fork. It should accept an AST and return the same structure or an explicit error. Only use a proven-preserving transformation.
local Ast = require('src.ast')
local M = {}
function M.run(ast,opts)
assert(Ast.isNode(ast))
-- Insert a well-specified transform here.
-- Do not alter bindings or node ordering accidentally.
assert(#Ast.validate(ast)==0)
return ast
end
return M
Run this after normalization, preserve Scope binding metadata and add a unit test before inserting it into src/obfuscate.lua.
Recipe 11 — Controlled compatibility build
Choose a representative test source with closures, tables, arithmetic, function calls and error behavior. Compile with a fixed seed, then run both original and output on the exact target runtime. Compare results. Record whether Lua 5.1, 5.2, 5.3, 5.4 and Luau were actually executed; do not count a parser syntax check as execution validation.
Recipe 12 — Fail on uncertainty in CI
lua v2/obfuscator.lua input.lua release.lua --preset strong --strict-verify
Exit code 3 means verification failed or was inconclusive. Your CI should propagate it rather than upload the possibly invalid output. A green local check still cannot prove all runtime environments behave identically.
Recipe 13 — Performance profile before and after
python v2/tests/benchmark_matrix.py --lua lua5.4 --runs 5 --json benchmark.json
Record input size, output size, compiler time, cold-start, steady-state and peak memory. Beware interpreting runtime differences on a single sample as universal improvements.
Recipe 14 — Version metadata and branding
local Release = require('src.release')
print(Release.version, Release.displayVersion, Release.vmFormat, Release.sealFormat)
The V0.5 GsXFuscator brand/banner and Discord URL are public branding, not a cryptographic signature. Changing these strings affects appearance but not the VM's semantics.
Recipe 15 — Build reproducibility and safe publishing
Store the source hash, compiler version, build seed and options in a build manifest; do not include secrets in the obfuscated script. Add a final zipfile.testzip() integrity check, inspect archive members and label files as tested/unverified based on the real test matrix.
Recommended next steps
Full documentation hub · Build from scratch · Compiler/AST · VM/bytecode · Security
15Security and threat model
Runtime Integrity, Anti-Debug and the Actual Security Boundary
This is a security engineering reference for GsXFuscator V0.5. It describes defensive detection, its observable limits, and how to test without inventing guarantees.
1. Assets and attacker capabilities
Assets may include source structure, bytecode layout, runtime state, and resistance to simple patching. Attackers may have varying control:
| Level | Typical capabilities | What defensive controls can reasonably do |
|---|---|---|
| Source file observer | Inspect, edit, grep, diff distributed Lua | Obfuscate syntax, obscure names, detect some edits |
| Script runtime observer | Install hooks, inspect globals, step through Lua | Detect some changes and runtime anomalies |
| Full host controller | Replace interpreter, patch/debug memory, alter calls | No reliable absolute protection from inside the same Lua process |
A complete threat model also asks what the protected code is allowed to do. Obfuscation never substitutes for server-side authorization, key custody or safe sandboxing.
2. Distinguish the layers
| Layer | Mechanism | What it detects/resists | What it does not prove |
|---|---|---|---|
| Seal | Per-block FNV + Adler, lengths and boundaries | Accidental or naive payload modification | Secret-key authentication |
| Bytecode container | Checksums, derived SipHash trailer, bounds | Many malformed/corrupt blobs | Secrecy against full runtime control |
| VM handler references | Independent pinning and runtime cross-checks | Selected handler replacement/mutation | Immutability of Lua tables |
| Prototypes | Total-length and current-window validation | Some metadata/cache alteration | All possible decoder attacks |
| Control-flow checks | pc, operand, branch shape validation |
Invalid state/jump tampering | Prevention of semantic devirtualization |
| Anti-debug probes | debug.gethook/behavioral checks in supported contexts |
Selected hooks/altered standard functions | Detecting every debugger |
CRC, FNV and Adler are not MACs
FNV-1a and Adler-32 are checksums. A capable editor can change both the protected data and a checksum constant. An unforgeable authorization decision requires a trust boundary outside the attacker's control. Even a keyed MAC loses that property if its key and trusted verification logic are fully available to the same attacker in the client process.
Metatables are not immutable storage
__newindex is not invoked for an ordinary assignment to an existing table field. rawset bypasses it. A protected __metatable field hides the metatable from ordinary getmetatable but does not make the original table immutable. Reference comparisons help detect changes; they are not the same as preventing changes. Some Luau environments offer table.freeze, but standard Lua does not.
3. Runtime checkpoints
For meaningful fail-closed behavior, a protection should check the relevant state before using it. A check only every 1,000 dispatches may never execute in a two-instruction program. Conversely, checking every handler at every step can impose substantial overhead.
Recommended checkpoints:
- Startup: shape and expected metadata/handler references before first dispatch.
- Dispatch: validate current instruction and program counter.
- Branch: validate next target and conditional operand shape.
- Periodic: audit a rotating portion of the handler/prototype inventory.
- Decode: verify block length, bounds and checksum before admitting decoded instructions.
- Termination: leave the runtime in a consistent state; no fallback to unchecked behavior after failure.
The current emitted VM contains a combination of such checks. The actual strength depends on whether the tested attack reaches a guarded path; use mutation tests, not code counts.
4. Anti-debug philosophy
A runtime check is a signal: active hook or unexpected standard function behavior may be caused by debugging, profiling, instrumentation, or a legitimate host integration. The objective is to report/stop under a known policy while minimizing false positives.
Do
- Capture expected references before untrusted code can replace them when practical.
- Query only supported debug APIs, inside guarded calls when they can be missing.
- Avoid mutating the host's hook state merely to test it.
- Make failure behavior predictable and testable.
- Test with and without the
debuglibrary and with benign profiling hooks. - Document potential false alarms in embedded/Roblox/luau-like hosts.
Avoid
- Claiming that
debug.gethooksees every instrumentation technique. - Setting a hook and failing to restore pre-existing host hooks.
- Infinite loops, destructive behavior or arbitrary external calls as a reaction to a suspected debugger.
- Relying on secret static tables distributed alongside the protected script.
5. How to write controlled live tests
Build a known fixture under a fixed seed. In a separate, authorized test runtime, introduce one mutation and assert whether the expected integrity error occurs.
Example classes:
| Mutation | Expected defensive outcome |
|---|---|
| Replace one live handler function | Detect before or at handler execution |
| Replace both live and backup references | Independent anchor/check catches tested mutation |
Add unexpected table entries via rawset |
Shape/count check catches tested mutation |
| Remove or alter a prototype's expected length | Prototype metadata check catches tested mutation |
| Use a zero or fractional program counter | Runtime rejects invalid PC |
| Redirect a jump to an out-of-bounds target | Branch target validation rejects |
| Corrupt a sealed chunk checksum or length | Seal decoder aborts |
| Install a Lua hook during execution | Selected hook probes report/stop when reachable |
Run without a debug library |
Legitimate supported clean execution should continue |
Record both detection and missed cases. Test with a clean control and repeat across seeds. A test that injects a corrupt field before the decoder gets there is not equivalent to arbitrary live code mutation in a hostile interpreter.
6. What runtime dumping can reveal
The external sealed wrapper reconstructs an obfuscated VM Lua script and passes it through load/loadstring. Tracing that call can reveal the inner VM script. That is not necessarily the original input source. A direct VM artifact omits the outer dynamic load stage but exposes the VM script statically. With access to interpreter memory and hooks, an analyst may still inspect execution state.
Devirtualization would additionally reconstruct program semantics from virtual instructions, constant pools and handler behavior. A static source-recovery tool failing once is not proof the VM is undevirtualizable.
7. Build-time and runtime secrets
- Treat build seed and emitted key material as recoverable, not secret.
- Do not ship cloud credentials, license authority or critical authorization decisions to the Lua output.
- Use a server-side entitlement API when you need trustworthy enforcement.
- If you add actual cryptographic authentication, define key provisioning, trust roots, rotation and verification outside an attacker-controlled client.
8. Review checklist for every new defense
- Write the exact tamper class the check is expected to detect.
- Specify the first instruction at which detection is guaranteed in the tested host.
- Add a clean non-attack test and a targeted mutation test.
- Test both handler mutation and independent reference mutation if relevant.
- Measure added cold-start/steady-state overhead.
- Test optional/missing debug APIs; distinguish unsupported API from attack.
- Document untested classes and host assumptions.
- Avoid silent fallback to a weaker mode on unverified output.
9. Scope of security claims
This project can make static inspection inconvenient, reject malformed payloads, and detect many selected runtime changes. It cannot establish confidential execution or complete anti-debug resistance when the attacker controls the interpreter. Describe security as coverage of explicitly tested alterations, not a universal numeric score.
Related: VM/bytecode, Testing, SEAL-FORMAT, SECURITY.
16Testing and benchmarking
Testing, Fuzzing, Differential Verification and Benchmarking
Goal: make each compiler transformation measurable and refutable. “It compiled” does not mean “it preserved Lua behavior”, and a large handler count does not mean an attacker cannot analyze it.
1. Types of tests
| Test layer | What it validates | Suggested fixture |
|---|---|---|
| Lexer unit test | tokens, escapes, positions, errors | long strings, \xFF, comments, malformed literals |
| Parser unit test | tree shape, precedence, recovery | 2^3^2, chained calls, invalid end |
| AST contract | every node type and child range valid | all statement forms |
| Scope/rename | binding identity, shadowing, upvalues | nested closure capture |
| Compiler unit test | instructions + constants, bounds | functions with varargs/multiple returns |
| Bytecode roundtrip | pack/unpack exact byte values | random constants, prototype graph |
| VM trace | expected registers and pc at each step | one program per opcode family |
| Differential end-to-end | original vs protected behavior | ordinary scripts and metamethod cases |
| Mutation/fault injection | corrupt data rejected | header, opcode, operand, jump, handler, prototype |
| Browser integration | file upload/build/download, DOM errors | Chromium desktop/mobile |
| Performance | build/cold/steady/peak memory | small/large representative inputs |
2. Existing repository test entry points
Run from the repository root. Replace lua or lua5.4 with your installed interpreter's binary.
lua v2/tests/module1.lua # lexer/parser
lua v2/tests/module8.lua # VM
lua v2/tests/module9.lua # bytecode
lua v2/tests/module10.lua # selfmod
lua v2/tests/module11.lua # anti-debug
lua v2/tests/module12.lua # end-to-end/integrity
The repository also includes v2/tests/run_native_matrix.py, v2/tests/transport_regression.py, v2/tests/v05_prototype_integrity_lab.lua, v2/tests/gsx_v05_runtime_guard_lab.lua and others. Some Python harnesses require optional third-party packages such as lupa; that requirement is distinct from the standalone native Lua tests.
Educational example test
python v2/examples/test_toy_vm.py
The test uses LUA_BIN when provided, otherwise attempts the lua / lua5.4 / lua5.3 interpreter on your PATH (with the bundled test environment's local runner as a final fallback). It compiles six supported expressions and rejects four unsupported inputs; it does not validate full language coverage.
3. Differential testing
Run original and protected code in equivalent environments with the same inputs. Compare:
- returned values, including
niland return count; - emitted stdout/stderr (if relevant);
- modifications to globals and external tables;
- called host functions, with call order and argument values;
- errors, exception timing and
pcallresults; - relevant metamethod invocations.
A simple single-return example:
local original = assert(loadfile('sample.lua'))
local protected = assert(loadfile('sample.obf.lua'))
assert(original() == protected())
That is not sufficient for arbitrary code. Programs may have side effects, multiple returns, nondeterminism, clocks and external I/O. The project verifier (src.verifier, exposed via Autofix.verify) provides a restricted sandbox comparison, but its result may be inconclusive. --strict-verify rejects an inconclusive build in the CLI.
4. Essential semantic regression matrix
| Category | Minimum cases |
|---|---|
| Names | shadowing; global/reference alias; _G/_ENV |
| Closures | nested upvalues, mutation, loop capture, recursion |
| Parameters | default-ish nil values, varargs, multiple returns, tail calls |
| Tables | array/hash keys, metatables, __index, __newindex, __len |
| Arithmetic | integer/float subtype, negatives, zero, %, //, overflow |
| Boolean logic | truthiness, short circuit, and/or returning operands |
| Strings | empty, long bracket, NUL, high bytes, escapes |
| Control flow | if/elseif, loops, break, goto, nested returns |
| Errors | pcall, xpcall, bad operands, error before side effects |
| Environments | Lua 5.1 getfenv versus 5.2+ _ENV, host overrides |
| Serialization | short/long varints, large prototypes, EOF bounds |
| Compatibility | all supported Lua versions and target Luau host |
5. Determinism and seed diversity
Same source, version, seed and options should produce the same artifact where the tool promises reproducibility. Different seeds should produce distinct mapping/layouts, but distinct bytes alone do not prove security. Snapshot output hashes for a fixed seed to catch accidental regressions; regenerate those baselines only after reviewing semantic changes.
lua v2/obfuscator.lua sample.lua a.lua --seed 123 --preset strong
lua v2/obfuscator.lua sample.lua b.lua --seed 123 --preset strong
# Compare a.lua and b.lua (sha256sum/cmp on POSIX).
6. Controlled mutation tests
Create one mutation at a time and hold all other conditions fixed.
| Payload/VM mutation | Expected behavior |
|---|---|
| Truncate bytecode body/header | Explicit rejection before use |
| Alter declared plaintext length | Length/checksum rejection |
| Change a fixed opcode ID to unknown | Unknown opcode rejection |
| Set program counter to 0, fraction or too-large value | CFI rejection |
| Replace one handler (and/or its backup) | Expected reference check catches tested mutation |
Add extra handler/prototype via rawset |
Shape/count check catches tested mutation |
Tamper lazy-decoded prototype's total |
Prototype validation rejects |
| Alter a sealed chunk FNV or Adler | Seal decoder rejects |
Always run a clean control. A mutation test is successful when the defense behaves as specified, not when “some error happened.” Record the error category, detection point, runtime version and seed.
7. Property-based and fuzz testing
Generate bounded ASTs rather than unstructured random strings when testing semantics. Start with arithmetic and booleans, then tables/calls/closures. Set caps on expression depth, token count, runtime steps and memory; record a seed for replay. Classify failures into:
- parse failure (supported versus unsupported syntax);
- syntax-incorrect emitted Lua;
- output mismatch;
- timeout/hang;
- integrity rejection on clean input;
- targeted mutation not detected.
Shrink failing cases to the smallest AST and store as regression vectors. Never silently exclude a failure because it reproduces only for one seed.
8. Performance benchmark methodology
Measure five or more warm/cold repetitions of representative sources, on a fixed runtime/hardware with version information. Compare medians and the spread (range or p95), and record peak memory when the host exposes it. Do not combine source compile time with program execution time unless explicitly labeled.
| Metric | Definition | Why it matters |
|---|---|---|
| Build duration | source → generated file | UX / CI cost |
| Cold start | launch process → first useful result | loader/VM init cost |
| Steady state | repetitive work after initialization | dispatch overhead |
| File bytes | compressed and expanded output sizes | downloads/storage |
| Peak RSS | OS-observed max resident memory | low-memory targets |
| Runtime correctness | output equivalence | speed is irrelevant if wrong |
Existing benchmark tools include v2/tests/benchmark_runtime.py, benchmark_matrix.py and benchmark_seal.lua. Benchmarks must be rerun after major changes and are not portable across hosts without new measurements.
Example benchmark invocation
python v2/tests/benchmark_matrix.py --lua lua5.4 --runs 5 --json results.json
Read the tool's --help and the script itself before supplying platform-specific flags. Results from one short sample cannot justify a universal “x% faster” statement.
9. Release acceptance checklist
- [ ] Parser and AST tests pass for supported grammar.
- [ ] Lexical scope and closure tests pass.
- [ ] Instruction/schema, bytecode roundtrip and bounds checks pass.
- [ ] Direct VM and sealed modes match the reference behavior.
- [ ] Negative/mutation fixtures fail closed for targeted classes.
- [ ] No unexpected failures with a clean environment.
- [ ]
--strict-verifyprotects outputs against inconclusive local checks. - [ ] Web UI passes keyboard/navigation and mobile tests if changed.
- [ ] Benchmark results include machine/runtime information and sample sizes.
- [ ] Required Lua versions and the actual Luau host are tested or marked unverified.
- [ ] Documentation and source options agree; no obsolete claims remain.
- [ ] ZIP integrity checked and its file list inspected.
Related: Security threat model, Build from scratch, API.
17Troubleshooting and FAQ
Troubleshooting, Compatibility Matrix and Frequently Asked Questions
Use this document when a build fails, a VM file behaves differently, or the dashboard cannot compile. Prefer a minimal reproducible example, fixed seed and exact runtime version over a vague “sometimes broken” report.
1. First diagnostic steps
- Record the GsXFuscator version (
lua v2/obfuscator.lua --version). - Record Lua interpreter/version and operating system.
- Minimize the source while keeping the failure.
- Retry with
--seed 12345to stabilize randomized output. - Save exact CLI flags and error stage.
- Run the original source in the target interpreter independently.
- Run the generated direct and sealed outputs separately to isolate the transport layer.
- Capture stdout, stderr, exit status, and any global side effects.
2. Build issues
| Symptom | Likely cause | Diagnostic action |
|---|---|---|
missing input file |
No positional source | Use CLI input path or -h |
unknown preset |
Typo or wrong value | Choose strong, normal, fast |
| Parse error line/column | Unsupported/malformed syntax | Run inspect_ast.lua; reduce source |
| Scope error | Invalid declaration/label/upvalue | Inspect shadowing, local function declarations, goto |
| Compile error | Unsupported expression or internal invariant | Preserve minimal input and version for bug report |
verification inconclusive |
Sandbox cannot conclusively compare | Test target runtime; --strict-verify avoids writing uncertain output |
| Output does not load | Syntax emission problem | Test loadfile/luac -p; preserve seed |
| Seal failure | Size/compression/encoding limit | Inspect Seal.MAX_BYTES, block size and mode |
| Generated artifact very large | Alias/decoy/VM fixed cost | Benchmark; --vm-size compact reduces redundancy at protection tradeoff |
3. Runtime problems
| Symptom | What to inspect |
|---|---|
integrity check failed |
Was output edited, truncated, copied with encoding changes, or run in an instrumented environment? |
| Works direct, fails sealed | Outer loader, dynamic load, seal data, environment and limits |
| Works sealed, fails direct | VM source exposure does not change language semantics; compare exact generated seeds and runtime context |
| Works on Lua 5.4, not 5.1 | _ENV, integer/bitwise syntax, //, table.unpack, load/loadstring, APIs |
| Debug library missing | Guard should best-effort tolerate clean hosts lacking debug, but test actual target |
| Metatable behavior differs | Check __index, __newindex, arithmetic metamethods and error ordering |
| Global assignments differ | Test _G/_ENV and any embedding host globals |
| Program slow at startup | VM function definitions, bytecode decode, seal transport; measure cold start separately |
| “Random failures” | Fix seed; record host hooks, globals and source properties |
4. Browser and HTTP issues
| Symptom | Diagnosis |
|---|---|
| Dashboard shows but build fails | Static page works; compiler runtime or private origin may be unavailable |
503 from /api/build |
GSX_BUILD_ORIGIN / GSX_BUILD_TOKEN not configured or origin unavailable |
403 |
Same-origin, local Host or bearer token check failed |
429 |
2 active build slots already used |
422 |
Build failure, compiler process error or resource timeout |
413 |
64 MiB request body or 5 MiB source limit |
| Font/style unreadable | Use Large reading text and browser zoom; verify Light/Night contrast |
| Preferences lost | Storage disabled/private browsing or cleared localStorage |
| API not reachable | Check web/service.py and required Python packages |
5. Frequently asked questions
Q: Can users make their own obfuscator from these docs?
Yes. The independent toy VM teaches the complete mechanism for a deliberately small grammar; the compiler, AST, ISA and extension guides explain how to expand it. Full Lua requires substantially more semantic and compatibility engineering.
Q: Is the packed payload encrypted with an unextractable secret?
No. Distributed code contains enough logic and material to run, and the host can inspect its runtime. Treat these methods as obfuscation/corruption detection, not secret-key custody.
Q: Does more decoy code always make protection stronger?
No. It can increase size and analysis noise, but a devirtualizer may ignore unused branches. Benchmark and run controlled analysis rather than scoring by function count.
Q: Can rawset be fully blocked with __newindex?
No. Lua metamethods can be bypassed with raw table operations. The runtime may detect some alterations using independent integrity checks, but the table itself is not absolutely immutable.
Q: Should I disable anti-debug if a host uses instrumentation?
First identify whether the host hook is legitimate and whether checks produce false positives. Document policy choices and test a clean/monitored pair. The browser's locked policy differs from CLI options.
Q: Why is --no-seal an option?
The sealed loader uses a dynamic load call that can be observed. Direct VM avoids that particular extra loader call but reveals VM source statically. It is a tradeoff, not universal protection.
Q: Does “verified” mean the script works on every platform?
No. The verifier compares behavior within its own sandbox and budgets; external APIs, concurrency and host differences need target-specific tests.
Q: Why are the parser and VM APIs labeled internal?
Their data structures are coupled to emission and may change as the compiler improves. The supported integration surface is Artifact.build, Obfuscate.run and the documented CLI/HTTP entry points.
Q: Can I bundle this into a site without a private build API?
The project includes a standalone browser build path. The private API is optional and has separate hosting, time and size constraints.
Q: What about the Discord address or output signature?
The V0.5 banner identifies GsXFuscator, links the same Discord invite and includes a Unicode ASCII comment. These are branding strings, not cryptographic signatures.
6. What to include in a useful bug report
GsXFuscator version:
Lua runtime and version:
Platform/OS:
Input size and minimal source:
Command/API options:
Fixed seed:
Expected behavior:
Observed behavior:
Build stage and error:
Direct VM result:
Sealed result:
Which clean/modified runtime was tested:
Sanitized logs and test fixture:
Do not paste real API keys, passwords or proprietary source without authorization. Include a minimal non-sensitive reproducer where possible.
7. Documentation lookup
Full index · From scratch · API · Testing · Runtime security
18Sealed transport specification
V0.5 başlık uyumluluğu
V0.5 sealed dosya artık CLAX-V0.5|SEAL2 veya benzeri iç transport işaretiyle başlamaz. Tek dış başlık This, File Protected By GsXFuscator V0.5 markasıdır; hemen ardından kullanıcının Unicode ASCII sanatı yorum olarak, ardından loader kodu gelir. Bu durum blokların şifre çözme ve FNV/Adler doğrulama formatını değiştirmez. Seal.isWrapped yalnızca heuristik tespittir, kriptografik doğrulama değildir.
Seal V2 blok biçimi (V0.5 geçmişi, V0.5 başlığı güncellendi)
Kaynak: v2/src/seal.lua. Tarih: 2026-11-21. Bu belge güncel sürümü açıklar; önceki seal çıktılarının iç biçimi farklıdır.
Yol haritası
VM programı (Lua metni)
-> 65536 baytlık ham bloklara ayırma (varsayılan)
-> auto: LZSS dene, daha küçük değilse ham sakla
raw: LZSS'i atla; lzss: sıkıştırılmış akışı zorla
-> 12 baytlık blok başlığı ekle
-> Kayan XOR byte stream dönüştürmesi
-> 64 sembollü karıştırılmış base64 kodlama
-> Tek Lua dosyası içinde blok tablosu (G)
Çalıştırma: base64 çöz -> XOR tersine çevir -> LZSS/ham -> iki hash kontrolü
-> bütün blokları birleştir -> host load()/loadstring() -> VM çalıştır
Bu format LZ4 değildir; 2048 bayt pencereli özel bir LZSS varyantı kullanır.
Blok başlığı — 12 bayt
| Ofset (0 bazlı) | Boyut | Anlamı |
|---|---|---|
| 0–3 | 4 | Little-endian ham uzunluk; 8388608 biti ham saklama bayrağı. |
| 4–7 | 4 | Önceki tüm çözülmüş bloklar üzerinden kümülatif FNV-1a32. |
| 8–11 | 4 | Önceki tüm çözülmüş bloklar üzerinden kümülatif Adler-32. |
| 12… | değişken | Sıkıştırılmış bit akışı veya ham blok. |
FNV-1a32 başlangıcı 2166136261, Adler-32 başlangıcı 1. Her blokta ikisi de güncellenir. Dış runtime nihai EXPECTED, EXPECTED_A değerlerini de kontrol eder. Bunların ikisi de sahteciliği kriptografik olarak engellemez: beklenen sabitler kod içinde bulunur.
LZSS
Tek bit: 0 ham byte, 1 geri referans. Geri referans 4 bit uzunluk eksi 3 ve 11 bit mesafe eksi 1 içerir; uzunluk aralığı 3–18, pencere 1–2048 bayttır. Akış MSB-first ilerler ve son byte dolgu bitlerinin sıfır olması gerekir. Geri referans hiçbir zaman henüz üretilmemiş bir baytı işaret edemez. Doğru ham uzunluğa ulaşıldığında decoder durur.
Kayan XOR
Her blokta durum 2166136261 + (blockIndex−1)×2654435761 (mod 2^32) biçiminde başlar. 16 baytlık K ile konuma bağlı katsayılar kullanılır. Bir önceki şifreli byte sonraki byte'a bağlanır. Bu bir stream-cipher taklididir; anahtar ve algoritma çıktı dosyasında olduğundan kriptografik şifreleme sayılmamalıdır.
Karıştırılmış base64
Alfabe 64 farklı yazdırılabilir sembolden üretilir; standart = dolgusu yerine 1 byte için 2, 2 byte için 3 sembol kullanılır. Çözücü geçersiz sembolleri ve sıfır olmayan terminal bitleri reddeder. Amaç basit dizgi taramalarının maliyetini artırmaktır, gizli anahtar saklamak değildir.
Decoder sınır kontrolleri
K16,A64 karakter olmalı ve alfabe tekrarsız olmalı.M,T,D,N,EXPECTEDveEXPECTED_Aalanları için tür, aralık ve tam sayı denetimleri bulunur.- Toplam 32 MiB üstü ham uzunluk reddedilir.
Seal.wrapüst sınırı 32 MiB ile sınırlar;maxBytesyalnız bunu azaltabilir. - En az 12 bayt başlık ve bir payload baytı beklenir; blok sayısı toplam uzunlukla tutmalıdır.
- Her blokta çözülmüş uzunluk tam eşleşmelidir; header/flag bozulması reddedilir.
- FNV-1a ve Adler-32 her blokta ve sonunda eşleşmelidir.
- Blok düzeyi hata
invalid()yolundan standart hata döndürür.
Maliyet ve kapasite
Seal.BLOCK = 65536,Seal.MAX_BYTES = 33554432(ham VM metni).- Base64 ve stream decode lineer maliyettedir. LZSS paketleyici, karma tablo araması içeren sınırlı backreference taraması yapar; büyük girdilerde zaman/alan maliyetini hedef host'ta ölçün.
- Çıktı decoder'ındaki XOR artık 65.536 tam bayt kombinasyonlu tablo yerine 256 girişli nibble tablosuyla hesaplanır. Bu özellikle başlangıç belleği açısından iyileşmedir; her host'ta daha hızlı çalışacağı garanti değildir.
- Birden fazla blok, geçici byte tabloları ve birleştirilmiş Lua metni yüzünden tepe bellek tüketimi tek dosya boyutunu geçebilir.
Sürümleme ve geriye dönük uyumluluk
Yeni üretilen dosyalar kendi decoder'larını taşır; bu nedenle eski dosyalar eski decoder ile çalışmaya devam edebilir. Buna rağmen blok formatı eski 8 baytlık başlıkla byte-uyumlu değildir. Eski G blob'larını yeni runtime'a elle yapıştırmayın; kodu yeniden üretin. Eski revizyonlar CLAX-V0.5|SEAL2 metaveri işareti taşıyabiliyordu. Bu V0.5 revizyonunun çıktısı bu işareti taşımaz. Eski işaretler dijital/kriptografik imza değildi.
Saldırgan modeli
Hata ve bozulma tespiti, bir istemciyi kontrol eden saldırgana karşı bütünlük ispatı değildir. Gerçek yetki kontrolü / lisans denetimi gerekiyorsa programın çalıştırıcısından bağımsız bir otorite veya sunucu kullanılmalıdır. Dış seal'in load() çağrısı incelenebiliyorsa --no-seal kullanmayı değerlendirin; bu seçim statik okunabilirlik takasını getirir.
Yeni sıkıştırma seçenekleri ve sınır hesabı
Seal.wrap(vm, seed, {compression="auto", blockSize=65536}) varsayılan davranıştır. compression="raw" LZSS aramasını atlar; zaten sıkışmayan payload'da üretimi hızlandırabilir. compression="lzss" LZSS'i zorlayarak sıkıştırılmış gövdenin ham gövdeden büyük olmasına da izin verir. Üç mod da aynı decoder'ı kullanır.
Zorunlu LZSS'te her literal byte 9 bit tutar. Dolayısıyla sıkıştırılmış boyut ham boyuttan büyük olabilir ve encoded-length kontrolü 12 + ceil(rawLen × 9/8) baytın base64 karşılığına kadar izin verir. Önceki rawLen+12 kontrolü, çok küçük bloklarda geçerli bir lzss paketini hatalı reddediyordu. Ham çıktı uzunluğu ve iki ayrı checksum ayrıca doğrulanır.
Paketleyicideki XOR lookup da 65.536 girdiden 256-entry nibble lookup'a indirilmiştir. Bu bellek tüketimini azaltır; hızlanma garantisi değildir.
V0.5 runtime dekoder performans notu
Format değişmedi. LZSS bit okuyucusu artık en fazla 11 bitlik alanları
24 bitlik, önceden sınır kontrolü yapılmış bir pencereden alır; p+bn > #t*8
reddi aynı sınır semantiğini korur. FNV-1a ve Adler-32 hash durumları birlikte
ilerletilir, her blok sonunda ve tüm dosya sonunda her iki değer yine ayrı ayrı
doğrulanır. Yanlış/veri dışı padding, yanlış uzunluk ve bozuk checksum hâlâ
integrity check failed ile durur. Bu iki kontrol MAC veya imza değildir.
Detay: V0.5 Runtime Bakım Raporu.
19Release signatures and branding
Current GSX V0.7 Zero-Dead revision: see V07-ZERO-DEAD-COMPACT.md. Historic dead-string, synthetic decoder, first-byte banner, alias and decoy descriptions below refer to earlier builds; current production outputs use a live
return setmetatableentry and zero decoy handlers.
GsXFuscator V0.5 — marka ve imza standardı
- Ad: GsXFuscator (önceden Claxfuscator); sürüm V0.5 kalır.
- Discord: https://discord.gg/cHawU8Wmzj (değişmedi; web menüsünde topluluk bağlantısı olarak da görünür).
- Logo:
web/assets/gsxfuscator-original.pngyüklenen orijinal resim; 256px WebP sayfa logosu ve 64px PNG favicon optimize edilmiş kopyalardır. İkisi web HTML içinedata:olarak gömülür; çevrimdışı açılabilir. - İmzalar: Hem CLI hem web tarafından üretilen Direct/Sealed çıktı
--[[ This, File Protected By GsXFuscator V0.5 https://discord.gg/cHawU8Wmzj ]]satırıyla başlar. Ardındananime_ascıı.txtgörseli, her satırının önüne--yazılarak Lua satır yorumları halinde eklenir. - Sözdizimi: Satır yorumları ek bir
]=====]kapanışı üretmez. Eski görsel sonu çizgisi vePROTECTED BY GsX FUSCATORsatırı kaldırıldı. - Tek satır değişikliği: Eski 'one-line/ASCII-only' çıktı tanımı artık geçerli değildir. UTF-8 desteklemeyen bir sisteme Unicode çıktıyı yapıştırmak sanatı bozabilir. Lua yorumları yürütme mantığını etkilemez.
- Eski kayıtlar:
clax.workspace.*tarayıcı depolama anahtarları kullanıcı görünüm ayarları kaybolmasın diye tutulur; yeni korumasız içerik geçmişi tutulmaz. - Güvenlik: İmzalar tanımlayıcıdır; dijital imza veya kırılamazlık iddiası değildir. FNV/Adler bozulmayı kontrol eder, saldırgan kökenini doğrulamaz.
Yeniden üretim
python web/build12.py
lua v2/obfuscator.lua input.lua output.lua --preset strong --strict-verify
Doğrulama
Her iki mod için: marka satırı, görselin varlığı ve UTF-8 bütünlüğü; Lua derleme/çalışma eşdeğerliği; web/favicon gömülü veri; ZIP CRC ve dosya listesi kontrol edilmelidir.
V0.5 runtime güvenlik revizyonu: VM ve runtime kontrol akışı.
GSX V0.7 — Yayın doğrulama ve 77fuscator kaynak durumu
Kaynak arşivindeki 259 dosya parola korumalıydı; doğrudan entegrasyon yapılmadı. Yeni ortak üretim politikası VM9 bytecode audit, Anti-Debug, Integrity, Self-Modifying ve gerçek kullanılan handler kontrollerini zorunlu tutar. Sabit dönüştürme optimizasyonu kısa program regresyonunda hata verdiği için geri alındı. Ayrıntılar: v2/docs/V07-FUSION-AUDIT.md.
Reading, Graphite Light & Night
The dashboard uses one graphite-gray palette; theme colors and font menus are removed. Go to Settings → Appearance to choose Light or Night, or enable Large reading text. These settings persist in this browser when storage is allowed.
Elegant is retained for display headings. Instructions, buttons and longer passages use clear system UI fonts, with generous spacing, visible keyboard focus and no dependency on downloading a webfont. Browser text zoom and accessibility settings are supported.
Animations are subtle. If your device requests reduced motion/data or reports low memory, decorative motion and effects are reduced automatically; all essential operations remain available. Reduced-motion is also honored through operating-system settings.
Performance and memory
VM size and opcode variety can increase load time and memory. A large obfuscated file is not evidence of stronger security. Avoid compiling the same source repeatedly on low-memory devices; export and keep the file you need.
- Record source size, output size, Lua version and preset.
- Measure a cold start and several warm executions of the same output.
- Compare median wall time and peak resident memory against the original.
- Check program output for equivalence and repeat on your target device.
V0.5 loader maintenance replaces per-bit LZSS reads with a bounded word reader and combines FNV/Adler checks into one byte pass. In one Lua 5.4 cold-start fixture, Strong Sealed Auto improved from a 0.573-second median to 0.431 seconds across four runs. This is a local sample, not a universal speedup or a low-RAM device guarantee.
For reproducible measurements use python v2/tests/benchmark_matrix.py --lua lua5.4 --runs 5 in the source package. The CLI exposes --vm-size compact for size-constrained deployments, but it reduces decoy diversity; the web policy uses Strong/compact VM.
Security model & limitations
GsXFuscator is an obfuscator, not an encryption vault. A determined analyst can decode the outer transport and inspect the resulting VM; this is not necessarily the original source. Runtime debugging, hooking and memory snapshots are possible when an attacker controls the Lua interpreter.
Anti-tamper and anti-debug checks detect selected changes to references, behavior and VM structures, but they do not guarantee that all modifications or debuggers will be detected. FNV and Adler checksums detect corruption; they are not keyed authentication or signatures.
Do not embed reusable secrets or authorization decisions solely in the client-side output. See v2/SECURITY.md for boundaries and the validation checklist.
Troubleshooting
| Symptom | What to try |
|---|---|
| Small or thin text | Use Settings → Large reading text, browser zoom, or OS text scaling. Light and Night both use Graphite contrast palettes. |
| Lag or stutter | Enable system reduced motion/data, close other heavy tabs, and test the CLI on a less constrained machine. |
| Font not loaded | System fonts render body text offline; Elegant display headings have a Georgia fallback. |
| Lost settings | Private mode, full storage or blocked localStorage may prevent remembering them; defaults remain safe. |
| Mismatch during verification | Inspect diagnostics, try a minimal reproduction, then test on the actual Lua runtime. Avoid disabling validation to silence an error. |
Workspace settings
Manage your profile, Graphite display mode, reading comfort and navigation.
Profile
JPG, PNG or WebP, up to 8 MB.
Appearance
Graphite is the fixed color palette. Choose a light or dark background; your preference is remembered on this device.
Navigation
Tab order
Drag tabs into position, or use the up and down buttons.
Rules & Guidelines
These guidelines apply to building and sharing Lua files with GsXFuscator.
Legal Use Only
Use scripts you own or have permission to modify.
No Malicious Scripts
Malware, phishing and scripts intended to harm other people or systems are prohibited.
Roblox ToS
Follow the Roblox Terms of Use when distributing or running scripts on Roblox.
No Guarantees
Code distributed to a client can be inspected. Keep credentials and confidential business logic on your server.
Build privacy
GsXFuscator does not save build history or upload generated files. Only appearance and profile preferences are saved locally when storage is available.
Access restrictions
Harmful use can result in loss of access.
Keep Secrets Server-Side
Never embed API keys, passwords or sensitive tokens in client-side Lua. Obfuscation cannot keep secrets from someone controlling the runtime.
Test Before Distribution
Run the protected script in the intended Lua environment. Compare behavior, startup time and memory use with the original before releasing it.
GsXFuscator is provided as-is. You are responsible for the scripts you distribute.