Files
reverse-engineering-anything/src/domain/desktop/appExportPython.ts
T
morluto 6904da4927 fix(artifacts): recognize standalone formats and route them to their readers (#14192)
* fix(artifacts): route native images to static readers and name their architecture

inspect_artifact sent every PE, ELF and Mach-O root straight to
open_binary (PE first to inspect_managed_artifact, whatever its CLI
header) and left architecture null on every inventory node and on the
inspection subject, although the header parsers already know the CPU.

Inventory classification now returns the header's CPU family with the
format, from the same ELF, Mach-O and PE record parsers target admission
uses, so each thin image node (including universal slices and archive
members) names its architecture; an undecoded machine stays null, and a
universal container node names none. When the inventory root is the
open target's own bytes, its Evidence subject carries the architecture
target admission parsed, as it already carried the selection.

Native next probes now list the provider-free readers for the format
before open_binary: PE imports, exports, load config, resources,
hardening and release exposure; ELF dependencies, exports, hardening and
release exposure; Mach-O inspect_macho, inspect_signature, hardening and
release exposure. inspect_managed_artifact leads only when the PE
declares a CLI header, is omitted when it declares none, and stays a
conditional probe for directory members whose declaration is unknown.
The PE hypothesis that inventory cannot tell managed from native is kept
only for that unknown case.

Fixes #14157

* fix(artifacts): recognize standalone formats and route them to their readers

inspect_artifact refused SQLite databases, Windows shortcuts, CPython
pyc files, flattened devicetrees and UEFI NVRAM variable-store volumes
as unsupported binary formats with no next probe, although dedicated
REA tools read each of them. The shared recognizer table, which target
admission and inventory classification both walk, had no entry for
them, and the UEFI admission probe required an FFS2/FFS3 volume even
though the UEFI inventory reader already retains other volumes.

Add sqlite, windows-shortcut, python-pyc and devicetree as artifact
formats recognized by their owners' detectors:
- The SQLite header moves to src/domain/sqliteFormat.ts. Desktop state
  detection now uses it too.
- The ShellLinkHeader size, LinkCLSID and GUID formatting move from
  the shortcut parser to src/domain/windows/windowsShortcutHeader.ts.
- A pyc must carry a pinned CPython magic. CR LF framing alone is not
  enough.
- A devicetree's header must pass the devicetree header parser after
  FIT has declined it. A malformed header is refused with its reason.

UEFI admission now accepts any aligned, checksum-valid firmware volume.

Inspection routes each format to its reader as an artifact-bytes next
probe: inspect_sqlite_database, inspect_windows_shortcut,
inspect_python_pyc, inspect_devicetree and inspect_uefi_firmware. The
reader is named once, in the domain inspection projection. Formats no
recognizer claims still refuse as before; their raw inventory is #14151.

Fixes #14174

* fix(artifacts): keep native readers for executables that carry a package

An executable whose contents inventory as an embedded package (Godot
PCK, PyInstaller, Node SEA, Deno, Bun or a .NET single-file bundle) is
also a native image. Previously inspection proposed only the package
reader and hid the native side.

The inspection now takes the native image facts that target admission
parsed for the root's own bytes, not only the PE CLI-header flag. When
inventory reads those bytes as a package, the package reader comes
first, then the carrier's static readers, then open_binary.

A probe names exactly one operation, so the static readers cannot be
grouped into one entry without changing the advertised schema. They
stay separate rows and share one short rationale, because each tool's
description already says what it reads. Each format's reader list is
now a table.

* test(targets): add vocabulary fixtures for the standalone artifact formats

The sqlite, windows-shortcut, python-pyc and devicetree target formats
had no TargetFixtures entry, so the exhaustive fixture map failed to
typecheck and the persistence and projection cases never covered them.

* fix(artifacts): bind a deep provider for managed PEs only at a native boundary

A PE declaring a CLI header recommended open_binary with generic
function-level advice, so pure managed assemblies were steered to a
deep native provider. Its rationale again requires managed inspection
to report a native or mixed boundary, and a PE whose header is unknown
states the same condition.

* test(artifacts): narrow the subject to a file before reading its format

* test(artifacts): assert universal slice inventory per host and prune probe snapshots

The universal Mach-O test assumed slice inventory on every host, but the
slice reader runs native lipo and is skipped off macOS, so it failed on the
Linux test shards and portable tests. The test now selects the host platform
through a HostPlatform mock: the slice inventory case runs only on a macOS
host, and the other-host case asserts unknown container coverage with only
the file occurrence on every host. Both keep the selected-slice subject
architecture and static reader order.

Pruning in the probe tests:
- Merge the ARM64 PE, ELF and Mach-O single-image probe tests into one
  parameterised case that asserts subject and root-node architecture, the
  complete static reader list, and that open_binary is the only probe beyond
  artifact bytes.
- Remove the Deno carrier ordering case from the native image probe test;
  the Deno CLI acceptance test covers the same three carriers through the
  public workflow and now asserts the same ordering and authority facts.
- Replace full next-probe arrays in the Bun, Deno, dotnet-bundle and
  PyInstaller CLI/MCP tests with a shared carrier assertion: package readers
  lead, the carrier's format reader is present, and open_binary is last and
  the only non-artifact-bytes probe. The per-format reader list stays owned
  by the native image probe test.

Malformed-header (undecoded machine), unknown architecture and package
subject identity coverage are unchanged.

* test(artifacts): fold the SQLite routing case into the standalone format table

The SQLite case asserted the same format, subject and single artifact-bytes
probe as the table above it and differed only in how the file is created.
Each table row now creates its own input, so the SQLite database joins the
table. The resembling-pyc refusal case is unchanged.

* fix(desktop): generate the exported reader's SQLite header from its owner

The exported Python reader kept its own SQLite header literal after
SQLITE_HEADER gained a shared owner. Generate it from that owner, as the
template already does for ZIP_SIGNATURES. Desktop fixtures that only need
a SQLite file now build it from the same constant; format-detection tests
and the tests that run the generated Python keep the literal header as an
independent check of the owner and the generated code.
2026-11-24 01:01:58 +00:00

655 lines
27 KiB
TypeScript

import { ZIP_EOCD_BYTES } from "../zipEndOfCentralDirectory.js";
import { ZIP_SIGNATURES } from "../zipPackageFormat.js";
import { SQLITE_HEADER } from "../sqliteFormat.js";
import { XML_ELEMENT_OPENING } from "../xmlDocument.js";
import {
DESKTOP_VIEW_DEFAULTS,
pythonDesktopViewPolicy,
type DesktopViewPolicy,
} from "./desktopViewPolicy.js";
import { PYTHON_JSON_READER } from "./appExportPythonJson.js";
import { PYTHON_XML_READER } from "./appExportPythonXml.js";
import { PYTHON_ZIP_HELPERS } from "./appExportPythonZip.js";
import {
DESKTOP_LINE_BREAK,
KEYFILE_CONTROL_LINE,
KEYFILE_ENTRY_LINE,
PYTHON_ECMASCRIPT_TRIM_CHARACTERS,
} from "./desktopTextSyntax.js";
import { PYTHON_X11_PROPERTIES } from "./x11Windows.js";
/** The generated module's imports. */
/** The class method that holds readiness until the app's own window shows, not a splash screen with its class. */
export const PYTHON_READY_CHECK = `
@ready_check
def main_window_shown(self) -> bool:
"""A window of the app's class that the taskbar lists is shown, not only a splash screen or a dialog."""
return _taskbar_window(WINDOW_CLASS)
`;
export const PYTHON_IMPORTS = `from __future__ import annotations
from array import array
from itertools import islice
import binascii
import contextlib
import copy
import hashlib
import io
import json
import math
import os
import errno
import re
import sqlite3
import struct
import subprocess
import sys
import tempfile
import zipfile
import zlib
from pathlib import Path
from xml.parsers import expat
from agentenv_protocol import add_data, get_data, reset_data
from agentenv_protocol.computer import AptSource, ComputerAppEnvironment, Download, Launch, Packages, Ready, RunScript, computer_app, linux, ready_check
from agentenv_protocol.computer.app_data import INITIAL, add, get, in_thread, keep_initial, reset
from agentenv_protocol.computer.dataplane import file_parts
from agentenv_protocol.types import DataPart
`;
/** Translate the shared XML grammar's code point escapes into Python regex escapes. */
const PYTHON_XML_ELEMENT_OPENING = XML_ELEMENT_OPENING.replaceAll(
/\\u\{([0-9a-f]+)\}/giu,
(_, code: string) => `\\U${code.padStart(8, "0")}`,
);
/** Python helpers the class uses to seed the home, load dconf keys and read typed views. */
const PYTHON_HELPER_BODY = String.raw`
XML_SUFFIXES = (".xml", ".xbel", ".plist", ".svg", ".ui")
XML_ELEMENT_OPENING = re.compile(r"${PYTHON_XML_ELEMENT_OPENING}")
def _opens_element(text: str) -> bool:
"""Whether text opens with an element, after a DOCTYPE with no internal subset or none. A '[' inside a quoted id is not a subset."""
if XML_ELEMENT_OPENING.match(text):
return True
declared = re.match(r"(?:<\?xml[^>]*>\s*)?<!DOCTYPE\b", text)
if declared is None:
return False
quote = ""
for index in range(declared.end(), len(text)):
character = text[index]
if quote:
if character == quote:
quote = ""
continue
if character in ('"', "'"):
quote = character
elif character == "[":
return False
elif character == ">":
return XML_ELEMENT_OPENING.match(text[index + 1:].lstrip()) is not None
return False
KEYFILE_CONTROL_LINE = re.compile(${JSON.stringify(KEYFILE_CONTROL_LINE)})
KEYFILE_ENTRY_LINE = re.compile(${JSON.stringify(KEYFILE_ENTRY_LINE)})
LINE_BREAK = re.compile(${JSON.stringify(DESKTOP_LINE_BREAK)})
ECMASCRIPT_TRIM_CHARACTERS = ${PYTHON_ECMASCRIPT_TRIM_CHARACTERS}
SQLITE_HEADER = bytes(${JSON.stringify([...SQLITE_HEADER].map((character) => character.charCodeAt(0)))})
GVDB_HEADER = b"GVariant"
ZIP_SIGNATURES = (${ZIP_SIGNATURES.map((signature) => `bytes(${JSON.stringify(signature)})`).join(", ")})
ZIP_HEADER = ZIP_SIGNATURES[0]
ZIP_EOCD_BYTES = ${String(ZIP_EOCD_BYTES)}
GZIP_HEADER = b"\x1f\x8b\x08"
XML_SPACE = "xml:space"
MAX_SAFE_INTEGER = 2**53 - 1
SQLITE_BUSY_S = 0.25
def _view_byte_limit(value: int) -> str:
return f"{value // (1024 * 1024)} MiB" if value % (1024 * 1024) == 0 else f"{value} bytes"
PARSED_TOO_LARGE = f"larger than the {_view_byte_limit(MAX_PARSED_BYTES)} limit for JSON and key file views"
JSON_TOO_DEEP = f"nested deeper than the {MAX_JSON_VIEW_DEPTH} levels a JSON view keeps"
def _respelled(text: str, home: Path) -> str:
"""The seed's home path respelled to this computer's home, only where a whole path segment ends after it."""
return re.sub(re.escape(SEED_HOME) + r"(?![\w.@+~-])", lambda _: str(home), text)
UTF16_CODECS = {b"\xff\xfe": "utf-16-le", b"\xfe\xff": "utf-16-be"}
def _respelled_utf16(data: bytes, home: Path) -> bytes:
"""A UTF-16 text file with a byte-order mark respelled like a text seed, its mark kept; any other bytes as given."""
mark = data[:2]
codec = UTF16_CODECS.get(mark)
if codec is None:
return data
try:
text = data[2:].decode(codec)
except UnicodeDecodeError:
return data
return mark + _respelled(text, home).encode(codec) if SEED_HOME in text else data
${PYTHON_X11_PROPERTIES}
def _taskbar_window(window_class: str) -> bool:
"""Whether a top-level window of the given class that the taskbar lists is shown; a splash screen or a dialog
skips the taskbar."""
def xprop(*args: str) -> str:
done = subprocess.run(["xprop", *args], capture_output=True, text=True)
return done.stdout if done.returncode == 0 else ""
root = _x11_properties(xprop("-root", "_NET_CLIENT_LIST"))
for window in _x11_client_ids(root):
props = _x11_properties(xprop("-id", window, "WM_CLASS", "_NET_WM_STATE", "_NET_WM_WINDOW_TYPE"))
if _x11_window_class(props) != window_class:
continue
states = [atom.strip(ECMASCRIPT_TRIM_CHARACTERS) for atom in props.get("_NET_WM_STATE", "").split(",")]
types = [atom.strip(ECMASCRIPT_TRIM_CHARACTERS) for atom in props.get("_NET_WM_WINDOW_TYPE", "").split(",")]
if "_NET_WM_STATE_SKIP_TASKBAR" not in states and "_NET_WM_WINDOW_TYPE_SPLASH" not in types:
return True
return False
def _seed_home(home: Path) -> None:
"""Copy the captured files into this computer's home; text files, UTF-16 ones too, have the seed's home path
respelled."""
seed = HERE / "seed"
for source in sorted(seed.rglob("*")) if seed.is_dir() else []:
if not source.is_file():
continue
relative = source.relative_to(seed).as_posix()
target = home / relative
target.parent.mkdir(parents=True, exist_ok=True)
data = source.read_bytes()
if data[:2] in UTF16_CODECS:
data = _respelled_utf16(data, home)
elif relative in TEXT_SEEDS:
data = _respelled(data.decode("utf-8"), home).encode("utf-8")
target.write_bytes(data)
mode = SEED_MODES.get(relative)
if mode is not None:
target.chmod(mode)
def _ensure_state_aliases(home: Path) -> None:
"""Restore selected aliases without replacing any existing user data."""
aliases = sorted(STATE_ALIASES, key=lambda pair: len(Path(pair[0]).parts))
for alias, target, kind in aliases:
link = home / alias
destination = home / target
# A recorded directory is created. A legacy alias with no kind is
# created only when another alias is inside it, which proves it is a
# directory. A legacy leaf stays unclassified so a missing file is not
# turned into a directory.
has_children = any(Path(alias) in Path(child).parents for child, *_ in aliases)
if kind == "directory" or (kind == "unknown" and has_children):
destination.mkdir(parents=True, exist_ok=True)
elif kind == "file":
# The file itself stays absent so the app can create it. Its parent
# has to exist or that write fails with ENOENT.
destination.parent.mkdir(parents=True, exist_ok=True)
if link.is_symlink() and link.resolve() == destination.resolve():
continue
if os.path.lexists(link):
raise FileExistsError(f"Cannot restore selected state alias; path already exists: {link}")
link.parent.mkdir(parents=True, exist_ok=True)
link.symlink_to(destination)
def _dconf(arguments: list, environment: dict) -> str:
child_environment = {**os.environ, **environment}
refusal = None
missing = None
for directory in os.get_exec_path(child_environment):
command = os.path.join(directory, "dconf")
if not os.path.isabs(command):
command = os.path.join(os.getcwd(), command)
try:
child = subprocess.Popen([command, *arguments], env=child_environment,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
except OSError as error:
# Popen identifies an exec failure with the executable filename;
# parent capacity, pipe setup and cwd failures are not PATH misses.
if error.filename != command:
raise
# Match Python's executable search: retain the first non-missing
# spawn error, but never retry a child that actually started.
if error.errno in (errno.ENOENT, errno.ENOTDIR):
missing = error
elif refusal is None:
refusal = error
continue
break
else:
if refusal is not None:
raise refusal
if missing is not None:
raise missing
raise FileNotFoundError(errno.ENOENT, "dconf is not installed (dconf-cli)", "dconf")
with child:
try:
stdout, stderr = child.communicate()
except BaseException:
child.kill()
raise
result = subprocess.CompletedProcess(child.args, child.returncode, stdout, stderr)
result.check_returncode()
return result.stdout
def _load_dconf(home: Path) -> None:
"""Compile the captured dconf keys into the user database without D-Bus, which is not up yet. Keys already there
stay unless captured: dconf compile reads the key files in name order and a later file wins. A failure is
reported and the app starts without them."""
if not DCONF:
return
database = home / ".config" / "dconf" / "user"
try:
database.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=database.parent) as scratch:
keyfiles = Path(scratch, "keyfiles")
keyfiles.mkdir()
if database.is_file():
profile = Path(scratch, "profile")
with database.open("rb") as source:
# Parent ownership survives wrappers replacing stdin or closing child fds.
source_path = f"/proc/{os.getpid()}/fd/{source.fileno()}"
# Missing descriptor paths must not become a successful empty dump.
os.stat(source_path)
profile.write_text(f"file-db:{source_path}\n")
existing = _dconf(["dump", "/"], {"DCONF_PROFILE": str(profile.resolve())})
(keyfiles / "00-existing").write_text(existing)
(keyfiles / "01-captured").write_text(_respelled(DCONF, home))
_dconf(["compile", str(Path(scratch, "user")), str(keyfiles)], {})
os.replace(Path(scratch, "user"), database)
except (OSError, subprocess.CalledProcessError) as error:
detail = (getattr(error, "stderr", None) or "").strip().splitlines()
print(f"warning: the captured dconf settings were not loaded: {detail[-1] if detail else error}",
file=sys.stderr)
def _sqlite_text(data: bytes, encoding: str):
text = data.decode(encoding, "replace")
return {"text": text, "bytes_hex": data.hex()} if "�" in text else text
def _cell(value, encoding: str):
if isinstance(value, str):
data = bytes.fromhex(value[1:])
return _sqlite_text(data, encoding) if value[0] == "t" else {"blob_hex": data.hex()}
if isinstance(value, int) and abs(value) > MAX_SAFE_INTEGER:
return {"integer": str(value)}
# Keep JSON's missing REAL values distinct from literal TEXT spellings.
if isinstance(value, float) and (math.isinf(value) or (value == 0 and math.copysign(1, value) < 0)):
return {"real": "Infinity" if value == math.inf else "-Infinity" if value == -math.inf else "-0"}
return value
def _view_json_bytes(value, budget: int) -> int:
"""Size the table/row JSON shapes without quoting a whole large cell.
Above budget the count establishes overflow only. Numeric spelling follows
Python's compact JSON encoder, rather than assuming JavaScript's spelling.
"""
if isinstance(value, str):
total = 2
for offset in range(0, len(value), 8192):
if total > budget:
break
# Public JSON quoting preserves escapes; remove each chunk's two
# quotes. A control-filled native cell never becomes one huge part.
total += len(json.dumps(value[offset:offset + 8192], ensure_ascii=False).encode("utf-8")) - 2
return total
if isinstance(value, list):
total = 2 + max(0, len(value) - 1)
for member in value:
if total > budget:
break
total += _view_json_bytes(member, budget - total)
return total
if isinstance(value, dict):
total = 2 + max(0, len(value) - 1)
for key, member in value.items():
if total > budget:
break
total += _view_json_bytes(key, budget - total) + 1
if total <= budget:
total += _view_json_bytes(member, budget - total)
return total
return len(json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))
def _table(db, name: str, primary_key: list, encoding: str) -> dict:
quoted = '"' + name.replace('"', '""') + '"'
columns = [column[0] for column in db.execute(f"select * from main.{quoted} limit 0").description]
# SQLite owns TEXT-to-BLOB conversion, so hex retains the database's original encoding.
projected = []
for name in columns:
column = '"' + name.replace('"', '""') + '"'
projected.append(f"CASE typeof({column}) WHEN 'text' THEN 't' || hex(CAST({column} AS BLOB)) "
f"WHEN 'blob' THEN 'b' || hex({column}) ELSE {column} END")
cursor = db.execute(f"select {', '.join(projected)} from main.{quoted} not indexed limit {MAX_ROWS + 1}")
view = {"columns": columns, "primary_key": primary_key, "rows": [], "truncated": True}
spent = _view_json_bytes(view, MAX_SQLITE_VIEW_BYTES)
if spent > MAX_SQLITE_VIEW_BYTES:
return {"error": SQLITE_VIEW_TOO_LARGE}
for index, row in enumerate(cursor):
if index == MAX_ROWS:
break
projected = [_cell(value, encoding) for value in row]
spent += (1 if view["rows"] else 0) + _view_json_bytes(projected, MAX_SQLITE_VIEW_BYTES - spent)
if spent > MAX_SQLITE_VIEW_BYTES:
return {"error": SQLITE_VIEW_TOO_LARGE}
view["rows"].append(projected)
else:
view["truncated"] = False
# JSON false takes one byte more than true, reserved only when known.
spent += 1
return {"error": SQLITE_VIEW_TOO_LARGE} if spent > MAX_SQLITE_VIEW_BYTES else view
def _sqlite(path: Path) -> dict:
"""The database's ordinary tables, in schema order, up to REA's table and row limits."""
with contextlib.closing(sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True, timeout=SQLITE_BUSY_S)) as db:
# Match the independent native value/record boundary before SQL hex
# expansion; the selected projected-view allowance is separate.
db.setlimit(sqlite3.SQLITE_LIMIT_LENGTH, SQLITE_VALUE_BYTES)
kinds = dict(db.execute("select name, type from temp.pragma_table_list where schema = 'main'"))
names = [name for (name,) in db.execute("select name from sqlite_schema where type = 'table'")
if kinds.get(name) == "table"]
keys = {name: [key for (key,) in db.execute(
"select name from temp.pragma_table_info(?, 'main') where pk > 0 order by pk", (name,))]
for name in names[:MAX_TABLES]}
encoding = {"UTF-8": "utf-8", "UTF-16le": "utf-16-le", "UTF-16be": "utf-16-be"}[
db.execute("PRAGMA encoding").fetchone()[0]]
tables = {}
for name in names[:MAX_TABLES]:
try:
tables[name] = _table(db, name, keys[name], encoding)
except sqlite3.Error as error:
reason = str(error)
if getattr(error, "sqlite_errorcode", None) == sqlite3.SQLITE_TOOBIG:
reason += (f". SQLite value/record exceeds the fixed {SQLITE_VALUE_BYTES}-byte native limit, including SQL hex expansion. "
"Increasing sqlite_view_bytes does not raise this boundary. Keep the complete database; "
"use a narrower REA SQLite table/column projection only if it preserves the required facts, "
"or use a format-specific reader.")
tables[name] = {"error": reason}
cut = len(names) > MAX_TABLES
return {"format": "sqlite", "view": {"tables": tables, "tables_truncated": cut},
"truncated": cut or any(table.get("truncated", "error" in table) for table in tables.values())}
def _text(text: str) -> dict:
count = text.count("\n") + int(bool(text) and not text.endswith("\n"))
lines = list(islice(_each_line(text), min(MAX_LINES, count)))
view = {"lines": lines, "line_count": count, "truncated": count > MAX_LINES}
return {"format": "text", "view": view, "truncated": view["truncated"]}
def _keyfile_line(raw: str) -> tuple:
"""A key file line as REA reads it: skip (blank or comment), group, entry or other."""
control = KEYFILE_CONTROL_LINE.fullmatch(raw.strip(ECMASCRIPT_TRIM_CHARACTERS))
if control is not None:
name = control.group(1)
return ("skip",) if name is None else ("group", name)
entry = KEYFILE_ENTRY_LINE.fullmatch(raw)
if entry is not None:
key = entry.group(1).strip(ECMASCRIPT_TRIM_CHARACTERS)
if key:
return ("entry", key, entry.group(2))
return ("other",)
def _each_line(text: str):
"""Each line of text as REA splits them, one at a time."""
start = 0
for line_break in LINE_BREAK.finditer(text):
yield text[start:line_break.start()]
start = line_break.end()
yield text[start:]
def _is_keyfile(text: str) -> bool:
"""REA's rule: at least one group, and nothing a key file view would drop. Lines are read one at a time, stopping
at the first it would drop."""
group = False
for line in _each_line(text):
kind = _keyfile_line(line)[0]
if kind == "other":
return False
group = group or kind == "group"
return group
def _keyfile(text: str) -> dict:
groups, group = {}, ""
for line in map(_keyfile_line, _each_line(text)):
if line[0] == "group":
group = line[1]
groups.setdefault(group, {})
elif line[0] == "entry":
groups.setdefault(group, {})[line[1]] = line[2]
return groups
${PYTHON_XML_READER}
${PYTHON_JSON_READER}
def _text_view(name: str, text: str, size: int) -> dict:
"""The format REA's state view detects for decoded text of size bytes, and its view; a JSON or key file over the
parsed-view limit is refused before its value is built."""
trimmed = text.lstrip(ECMASCRIPT_TRIM_CHARACTERS)
if name.lower().endswith(".json") or trimmed[:1] in ("[", "{"):
view = _json_view(text, size)
if view is not None:
return view
lowered = name.lower()
# Text that opens with an element, after a DOCTYPE with no internal subset or none, is XML if it parses, whatever
# the file is called, as a Freeplane map or KmPlot's <!DOCTYPE kmpdoc> plot.
if lowered.endswith(XML_SUFFIXES) or trimmed.startswith("<?xml") or _opens_element(trimmed):
view = _xml_view(text)
return _text(text) if view is None else {"format": "xml", "view": view, "truncated": view["truncated"]}
if _is_keyfile(text):
if size > MAX_PARSED_BYTES:
return {"format": "keyfile", "view": None, "error": PARSED_TOO_LARGE}
return {"format": "keyfile", "view": {"groups": _keyfile(text)}, "truncated": False}
return _text(text)
def _bytes_view(name: str, data: bytes) -> dict:
"""The view of a document that is no database or archive: its text's, or none when it is binary."""
try:
codec = UTF16_CODECS.get(bytes(data[:2]))
if codec is not None:
text = data[2:].decode(codec)
else:
text = data.decode("utf-8-sig") if b"\x00" not in data[:8192] else None
except UnicodeDecodeError:
text = None
if text is None or (codec is not None and "\x00" in text):
return {"format": "binary", "view": None, "truncated": False}
return _text_view(name, text, len(data))
def _is_zip(data: bytes) -> bool:
"""Recognize storage signatures before the directory reader checks validity."""
return data.startswith(ZIP_HEADER) or (len(data) >= ZIP_EOCD_BYTES and data.startswith(ZIP_SIGNATURES))
def _view(path: Path) -> dict:
"""A typed JSON view of one file in the shapes of REA's state view; truncated says the view is partial."""
too_large = {"format": None, "view": None, "error": VIEW_TOO_LARGE}
if path.stat().st_size > MAX_VIEW_BYTES:
return too_large
with path.open("rb") as file:
data = file.read(min(8192, MAX_VIEW_BYTES + 1))
if len(data) > MAX_VIEW_BYTES:
return too_large
whole = (data.startswith(GZIP_HEADER) or data[:2] in UTF16_CODECS
or (not data.startswith(SQLITE_HEADER) and b"\x00" not in data))
remaining = MAX_VIEW_BYTES + 1 - len(data)
if whole and remaining > 0:
data += file.read(remaining)
if len(data) > MAX_VIEW_BYTES:
return too_large
if data.startswith(SQLITE_HEADER):
return _sqlite(path)
if _is_zip(data):
with path.open("rb") as file:
return _zip(file, os.fstat(file.fileno()).st_size)
if data.startswith(GZIP_HEADER):
return _gzip(path.name, data)
return _bytes_view(path.name, data)
def _write_withheld(home: Path, settings, withheld: dict) -> None:
"""Write each withheld file from its secret setting, its bytes in base64, readable by its owner alone."""
for name, relative in withheld.items():
target = home / relative
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(binascii.a2b_base64(getattr(settings, name).get_secret_value(), strict_mode=True))
target.chmod(0o600)
def _views(home: Path, paths: list, leaving_out=()) -> dict:
"""A view of every file under the app's paths but those it leaves out, keyed by its home-relative path."""
files = {}
for owned in paths:
root = home / owned
candidates = [root] if root.is_file() else sorted(root.rglob("*")) if root.is_dir() else []
for path in candidates:
if path.is_file() and not path.is_symlink():
key = path.relative_to(home).as_posix()
if key in leaving_out:
continue
try:
files[key] = _view(path)
except (OSError, ValueError, sqlite3.Error, RecursionError) as error:
files[key] = {"format": None, "view": None, "error": str(error)}
return files
`.concat(PYTHON_ZIP_HELPERS);
/** Render the accepted policy before helpers which consume it. */
export const renderPythonHelpers = (policy: DesktopViewPolicy): string =>
`\n${pythonDesktopViewPolicy(policy)}\n${PYTHON_HELPER_BODY}`;
/** Default helpers for existing generated-reader consumers. */
export const PYTHON_HELPERS = renderPythonHelpers(DESKTOP_VIEW_DEFAULTS);
/** Constants the class module assigns before the helpers. */
const PYTHON_CONSTANTS = [
"HERE",
"SEED_HOME",
"PATHS",
"DCONF",
"TEXT_SEEDS",
"SEED_MODES",
"STATE_ALIASES",
"WINDOW_CLASS",
"WITHHELD",
] as const;
/** Names a Python source binds at its top level: imports, assignments, functions and classes. */
const boundNames = (source: string): readonly string[] => [
...[...source.matchAll(/^(?:from \S+ )?import (?<names>.+)$/gmu)].flatMap(
(match) =>
(match.groups?.names ?? "")
.split(",")
.map(
(name) =>
name
.trim()
.split(/\s+as\s+/u)
.at(-1) ?? "",
)
.map((name) => name.split(".")[0] ?? ""),
),
...[
...source.matchAll(/^(?:def |class )?(?<name>[A-Za-z_]\w*)(?: =|\()/gmu),
].map((match) => match.groups?.name ?? ""),
];
/** Every name the generated module binds besides the app class, which the class must not take. */
export const PYTHON_MODULE_NAMES: ReadonlySet<string> = new Set([
...boundNames(PYTHON_IMPORTS),
...boundNames(PYTHON_HELPERS),
...PYTHON_CONSTANTS,
]);
/**
* The class body of an app that owns no files: launched at boot, its captured
* dconf settings loaded if any, serving no data operations, or, when its task
* judges its screen, a reset that only relaunches it.
*/
export const ownlessBody = (
title: string,
dconf: boolean,
relaunch: boolean,
aliases = false,
): string => {
const reset = relaunch
? `
@reset_data
async def relaunch(self) -> None:
"""Nothing to restore: the app is stopped before this and relaunched after it, back to its first screen."""
`
: "";
const serves = relaunch
? "and keeps its task's state on screen, so its reset only relaunches it"
: "so it serves no data operations";
const restore = aliases ? "\n _ensure_state_aliases(Path.home())" : "";
if (dconf)
return ` """${title}, launched at boot with its captured settings. It owns no files, ${serves}."""
def __init__(self) -> None:
super().__init__()
_load_dconf(Path.home())${restore}
${reset}${PYTHON_READY_CHECK}`;
if (!aliases)
return ` """${title}, launched at boot. No state was observed, ${serves}."""\n${reset}${PYTHON_READY_CHECK}`;
return ` """${title}, launched at boot. No state was observed, ${serves}."""
def __init__(self) -> None:
super().__init__()
_ensure_state_aliases(Path.home())
${reset}${PYTHON_READY_CHECK}`;
};
/** The data hooks of an app whose withheld files no get serves: neither as parts nor in the views. */
export const PYTHON_WITHHELD_DATA_HOOKS = `
@add_data
async def add_files(self, parts: list) -> None:
await add(parts, self.paths)
@get_data
async def get_files(self, write_namespace=None) -> list:
files = await file_parts(Path.home(), self.paths, write_namespace, list(WITHHELD.values()))
views = await in_thread(_views, Path.home(), self.paths, list(WITHHELD.values()))
return [*files, DataPart(data={"state": views})]
@reset_data
async def reset_files(self) -> None:
await reset(self.paths)
`;
/** The data hooks of an app that owns paths; `_views` reads files, so it runs in a thread. */
export const PYTHON_DATA_HOOKS = `
@add_data
async def add_files(self, parts: list) -> None:
await add(parts, self.paths)
@get_data
async def get_files(self, write_namespace=None) -> list:
files = await get(self.paths, write_namespace)
views = await in_thread(_views, Path.home(), self.paths)
return [*files, DataPart(data={"state": views})]
@reset_data
async def reset_files(self) -> None:
await reset(self.paths)
`;