repeat task.wait() until game:IsLoaded()

local Players = game:GetService("Players")
local LocalPlayer = Players.LocalPlayer

local BRAND = "efg2g"
local DOMAIN = "efg2g.pages.dev"
local API_AUTHORIZE_URL = "https://" .. DOMAIN .. "/api/authorize"
local API_SCRIPT_URL = "https://" .. DOMAIN .. "/api/script"

local JUNKIE = {
    ENABLED = true,
    SDK_URL = "https://jnkie.com/sdk/library.lua",
    SERVICE = "efg2g-free",
    IDENTIFIER = "1136363",
    PROVIDER = "Free",
    SAVE_KEY = true,
    KEY_FOLDER = "efg2g",
    KEY_FILE = "efg2g/key.txt",
    KEYLESS_PROBE = true,
}

local function kick(msg)
    pcall(function()
        LocalPlayer:Kick("[" .. BRAND .. "] " .. msg)
    end)
end

local function notify(title, text, duration)
    pcall(function()
        game:GetService("StarterGui"):SetCore("SendNotification", {
            Title = title,
            Text = text,
            Duration = duration or 4,
        })
    end)
end

local function trim(s)
    return (tostring(s or ""):gsub("^%s+", ""):gsub("%s+$", ""))
end

local function parseResponse(resp)
    if type(resp) == "string" then
        return 0, resp
    end

    if type(resp) ~= "table" then
        return 0, nil
    end

    local code = tonumber(
        resp.StatusCode or resp.status_code
        or resp.Status or resp.status
    ) or 0

    local body = resp.Body
        or resp.body
        or resp.ResponseBody
        or resp.responseBody

    if body ~= nil then
        body = tostring(body)
    end

    return code, body
end

local function httpGet(url)
    local requestError

    if type(request) == "function" then
        local ok, resp = pcall(function()
            return request({
                Url = url,
                Method = "GET",
                Headers = {
                    ["Accept"] = "text/plain,application/octet-stream,*/*",
                },
            })
        end)

        if ok then
            local code, body = parseResponse(resp)
            if body and #body > 0 and (code == 0 or (code >= 200 and code < 300)) then
                return body
            end
            requestError = code >= 400 and ("HTTP " .. tostring(code))
                or "empty response from request()"
        else
            requestError = tostring(resp)
        end
    end

    local ok, res = pcall(function()
        return game:HttpGet(url, true)
    end)

    if ok and type(res) == "string" and #res > 0 then
        return res
    end

    if not ok then
        return nil, requestError or "network error"
    end

    return nil, requestError or "empty response"
end

local function jsonEscape(value)
    return tostring(value)
        :gsub("\\", "\\\\")
        :gsub('"', '\\"')
        :gsub("\n", "\\n")
        :gsub("\r", "\\r")
        :gsub("\t", "\\t")
end

local function jsonEncode(payload)
    local ok, service = pcall(function()
        return game:GetService("HttpService")
    end)

    if ok and service and type(service.JSONEncode) == "function" then
        local encoded, result = pcall(function()
            return service:JSONEncode(payload)
        end)
        if encoded and type(result) == "string" then
            return result
        end
    end

    local fields = {}
    for key, value in pairs(payload) do
        table.insert(fields, '"' .. jsonEscape(key) .. '":"' .. jsonEscape(value) .. '"')
    end
    return "{" .. table.concat(fields, ",") .. "}"
end

local function decodeAuthorization(body)
    if type(body) ~= "string" then
        return nil
    end

    local ok, service = pcall(function()
        return game:GetService("HttpService")
    end)

    if ok and service and type(service.JSONDecode) == "function" then
        local decodedOk, decoded = pcall(function()
            return service:JSONDecode(body)
        end)
        if decodedOk and type(decoded) == "table" then
            return decoded
        end
    end

    local capability = body:match('"capability"%s*:%s*"([a-fA-F0-9]+)"')
    local authorized = body:match('"authorized"%s*:%s*true') ~= nil
    if authorized and capability then
        return { authorized = true, capability = capability }
    end
    return nil
end

local function postJson(url, payload)
    if type(request) ~= "function" then
        return nil, nil, "POST is unavailable in this executor"
    end

    local ok, resp = pcall(function()
        return request({
            Url = url,
            Method = "POST",
            Headers = {
                ["Accept"] = "application/json,text/plain,*/*",
                ["Content-Type"] = "application/json",
            },
            Body = jsonEncode(payload),
        })
    end)

    if not ok then
        return nil, nil, "network error"
    end

    local code, body = parseResponse(resp)
    return code, body, nil
end

local function makeNonce()
    local ok, service = pcall(function()
        return game:GetService("HttpService")
    end)

    if ok and service and type(service.GenerateGUID) == "function" then
        local guidOk, guid = pcall(function()
            return service:GenerateGUID(false)
        end)
        if guidOk and type(guid) == "string" then
            return guid:gsub("[^%w_-]", ""):sub(1, 64)
        end
    end

    local raw = tostring(os.clock())
        .. tostring(math.random())
        .. tostring({})
        .. tostring(game.PlaceId)
    local nonce = raw:gsub("[^%w]", "")
    if #nonce < 16 then
        nonce = nonce .. string.rep("x", 16 - #nonce)
    end
    return nonce:sub(1, 64)
end

local function authorizeGame(placeId, key)
    local nonce = makeNonce()
    local code, body, requestError = postJson(API_AUTHORIZE_URL, {
        placeId = tostring(placeId),
        nonce = nonce,
        key = trim(key),
    })

    if not code then
        return nil, nil, requestError or "network error"
    end

    if code ~= 0 and (code < 200 or code >= 300) then
        if code == 429 then
            return nil, nil, "RATE_LIMITED"
        end
        return nil, nil, "AUTHORIZATION_FAILED"
    end

    local response = decodeAuthorization(body)
    if not response or response.authorized ~= true
        or type(response.capability) ~= "string"
        or #response.capability ~= 64 then
        return nil, nil, "AUTHORIZATION_FAILED"
    end

    return response.capability, nonce, nil
end

local function fetchGameScript(placeId, capability, nonce)
    local code, body, requestError = postJson(API_SCRIPT_URL, {
        placeId = tostring(placeId),
        capability = capability,
        nonce = nonce,
    })

    if not code then
        return nil, requestError or "network error"
    end
    if code ~= 0 and (code < 200 or code >= 300) then
        if code == 429 then
            return nil, "RATE_LIMITED"
        end
        return nil, "AUTHORIZATION_FAILED"
    end
    if not body or #body == 0 then
        return nil, "empty response"
    end
    return body, nil
end

local ERROR_TEXT = {
    KEY_INVALID = "Invalid key. Please check and try again.",
    KEY_EXPIRED = "Your key has expired. Click 'Get Key' for a new one.",
    HWID_BANNED = "You are HWID banned from this script.",
    KEY_INVALIDATED = "This key has been disabled.",
    ALREADY_USED = "This one-time key was already used.",
    HWID_MISMATCH = "This key is bound to another device (HWID limit reached).",
    SERVICE_NOT_FOUND = "Authorization failed. Please re-execute.",
    SERVICE_MISMATCH = "Authorization failed. Please check your key.",
    PREMIUM_REQUIRED = "A premium key is required for this script.",
    RATE_LIMITED = "Rate limited. Please wait ~5 minutes and try again.",
    ERROR = "Network error. Please try again.",
}

local function describe(code)
    code = tostring(code or "ERROR")

    if ERROR_TEXT[code] then
        return ERROR_TEXT[code]
    end

    if code:match("^http %d+") then
        return "Network error. Please try again."
    end

    return ERROR_TEXT.ERROR
end

local function loadJunkie()
    local ok, lib = pcall(function()
        local src, fetchErr = httpGet(JUNKIE.SDK_URL)

        if not src then
            error(fetchErr or "empty response")
        end

        local chunk, compileErr = loadstring(src)

        if not chunk then
            error(compileErr or "invalid SDK response")
        end

        return chunk()
    end)

    if not ok or type(lib) ~= "table" then
        return nil, tostring(lib)
    end

    lib.service = JUNKIE.SERVICE
    lib.identifier = tostring(JUNKIE.IDENTIFIER)
    lib.provider = JUNKIE.PROVIDER

    return lib
end

local function checkKey(Junkie, key)
    local ok, res = pcall(Junkie.check_key, key)

    if not ok or type(res) ~= "table" then
        return false, "ERROR"
    end

    if res.valid or res.success then
        return true, res.message or "KEY_VALID"
    end

    return false, res.error or res.message or "KEY_INVALID"
end

local function getKeyLink(Junkie)
    local ok, link, err = pcall(Junkie.get_key_link)

    if not ok then
        return nil, "ERROR"
    end

    if type(link) == "string" and #link > 0 then
        return link, nil
    end

    return nil, tostring(err or "ERROR")
end

local function fsAvailable()
    return JUNKIE.SAVE_KEY
        and type(readfile) == "function"
        and type(writefile) == "function"
        and type(isfile) == "function"
end

local function loadSavedKey()
    if not fsAvailable() then
        return nil
    end

    local ok, key = pcall(function()
        if isfile(JUNKIE.KEY_FILE) then
            return readfile(JUNKIE.KEY_FILE)
        end

        return nil
    end)

    if ok and type(key) == "string" then
        key = trim(key)

        if #key > 0 then
            return key
        end
    end

    return nil
end

local function saveKey(key)
    if not fsAvailable() then
        return
    end

    pcall(function()
        if type(makefolder) == "function" and type(isfolder) == "function" then
            if not isfolder(JUNKIE.KEY_FOLDER) then
                makefolder(JUNKIE.KEY_FOLDER)
            end
        end

        writefile(JUNKIE.KEY_FILE, key)
    end)
end

local function clearSavedKey()
    if not fsAvailable() then
        return
    end

    pcall(function()
        if isfile(JUNKIE.KEY_FILE) then
            if type(delfile) == "function" then
                delfile(JUNKIE.KEY_FILE)
            else
                writefile(JUNKIE.KEY_FILE, "")
            end
        end
    end)
end

local function copyToClipboard(text)
    local fn = setclipboard
        or toclipboard
        or set_clipboard
        or (Clipboard and Clipboard.set)

    if type(fn) ~= "function" then
        return false
    end

    return pcall(fn, text)
end

local THEME = {
    Background = Color3.fromRGB(12, 12, 15),
    Panel = Color3.fromRGB(21, 21, 27),
    Stroke = Color3.fromRGB(42, 42, 54),
    Accent = Color3.fromRGB(0, 212, 255),
    AccentText = Color3.fromRGB(5, 5, 8),
    Text = Color3.fromRGB(240, 240, 245),
    Muted = Color3.fromRGB(140, 140, 158),
    Success = Color3.fromRGB(80, 220, 140),
    Error = Color3.fromRGB(255, 92, 92),
    Warning = Color3.fromRGB(255, 190, 70),
}

local function new(class, props, parent)
    local inst = Instance.new(class)

    for k, v in pairs(props or {}) do
        inst[k] = v
    end

    if parent then
        inst.Parent = parent
    end

    return inst
end

local function getGuiParent(gui)
    if type(protect_gui) == "function" then
        pcall(protect_gui, gui)
    end

    if type(gethui) == "function" then
        local ok, hui = pcall(gethui)

        if ok and hui then
            return hui
        end
    end

    local okCore = pcall(function()
        return game:GetService("CoreGui"):GetChildren()
    end)

    if okCore then
        return game:GetService("CoreGui")
    end

    return LocalPlayer:WaitForChild("PlayerGui")
end

local function makeDraggable(frame, handle)
    local UIS = game:GetService("UserInputService")
    local dragging, dragInput, dragStart, startPos

    handle.InputBegan:Connect(function(input)
        if input.UserInputType == Enum.UserInputType.MouseButton1
            or input.UserInputType == Enum.UserInputType.Touch then

            dragging = true
            dragStart = input.Position
            startPos = frame.Position

            input.Changed:Connect(function()
                if input.UserInputState == Enum.UserInputState.End then
                    dragging = false
                end
            end)
        end
    end)

    handle.InputChanged:Connect(function(input)
        if input.UserInputType == Enum.UserInputType.MouseMovement
            or input.UserInputType == Enum.UserInputType.Touch then

            dragInput = input
        end
    end)

    UIS.InputChanged:Connect(function(input)
        if dragging and input == dragInput then
            local delta = input.Position - dragStart

            frame.Position = UDim2.new(
                startPos.X.Scale,
                startPos.X.Offset + delta.X,
                startPos.Y.Scale,
                startPos.Y.Offset + delta.Y
            )
        end
    end)
end

local function createKeyUI(handlers)
    local gui = new("ScreenGui", {
        Name = BRAND .. "_KeySystem",
        ResetOnSpawn = false,
        ZIndexBehavior = Enum.ZIndexBehavior.Sibling,
        DisplayOrder = 999,
    })

    gui.Parent = getGuiParent(gui)

    local window = new("Frame", {
        Name = "Window",
        AnchorPoint = Vector2.new(0.5, 0.5),
        Position = UDim2.new(0.5, 0, 0.5, 0),
        Size = UDim2.new(0, 380, 0, 262),
        BackgroundColor3 = THEME.Background,
        BorderSizePixel = 0,
    }, gui)

    new("UICorner", {
        CornerRadius = UDim.new(0, 12),
    }, window)

    new("UIStroke", {
        Color = THEME.Stroke,
        Thickness = 1,
    }, window)

    local header = new("Frame", {
        Name = "Header",
        Size = UDim2.new(1, 0, 0, 52),
        BackgroundTransparency = 1,
    }, window)

    new("TextLabel", {
        Name = "Title",
        Position = UDim2.new(0, 16, 0, 10),
        Size = UDim2.new(1, -70, 0, 20),
        BackgroundTransparency = 1,
        Text = BRAND,
        TextColor3 = THEME.Text,
        Font = Enum.Font.GothamBold,
        TextSize = 17,
        TextXAlignment = Enum.TextXAlignment.Left,
    }, header)

    new("TextLabel", {
        Name = "Subtitle",
        Position = UDim2.new(0, 16, 0, 30),
        Size = UDim2.new(1, -70, 0, 16),
        BackgroundTransparency = 1,
        Text = "Key System  •  complete the checkpoint to get your key",
        TextColor3 = THEME.Muted,
        Font = Enum.Font.Gotham,
        TextSize = 11,
        TextXAlignment = Enum.TextXAlignment.Left,
        TextTruncate = Enum.TextTruncate.AtEnd,
    }, header)

    local closeBtn = new("TextButton", {
        Name = "Close",
        AnchorPoint = Vector2.new(1, 0),
        Position = UDim2.new(1, -12, 0, 12),
        Size = UDim2.new(0, 28, 0, 28),
        BackgroundColor3 = THEME.Panel,
        Text = "×",
        TextColor3 = THEME.Muted,
        Font = Enum.Font.GothamBold,
        TextSize = 18,
        AutoButtonColor = false,
    }, header)

    new("UICorner", {
        CornerRadius = UDim.new(0, 8),
    }, closeBtn)

    local keyBox = new("TextBox", {
        Name = "KeyInput",
        Position = UDim2.new(0, 16, 0, 62),
        Size = UDim2.new(1, -32, 0, 38),
        BackgroundColor3 = THEME.Panel,
        BorderSizePixel = 0,
        Text = "",
        PlaceholderText = "Paste your key here...",
        PlaceholderColor3 = THEME.Muted,
        TextColor3 = THEME.Text,
        Font = Enum.Font.Gotham,
        TextSize = 13,
        ClearTextOnFocus = false,
        TextXAlignment = Enum.TextXAlignment.Left,
    }, window)

    new("UICorner", {
        CornerRadius = UDim.new(0, 8),
    }, keyBox)

    new("UIStroke", {
        Color = THEME.Stroke,
        Thickness = 1,
    }, keyBox)

    new("UIPadding", {
        PaddingLeft = UDim.new(0, 12),
        PaddingRight = UDim.new(0, 12),
    }, keyBox)

    local getKeyBtn = new("TextButton", {
        Name = "GetKey",
        Position = UDim2.new(0, 16, 0, 110),
        Size = UDim2.new(0.5, -20, 0, 36),
        BackgroundColor3 = THEME.Accent,
        BorderSizePixel = 0,
        Text = "Get Key",
        TextColor3 = THEME.AccentText,
        Font = Enum.Font.GothamBold,
        TextSize = 13,
        AutoButtonColor = false,
    }, window)

    new("UICorner", {
        CornerRadius = UDim.new(0, 8),
    }, getKeyBtn)

    local checkBtn = new("TextButton", {
        Name = "CheckKey",
        AnchorPoint = Vector2.new(1, 0),
        Position = UDim2.new(1, -16, 0, 110),
        Size = UDim2.new(0.5, -20, 0, 36),
        BackgroundColor3 = THEME.Panel,
        BorderSizePixel = 0,
        Text = "Check Key",
        TextColor3 = THEME.Text,
        Font = Enum.Font.GothamBold,
        TextSize = 13,
        AutoButtonColor = false,
    }, window)

    new("UICorner", {
        CornerRadius = UDim.new(0, 8),
    }, checkBtn)

    new("UIStroke", {
        Color = THEME.Stroke,
        Thickness = 1,
    }, checkBtn)

    local linkBox = new("TextBox", {
        Name = "KeyLink",
        Position = UDim2.new(0, 16, 0, 156),
        Size = UDim2.new(1, -32, 0, 30),
        BackgroundColor3 = THEME.Panel,
        BorderSizePixel = 0,
        Text = "",
        TextColor3 = THEME.Accent,
        Font = Enum.Font.Code,
        TextSize = 11,
        ClearTextOnFocus = false,
        TextEditable = false,
        TextXAlignment = Enum.TextXAlignment.Left,
        Visible = false,
    }, window)

    new("UICorner", {
        CornerRadius = UDim.new(0, 8),
    }, linkBox)

    new("UIPadding", {
        PaddingLeft = UDim.new(0, 10),
        PaddingRight = UDim.new(0, 10),
    }, linkBox)

    local status = new("TextLabel", {
        Name = "Status",
        Position = UDim2.new(0, 16, 0, 192),
        Size = UDim2.new(1, -32, 0, 40),
        BackgroundTransparency = 1,
        Text = "Click 'Get Key' to receive your key link, then paste the key above.",
        TextColor3 = THEME.Muted,
        Font = Enum.Font.Gotham,
        TextSize = 12,
        TextWrapped = true,
        TextXAlignment = Enum.TextXAlignment.Left,
        TextYAlignment = Enum.TextYAlignment.Top,
    }, window)

    new("TextLabel", {
        Name = "Footer",
        Position = UDim2.new(0, 16, 1, -22),
        Size = UDim2.new(1, -32, 0, 14),
        BackgroundTransparency = 1,
        Text = BRAND .. "  •  secured by Junkie",
        TextColor3 = THEME.Stroke,
        Font = Enum.Font.Gotham,
        TextSize = 10,
        TextXAlignment = Enum.TextXAlignment.Right,
    }, window)

    makeDraggable(window, header)

    local function hover(btn, normal, hovered)
        btn.MouseEnter:Connect(function()
            btn.BackgroundColor3 = hovered
        end)

        btn.MouseLeave:Connect(function()
            btn.BackgroundColor3 = normal
        end)
    end

    hover(getKeyBtn, THEME.Accent, Color3.fromRGB(80, 226, 255))
    hover(checkBtn, THEME.Panel, Color3.fromRGB(32, 32, 41))
    hover(closeBtn, THEME.Panel, Color3.fromRGB(60, 30, 34))

    getKeyBtn.MouseButton1Click:Connect(function()
        handlers.onGetKey()
    end)

    checkBtn.MouseButton1Click:Connect(function()
        handlers.onCheck(keyBox.Text)
    end)

    keyBox.FocusLost:Connect(function(enterPressed)
        if enterPressed then
            handlers.onCheck(keyBox.Text)
        end
    end)

    closeBtn.MouseButton1Click:Connect(function()
        handlers.onClose()
    end)

    local ui = {}

    function ui:SetStatus(text, kind)
        status.Text = text

        if kind == "ok" then
            status.TextColor3 = THEME.Success
        elseif kind == "err" then
            status.TextColor3 = THEME.Error
        elseif kind == "warn" then
            status.TextColor3 = THEME.Warning
        else
            status.TextColor3 = THEME.Muted
        end
    end

    function ui:ShowLink(link)
        linkBox.Text = link
        linkBox.Visible = true
        getKeyBtn.Text = "Copy Link"
    end

    function ui:SetBusy(busy)
        getKeyBtn.Active = not busy
        checkBtn.Active = not busy
        checkBtn.Text = busy and "Checking..." or "Check Key"
    end

    function ui:Destroy()
        pcall(function()
            gui:Destroy()
        end)
    end

    return ui
end

local function runKeySystem()
    local Junkie = loadJunkie()

    if not Junkie then
        kick("Failed to load key system. Please re-execute.")
        return nil
    end

    local candidates = {}
    local preset = getgenv().SCRIPT_KEY

    if type(preset) == "string" and #trim(preset) > 0 then
        table.insert(candidates, {
            key = trim(preset),
            source = "preset",
        })
    end

    local saved = loadSavedKey()

    if saved and saved ~= (candidates[1] and candidates[1].key) then
        table.insert(candidates, {
            key = saved,
            source = "saved",
        })
    end

    if #candidates == 0 and JUNKIE.KEYLESS_PROBE then
        table.insert(candidates, {
            key = "KEYLESS",
            source = "probe",
        })
    end

    for _, c in ipairs(candidates) do
        local valid, code = checkKey(Junkie, c.key)

        if valid then
            if c.source == "preset" and code ~= "KEYLESS" then
                saveKey(c.key)
            end

            return c.key, code
        end

        if code == "HWID_BANNED" then
            kick(ERROR_TEXT.HWID_BANNED)
            return nil
        end

        if c.source == "saved" and (
            code == "KEY_INVALID"
            or code == "KEY_EXPIRED"
            or code == "KEY_INVALIDATED"
            or code == "ALREADY_USED"
            or code == "SERVICE_MISMATCH"
        ) then
            clearSavedKey()
        end
    end

    local result = nil
    local resultCode = nil
    local busy = false
    local cachedLink = nil
    local ui

    ui = createKeyUI({
        onGetKey = function()
            if busy then
                return
            end

            if cachedLink then
                local copied = copyToClipboard(cachedLink)

                ui:SetStatus(
                    copied
                        and "Link copied to clipboard again!"
                        or "Copy the link above, finish the checkpoint, then paste your key.",
                    "ok"
                )

                return
            end

            busy = true
            ui:SetBusy(true)
            ui:SetStatus("Generating your key link...", "info")

            task.spawn(function()
                local link, err = getKeyLink(Junkie)

                if link then
                    cachedLink = link
                    ui:ShowLink(link)

                    local copied = copyToClipboard(link)

                    if copied then
                        ui:SetStatus(
                            "Link copied to clipboard! Open it in your browser, finish the checkpoint, then paste the key here.",
                            "ok"
                        )
                    else
                        ui:SetStatus(
                            "Copy the link above, open it in your browser, finish the checkpoint, then paste the key here.",
                            "ok"
                        )
                    end
                else
                    ui:SetStatus(
                        describe(err),
                        err == "RATE_LIMITED" and "warn" or "err"
                    )
                end

                busy = false
                ui:SetBusy(false)
            end)
        end,

        onCheck = function(text)
            if busy then
                return
            end

            local key = trim(text)

            if #key == 0 then
                ui:SetStatus("Please paste your key first.", "err")
                return
            end

            busy = true
            ui:SetBusy(true)
            ui:SetStatus("Checking key...", "info")

            task.spawn(function()
                local valid, code = checkKey(Junkie, key)

                if valid then
                    ui:SetStatus(
                        "Key accepted by SDK. Verifying script access...",
                        "info"
                    )

                    saveKey(key)
                    resultCode = code
                    result = key
                else
                    ui:SetStatus(describe(code), "err")

                    if code == "HWID_BANNED" then
                        result = false
                        kick(ERROR_TEXT.HWID_BANNED)
                    end
                end

                busy = false
                ui:SetBusy(false)
            end)
        end,

        onClose = function()
            result = false
        end,
    })

    repeat
        task.wait(0.1)
    until result ~= nil

    task.wait(0.4)
    ui:Destroy()

    if result == false then
        return nil
    end

    return result, resultCode
end

if JUNKIE.ENABLED then
    local key, code = runKeySystem()

    if not key then
        return
    end

    getgenv().SCRIPT_KEY = key

    notify(
        BRAND,
        code == "KEYLESS"
            and "Keyless mode active. Loading..."
            or "Key accepted by SDK. Verifying script access...",
        3
    )
end

if not JUNKIE.ENABLED then
    -- Disabling the client UI is not a server bypass. The Worker must have
    -- explicitly enabled KEYLESS mode for this request to be authorized.
    getgenv().SCRIPT_KEY = trim(getgenv().SCRIPT_KEY)
    if #getgenv().SCRIPT_KEY == 0 then
        getgenv().SCRIPT_KEY = "KEYLESS"
    end
end

local capability, nonce, authorizeError = authorizeGame(
    game.PlaceId,
    getgenv().SCRIPT_KEY
)

if not capability then
    local message = authorizeError == "RATE_LIMITED"
        and "Too many requests. Please wait and re-execute."
        or "Authorization failed. Please re-execute."
    kick(message)
    return
end

local content = fetchGameScript(game.PlaceId, capability, nonce)

if not content or #content == 0 then
    kick("Failed to load script. Please re-execute.")
    return
end

if content:sub(1, 1) == "<"
    or content:find("-- efg2g authorization failed", 1, true) then
    kick("Failed to load script. Please re-execute.")
    return
end

local fn, err = loadstring(content)

if not fn then
    kick("Failed to prepare script. Please re-execute.")
    return
end

local okRun, runErr = pcall(fn)

if not okRun then
    warn("[" .. BRAND .. "] Script error: " .. tostring(runErr))
end
