okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
538acd098
main
1"""Owner-only files on every platform. 2 3POSIX keeps what the code always did (``0600`` files, ``0700`` directories). NTFS has no mode bits, 4so on Windows the same promise is an ACL: a protected (non-inherited) DACL with exactly one 5allow entry, for the current user. This uses ``advapi32`` through ``ctypes``; there is no 6``pywin32`` or ``icacls`` dependency and no output parsing that depends on the display language. 7""" 8from __future__import annotations 9 10import os 11import re 12from pathlib import Path 13 14WINDOWS = os .name == "nt" 15 16if WINDOWS : 17import ctypes 18from ctypes import wintypes 19 20_advapi = ctypes .WinDLL ("advapi32" ,use_last_error = True ) 21_kernel = ctypes .WinDLL ("kernel32" ,use_last_error = True ) 22 23_kernel .GetCurrentProcess .restype = wintypes .HANDLE 24_kernel .LocalFree .argtypes = [ctypes .c_void_p ] 25_kernel .LocalFree .restype = ctypes .c_void_p 26_kernel .CloseHandle .argtypes = [wintypes .HANDLE ] 27_advapi .OpenProcessToken .argtypes = [wintypes .HANDLE ,wintypes .DWORD ,ctypes .POINTER (wintypes .HANDLE )] 28_advapi .GetTokenInformation .argtypes = [wintypes .HANDLE ,ctypes .c_int ,ctypes .c_void_p ,wintypes .DWORD , 29ctypes .POINTER (wintypes .DWORD )] 30_advapi .ConvertSidToStringSidW .argtypes = [ctypes .c_void_p ,ctypes .POINTER (wintypes .LPWSTR )] 31_advapi .ConvertStringSecurityDescriptorToSecurityDescriptorW .argtypes = [ 32wintypes .LPCWSTR ,wintypes .DWORD ,ctypes .POINTER (ctypes .c_void_p ),ctypes .c_void_p ] 33_advapi .GetSecurityDescriptorDacl .argtypes = [ctypes .c_void_p ,ctypes .POINTER (wintypes .BOOL ), 34ctypes .POINTER (ctypes .c_void_p ),ctypes .POINTER (wintypes .BOOL )] 35_advapi .SetNamedSecurityInfoW .argtypes = [wintypes .LPWSTR ,ctypes .c_int ,wintypes .DWORD ,ctypes .c_void_p , 36ctypes .c_void_p ,ctypes .c_void_p ,ctypes .c_void_p ] 37_advapi .SetNamedSecurityInfoW .restype = wintypes .DWORD 38_advapi .GetNamedSecurityInfoW .argtypes = [wintypes .LPCWSTR ,ctypes .c_int ,wintypes .DWORD ,ctypes .c_void_p , 39ctypes .c_void_p ,ctypes .POINTER (ctypes .c_void_p ),ctypes .c_void_p , 40ctypes .POINTER (ctypes .c_void_p )] 41_advapi .GetNamedSecurityInfoW .restype = wintypes .DWORD 42_advapi .ConvertSecurityDescriptorToStringSecurityDescriptorW .argtypes = [ 43ctypes .c_void_p ,wintypes .DWORD ,wintypes .DWORD ,ctypes .POINTER (wintypes .LPWSTR ),ctypes .c_void_p ] 44_advapi .ConvertStringSidToSidW .argtypes = [wintypes .LPCWSTR ,ctypes .POINTER (ctypes .c_void_p )] 45_advapi .SetTokenInformation .argtypes = [wintypes .HANDLE ,ctypes .c_int ,ctypes .c_void_p ,wintypes .DWORD ] 46_advapi .LookupPrivilegeValueW .argtypes = [wintypes .LPCWSTR ,wintypes .LPCWSTR ,ctypes .c_void_p ] 47_advapi .AdjustTokenPrivileges .argtypes = [wintypes .HANDLE ,wintypes .BOOL ,ctypes .c_void_p ,wintypes .DWORD , 48ctypes .c_void_p ,ctypes .c_void_p ] 49 50_SE_FILE_OBJECT = 1 51_DACL = 0x4 52_PROTECTED_DACL = 0x80000000 53_TOKEN_QUERY = 0x8 54_TOKEN_ADJUST_PRIVILEGES = 0x20 55_TOKEN_ADJUST_DEFAULT = 0x80 56_TOKEN_OWNER = 4 57_TOKEN_DEFAULT_DACL = 6 58_OWNER = 0x1 59_TOKEN_USER = 1 60_SDDL_REVISION_1 = 1 61_sid_cache :str | None = None 62 63 64def _winerr (what :str ,code :int | None = None )-> OSError : 65return ctypes .WinError (code if code is not None else ctypes .get_last_error (),what )# type: ignore[attr-defined] 66 67 68def current_user_sid ()-> str : 69"""The string SID of the user this process runs as (Windows only).""" 70global _sid_cache 71if not WINDOWS : 72raise OSError ("SIDs exist on Windows only" ) 73if _sid_cache : 74return _sid_cache 75token = wintypes .HANDLE () 76if not _advapi .OpenProcessToken (_kernel .GetCurrentProcess (),_TOKEN_QUERY ,ctypes .byref (token )): 77raise _winerr ("OpenProcessToken" ) 78try : 79needed = wintypes .DWORD () 80_advapi .GetTokenInformation (token ,_TOKEN_USER ,None ,0 ,ctypes .byref (needed )) 81buffer = ctypes .create_string_buffer (needed .value ) 82if not _advapi .GetTokenInformation (token ,_TOKEN_USER ,buffer ,needed ,ctypes .byref (needed )): 83raise _winerr ("GetTokenInformation" ) 84psid = ctypes .c_void_p .from_buffer (buffer ).value # TOKEN_USER starts with the SID pointer 85text = wintypes .LPWSTR () 86if not _advapi .ConvertSidToStringSidW (psid ,ctypes .byref (text )): 87raise _winerr ("ConvertSidToStringSidW" ) 88try : 89_sid_cache = text .value 90finally : 91_kernel .LocalFree (ctypes .cast (text ,ctypes .c_void_p )) 92finally : 93_kernel .CloseHandle (token ) 94assert _sid_cache 95return _sid_cache 96 97 98def _same_sid (sddl_trustee :str ,sid :str )-> bool : 99"""True when an SDDL trustee names ``sid``. SDDL prints well-known accounts as two-letter aliases (the built-in 100Administrator, RID 500, is ``LA``), so an alias is turned into its string SID before the compare (#3302).""" 101if sddl_trustee == sid : 102return True 103if not WINDOWS : 104return False 105return _string_sid (sddl_trustee )== sid .upper () 106 107 108def restrict_to_current_user (path :str | os .PathLike ,* ,directory :bool | None = None )-> None : 109"""Make ``path`` readable and writable by the current user only. 110 111POSIX: ``chmod 0600`` (``0700`` for a directory). Windows: replace the DACL with one protected 112entry granting the current user full control (inherited by children when ``path`` is a 113directory) and drop every inherited entry. 114""" 115path = os .fspath (path ) 116if directory is None : 117directory = os .path .isdir (path ) 118if not WINDOWS : 119os .chmod (path ,0o700 if directory else 0o600 ) 120return 121flags = "OICI" if directory else "" 122sddl = f"D:PAI(A; { flags } ;FA;;; { current_user_sid () } )" 123descriptor = ctypes .c_void_p () 124if not _advapi .ConvertStringSecurityDescriptorToSecurityDescriptorW ( 125sddl ,_SDDL_REVISION_1 ,ctypes .byref (descriptor ),None ): 126raise _winerr ("ConvertStringSecurityDescriptorToSecurityDescriptorW" ) 127try : 128present ,defaulted ,dacl = wintypes .BOOL (),wintypes .BOOL (),ctypes .c_void_p () 129if not _advapi .GetSecurityDescriptorDacl (descriptor ,ctypes .byref (present ),ctypes .byref (dacl ), 130ctypes .byref (defaulted ))or not present .value : 131raise _winerr ("GetSecurityDescriptorDacl" ) 132# The explicit entry for the user's own SID is what makes the file reachable from a normal (non-elevated) session: 133# a file made by an elevated process is owned by BUILTIN\Administrators, and a rule naming only SYSTEM, 134# Administrators and OWNER RIGHTS shuts the same person out when UAC filters Administrators from their token. 135# So the owner becomes the user too, where Windows allows it; when it does not, the explicit entry still stands. 136owner = _user_psid () 137code = _advapi .SetNamedSecurityInfoW (path ,_SE_FILE_OBJECT ,_OWNER | _DACL | _PROTECTED_DACL , 138owner ,None ,dacl ,None )if owner else 1 139if code : 140code = _advapi .SetNamedSecurityInfoW (path ,_SE_FILE_OBJECT ,_DACL | _PROTECTED_DACL , 141None ,None ,dacl ,None ) 142if code : 143raise _winerr (f"SetNamedSecurityInfoW { path } " ,code ) 144finally : 145_kernel .LocalFree (descriptor ) 146 147 148def dacl_sddl (path :str | os .PathLike )-> str : 149"""The DACL of ``path`` as an SDDL string such as ``D:PAI(A;;FA;;;S-1-5-21-...)`` (Windows only).""" 150if not WINDOWS : 151raise OSError ("DACLs exist on Windows only" ) 152descriptor = ctypes .c_void_p () 153code = _advapi .GetNamedSecurityInfoW (os .fspath (path ),_SE_FILE_OBJECT ,_DACL ,None ,None ,None ,None , 154ctypes .byref (descriptor )) 155if code : 156raise _winerr (f"GetNamedSecurityInfoW { path } " ,code ) 157try : 158text = wintypes .LPWSTR () 159if not _advapi .ConvertSecurityDescriptorToStringSecurityDescriptorW ( 160descriptor ,_SDDL_REVISION_1 ,_DACL ,ctypes .byref (text ),None ): 161raise _winerr ("ConvertSecurityDescriptorToStringSecurityDescriptorW" ) 162try : 163return text .value 164finally : 165_kernel .LocalFree (ctypes .cast (text ,ctypes .c_void_p )) 166finally : 167_kernel .LocalFree (descriptor ) 168 169 170def is_private (path :str | os .PathLike )-> bool : 171"""True when only the current user can reach ``path``. 172 173POSIX: no group or other permission bits. Windows: the DACL is protected (no inherited entries) 174and consists of exactly one allow entry for the current user. 175""" 176if not WINDOWS : 177return not (os .lstat (path ).st_mode & 0o077 ) 178if not volume_has_acls (path ): 179return True # FAT / exFAT: there are no permissions to check 180sddl = dacl_sddl (path ) 181head = sddl .split ("(" ,1 )[0 ] 182entries = re .findall (r"\(([^()]*)\)" ,sddl ) 183if not head .startswith ("D:" )or "P" not in head [2 :]or len (entries )!= 1 : 184return False 185fields = entries [0 ].split (";" ) 186return len (fields )>= 6 and fields [0 ]== "A" and _same_sid (fields [5 ],current_user_sid ()) 187 188 189def is_unshared (path :str | os .PathLike )-> bool : 190"""True when nobody but this user, SYSTEM and the administrators can reach ``path``. 191 192The relaxed form of :func:`is_private`, for files created under the user's profile where the 193inherited ACL already shuts out other accounts: any allow entry for Everyone, Users, 194Authenticated Users or another account makes it False. POSIX is the same check as 195:func:`is_private`. 196""" 197if not WINDOWS : 198return is_private (path ) 199if not volume_has_acls (path ): 200return True # FAT / exFAT: there are no permissions to check 201return not unshared_offenders (dacl_sddl (path )) 202 203 204def volume_has_acls (path :str | os .PathLike )-> bool : 205"""False for a drive without file permissions (FAT, exFAT); True for NTFS/ReFS, and when it cannot be told (Windows only).""" 206if not WINDOWS : 207return True 208try : 209drive = os .path .splitdrive (os .path .abspath (os .fspath (path )))[0 ] 210if not drive : 211return True 212flags = wintypes .DWORD () 213fn = _kernel .GetVolumeInformationW 214fn .argtypes = [wintypes .LPCWSTR ,wintypes .LPWSTR ,wintypes .DWORD ,ctypes .c_void_p ,ctypes .c_void_p , 215ctypes .POINTER (wintypes .DWORD ),wintypes .LPWSTR ,wintypes .DWORD ] 216if not fn (drive .rstrip ("\\" )+ "\\" ,None ,0 ,None ,None ,ctypes .byref (flags ),None ,0 ): 217return True 218return bool (flags .value & 0x00000008 )# FILE_PERSISTENT_ACLS 219except (OSError ,ValueError ): 220return True 221 222 223_ACCOUNT_NAMES = {"WD" :"Everyone" ,"BU" :"Users" ,"AU" :"Authenticated Users" ,"IU" :"Interactive users" , 224"NU" :"Network users" ,"AN" :"Anonymous" ,"DU" :"Domain Users" ,"S-1-1-0" :"Everyone" , 225"S-1-5-32-545" :"Users" ,"S-1-5-11" :"Authenticated Users" ,"S-1-5-4" :"Interactive users" } 226 227 228def _string_sid (trustee :str )-> str : 229"""An SDDL trustee (a string SID or a two-letter alias such as LA, BA, SY, WD) as an upper-case string SID; the text itself 230when Windows does not know it.""" 231if trustee .upper ().startswith ("S-1-" ): 232return trustee .upper () 233pointer = ctypes .c_void_p () 234if not _advapi .ConvertStringSidToSidW (trustee ,ctypes .byref (pointer )): 235return trustee .upper () 236try : 237text = wintypes .LPWSTR () 238if not _advapi .ConvertSidToStringSidW (pointer .value ,ctypes .byref (text )): 239return trustee .upper () 240try : 241return text .value .upper () 242finally : 243_kernel .LocalFree (ctypes .cast (text ,ctypes .c_void_p )) 244finally : 245_kernel .LocalFree (pointer ) 246 247 248def _is_privileged_sid (sid :str )-> bool : 249"""SYSTEM, the Administrators group, the built-in Administrator account (RID 500, SDDL "LA"), OWNER RIGHTS / CREATOR OWNER / GROUP.""" 250return sid in ("S-1-5-18" ,"S-1-5-32-544" ,"S-1-3-4" ,"S-1-3-0" ,"S-1-3-1" )or \ 251re .fullmatch (r"S-1-5-21-[0-9-]+-500" ,sid )is not None 252 253 254def unshared_offenders (sddl :str )-> list [str ]: 255"""The trustees of an SDDL DACL that make the object reachable by someone besides this user, SYSTEM and the administrators: 256every allow entry that applies to the object itself, whatever form its account is written in (a string SID or an alias such 257as LA). An inherit-only entry (flag IO) is for the children of a folder, not for the folder, and is left out.""" 258me = current_user_sid ().upper () 259out :list [str ]= [] 260for entry in re .findall (r"\(([^()]*)\)" ,sddl ): 261fields = entry .split (";" ) 262if len (fields )< 6 or fields [0 ]not in ("A" ,"OA" )or "IO" in re .findall (".." ,fields [1 ].upper ()): 263continue 264sid = _string_sid (fields [5 ]) 265if sid == me or _is_privileged_sid (sid )or fields [5 ].upper ()in ("SY" ,"BA" ,"OW" ,"CO" ,"CG" ,"LA" ): 266continue 267if fields [5 ]not in out : 268out .append (fields [5 ]) 269return out 270 271 272def account_name (trustee :str )-> str : 273"""A plain name for an SDDL trustee (Everyone, Users, DOMAIN\\name), or the SID text when it cannot be looked up.""" 274plain = _ACCOUNT_NAMES .get (trustee .upper ())or _ACCOUNT_NAMES .get (_string_sid (trustee )) 275if plain or not WINDOWS : 276return plain or trustee 277pointer = ctypes .c_void_p () 278if not _advapi .ConvertStringSidToSidW (trustee ,ctypes .byref (pointer )): 279return trustee 280try : 281name ,domain = ctypes .create_unicode_buffer (256 ),ctypes .create_unicode_buffer (256 ) 282n ,d ,use = wintypes .DWORD (256 ),wintypes .DWORD (256 ),wintypes .DWORD () 283lookup = _advapi .LookupAccountSidW 284lookup .argtypes = [wintypes .LPCWSTR ,ctypes .c_void_p ,wintypes .LPWSTR ,ctypes .POINTER (wintypes .DWORD ), 285wintypes .LPWSTR ,ctypes .POINTER (wintypes .DWORD ),ctypes .POINTER (wintypes .DWORD )] 286if lookup (None ,pointer ,name ,ctypes .byref (n ),domain ,ctypes .byref (d ),ctypes .byref (use )): 287return f" { domain . value } \\ { name . value } " if domain .value else name .value 288return trustee 289finally : 290_kernel .LocalFree (pointer ) 291 292 293def who_can_reach (path :str | os .PathLike )-> list [str ]: 294"""Plain names of the accounts besides this user, SYSTEM and the administrators that can reach ``path`` (Windows; [] elsewhere).""" 295if not WINDOWS : 296return [] 297return [account_name (t )for t in unshared_offenders (dacl_sddl (path ))] 298 299 300# ---------------------------------------------------------------------------------------------- access repair 301 302def _user_psid (): 303"""The current user's SID as a native pointer (kept for the life of the process), or None.""" 304global _psid_cache 305if not WINDOWS : 306return None 307if _psid_cache is not None : 308return _psid_cache 309pointer = ctypes .c_void_p () 310if not _advapi .ConvertStringSidToSidW (current_user_sid (),ctypes .byref (pointer )): 311return None 312_psid_cache = pointer .value 313return _psid_cache 314 315 316_psid_cache = None 317_keep :list = [] 318 319 320def private_mkdir (path :str | os .PathLike ,* ,parents :bool = False ,exist_ok :bool = True )-> Path : 321"""Create a folder only the user can reach, on every platform. 322 323POSIX: ``mkdir(mode=0o700)``. Windows: Python 3.13 turns ``mode=0o700`` into an ACL of SYSTEM, Administrators and OWNER 324RIGHTS (inherited by everything inside), which locks the user out when an elevated process created the folder. This 325creates the missing folders plainly and gives each one the explicit entry for the user's own SID (and the user as owner). 326""" 327target = Path (path ) 328if not WINDOWS : 329target .mkdir (mode = 0o700 ,parents = parents ,exist_ok = exist_ok ) 330return target 331missing = [] 332probe = target 333while not probe .exists ()and probe != probe .parent : 334missing .append (probe ) 335if not parents : 336break 337probe = probe .parent 338if not missing and not exist_ok : 339raise FileExistsError (str (target )) 340for folder in reversed (missing ): 341folder .mkdir (exist_ok = exist_ok ) 342try : 343restrict_to_current_user (folder ,directory = True ) 344except OSError : 345pass # the folder exists with its inherited rule; a later read repairs it if that is not enough 346return target 347 348 349def adopt_user_defaults ()-> bool : 350"""Make files this process creates belong to, and be open to, the user (Windows; no effect elsewhere). 351 352An elevated process otherwise creates files owned by BUILTIN\\Administrators with a default rule of SYSTEM and 353Administrators only. Setting the token's default owner and default rule to the user's own SID fixes that for every file 354the process (and what it starts) creates afterwards. Returns True when both were set; never raises. 355""" 356if not WINDOWS : 357return False 358try : 359sid = current_user_sid () 360psid = _user_psid () 361token = wintypes .HANDLE () 362if not psid or not _advapi .OpenProcessToken (_kernel .GetCurrentProcess (),_TOKEN_QUERY | _TOKEN_ADJUST_DEFAULT , 363ctypes .byref (token )): 364return False 365try : 366class _Owner (ctypes .Structure ): 367_fields_ = [("owner" ,ctypes .c_void_p )] 368 369class _DefaultDacl (ctypes .Structure ): 370_fields_ = [("dacl" ,ctypes .c_void_p )] 371 372ok_owner = bool (_advapi .SetTokenInformation (token ,_TOKEN_OWNER ,ctypes .byref (_Owner (psid )), 373ctypes .sizeof (_Owner ))) 374descriptor = ctypes .c_void_p () 375# A token default DACL also applies to processes, not just files. FA is 376# FILE_ALL_ACCESS (0x1f01ff), which omits process query/set-information. 377# GA is mapped to the full rights of the object being created. 378if not _advapi .ConvertStringSecurityDescriptorToSecurityDescriptorW ( 379f"D:(A;;GA;;; { sid } )(A;;GA;;;SY)(A;;GA;;;BA)" ,_SDDL_REVISION_1 ,ctypes .byref (descriptor ),None ): 380return False 381present ,defaulted ,dacl = wintypes .BOOL (),wintypes .BOOL (),ctypes .c_void_p () 382if not _advapi .GetSecurityDescriptorDacl (descriptor ,ctypes .byref (present ),ctypes .byref (dacl ), 383ctypes .byref (defaulted ))or not present .value : 384return False 385_keep .append (descriptor )# the token keeps pointing into it 386ok_dacl = bool (_advapi .SetTokenInformation (token ,_TOKEN_DEFAULT_DACL ,ctypes .byref (_DefaultDacl (dacl .value )), 387ctypes .sizeof (_DefaultDacl ))) 388return ok_owner and ok_dacl 389finally : 390_kernel .CloseHandle (token ) 391except OSError : 392return False 393 394 395def _enable_privilege (name :str )-> bool : 396token = wintypes .HANDLE () 397if not _advapi .OpenProcessToken (_kernel .GetCurrentProcess (),_TOKEN_QUERY | _TOKEN_ADJUST_PRIVILEGES , 398ctypes .byref (token )): 399return False 400try : 401class _Luid (ctypes .Structure ): 402_fields_ = [("low" ,wintypes .DWORD ), ("high" ,ctypes .c_long )] 403 404class _Privileges (ctypes .Structure ): 405_fields_ = [("count" ,wintypes .DWORD ), ("luid" ,_Luid ), ("attributes" ,wintypes .DWORD )] 406 407luid = _Luid () 408if not _advapi .LookupPrivilegeValueW (None ,name ,ctypes .byref (luid )): 409return False 410privileges = _Privileges (1 ,luid ,2 )# SE_PRIVILEGE_ENABLED 411ctypes .set_last_error (0 ) 412_advapi .AdjustTokenPrivileges (token ,False ,ctypes .byref (privileges ),ctypes .sizeof (privileges ),None ,None ) 413return ctypes .get_last_error ()== 0 414finally : 415_kernel .CloseHandle (token ) 416 417 418def user_roots ()-> list [Path ]: 419"""The folders that are the user's own per-user data: a file inside one may be repaired by that user.""" 420roots :list [Path ]= [] 421for key in ("APPDATA" ,"LOCALAPPDATA" ,"STRATA_HOME" ,"STRATA_PROFILE_DIR" ,"STRATA_INSTALL_DIR" ,"STRATA_RUNTIME_DIR" , 422"STRATA_STATE_DIR" ): 423value = os .environ .get (key ) 424if value : 425roots .append (Path (value )) 426roots .append (Path .home ()) 427result = [] 428for root in roots : 429try : 430result .append (root .resolve ()) 431except OSError : 432continue 433return result 434 435 436def is_users_own (path :str | os .PathLike )-> bool : 437"""True when ``path`` is inside the user's own profile or data folders (never the system folders).""" 438try : 439target = Path (path ).resolve () 440except OSError : 441return False 442return any (target == root or root in target .parents for root in user_roots ()) 443 444 445def repair_access (path :str | os .PathLike ,* ,tree :bool = True )-> bool : 446"""Give the current user back a file or folder in their own data folders that an elevated process locked them out of. 447 448Takes ownership and writes the explicit protected entry for the user's SID (a folder's children are repaired too). 449Needs the right to do that: an elevated session, or a user holding the take-ownership right; a normal session locked 450out by someone else's elevated process cannot do it, and this returns False (the caller shows the plain message). 451Windows only; elsewhere there is nothing to repair. Refuses anything outside the user's own folders. 452""" 453if not WINDOWS or not is_users_own (path ): 454return False 455_enable_privilege ("SeTakeOwnershipPrivilege" ) 456_enable_privilege ("SeRestorePrivilege" ) 457fixed = True 458target = Path (path ) 459try : 460restrict_to_current_user (target ,directory = target .is_dir ()) 461except OSError : 462fixed = False 463if tree and fixed and target .is_dir (): 464try : 465for dirpath ,dirnames ,filenames in os .walk (target ): 466for name in dirnames + filenames : 467child = os .path .join (dirpath ,name ) 468if os .path .islink (child ): 469continue 470try : 471restrict_to_current_user (child ,directory = os .path .isdir (child )) 472except OSError : 473fixed = False 474except OSError : 475fixed = False 476return fixed 477 478 479def read_bytes_repairing (path :str | os .PathLike )-> bytes : 480"""``Path.read_bytes`` that, on an access error in the user's own folders, repairs the access once and tries again.""" 481target = Path (path ) 482try : 483return target .read_bytes () 484except PermissionError : 485if not repair_access (target ,tree = False ): 486raise 487return target .read_bytes () 488 489 490ACCESS_MESSAGE = ("Strata is not allowed to open one of its own files. Run `strata repair-access` (or press Repair in the app); " 491"these files were probably made while Strata ran as administrator, so run it as your normal user from now on." ) 492IN_USE_MESSAGE = ("A file Strata needs is in use by another program (usually antivirus, a backup or a sync tool). " 493"Wait a moment and run the same command again." ) 494 495 496def is_sharing_violation (error :BaseException )-> bool : 497"""Windows "file in use" (WinError 32 or 33), as opposed to a real refusal (WinError 5): waiting helps, repairing does not.""" 498code = getattr (error ,"winerror" ,None ) 499if code in (32 ,33 ): 500return True 501text = str (error ) 502return "WinError 32" in text or "WinError 33" in text or "being used by another process" in text 503 504 505_SKIP_DIRS = {"models" ,"node_modules" ,"harness" ,"python" ,"host" ,"node" ,"control" ,"__pycache__" ,".git" } 506_SKIP_SUFFIXES = (".gguf" ,".part" ,".bin" ,".safetensors" ,".zip" ,".exe" ,".dll" ) 507 508 509def known_roots ()-> list [Path ]: 510"""Strata's per-user data folders: APPDATA/Strata, LOCALAPPDATA/Strata and ~/.strata (plus the STRATA_* overrides).""" 511roots :list [Path ]= [] 512for key ,sub in (("APPDATA" ,"Strata" ), ("LOCALAPPDATA" ,"Strata" )): 513value = os .environ .get (key ) 514if value : 515roots .append (Path (value )/ sub ) 516roots .append (Path .home ()/ ".strata" ) 517for key in ("STRATA_HOME" ,"STRATA_PROFILE_DIR" ,"STRATA_RUNTIME_DIR" ,"STRATA_STATE_DIR" ,"STRATA_INSTALL_DIR" ): 518value = os .environ .get (key ) 519if value : 520roots .append (Path (value )) 521seen ,result = set (), [] 522for root in roots : 523key = str (root ).lower () 524if key not in seen and root .exists (): 525seen .add (key ) 526result .append (root ) 527return result 528 529 530def repair_known_roots (* ,limit :int = 20000 )-> dict : 531"""Walk Strata's own per-user folders and repair every entry the user cannot open (Windows). 532 533Meant to run when Strata starts: files and folders an elevated run created (owner Administrators, a rule that names 534only SYSTEM, Administrators and OWNER RIGHTS) are given back to the user. A normal session can only repair what its 535own token may change; an elevated start repairs everything. Never raises; returns what it did. 536""" 537report = {"checked" :0 ,"repaired" :0 ,"failed" :0 } 538if not WINDOWS : 539return report 540for root in known_roots (): 541stack = [root ] 542while stack and report ["checked" ]< limit : 543folder = stack .pop () 544try : 545entries = list (os .scandir (folder )) 546except PermissionError : 547report ["checked" ]+= 1 548if repair_access (folder ,tree = False ): 549report ["repaired" ]+= 1 550try : 551entries = list (os .scandir (folder )) 552except OSError : 553continue 554else : 555report ["failed" ]+= 1 556continue 557except OSError : 558continue 559for entry in entries : 560report ["checked" ]+= 1 561try : 562if entry .is_symlink (): 563continue 564if entry .is_dir (follow_symlinks = False ): 565if entry .name .lower ()not in _SKIP_DIRS : 566stack .append (Path (entry .path )) 567continue 568if entry .name .lower ().endswith (_SKIP_SUFFIXES ): 569continue 570with open (entry .path ,"rb" ): 571pass 572except PermissionError : 573if repair_access (entry .path ,tree = False ): 574report ["repaired" ]+= 1 575else : 576report ["failed" ]+= 1 577except OSError : 578continue 579return report