luajitos

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs

commit 39106a9d7c9a4f1f79ebe1bf3ce6c76a29aaff61
parent e78bfef79b471d479f4a152287cf940d0887a62f
Author: luajitos <bbhbb2094@gmail.com>
Date:   Sun, 30 Nov 2025 09:44:47 +0000

removed old files

Diffstat:
M.gitignore | 4----
DNotes/Directory.txt | 22----------------------
DNotes/Permissions.txt | 75---------------------------------------------------------------------------
DOS_Other/OrbitManager.lua | 593-------------------------------------------------------------------------------
DOS_Other/example_manifest_usage.lua | 70----------------------------------------------------------------------
DOS_Other/example_sandbox_runner.lua | 226-------------------------------------------------------------------------------
DOS_Other/fs.lua | 29-----------------------------
DOS_Other/init3.lua | 80-------------------------------------------------------------------------------
DOS_Other/mymodule.lua | 12------------
DOS_Other/perms.lua | 23-----------------------
DOS_Other/ramdisk2.lua | 416-------------------------------------------------------------------------------
DOS_Other/ramfs.lua | 225-------------------------------------------------------------------------------
DOS_Other/sandboxEnv.lua | 139-------------------------------------------------------------------------------
DOS_Other/stringfix.lua | 169-------------------------------------------------------------------------------
DOS_Other/test_escape.lua | 40----------------------------------------
DOS_Other/test_lpm.lua | 26--------------------------
DOS_Other/test_orbit.lua | 128-------------------------------------------------------------------------------
DOS_Other/test_orbit_manifest.lua | 179-------------------------------------------------------------------------------
DOS_Other/test_ramdisk2.lua | 95-------------------------------------------------------------------------------
DOS_Other/test_runstring.lua | 70----------------------------------------------------------------------
DOS_Other/test_sandbox.lua | 212-------------------------------------------------------------------------------
DOS_Other/testinit.lua | 0
22 files changed, 0 insertions(+), 2833 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -33,10 +33,6 @@ todo2.txt *~ .*.kate-swp -# OS_Other_Notes -OS_Other/ -Notes/ - # Temp files *.tmp *.bak diff --git a/Notes/Directory.txt b/Notes/Directory.txt @@ -1,22 +0,0 @@ -/ - -/apps/ - -/apps/com.devname.progname/ = $ (like /home/b/ = ~) - $/src/ (for lua soure files) - $/res/ (for static resources, cant be changed by program, only updates) - $/data/ (all program data) - $/settings/ (application settings) - $/os/ (for OS use only) - $/os/hashes (a list of relative to $ filepaths, file hash) - $/os/hashes.sig ($/os/hashes fingerprint when signed by the developers public key) - $/os/dev.pub (the developers public key) - $/proc (the process, if its not running then it will be missing) - $/parent (symlink to /app/com.parent.app/ if it has a parent) - - - - - - - diff --git a/Notes/Permissions.txt b/Notes/Permissions.txt @@ -1,75 +0,0 @@ -I want LuaJITOS to use a new permission system, simmilar to what android has. - -each application comes with a manifest.lua file, this file has the following stucture: - -return { - app = { - name = "testapp2"; - dev = "testdev"; - support = "testdev@xmail.com" - privateDir = true; -- gives the program its own folder /apps/addDev.appName/appdata where it can read and write freely, this folder can be accessed by $/my_file.txt - version = "0.0.3" - } - paths = { - all = { - "~/Documents/" - }; - - -- or - - read = { - "~/Documents/" - }; - write = { - "~/Documents/" - }; - delete = { - "~/Documents/" - }; - move = { - "~/Documents/" - }; - }; - domains = { - "www.example.com", - "*.example.com" - } - permissions = { - requestPermissions = true; --alows the app to request permissions at runtime like android - - system = { - execute = false; - enviroment = false; - info = false; - time = true; - }; - - fs = { - read = true; - write = true; - delete = false; - mount = false; - }; - - net = { - internet = true; - local = false; - listen = false; - }; - - hardware = { - audioOut = true; - audioIn = false; - camera = false; - usb = false; - }; - - security = { - crypto = true; - keyring = true; - } - - } -}; - -This lua file is run sandboxed, without any functions, even string and maths removed. It can only return a single table and that MUST have app {name = ... dev = ... }, permissions can be a table of permission or "none", "sandboxed", "user", "admin", "superadmin" diff --git a/OS_Other/OrbitManager.lua b/OS_Other/OrbitManager.lua @@ -1,593 +0,0 @@ --- OrbitManager: Secure permissions manager for LuaJIT OS --- Provides sandboxing and permission-based access control for global functions - -local OrbitManager = {} - --- Private storage using weak tables to prevent external access -local private = setmetatable({}, {__mode = "k"}) - --- Stub function generator - creates wrapper functions that check permissions -local function createStub(orbitInstance, funcPath, realFunc) - return function(...) - local priv = private[orbitInstance] - - -- Find the permission category for this function - local permCategory = priv.map[funcPath] - - if not permCategory then - error("OrbitManager: Function " .. funcPath .. " is not mapped to a permission category", 2) - end - - -- Check if permission is granted - if not priv.perms[permCategory] then - error("OrbitManager: Attempted to call " .. funcPath .. " without required permissions (needs " .. permCategory .. ")", 2) - end - - -- Special handling for filesystem operations - if permCategory == "perms.fs" then - local path = select(1, ...) - if path and type(path) == "string" then - if not orbitInstance:checkPathAllowed(path) then - error("OrbitManager: Attempted to access path '" .. path .. "' which is not in allowedPaths", 2) - end - end - end - - -- Special handling for network operations - if permCategory == "perms.network" then - local domain = select(1, ...) - if domain and type(domain) == "string" then - if not orbitInstance:checkDomainAllowed(domain) then - error("OrbitManager: Attempted to access domain '" .. domain .. "' which is not in allowedDomains", 2) - end - end - end - - -- Call the real function - return realFunc(...) - end -end - --- Wildcard path matching helper -local function matchWildcard(pattern, str) - -- Convert wildcard pattern to Lua pattern - -- Escape special Lua pattern characters except * - local luaPattern = pattern:gsub("[%(%)%.%%%+%-%?%[%]%^%$]", "%%%1") - -- Convert * to .* - luaPattern = luaPattern:gsub("%*", ".*") - -- Anchor the pattern - luaPattern = "^" .. luaPattern .. "$" - - return str:match(luaPattern) ~= nil -end - --- Recursively iterate through a table and replace functions -local function replaceGlobalFunctions(orbitInstance, tbl, priv, path) - path = path or "" - - for key, value in pairs(tbl) do - local fullPath = path == "" and key or (path .. "." .. key) - - if type(value) == "function" then - -- Check if this function is in our map - if priv.map[fullPath] then - -- Store the real function - priv.reals[fullPath] = value - -- Replace with stub - tbl[key] = createStub(orbitInstance, fullPath, value) - end - elseif type(value) == "table" and key ~= "_G" then - -- Recursively process tables, but avoid infinite loops - replaceGlobalFunctions(orbitInstance, value, priv, fullPath) - end - end -end - --- Helper function to initialize instance with common setup -local function initializeInstance(target_G, permsData) - local instance = {} - - -- Initialize private storage for this instance - private[instance] = { - map = { - ["io.open"] = "perms.fs", - ["io.read"] = "perms.fs", - ["io.write"] = "perms.fs", - ["io.close"] = "perms.fs", - ["io.lines"] = "perms.fs", - ["io.input"] = "perms.fs", - ["io.output"] = "perms.fs", - ["os.execute"] = "perms.os", - ["os.exit"] = "perms.os", - ["os.remove"] = "perms.fs", - ["os.rename"] = "perms.fs", - ["os.getenv"] = "perms.os", - ["os.clock"] = "perms.os", - ["os.date"] = "perms.os", - ["os.time"] = "perms.os", - ["os.tmpname"] = "perms.fs", - }, - perms = { - ["perms.fs"] = false, - ["perms.os"] = false, - ["perms.network"] = false, - }, - reals = {}, - allowedPaths = {}, - allowedDomains = {}, - manifestData = {}, -- Store manifest metadata - } - - local priv = private[instance] - - -- Apply permissions data if provided - if permsData and type(permsData) == "table" then - -- Store manifest metadata (name, dev, etc.) - if permsData.name then - priv.manifestData.name = permsData.name - end - if permsData.dev then - priv.manifestData.dev = permsData.dev - end - - -- Update permissions - handle both "perms.fs" and "fs" formats - if permsData.perms then - for perm, value in pairs(permsData.perms) do - -- Normalize permission names - local normalizedPerm = perm - if not perm:match("^perms%.") then - normalizedPerm = "perms." .. perm - end - priv.perms[normalizedPerm] = value - end - end - - -- Update allowed paths - if permsData.allowedPaths then - priv.allowedPaths = permsData.allowedPaths - end - - -- Update allowed domains - if permsData.allowedDomains then - priv.allowedDomains = permsData.allowedDomains - end - end - - -- Replace functions in target_G - if target_G then - replaceGlobalFunctions(instance, target_G, priv, "") - end - - -- Check if a path is allowed - function instance:checkPathAllowed(path) - local priv = private[self] - - -- If no restrictions, deny by default - if not priv.allowedPaths or #priv.allowedPaths == 0 then - return false - end - - -- Check against all allowed paths - for _, allowedPath in ipairs(priv.allowedPaths) do - if matchWildcard(allowedPath, path) then - return true - end - end - - return false - end - - -- Check if a domain is allowed - function instance:checkDomainAllowed(domain) - local priv = private[self] - - -- If no restrictions, deny by default - if not priv.allowedDomains or #priv.allowedDomains == 0 then - return false - end - - -- Check against all allowed domains - for _, allowedDomain in ipairs(priv.allowedDomains) do - if matchWildcard(allowedDomain, domain) then - return true - end - end - - return false - end - - -- Check if a function can be run with optional path/domain - function instance:canRun(funcPath, pathOrDomain) - local priv = private[self] - - -- Find the permission category - local permCategory = priv.map[funcPath] - - if not permCategory then - return false, "Function not mapped to any permission category" - end - - -- Check if permission is granted - if not priv.perms[permCategory] then - return false, "Permission " .. permCategory .. " not granted" - end - - -- Additional checks for filesystem and network - if pathOrDomain then - if permCategory == "perms.fs" then - if not self:checkPathAllowed(pathOrDomain) then - return false, "Path not in allowedPaths" - end - elseif permCategory == "perms.network" then - if not self:checkDomainAllowed(pathOrDomain) then - return false, "Domain not in allowedDomains" - end - end - end - - return true - end - - -- Grant a permission - function instance:grantPermission(permCategory) - local priv = private[self] - -- Normalize permission name - if not permCategory:match("^perms%.") then - permCategory = "perms." .. permCategory - end - priv.perms[permCategory] = true - end - - -- Revoke a permission - function instance:revokePermission(permCategory) - local priv = private[self] - -- Normalize permission name - if not permCategory:match("^perms%.") then - permCategory = "perms." .. permCategory - end - priv.perms[permCategory] = false - end - - -- Add an allowed path - function instance:addAllowedPath(path) - local priv = private[self] - table.insert(priv.allowedPaths, path) - end - - -- Add an allowed domain - function instance:addAllowedDomain(domain) - local priv = private[self] - table.insert(priv.allowedDomains, domain) - end - - -- Get manifest metadata - function instance:getManifestData() - local priv = private[self] - -- Return a copy to prevent modification - local copy = {} - for k, v in pairs(priv.manifestData) do - copy[k] = v - end - return copy - end - - -- Protected metatable - prevents access to internal structure - setmetatable(instance, { - __index = function(t, k) - if k == "map" or k == "perms" or k == "reals" or k == "manifestData" then - error("OrbitManager: Direct access to '" .. k .. "' is not allowed", 2) - end - return rawget(t, k) - end, - __newindex = function(t, k, v) - if k == "map" or k == "perms" or k == "reals" or k == "manifestData" then - error("OrbitManager: Direct modification of '" .. k .. "' is not allowed", 2) - end - rawset(t, k, v) - end, - __metatable = false, -- Hide the metatable - }) - - return instance -end - --- Create a new OrbitManager instance from a permissions file -function OrbitManager.new(target_G, permissionsFile) - permissionsFile = permissionsFile or "perms.lua" - - local permsData = nil - - -- Load permissions from file - local permsChunk, err = loadfile(permissionsFile) - if permsChunk then - permsData = permsChunk() - end - - return initializeInstance(target_G, permsData) -end - --- Create a new OrbitManager instance from a manifest string -function OrbitManager.newFromManifest(target_G, manifestString) - if type(manifestString) ~= "string" then - error("OrbitManager.newFromManifest: manifestString must be a string", 2) - end - - -- Load and execute the manifest string - local manifestChunk, err = load(manifestString, "manifest", "t") - if not manifestChunk then - error("OrbitManager.newFromManifest: Failed to parse manifest: " .. tostring(err), 2) - end - - local success, manifestData = pcall(manifestChunk) - if not success then - error("OrbitManager.newFromManifest: Failed to execute manifest: " .. tostring(manifestData), 2) - end - - if type(manifestData) ~= "table" then - error("OrbitManager.newFromManifest: Manifest must return a table", 2) - end - - return initializeInstance(target_G, manifestData) -end - --- Deep copy a table recursively -local function deepCopy(orig, copies) - copies = copies or {} - local orig_type = type(orig) - local copy - if orig_type == 'table' then - if copies[orig] then - copy = copies[orig] - else - copy = {} - copies[orig] = copy - for orig_key, orig_value in next, orig, nil do - copy[deepCopy(orig_key, copies)] = deepCopy(orig_value, copies) - end - setmetatable(copy, deepCopy(getmetatable(orig), copies)) - end - else - copy = orig - end - return copy -end - --- Recursively build sandbox from whitelist -local function buildSandboxFromWhitelist(whitelist, sourceEnv, orbitInstance, path) - path = path or "" - local sandbox = {} - - for key, value in pairs(whitelist) do - local fullPath = path == "" and key or (path .. "." .. key) - local sourceValue = sourceEnv[key] - - if value == true then - -- Whitelisted - copy directly from source - if sourceValue ~= nil then - if type(sourceValue) == "table" then - sandbox[key] = deepCopy(sourceValue) - else - sandbox[key] = sourceValue - end - end - elseif type(value) == "string" then - -- Permission-controlled function - if type(sourceValue) == "function" then - local priv = private[orbitInstance] - priv.reals[fullPath] = sourceValue - priv.map[fullPath] = value - sandbox[key] = createStub(orbitInstance, fullPath, sourceValue) - elseif sourceValue ~= nil then - sandbox[key] = sourceValue - end - elseif type(value) == "table" then - -- Nested table - recurse - if type(sourceValue) == "table" then - sandbox[key] = buildSandboxFromWhitelist(value, sourceValue, orbitInstance, fullPath) - else - -- Source doesn't have this table, create empty - sandbox[key] = buildSandboxFromWhitelist(value, {}, orbitInstance, fullPath) - end - end - -- If value is false or nil, the function is blocked (not added to sandbox) - end - - return sandbox -end - --- Create a new sandbox environment with OrbitManager from a manifest string -function OrbitManager.newSandbox(manifestString, sandboxEnvPath) - if type(manifestString) ~= "string" then - error("OrbitManager.newSandbox: manifestString must be a string", 2) - end - - sandboxEnvPath = sandboxEnvPath or "/home/b/Programming/LuajitOS/OS/sandboxEnv.lua" - - -- Load the manifest - local manifestChunk, err = load(manifestString, "manifest", "t") - if not manifestChunk then - error("OrbitManager.newSandbox: Failed to parse manifest: " .. tostring(err), 2) - end - - local success, manifestData = pcall(manifestChunk) - if not success then - error("OrbitManager.newSandbox: Failed to execute manifest: " .. tostring(manifestData), 2) - end - - if type(manifestData) ~= "table" then - error("OrbitManager.newSandbox: Manifest must return a table", 2) - end - - -- Load the sandbox whitelist - local whitelistChunk, err = loadfile(sandboxEnvPath) - if not whitelistChunk then - error("OrbitManager.newSandbox: Failed to load sandboxEnv.lua: " .. tostring(err), 2) - end - - local whitelist = whitelistChunk() - if type(whitelist) ~= "table" then - error("OrbitManager.newSandbox: sandboxEnv.lua must return a table", 2) - end - - -- Create an OrbitManager instance (without target_G for now) - local instance = {} - - -- Initialize private storage - private[instance] = { - map = {}, - perms = { - ["perms.fs"] = false, - ["perms.os"] = false, - ["perms.network"] = false, - ["perms.modules"] = false, - }, - reals = {}, - allowedPaths = {}, - allowedDomains = {}, - manifestData = {}, - } - - local priv = private[instance] - - -- Apply manifest data - if manifestData.name then - priv.manifestData.name = manifestData.name - end - if manifestData.dev then - priv.manifestData.dev = manifestData.dev - end - - if manifestData.perms then - for perm, value in pairs(manifestData.perms) do - local normalizedPerm = perm - if not perm:match("^perms%.") then - normalizedPerm = "perms." .. perm - end - priv.perms[normalizedPerm] = value - end - end - - if manifestData.allowedPaths then - priv.allowedPaths = manifestData.allowedPaths - end - - if manifestData.allowedDomains then - priv.allowedDomains = manifestData.allowedDomains - end - - -- Build the sandbox from the whitelist - local sandbox = buildSandboxFromWhitelist(whitelist, _G, instance, "") - - -- Add the _G self-reference - sandbox._G = sandbox - - -- Add instance methods - function instance:checkPathAllowed(path) - local priv = private[self] - if not priv.allowedPaths or #priv.allowedPaths == 0 then - return false - end - for _, allowedPath in ipairs(priv.allowedPaths) do - if matchWildcard(allowedPath, path) then - return true - end - end - return false - end - - function instance:checkDomainAllowed(domain) - local priv = private[self] - if not priv.allowedDomains or #priv.allowedDomains == 0 then - return false - end - for _, allowedDomain in ipairs(priv.allowedDomains) do - if matchWildcard(allowedDomain, domain) then - return true - end - end - return false - end - - function instance:canRun(funcPath, pathOrDomain) - local priv = private[self] - local permCategory = priv.map[funcPath] - if not permCategory then - return false, "Function not mapped to any permission category" - end - if not priv.perms[permCategory] then - return false, "Permission " .. permCategory .. " not granted" - end - if pathOrDomain then - if permCategory == "perms.fs" then - if not self:checkPathAllowed(pathOrDomain) then - return false, "Path not in allowedPaths" - end - elseif permCategory == "perms.network" then - if not self:checkDomainAllowed(pathOrDomain) then - return false, "Domain not in allowedDomains" - end - end - end - return true - end - - function instance:grantPermission(permCategory) - local priv = private[self] - if not permCategory:match("^perms%.") then - permCategory = "perms." .. permCategory - end - priv.perms[permCategory] = true - end - - function instance:revokePermission(permCategory) - local priv = private[self] - if not permCategory:match("^perms%.") then - permCategory = "perms." .. permCategory - end - priv.perms[permCategory] = false - end - - function instance:addAllowedPath(path) - local priv = private[self] - table.insert(priv.allowedPaths, path) - end - - function instance:addAllowedDomain(domain) - local priv = private[self] - table.insert(priv.allowedDomains, domain) - end - - function instance:getManifestData() - local priv = private[self] - local copy = {} - for k, v in pairs(priv.manifestData) do - copy[k] = v - end - return copy - end - - function instance:getSandbox() - return sandbox - end - - -- Protected metatable - setmetatable(instance, { - __index = function(t, k) - if k == "map" or k == "perms" or k == "reals" or k == "manifestData" then - error("OrbitManager: Direct access to '" .. k .. "' is not allowed", 2) - end - return rawget(t, k) - end, - __newindex = function(t, k, v) - if k == "map" or k == "perms" or k == "reals" or k == "manifestData" then - error("OrbitManager: Direct modification of '" .. k .. "' is not allowed", 2) - end - rawset(t, k, v) - end, - __metatable = false, - }) - - return instance, sandbox -end - -return OrbitManager diff --git a/OS_Other/example_manifest_usage.lua b/OS_Other/example_manifest_usage.lua @@ -1,70 +0,0 @@ --- Example: How to use OrbitManager with manifest files and strings - -local OrbitManager = require("OrbitManager") - -print("=== OrbitManager Usage Examples ===\n") - --- Example 1: Create from manifest string (embedded in code) -print("Example 1: Creating from manifest string...") -local manifestString = [[ -return { - name = "myapp"; - dev = "devname"; - perms = { - fs = true, - os = false - }; - allowedPaths = { "/tmp/*" }; - allowedDomains = { "api.myapp.io" } -} -]] - -local sandbox1 = { io = { open = function() end }, os = { clock = function() end } } -local orbit1 = OrbitManager.newFromManifest(sandbox1, manifestString) -print("✓ Created from manifest string\n") - --- Example 2: Create from manifest file -print("Example 2: Creating from manifest file...") -local manifestPath = "/home/b/Programming/LuajitOS/OS/apps/com.luajitos.testapp/settings/orbit_manifest.lua" - --- Read the manifest file -local file = io.open(manifestPath, "r") -if file then - local manifestContent = file:read("*all") - file:close() - - local sandbox2 = { io = { open = function() end }, os = { clock = function() end } } - local orbit2 = OrbitManager.newFromManifest(sandbox2, manifestContent) - - local metadata = orbit2:getManifestData() - print("✓ Created from manifest file") - print(" App:", metadata.name) - print(" Developer:", metadata.dev) - print(" Version:", metadata.version or "N/A") -else - print("✗ Could not open manifest file") -end -print() - --- Example 3: Create from perms.lua file (original method) -print("Example 3: Creating from perms.lua (traditional method)...") -local sandbox3 = { io = { open = function() end }, os = { clock = function() end } } -local orbit3 = OrbitManager.new(sandbox3, "perms.lua") -print("✓ Created from perms.lua\n") - --- Example 4: Using canRun to check permissions -print("Example 4: Checking permissions with canRun...") -local canRun, reason = orbit2:canRun("io.open", "/tmp/test.txt") -print(" Can run io.open('/tmp/test.txt'):", canRun) -if not canRun then - print(" Reason:", reason) -end - -canRun, reason = orbit2:canRun("io.open", "/etc/shadow") -print(" Can run io.open('/etc/shadow'):", canRun) -if not canRun then - print(" Reason:", reason) -end -print() - -print("=== Examples Complete ===") diff --git a/OS_Other/example_sandbox_runner.lua b/OS_Other/example_sandbox_runner.lua @@ -1,226 +0,0 @@ --- Example: How to run untrusted code in an OrbitManager sandbox - -local OrbitManager = require("OrbitManager") - -print("=== Sandbox Runner Example ===\n") - --- Example 1: Running a simple app with limited permissions -print("Example 1: Running user code in a sandbox\n") - -local appManifest = [[ -return { - name = "userapp"; - dev = "untrusteddev"; - perms = { - fs = false, - os = false, - network = false - }; - allowedPaths = {}; - allowedDomains = {} -} -]] - --- Create the sandbox -local orbit, sandbox = OrbitManager.newSandbox(appManifest) -print("Created sandbox for 'userapp' by 'untrusteddev'") - --- Untrusted user code -local userCode = [[ - -- This code runs in the sandbox - local function fibonacci(n) - if n <= 1 then return n end - return fibonacci(n - 1) + fibonacci(n - 2) - end - - local result = {} - for i = 1, 10 do - table.insert(result, fibonacci(i)) - end - - return table.concat(result, ", ") -]] - -print("\nRunning user code...") -local chunk, err = load(userCode, "userCode", "t", sandbox) -if chunk then - local success, result = pcall(chunk) - if success then - print("✓ Result:", result) - else - print("✗ Error:", result) - end -else - print("✗ Compile error:", err) -end - -print("\n" .. string.rep("-", 60) .. "\n") - --- Example 2: Running code that tries to do something malicious -print("Example 2: Blocking malicious code\n") - -local maliciousCode = [[ - -- Try to access the filesystem (should fail) - local file = io.open("/etc/passwd", "r") - if file then - return "SECURITY BREACH: Accessed /etc/passwd" - else - return "Failed to open file (good!)" - end -]] - -print("Running malicious code that tries to access /etc/passwd...") -chunk, err = load(maliciousCode, "maliciousCode", "t", sandbox) -if chunk then - local success, result = pcall(chunk) - if success then - print("✓ Code ran, result:", result) - else - print("✓ Security worked! Error:", result) - end -else - print("✗ Compile error:", err) -end - -print("\n" .. string.rep("-", 60) .. "\n") - --- Example 3: App with filesystem access to specific directory -print("Example 3: App with limited filesystem access\n") - -local fsAppManifest = [[ -return { - name = "fileprocessor"; - dev = "trusteddev"; - perms = { - fs = true, - os = false, - network = false - }; - allowedPaths = { - "/tmp/*" - }; - allowedDomains = {} -} -]] - -local orbit3, sandbox3 = OrbitManager.newSandbox(fsAppManifest) -print("Created sandbox with /tmp/* access") - -local fsCode = [[ - -- Try to open a file in /tmp (should work) - local tmpFile = io.open("/tmp/test.txt", "w") - if tmpFile then - -- In real scenario, this would write to the file - return "SUCCESS: Can access /tmp/test.txt" - else - return "FAILED: Could not access /tmp/test.txt" - end -]] - -print("\nRunning code with /tmp access...") -chunk, err = load(fsCode, "fsCode", "t", sandbox3) -if chunk then - local success, result = pcall(chunk) - print((success and "✓" or "✗") .. " " .. tostring(result)) -else - print("✗ Compile error:", err) -end - --- Now try to access something outside allowed paths -local unauthorizedFsCode = [[ - -- Try to open a file outside allowed paths (should fail) - local file = io.open("/etc/shadow", "r") - if file then - return "SECURITY BREACH: Accessed /etc/shadow" - else - return "Correctly blocked" - end -]] - -print("Running code trying to access /etc/shadow...") -chunk, err = load(unauthorizedFsCode, "unauthorizedFsCode", "t", sandbox3) -if chunk then - local success, result = pcall(chunk) - if not success then - print("✓ Access blocked:", result) - else - print("✗ " .. result) - end -else - print("✗ Compile error:", err) -end - -print("\n" .. string.rep("-", 60) .. "\n") - --- Example 4: Demonstrating the complete app lifecycle -print("Example 4: Complete app lifecycle\n") - -local appManifest4 = [[ -return { - name = "calculator"; - dev = "mathdev"; - version = "1.0"; - perms = { - fs = false, - os = false, - network = false - }; - allowedPaths = {}; - allowedDomains = {} -} -]] - -local orbit4, sandbox4 = OrbitManager.newSandbox(appManifest4) -local metadata = orbit4:getManifestData() - -print("Loaded app:", metadata.name) -print("Developer:", metadata.dev) -print("Version:", metadata.version or "N/A") - --- The app's main code -local appCode = [[ - -- Simple calculator app - local Calculator = {} - - function Calculator.add(a, b) - return a + b - end - - function Calculator.multiply(a, b) - return a * b - end - - function Calculator.factorial(n) - if n <= 1 then return 1 end - return n * Calculator.factorial(n - 1) - end - - -- Return the API - return Calculator -]] - -print("\nLoading calculator app...") -chunk, err = load(appCode, "calculator", "t", sandbox4) -if chunk then - local success, Calculator = pcall(chunk) - if success then - print("✓ App loaded successfully") - print("\nTesting calculator:") - print(" 2 + 3 =", Calculator.add(2, 3)) - print(" 4 * 5 =", Calculator.multiply(4, 5)) - print(" 5! =", Calculator.factorial(5)) - else - print("✗ Error:", Calculator) - end -else - print("✗ Compile error:", err) -end - -print("\n" .. string.rep("-", 60) .. "\n") -print("=== Examples Complete ===") -print("\nKey takeaways:") -print("1. newSandbox creates a safe environment based on sandboxEnv.lua") -print("2. Only whitelisted functions are available to sandboxed code") -print("3. Permission-controlled functions (io, os) are wrapped with stubs") -print("4. Stubs check manifest permissions before allowing execution") -print("5. Filesystem and network access can be restricted to specific paths/domains") diff --git a/OS_Other/fs.lua b/OS_Other/fs.lua @@ -1,29 +0,0 @@ - -local rootNode = { - "os" - "apps" - "tmp" -} - -local FS = {} -local FSInstance = {} - -FSInstance.checkPath = function(path) - -end - -FSInstance.fileRead = function(path) - -end - -function FS.removeDots(input) - for i=1, str.len() -end - -function FS.new(path, manifest) - local instance = { - rootDir = path or "/"; - curPath = "/app/com."..manifest.devName.."." - allowedPaths = manifest.allowedPaths or {}; - } -end diff --git a/OS_Other/init3.lua b/OS_Other/init3.lua @@ -1,80 +0,0 @@ -osprint("LuaJIT OS initialized\n") - --- Test if built-in string functions work now that we loaded the string library -osprint("\n=== Testing string.byte ===\n") -local b = string.byte("H") -osprint("byte('H') = ") -osprint(tostring(b)) -osprint("\n") - -osprint("\n=== Testing string.char ===\n") -local c = string.char(72, 69, 76, 76, 79) -osprint("char(72, 69, 76, 76, 79) = ") -osprint(c) -osprint("\n") - -osprint("\n=== Testing string.sub ===\n") -local s = string.sub("HELLO WORLD", 7, 11) -osprint("sub('HELLO WORLD', 7, 11) = ") -osprint(s) -osprint("\n") - -osprint("\n=== Testing string.upper ===\n") -local u = string.upper("hello") -osprint("upper('hello') = ") -osprint(u) -osprint("\n") - -osprint("\n=== Testing string.lower ===\n") -local l = string.lower("WORLD") -osprint("lower('WORLD') = ") -osprint(l) -osprint("\n") - -osprint("\n=== Testing string.find ===\n") -local pos = string.find("hello world", "world") -osprint("find('hello world', 'world') = ") -osprint(tostring(pos)) -osprint("\n") - -osprint("\n=== Testing string.gsub ===\n") -local result = string.gsub("hello world", "world", "LuaJIT") -osprint("gsub('hello world', 'world', 'LuaJIT') = ") -osprint(result) -osprint("\n") - -osprint("\n=== Testing string.match ===\n") -local match = string.match("hello world", "w%w+") -osprint("match('hello world', 'w%%w+') = ") -osprint(tostring(match)) -osprint("\n") - -osprint("\n=== Testing string.gmatch ===\n") -osprint("gmatch('one two three', '%%w+'):\n") -for word in string.gmatch("one two three", "%w+") do - osprint(" ") - osprint(word) - osprint("\n") -end - -osprint("\n=== All string tests passed! ===\n") - -osprint("\n=== Testing RunString ===\n") -local result = RunString("osprint('Hello from RunString!\\n')") -osprint("RunString result: ") -osprint(tostring(result)) -osprint("\n") - -osprint("\n=== Testing CompileString ===\n") -local func, err = CompileString("return 2 + 2") -if func then - osprint("CompileString: Compilation successful\n") - local success, result = pcall(func) - if success then - osprint("Execution result: ") - osprint(tostring(result)) - osprint("\n") - end -end - -osprint("\n=== All tests completed successfully! ===\n") diff --git a/OS_Other/mymodule.lua b/OS_Other/mymodule.lua @@ -1,12 +0,0 @@ --- Test module -local M = {} - -function M.hello() - return "Hello from mymodule!" -end - -function M.add(a, b) - return a + b -end - -return M diff --git a/OS_Other/perms.lua b/OS_Other/perms.lua @@ -1,23 +0,0 @@ --- Permissions configuration file --- This file is loaded by OrbitManager to determine what permissions are granted - -return { - -- Permission grants - perms = { - ["perms.fs"] = false, -- Filesystem access - ["perms.os"] = false, -- OS functions - ["perms.network"] = false, -- Network access - }, - - -- Allowed filesystem paths (supports wildcards) - allowedPaths = { - "/tmp/*", -- Allow all files in /tmp - "/home/user/data/*" -- Allow all files in /home/user/data - }, - - -- Allowed network domains (supports wildcards) - allowedDomains = { - "*.example.com", -- Allow all subdomains of example.com - "api.trusted.org" -- Allow specific domain - }, -} diff --git a/OS_Other/ramdisk2.lua b/OS_Other/ramdisk2.lua @@ -1,416 +0,0 @@ -local ramdisk = {} - --- Node metatable for directories -local dirNode = {} -dirNode.__index = dirNode - --- Node metatable for files -local fileNode = {} -fileNode.__index = fileNode - --- Helper function to split path into components -local function splitPath(path) - local components = {} - -- Remove leading slash if present - path = path:gsub("^/+", "") - -- Split by slash - for component in path:gmatch("[^/]+") do - table.insert(components, component) - end - return components -end - --- Helper function to find root node -local function findRoot(node) - while node.parent ~= nil do - node = node.parent - end - return node -end - --- Traverse method for both file and directory nodes -local function traverse(self, path) - -- Start from root - local root = findRoot(self) - local current = root - - -- Split path into components - local components = splitPath(path) - - -- Traverse through each component - for i, component in ipairs(components) do - if current.type ~= "directory" then - return nil, "not a directory: " .. current.name - end - - -- Check if this is the last component - local isLast = (i == #components) - - -- Search in directories first - local found = false - for _, dir in ipairs(current.dirs) do - if dir.name == component then - current = dir - found = true - break - end - end - - -- If not found in dirs and this is the last component, check files - if not found and isLast then - for _, file in ipairs(current.files) do - if file.name == component then - current = file - found = true - break - end - end - end - - -- If still not found, check in dirs for last component (could be a directory) - if not found then - return nil, "path not found: " .. component - end - end - - return current -end - --- Method to create a new directory -function dirNode:newDir(name) - local dir = { - name = name, - type = "directory", - parent = self, - dirs = {}, - files = {} - } - setmetatable(dir, dirNode) - table.insert(self.dirs, dir) - return dir -end - --- Method to create a new file -function dirNode:newFile(name, contents) - local file = { - name = name, - type = "file", - parent = self, - contents = contents or "" - } - setmetatable(file, fileNode) - table.insert(self.files, file) - return file -end - --- Read method for files -function fileNode:read() - return self.contents -end - --- Write method for files -function fileNode:write(contents) - self.contents = contents -end - --- Delete method for files -function fileNode:delete() - if self.parent then - -- Remove from parent's files array - for i, file in ipairs(self.parent.files) do - if file == self then - table.remove(self.parent.files, i) - break - end - end - end - -- Clear file data - self.name = nil - self.parent = nil - self.contents = nil -end - --- Delete method for directories -function dirNode:delete() - if self.parent then - -- Remove from parent's dirs array - for i, dir in ipairs(self.parent.dirs) do - if dir == self then - table.remove(self.parent.dirs, i) - break - end - end - end - -- Clear directory data - self.name = nil - self.parent = nil - -- Note: dirs and files arrays are left for garbage collection -end - --- Add traverse method to both metatables -dirNode.traverse = traverse -fileNode.traverse = traverse - --- Function to create a root directory node -function ramdisk.createRoot() - local root = { - name = "", - type = "directory", - parent = nil, - dirs = {}, - files = {} - } - setmetatable(root, dirNode) - return root -end - --- Helper function to get full path of a node -local function getFullPath(node) - local parts = {} - local current = node - - while current.parent ~= nil do - table.insert(parts, 1, current.name) - current = current.parent - end - - return table.concat(parts, "/") -end - --- Helper function to check if content is binary (contains non-printable chars) -local function isBinary(content) - if type(content) ~= "string" then - return false - end - - for i = 1, #content do - local byte = content:byte(i) - -- Check for control characters except tab, newline, carriage return - if byte < 32 and byte ~= 9 and byte ~= 10 and byte ~= 13 then - return true - end - -- Check for extended ASCII - if byte > 127 then - return true - end - end - return false -end - --- Helper function to encode binary data to base64 -local function base64Encode(data) - local b = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' - return ((data:gsub('.', function(x) - local r,b='',x:byte() - for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end - return r; - end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x) - if (#x < 6) then return '' end - local c=0 - for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end - return b:sub(c+1,c+1) - end)..({ '', '==', '=' })[#data%3+1]) -end - --- Helper function to decode base64 to binary data -local function base64Decode(data) - local b = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' - data = string.gsub(data, '[^'..b..'=]', '') - return (data:gsub('.', function(x) - if (x == '=') then return '' end - local r,f='',(b:find(x)-1) - for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end - return r; - end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x) - if (#x ~= 8) then return '' end - local c=0 - for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end - return string.char(c) - end)) -end - --- Helper function to escape special characters in text content -local function escapeText(text) - text = text:gsub("\\", "\\\\") -- Backslash must be first - text = text:gsub("\n", "\\n") -- Newline - text = text:gsub("\t", "\\t") -- Tab - text = text:gsub("\r", "\\r") -- Carriage return - return text -end - --- Helper function to unescape special characters in text content -local function unescapeText(text) - text = text:gsub("\\r", "\r") -- Carriage return - text = text:gsub("\\t", "\t") -- Tab - text = text:gsub("\\n", "\n") -- Newline - text = text:gsub("\\\\", "\\") -- Backslash must be last - return text -end - --- Function to save the filesystem to serialized format -function ramdisk.saveFS(rootdir) - local dirs = {} - local files = {} - - -- Recursive function to traverse directories - local function traverseDir(dir, currentPath) - -- Add directory path (with trailing slash) - if currentPath ~= "" then - table.insert(dirs, currentPath .. "/") - end - - -- Process subdirectories - for _, subdir in ipairs(dir.dirs) do - local subdirPath = currentPath == "" and subdir.name or currentPath .. "/" .. subdir.name - traverseDir(subdir, subdirPath) - end - - -- Process files - for _, file in ipairs(dir.files) do - local filePath = currentPath == "" and file.name or currentPath .. "/" .. file.name - local contents = file.contents or "" - - if isBinary(contents) then - table.insert(files, filePath .. "~~~~BIN:" .. base64Encode(contents)) - else - table.insert(files, filePath .. "~~~~" .. escapeText(contents)) - end - end - end - - -- Start traversal from root - traverseDir(rootdir, "") - - -- Build the final format: [[dirs||||files]] - local dirSection = table.concat(dirs, "||||") - local fileSection = table.concat(files, "||||") - - return "[[" .. dirSection .. "||||" .. fileSection .. "]]" -end - --- Function to load a filesystem from serialized format -function ramdisk.loadFS(serialized) - -- Create new root - local root = ramdisk.createRoot() - - -- Remove the [[ and ]] wrapper - if not serialized:match("^%[%[.*%]%]$") then - error("Invalid serialized format: missing [[ ]] wrapper") - end - - local content = serialized:sub(3, -3) -- Remove [[ and ]] - - -- Split by |||| to separate entries - local entries = {} - local currentEntry = "" - local i = 1 - while i <= #content do - -- Check if we're at a |||| separator - if content:sub(i, i+3) == "||||" then - if currentEntry ~= "" then - table.insert(entries, currentEntry) - currentEntry = "" - end - i = i + 4 -- Skip the |||| - else - currentEntry = currentEntry .. content:sub(i, i) - i = i + 1 - end - end - -- Don't forget the last entry - if currentEntry ~= "" then - table.insert(entries, currentEntry) - end - - -- Track created directories - local createdDirs = {} - createdDirs[""] = root -- Root is always available - - -- Helper to ensure directory exists - local function ensureDir(path) - if createdDirs[path] then - return createdDirs[path] - end - - -- Split path into components - local components = splitPath(path) - local current = root - local currentPath = "" - - for _, component in ipairs(components) do - local nextPath = currentPath == "" and component or currentPath .. "/" .. component - - if not createdDirs[nextPath] then - -- Check if directory already exists - local found = false - for _, dir in ipairs(current.dirs) do - if dir.name == component then - current = dir - found = true - break - end - end - - if not found then - current = current:newDir(component) - end - - createdDirs[nextPath] = current - else - current = createdDirs[nextPath] - end - - currentPath = nextPath - end - - return current - end - - -- First pass: create all directories - for _, entry in ipairs(entries) do - if entry:match("/$") then -- It's a directory - local dirPath = entry:sub(1, -2) -- Remove trailing slash - ensureDir(dirPath) - end - end - - -- Second pass: create all files - for _, entry in ipairs(entries) do - if entry:match("~~~~") then -- It's a file - local separatorPos = entry:find("~~~~") - if separatorPos then - local filePath = entry:sub(1, separatorPos - 1) - local fileContent = entry:sub(separatorPos + 4) - - -- Determine parent directory and filename - local lastSlash = filePath:match("^.*()/") - local parentPath, fileName - - if lastSlash then - parentPath = filePath:sub(1, lastSlash - 1) - fileName = filePath:sub(lastSlash + 1) - else - parentPath = "" - fileName = filePath - end - - -- Get or create parent directory - local parentDir = ensureDir(parentPath) - - -- Check if it's binary - if fileContent:match("^BIN:") then - local base64Data = fileContent:sub(5) -- Remove "BIN:" prefix - local binaryContent = base64Decode(base64Data) - parentDir:newFile(fileName, binaryContent) - else - local textContent = unescapeText(fileContent) - parentDir:newFile(fileName, textContent) - end - end - end - end - - return root -end - -return ramdisk diff --git a/OS_Other/ramfs.lua b/OS_Other/ramfs.lua @@ -1,225 +0,0 @@ -local ramdisk_packed =[[os/ -apps/ -os/test.lua osprint("test123! test123! test123!")\nosprint("\_-'-_/")\n]] - - -function string.trimr(str, char) - char = char or " " - - local len, epos = string.len(str), 1 - - for i=1,len do - if str:sub(len - epos, len - epos) == char then - epos = epos + 1 - end - end - - return str:sub(1, len - epos) -end - -function string.triml(str, char) - char = char or " " - - local len, spos = string.len(str), 1 - - for i=1,len do - if str:sub(spos, spos) == char then - spos = spos + 1 - end - end - return str:sub(spos, len) -end - -function string.trim(str, char) - return string.triml(string.trimr(str, char), char) -end - -function ramdisk_followPath(fs, path, curnode) - path = string.trim(path:triml("/"), "/") - - curnode = curnode or fs - - -- Empty path means we're at the target - if string.len(path) == 0 then - return curnode, "" - end - - if path:match("^..") then - if curnode.parent == nil then - return curnode, path - else - curnode = curnode.parent - end - end - - local name = path:match("([^/]+)") - local remaining = path:match("/(.*)$") or "" - - print("DEBUG: path='"..path.."' name='"..name.."' remaining='"..remaining.."'") - - if curnode.dirs[name] then - if string.len(remaining) > 0 then - return ramdisk_followPath(fs, remaining, curnode.dirs[name]) - else - return curnode.dirs[name], "" - end - end - - if curnode.files then - if curnode.files[name] then - if string.len(remaining) > 0 then - return ramdisk_followPath(fs, remaining, curnode.files[name]) - else - return curnode.files[name] - end - end - end - - return curnode, name -end - - -local FSInstance = { - new = function(filesystem, manifest) - if filesystem == nil or manifest == nil or manifest.allowedDirs == nil then - return nil - end - local allowedDirs = manifest.allowedDirs - local instance = { - root = filesystem; - allowedDirs = allowedDirs; - pathHashes = {}; - } - return setmetatable(instance, FSInstance) - end -} -FSInstance.__index = FSInstance - -function FSInstance.read(path) - local node, path = ramdisk_followPath(self.root, path) - if node and node.type == "file" then - return node.content - end -end - - -function ramdisk_addDir(filesystem, path) - local node, name = ramdisk_followPath(filesystem, path) - - local dir = { - name = name; - type = "directory"; - dirs = {}; - files = {}; - parent = node; - } - - node.dirs[name] = dir -end - -function ramdisk_addFile(filesystem, path, content) - local node, name = ramdisk_followPath(filesystem, path) - local file = { - name = name; - type = "file"; - content = content; - parent = node; - } - - node.files[name] = file -end - -function ramdisk_print(node, path) - if node == nil then return nil end - - local path = path or "" - local fullpath = path..(node.name or "") - - if node.type == "directory" then - fullpath = fullpath.."/" - end - - print(fullpath) - - if node.type == "directory" then - -- Sort keys to ensure consistent ordering - local dirKeys = {} - for k in pairs(node.dirs) do - table.insert(dirKeys, k) - end - table.sort(dirKeys) - - -- Print directories depth-first - for _, k in ipairs(dirKeys) do - ramdisk_print(node.dirs[k], fullpath) - end - - -- Then print files - local fileKeys = {} - for k in pairs(node.files) do - table.insert(fileKeys, k) - end - table.sort(fileKeys) - - for _, k in ipairs(fileKeys) do - ramdisk_print(node.files[k], fullpath) - end - end -end - ---ramdisk_addDir(filesystem, "/os/") - ---ramdisk_addDir(filesystem, "/apps/") - - - - - -function ramdisk_unpack(packed, allowedDirs) - local fs = { - type = "directory"; - dirs = {}; - files = {}; - allowedDirs = allowedDirs; - parent = nil; - } - - while packed and string.len(packed) > 0 do - local line = packed:match("([^\n]*)\n?") - packed = packed:sub(string.len(line) + 2, string.len(packed)) - - if string.len(line) <= 1 then - break - end - - local path, content = line:match("([^\t]+)\t(.*)") - - if path == nil and line:match("^.+/$") then - path = line - print("dir: "..path) - ramdisk_addDir(fs, path) - elseif path ~= nil then - print("file: "..path) - print("content: "..(content or "")) - ramdisk_addFile(fs, path, content) - end - - end - - return fs -end - -local unpacked_fs = ramdisk_unpack(ramdisk_packed) - -print("~~~~~~~~~~~~~~~~~~") -print("Manual filesystem:") -ramdisk_print(filesystem) -print("~~~~~~~~~~~~~~~~~~") -print("Unpacked filesystem:") -ramdisk_print(unpacked_fs) -print("~~~~~~~~~~~~~~~~~~") -local fs = FSInstance.new(unpacked_fs, { allowedDirs = "all" }) -print("test.lua:", fs:read("/os/test.lua")) -print("~~~~~~~~~~~~~~~~~~") - - diff --git a/OS_Other/sandboxEnv.lua b/OS_Other/sandboxEnv.lua @@ -1,139 +0,0 @@ --- Sandbox Environment Whitelist --- This file defines which functions are available in a sandboxed environment --- Functions not listed here will be stubbed out or replaced with permission-checked versions - -return { - -- Basic Lua functions (always safe) - assert = true, - error = true, - ipairs = true, - next = true, - pairs = true, - pcall = true, - print = true, - select = true, - tonumber = true, - tostring = true, - type = true, - unpack = true, - xpcall = true, - _VERSION = true, - - -- String library (safe) - string = { - byte = true, - char = true, - find = true, - format = true, - gmatch = true, - gsub = true, - len = true, - lower = true, - match = true, - rep = true, - reverse = true, - sub = true, - upper = true, - }, - - -- Table library (safe) - table = { - concat = true, - insert = true, - maxn = true, - remove = true, - sort = true, - }, - - -- Math library (safe) - math = { - abs = true, - acos = true, - asin = true, - atan = true, - atan2 = true, - ceil = true, - cos = true, - cosh = true, - deg = true, - exp = true, - floor = true, - fmod = true, - frexp = true, - huge = true, - ldexp = true, - log = true, - log10 = true, - max = true, - min = true, - modf = true, - pi = true, - pow = true, - rad = true, - random = true, - randomseed = true, - sin = true, - sinh = true, - sqrt = true, - tan = true, - tanh = true, - }, - - -- OS library (restricted - requires permissions) - os = { - clock = "perms.os", -- Requires OS permission - date = "perms.os", -- Requires OS permission - difftime = "perms.os", -- Requires OS permission - time = "perms.os", -- Requires OS permission - execute = "perms.os", -- Requires OS permission - exit = "perms.os", -- Requires OS permission - getenv = "perms.os", -- Requires OS permission - remove = "perms.fs", -- Requires FS permission - rename = "perms.fs", -- Requires FS permission - tmpname = "perms.fs", -- Requires FS permission - }, - - -- IO library (restricted - requires permissions) - io = { - close = "perms.fs", - flush = "perms.fs", - input = "perms.fs", - lines = "perms.fs", - open = "perms.fs", - output = "perms.fs", - read = "perms.fs", - tmpfile = "perms.fs", - type = "perms.fs", - write = "perms.fs", - }, - - -- Debug library (completely blocked for security) - -- debug = nil, - - -- Package/module system (restricted) - require = "perms.modules", - module = "perms.modules", - package = { - loaded = true, - preload = true, - -- Block these for security - -- loadlib = nil, - -- cpath = nil, - -- path = nil, - }, - - -- Coroutine library (safe) - coroutine = { - create = true, - resume = true, - running = true, - status = true, - wrap = true, - yield = true, - }, - - -- Custom LuaJIT OS functions (if available) - osprint = true, - RunString = "perms.os", - CompileString = "perms.os", -} diff --git a/OS_Other/stringfix.lua b/OS_Other/stringfix.lua @@ -1,169 +0,0 @@ --- stringfix.lua: Pure Lua string function implementations --- for bare metal LuajitOS where C string functions cause triple faults - -osprint("Loading stringfix.lua...\n") - --- Save the built-in sub function if it exists and works -local builtin_sub = string.sub - --- Create character/byte lookup tables using only string literals and sub -local byte_to_char = {} -local char_to_byte = {} - --- Build lookup using string literals with all ASCII characters -local ascii = "" -for i = 0, 255 do - if i < 32 then - -- Control characters - if i == 0 then ascii = ascii .. "\x00" - elseif i == 1 then ascii = ascii .. "\x01" - elseif i == 2 then ascii = ascii .. "\x02" - elseif i == 3 then ascii = ascii .. "\x03" - elseif i == 4 then ascii = ascii .. "\x04" - elseif i == 5 then ascii = ascii .. "\x05" - elseif i == 6 then ascii = ascii .. "\x06" - elseif i == 7 then ascii = ascii .. "\x07" - elseif i == 8 then ascii = ascii .. "\x08" - elseif i == 9 then ascii = ascii .. "\x09" - elseif i == 10 then ascii = ascii .. "\x0A" - elseif i == 11 then ascii = ascii .. "\x0B" - elseif i == 12 then ascii = ascii .. "\x0C" - elseif i == 13 then ascii = ascii .. "\x0D" - elseif i == 14 then ascii = ascii .. "\x0E" - elseif i == 15 then ascii = ascii .. "\x0F" - elseif i == 16 then ascii = ascii .. "\x10" - elseif i == 17 then ascii = ascii .. "\x11" - elseif i == 18 then ascii = ascii .. "\x12" - elseif i == 19 then ascii = ascii .. "\x13" - elseif i == 20 then ascii = ascii .. "\x14" - elseif i == 21 then ascii = ascii .. "\x15" - elseif i == 22 then ascii = ascii .. "\x16" - elseif i == 23 then ascii = ascii .. "\x17" - elseif i == 24 then ascii = ascii .. "\x18" - elseif i == 25 then ascii = ascii .. "\x19" - elseif i == 26 then ascii = ascii .. "\x1A" - elseif i == 27 then ascii = ascii .. "\x1B" - elseif i == 28 then ascii = ascii .. "\x1C" - elseif i == 29 then ascii = ascii .. "\x1D" - elseif i == 30 then ascii = ascii .. "\x1E" - elseif i == 31 then ascii = ascii .. "\x1F" - end - elseif i >= 32 and i < 127 then - -- Printable ASCII - build from literal string - local printable = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" - ascii = ascii .. builtin_sub(printable, i - 31, i - 31) - elseif i == 127 then - ascii = ascii .. "\x7F" - else - -- Extended ASCII - use placeholder - ascii = ascii .. "?" - end - - -- Build lookup tables - local ch = builtin_sub(ascii, i + 1, i + 1) - byte_to_char[i] = ch - if i < 128 then -- Only map standard ASCII to avoid collisions - char_to_byte[ch] = i - end -end - -osprint("Lookup tables built\n") - --- Override string.byte with pure Lua implementation -function string.byte(s, i, j) - i = i or 1 - j = j or i - local len = #s - - -- Handle negative indices - if i < 0 then i = len + i + 1 end - if j < 0 then j = len + j + 1 end - - -- Clamp to bounds - if i < 1 then i = 1 end - if j > len then j = len end - if i > j then return end - - -- Extract bytes - local results = {} - for pos = i, j do - local ch = builtin_sub(s, pos, pos) - local b = char_to_byte[ch] - if b then - results[#results + 1] = b - else - -- Unknown character, return '?' - results[#results + 1] = 63 - end - end - - -- Return multiple values - if #results == 1 then - return results[1] - else - return table.unpack(results) - end -end - --- Override string.char with pure Lua implementation -function string.char(...) - local args = {...} - local result = {} - - for i = 1, #args do - local b = args[i] - if b < 0 or b > 255 then - error("bad argument to 'char' (invalid byte value)") - end - result[i] = byte_to_char[b] or "?" - end - - return table.concat(result) -end - -osprint("string.byte and string.char overridden\n") - --- Additional string functions using our safe byte/char - -function string.charAt(s, i) - local len = #s - if i < 0 then i = len + i + 1 end - if i < 1 or i > len then return "" end - return builtin_sub(s, i, i) -end - -function string.reverse(s) - local result = {} - for i = #s, 1, -1 do - result[#result + 1] = builtin_sub(s, i, i) - end - return table.concat(result) -end - -function string.lower(s) - local result = {} - for i = 1, #s do - local b = string.byte(s, i) - -- A-Z is 65-90 - if b >= 65 and b <= 90 then - b = b + 32 - end - result[#result + 1] = string.char(b) - end - return table.concat(result) -end - -function string.upper(s) - local result = {} - for i = 1, #s do - local b = string.byte(s, i) - -- a-z is 97-122 - if b >= 97 and b <= 122 then - b = b - 32 - end - result[#result + 1] = string.char(b) - end - return table.concat(result) -end - -osprint("stringfix.lua loaded successfully!\n") diff --git a/OS_Other/test_escape.lua b/OS_Other/test_escape.lua @@ -1,40 +0,0 @@ -local ramdisk = require("ramdisk2") - --- Create a simple test -local root = ramdisk.createRoot() -local testDir = root:newDir("test") -testDir:newFile("example.txt", "Line 1\nLine 2\tTabbed\rCarriage\nPath: C:\\Windows") - -print("=== Original File Content ===") -local file = root:traverse("test/example.txt") -print(file:read()) - -print("\n=== Serialized (should have escaped chars) ===") -local serialized = ramdisk.saveFS(root) --- Show character by character for newlines -for i = 1, #serialized do - local char = serialized:sub(i, i) - local byte = char:byte() - if byte == 10 then - io.write("[\\n]") - elseif byte == 9 then - io.write("[\\t]") - elseif byte == 13 then - io.write("[\\r]") - elseif byte == 92 then - io.write("[\\]") - else - io.write(char) - end -end -print("\n") - -print("\n=== Loading back ===") -local loadedRoot = ramdisk.loadFS(serialized) -local loadedFile = loadedRoot:traverse("test/example.txt") -if loadedFile then - print("Loaded file content:") - print(loadedFile:read()) -else - print("ERROR: Could not load file!") -end diff --git a/OS_Other/test_lpm.lua b/OS_Other/test_lpm.lua @@ -1,26 +0,0 @@ -#!/usr/bin/env luajit --- Test script for LPM - -local lpm = require("lpm") - --- Test package from your example -local test_package = [[$/data/myfolder/||||$/src/init.lua~~~~print("test123! test123! test123!")\nprint("\_-'-_/")\nprint(12345)||||$/settings/manifest.lua~~~~return { name = 'testapp', devOrCompany='luajitos', permissions = { }, allowedPaths = {}, allowedDomains = {'api.testapp.io'}}||||$/src/secondary.lua~~~~function f(a,b) return a * b end\nprint(f(3,7))]] - -print("Testing LPM installation...") -print("Package string:") -print(test_package) -print("\n" .. string.rep("=", 60) .. "\n") - -local success, app_id = pcall(function() - return lpm.install(test_package) -end) - -if success then - print("\n" .. string.rep("=", 60)) - print("Installation successful!") - print("App ID: " .. app_id) - print("\nYou can now run: luajit lpm.lua run testapp") -else - print("\n" .. string.rep("=", 60)) - print("Installation failed: " .. app_id) -end diff --git a/OS_Other/test_orbit.lua b/OS_Other/test_orbit.lua @@ -1,128 +0,0 @@ --- Test file for OrbitManager - -local OrbitManager = require("OrbitManager") - -print("=== OrbitManager Test Suite ===\n") - --- Create a sandboxed environment -local sandbox = { - io = { - open = function(path, mode) - print("REAL io.open called with:", path, mode) - return "file_handle_mock" - end, - }, - os = { - clock = function() - print("REAL os.clock called") - return 12345.67 - end, - execute = function(cmd) - print("REAL os.execute called with:", cmd) - return true - end, - } -} - --- Create OrbitManager instance -print("1. Creating OrbitManager instance...") -local orbit = OrbitManager.new(sandbox, "perms.lua") -print(" ✓ OrbitManager created\n") - --- Test 1: Try to access protected properties (should fail) -print("2. Testing metatable protection...") -local success, err = pcall(function() - local x = orbit.map -end) -if not success then - print(" ✓ Direct access to orbit.map blocked:", err) -else - print(" ✗ FAILED: Should not be able to access orbit.map") -end - -success, err = pcall(function() - orbit.perms = {} -end) -if not success then - print(" ✓ Direct write to orbit.perms blocked:", err) -else - print(" ✗ FAILED: Should not be able to modify orbit.perms") -end -print() - --- Test 2: Try to call functions without permissions (should fail) -print("3. Testing function calls without permissions...") -success, err = pcall(function() - sandbox.io.open("/tmp/test.txt", "r") -end) -if not success then - print(" ✓ Blocked io.open:", err) -else - print(" ✗ FAILED: Should have blocked io.open") -end -print() - --- Test 3: Grant permissions and test canRun -print("4. Testing canRun method...") -local canRun, reason = orbit:canRun("io.open", "/tmp/test.txt") -print(" canRun('io.open', '/tmp/test.txt'):", canRun, reason) - -print(" Granting perms.fs permission...") -orbit:grantPermission("perms.fs") - -canRun, reason = orbit:canRun("io.open", "/tmp/test.txt") -print(" canRun('io.open', '/tmp/test.txt'):", canRun, reason) - -canRun, reason = orbit:canRun("io.open", "/etc/passwd") -print(" canRun('io.open', '/etc/passwd'):", canRun, reason) -print() - --- Test 4: Call functions with permissions (should succeed for allowed paths) -print("5. Testing function calls with permissions...") -success, err = pcall(function() - local result = sandbox.io.open("/tmp/test.txt", "r") - print(" ✓ io.open succeeded, returned:", result) -end) -if not success then - print(" ✗ FAILED:", err) -end - -success, err = pcall(function() - sandbox.io.open("/etc/passwd", "r") -end) -if not success then - print(" ✓ Blocked access to non-allowed path:", err) -else - print(" ✗ FAILED: Should have blocked /etc/passwd") -end -print() - --- Test 5: Test OS permissions -print("6. Testing OS permissions...") -success, err = pcall(function() - sandbox.os.execute("ls") -end) -if not success then - print(" ✓ Blocked os.execute without perms.os:", err) -else - print(" ✗ FAILED: Should have blocked os.execute") -end - -orbit:grantPermission("perms.os") -success, err = pcall(function() - sandbox.os.execute("ls") - print(" ✓ os.execute succeeded with perms.os granted") -end) -if not success then - print(" ✗ FAILED:", err) -end -print() - --- Test 6: Test adding allowed paths dynamically -print("7. Testing dynamic path management...") -orbit:addAllowedPath("/var/log/*") -canRun, reason = orbit:canRun("io.open", "/var/log/system.log") -print(" After adding /var/log/* - canRun('/var/log/system.log'):", canRun, reason) -print() - -print("=== All Tests Complete ===") diff --git a/OS_Other/test_orbit_manifest.lua b/OS_Other/test_orbit_manifest.lua @@ -1,179 +0,0 @@ --- Test file for OrbitManager.newFromManifest - -local OrbitManager = require("OrbitManager") - -print("=== OrbitManager.newFromManifest Test Suite ===\n") - --- Create a sandboxed environment -local sandbox = { - io = { - open = function(path, mode) - print("REAL io.open called with:", path, mode) - return "file_handle_mock" - end, - }, - os = { - clock = function() - print("REAL os.clock called") - return 12345.67 - end, - execute = function(cmd) - print("REAL os.execute called with:", cmd) - return true - end, - } -} - --- Test manifest string -local manifestString = [[ -return { - name = "myapp"; - dev = "devname"; - perms = { - fs = true, - os = false, - network = true - }; - allowedPaths = { - "/tmp/*", - "/home/user/myapp/*" - }; - allowedDomains = { - "api.myapp.io", - "*.example.com" - } -} -]] - --- Test 1: Create instance from manifest -print("1. Creating OrbitManager from manifest string...") -local orbit = OrbitManager.newFromManifest(sandbox, manifestString) -print(" ✓ OrbitManager created from manifest\n") - --- Test 2: Verify manifest metadata -print("2. Checking manifest metadata...") -local manifestData = orbit:getManifestData() -print(" App name:", manifestData.name) -print(" Developer:", manifestData.dev) -print(" ✓ Manifest metadata accessible\n") - --- Test 3: Test permissions were loaded correctly -print("3. Testing loaded permissions...") -local canRun, reason = orbit:canRun("io.open", "/tmp/test.txt") -print(" canRun('io.open', '/tmp/test.txt'):", canRun, reason) - -canRun, reason = orbit:canRun("os.execute") -print(" canRun('os.execute'):", canRun, reason) -print() - --- Test 4: Test filesystem access with allowed path -print("4. Testing filesystem access with allowed paths...") -local success, err = pcall(function() - local result = sandbox.io.open("/tmp/test.txt", "r") - print(" ✓ io.open('/tmp/test.txt') succeeded, returned:", result) -end) -if not success then - print(" ✗ FAILED:", err) -end - -success, err = pcall(function() - sandbox.io.open("/etc/passwd", "r") -end) -if not success then - print(" ✓ Blocked access to /etc/passwd:", err) -else - print(" ✗ FAILED: Should have blocked /etc/passwd") -end -print() - --- Test 5: Test path matching with wildcards -print("5. Testing wildcard path matching...") -canRun, reason = orbit:canRun("io.open", "/home/user/myapp/config.txt") -print(" canRun('io.open', '/home/user/myapp/config.txt'):", canRun, reason) - -canRun, reason = orbit:canRun("io.open", "/home/user/other/file.txt") -print(" canRun('io.open', '/home/user/other/file.txt'):", canRun, reason) -print() - --- Test 6: Test OS permission (should be denied) -print("6. Testing OS permissions (should be denied)...") -success, err = pcall(function() - sandbox.os.execute("ls") -end) -if not success then - print(" ✓ Blocked os.execute (perms.os = false):", err) -else - print(" ✗ FAILED: Should have blocked os.execute") -end -print() - --- Test 7: Test metatable protection -print("7. Testing metatable protection...") -success, err = pcall(function() - local x = orbit.map -end) -if not success then - print(" ✓ Direct access to orbit.map blocked:", err) -else - print(" ✗ FAILED: Should not be able to access orbit.map") -end - -success, err = pcall(function() - orbit.manifestData = {} -end) -if not success then - print(" ✓ Direct write to orbit.manifestData blocked:", err) -else - print(" ✗ FAILED: Should not be able to modify orbit.manifestData") -end -print() - --- Test 8: Test another manifest with different perms -print("8. Testing another manifest with different permissions...") -local manifest2 = [[ -return { - name = "systemtool"; - dev = "admin"; - perms = { - fs = false, - os = true - }; - allowedPaths = {}; - allowedDomains = {} -} -]] - -local orbit2 = OrbitManager.newFromManifest(nil, manifest2) -local data2 = orbit2:getManifestData() -print(" App name:", data2.name) -print(" Developer:", data2.dev) - -canRun, reason = orbit2:canRun("os.clock") -print(" canRun('os.clock'):", canRun, reason) - -canRun, reason = orbit2:canRun("io.open", "/tmp/test.txt") -print(" canRun('io.open', '/tmp/test.txt'):", canRun, reason) -print() - --- Test 9: Test invalid manifest handling -print("9. Testing invalid manifest handling...") -success, err = pcall(function() - local badOrbit = OrbitManager.newFromManifest(nil, "return 'not a table'") -end) -if not success then - print(" ✓ Rejected invalid manifest:", err) -else - print(" ✗ FAILED: Should have rejected manifest that doesn't return a table") -end - -success, err = pcall(function() - local badOrbit = OrbitManager.newFromManifest(nil, "this is not valid lua") -end) -if not success then - print(" ✓ Rejected unparseable manifest:", err) -else - print(" ✗ FAILED: Should have rejected invalid Lua") -end -print() - -print("=== All Tests Complete ===") diff --git a/OS_Other/test_ramdisk2.lua b/OS_Other/test_ramdisk2.lua @@ -1,95 +0,0 @@ -local ramdisk = require("ramdisk2") - --- Create a new root filesystem -local root = ramdisk.createRoot() - --- Create directories -local osDir = root:newDir("os") -local appsDir = root:newDir("apps") -local binDir = root:newDir("bin") - --- Add text files to /os/ (with special characters to test escaping) -osDir:newFile("init.lua", "-- OS Initialization\nprint('LuajitOS Starting...')\nreturn true") -osDir:newFile("config.txt", "version=1.0\nauthor=LuajitOS Team\ndebug=true\npath=C:\\Windows\\System32") -osDir:newFile("readme.md", "# LuajitOS\n\nA lightweight operating system written in Lua.\n\tIndented line\r\nWindows newline") - --- Add a binary file to /os/ (simulated binary data with non-printable characters) -local binaryData = string.char(0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A) .. "PNG_HEADER_DATA" -osDir:newFile("logo.png", binaryData) - --- Add a file to /bin/ -binDir:newFile("shell.lua", "-- Shell binary\nfunction run()\n print('Shell running')\nend") - --- Add a file to /apps/ -appsDir:newFile("calculator.lua", "-- Calculator app\nlocal calc = {}\nreturn calc") - --- Create a subdirectory in /os/ -local libDir = osDir:newDir("lib") -libDir:newFile("utils.lua", "local utils = {}\nfunction utils.log(msg)\n print('[LOG] ' .. msg)\nend\nreturn utils") - --- Another binary file in lib -local elfData = string.char(0x7F, 0x45, 0x4C, 0x46, 0x02, 0x01, 0x01, 0x00) .. "ELF_BINARY" -libDir:newFile("native.so", elfData) - --- Save and print the filesystem -print("=== Filesystem Structure ===") -print("\nDirectories:") -print(" /") -print(" /os/") -print(" /apps/") -print(" /bin/") -print(" /os/lib/") - -print("\nFiles:") -print(" /os/init.lua (text)") -print(" /os/config.txt (text)") -print(" /os/readme.md (text)") -print(" /os/logo.png (binary)") -print(" /os/lib/utils.lua (text)") -print(" /os/lib/native.so (binary)") -print(" /bin/shell.lua (text)") -print(" /apps/calculator.lua (text)") - -print("\n=== Serialized Filesystem ===") -local serialized = ramdisk.saveFS(root) -print(serialized) - -print("\n=== Serialized Length ===") -print("Total bytes: " .. #serialized) - -print("\n=== Testing Load/Save Round Trip ===") --- Load the serialized filesystem -local loadedRoot = ramdisk.loadFS(serialized) - --- Read a few files to verify -local loadedConfigFile = loadedRoot:traverse("os/config.txt") -local loadedLibUtilsFile = loadedRoot:traverse("os/lib/utils.lua") -local loadedBinaryFile = loadedRoot:traverse("os/logo.png") - -if not loadedConfigFile then - print("ERROR: Could not load config.txt") - os.exit(1) -end - -print("\n--- Loaded config.txt content: ---") -print(loadedConfigFile:read()) - -print("\n--- Loaded os/lib/utils.lua content: ---") -print(loadedLibUtilsFile:read()) - -print("\n--- Binary file verification: ---") -local originalBinary = binaryData -local loadedBinary = loadedBinaryFile:read() -print("Original binary length: " .. #originalBinary) -print("Loaded binary length: " .. #loadedBinary) -print("Binary match: " .. tostring(originalBinary == loadedBinary)) - -print("\n--- Verifying special characters: ---") -local loadedReadme = loadedRoot:traverse("os/readme.md") -local readmeContent = loadedReadme:read() -print("Contains newline (\\n): " .. tostring(readmeContent:find("\n") ~= nil)) -print("Contains tab (\\t): " .. tostring(readmeContent:find("\t") ~= nil)) -print("Contains carriage return (\\r): " .. tostring(readmeContent:find("\r") ~= nil)) -print("Contains backslash (\\\\): " .. tostring(loadedConfigFile:read():find("\\") ~= nil)) - -print("\n=== Round Trip Successful! ===") diff --git a/OS_Other/test_runstring.lua b/OS_Other/test_runstring.lua @@ -1,70 +0,0 @@ --- Test for RunString and CompileString functions - -print("=== Testing RunString ===") - --- Test 1: Simple code execution -print("Test 1: Simple code execution") -local result = RunString("print('Hello from RunString!')") -print("Result:", result) - --- Test 2: Code with syntax error -print("\nTest 2: Code with syntax error") -local result2 = RunString("print('Missing closing quote)") -print("Result:", result2) - --- Test 3: Code with runtime error -print("\nTest 3: Code with runtime error") -local result3 = RunString("error('Intentional error')") -print("Result:", result3) - -print("\n=== Testing CompileString ===") - --- Test 4: Compile valid code -print("Test 4: Compile valid code") -local func, err = CompileString("return 2 + 2") -if func then - print("Compiled successfully, type:", type(func)) - local success, result = pcall(func) - if success then - print("Execution result:", result) - else - print("Execution failed:", result) - end -else - print("Compilation failed:", err) -end - --- Test 5: Compile invalid code -print("\nTest 5: Compile invalid code") -local func2, err2 = CompileString("return 2 +") -if func2 then - print("Compiled successfully (unexpected)") -else - print("Compilation failed (expected):", err2) -end - --- Test 6: Compile and execute multiple times -print("\nTest 6: Compile and execute multiple times") -local counter_func, err3 = CompileString([[ - local count = 0 - return function() - count = count + 1 - return count - end -]]) - -if counter_func then - print("Compiled successfully") - local success, counter = pcall(counter_func) - if success and type(counter) == "function" then - print("Counter 1:", counter()) - print("Counter 2:", counter()) - print("Counter 3:", counter()) - else - print("Execution failed") - end -else - print("Compilation failed:", err3) -end - -print("\n=== All tests completed ===") diff --git a/OS_Other/test_sandbox.lua b/OS_Other/test_sandbox.lua @@ -1,212 +0,0 @@ --- Test file for OrbitManager.newSandbox - -local OrbitManager = require("OrbitManager") - -print("=== OrbitManager.newSandbox Test Suite ===\n") - --- Test manifest -local manifestString = [[ -return { - name = "sandboxedapp"; - dev = "testdev"; - perms = { - fs = true, - os = false, - network = false - }; - allowedPaths = { - "/tmp/*", - "/home/user/data/*" - }; - allowedDomains = { - "api.example.com" - } -} -]] - --- Test 1: Create a sandbox -print("1. Creating sandbox with OrbitManager.newSandbox...") -local orbit, sandbox = OrbitManager.newSandbox(manifestString) -print(" ✓ Sandbox created successfully\n") - --- Test 2: Check that safe functions are available -print("2. Testing safe functions in sandbox...") -print(" print available:", type(sandbox.print)) -print(" string.upper available:", type(sandbox.string.upper)) -print(" math.sin available:", type(sandbox.math.sin)) -print(" table.insert available:", type(sandbox.table.insert)) -print(" ✓ Safe functions are accessible\n") - --- Test 3: Check that dangerous functions are blocked -print("3. Testing that dangerous functions are blocked...") -print(" debug library:", type(sandbox.debug)) -print(" loadfile:", type(sandbox.loadfile)) -print(" dofile:", type(sandbox.dofile)) -print(" ✓ Dangerous functions are nil (blocked)\n") - --- Test 4: Check that permission-controlled functions exist but are stubbed -print("4. Testing permission-controlled functions...") -print(" io.open available:", type(sandbox.io.open)) -print(" os.execute available:", type(sandbox.os.execute)) -print(" os.clock available:", type(sandbox.os.clock)) -print() - --- Test 5: Try to use io.open with permissions granted -print("5. Testing io.open with fs permissions (should work for allowed paths)...") -local success, err = pcall(function() - -- This should work because perms.fs = true and /tmp/* is allowed - sandbox.io.open("/tmp/test.txt", "r") -end) -if success then - print(" ✓ io.open('/tmp/test.txt') succeeded") -else - print(" ✗ io.open failed:", err) -end - -success, err = pcall(function() - -- This should fail because /etc/passwd is not in allowedPaths - sandbox.io.open("/etc/passwd", "r") -end) -if not success then - print(" ✓ io.open('/etc/passwd') blocked:", err) -else - print(" ✗ FAILED: Should have blocked /etc/passwd") -end -print() - --- Test 6: Try to use os.execute without permissions -print("6. Testing os.execute without os permissions (should fail)...") -success, err = pcall(function() - sandbox.os.execute("ls") -end) -if not success then - print(" ✓ os.execute blocked:", err) -else - print(" ✗ FAILED: Should have blocked os.execute") -end -print() - --- Test 7: Test safe string operations in sandbox -print("7. Testing safe operations in sandbox...") -local testCode = [[ - local str = "hello world" - local upper = string.upper(str) - local result = string.sub(upper, 1, 5) - return result -]] - -local chunk, compileErr = load(testCode, "testCode", "t", sandbox) -if chunk then - local ok, result = pcall(chunk) - if ok then - print(" ✓ Sandbox code executed successfully, result:", result) - else - print(" ✗ Sandbox code failed:", result) - end -else - print(" ✗ Failed to compile:", compileErr) -end -print() - --- Test 8: Test that sandbox cannot access global _G -print("8. Testing sandbox isolation from global environment...") -local isolationTest = [[ - -- Try to access something from the real _G (should not be possible) - -- The sandbox _G should point to itself, not the real global - return _G == _ENV -]] - -chunk, compileErr = load(isolationTest, "isolationTest", "t", sandbox) -if chunk then - local ok, result = pcall(chunk) - print(" Sandbox _G == _ENV:", result) - print(" ✓ Sandbox has its own _G\n") -end - --- Test 9: Test that blocked functions really don't exist -print("9. Testing execution of code that tries to use blocked functions...") -local blockedTest = [[ - if debug then - return "FAIL: debug should be blocked" - end - if loadfile then - return "FAIL: loadfile should be blocked" - end - return "SUCCESS: blocked functions are nil" -]] - -chunk, compileErr = load(blockedTest, "blockedTest", "t", sandbox) -if chunk then - local ok, result = pcall(chunk) - print(" " .. (result or "error")) -end -print() - --- Test 10: Test math and table operations -print("10. Testing math and table operations in sandbox...") -local mathTest = [[ - local nums = {1, 5, 3, 9, 2} - table.sort(nums) - local sum = 0 - for i = 1, #nums do - sum = sum + nums[i] - end - return sum, math.sqrt(sum) -]] - -chunk, compileErr = load(mathTest, "mathTest", "t", sandbox) -if chunk then - local ok, sum, sqrt = pcall(chunk) - if ok then - print(" ✓ Math operations work: sum =", sum, "sqrt =", sqrt) - else - print(" ✗ Failed:", sum) - end -end -print() - --- Test 11: Create another sandbox with different permissions -print("11. Testing second sandbox with OS permissions but no FS...") -local manifest2 = [[ -return { - name = "ostool"; - dev = "admin"; - perms = { - fs = false, - os = true - }; - allowedPaths = {}; - allowedDomains = {} -} -]] - -local orbit2, sandbox2 = OrbitManager.newSandbox(manifest2) -print(" Created second sandbox") - -success, err = pcall(function() - sandbox2.os.clock() -end) -if success then - print(" ✓ os.clock works with os permissions") -else - print(" ✗ os.clock failed:", err) -end - -success, err = pcall(function() - sandbox2.io.open("/tmp/test.txt", "r") -end) -if not success then - print(" ✓ io.open blocked without fs permissions:", err) -else - print(" ✗ FAILED: Should have blocked io.open") -end -print() - --- Test 12: Test getSandbox method -print("12. Testing getSandbox method...") -local retrievedSandbox = orbit:getSandbox() -print(" getSandbox returned:", type(retrievedSandbox)) -print(" Same as original sandbox:", retrievedSandbox == sandbox) -print() - -print("=== All Tests Complete ===") diff --git a/OS_Other/testinit.lua b/OS_Other/testinit.lua