ipsw-parser 1.8.3__tar.gz → 1.9.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/.github/workflows/python-app.yml +4 -0
  2. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/PKG-INFO +2 -2
  3. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/ipsw_parser/__main__.py +2 -3
  4. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/ipsw_parser/_version.py +3 -3
  5. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/ipsw_parser/archive.py +31 -12
  6. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/ipsw_parser/build_identity.py +45 -28
  7. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/ipsw_parser/build_manifest.py +10 -10
  8. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/ipsw_parser/component.py +16 -10
  9. ipsw_parser-1.9.0/ipsw_parser/firmware.py +58 -0
  10. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/ipsw_parser/ipsw.py +7 -6
  11. ipsw_parser-1.9.0/ipsw_parser/py.typed +0 -0
  12. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/ipsw_parser.egg-info/PKG-INFO +2 -2
  13. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/ipsw_parser.egg-info/SOURCES.txt +3 -0
  14. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/ipsw_parser.egg-info/requires.txt +1 -1
  15. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/ipsw_parser.egg-info/scm_file_list.json +3 -0
  16. ipsw_parser-1.9.0/ipsw_parser.egg-info/scm_version.json +8 -0
  17. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/pyproject.toml +9 -0
  18. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/requirements.txt +1 -1
  19. ipsw_parser-1.9.0/tests/test_firmware.py +30 -0
  20. ipsw_parser-1.9.0/tests/test_kernelcache.py +37 -0
  21. ipsw_parser-1.8.3/ipsw_parser/firmware.py +0 -45
  22. ipsw_parser-1.8.3/ipsw_parser.egg-info/scm_version.json +0 -8
  23. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/.gitattributes +0 -0
  24. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
  25. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
  26. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/.github/workflows/codeql.yml +0 -0
  27. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/.github/workflows/python-publish.yml +0 -0
  28. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/.gitignore +0 -0
  29. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/.pre-commit-config.yaml +0 -0
  30. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/CODE_OF_CONDUCT.md +0 -0
  31. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/LICENSE +0 -0
  32. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/README.md +0 -0
  33. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/ipsw_parser/__init__.py +0 -0
  34. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/ipsw_parser/dsc.py +0 -0
  35. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/ipsw_parser/exceptions.py +0 -0
  36. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/ipsw_parser/process.py +0 -0
  37. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/ipsw_parser.egg-info/dependency_links.txt +0 -0
  38. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/ipsw_parser.egg-info/entry_points.txt +0 -0
  39. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/ipsw_parser.egg-info/top_level.txt +0 -0
  40. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/pytest.ini +0 -0
  41. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/setup.cfg +0 -0
  42. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/tests/test_archive_backends.py +0 -0
  43. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/tests/test_dsc.py +0 -0
  44. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/tests/test_process.py +0 -0
  45. {ipsw_parser-1.8.3 → ipsw_parser-1.9.0}/tests/test_sandbox_profiles.py +0 -0
@@ -32,6 +32,10 @@ jobs:
32
32
  - name: Test install
33
33
  run: |
34
34
  python -m pip install -U .
35
+ - name: Type check
36
+ run: |
37
+ python -m pip install pytest pyright==1.1.411
38
+ pyright
35
39
  - name: Test show usage
36
40
  run: |
37
41
  python -m ipsw_parser --help
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ipsw-parser
3
- Version: 1.8.3
3
+ Version: 1.9.0
4
4
  Summary: python3 utility for parsing and extracting data from IPSW
5
5
  Author-email: doronz88 <doron88@gmail.com>
6
6
  Maintainer-email: doronz88 <doron88@gmail.com>
@@ -695,8 +695,8 @@ Classifier: Programming Language :: Python :: 3 :: Only
695
695
  Requires-Python: >=3.9
696
696
  Description-Content-Type: text/markdown
697
697
  License-File: LICENSE
698
+ Requires-Dist: ansilogs>=1.1.0
698
699
  Requires-Dist: bytestruct>=0.1.0
699
- Requires-Dist: coloredlogs
700
700
  Requires-Dist: pyimg4>=0.8.8
701
701
  Requires-Dist: requests
702
702
  Requires-Dist: remotezip2
@@ -3,18 +3,17 @@ import logging
3
3
  from pathlib import Path
4
4
  from typing import Annotated, Optional
5
5
 
6
- import coloredlogs
6
+ import ansilogs
7
7
  import typer
8
8
 
9
9
  from ipsw_parser.ipsw import IPSW
10
10
 
11
- coloredlogs.install(level=logging.DEBUG)
11
+ ansilogs.install(logging.DEBUG)
12
12
 
13
13
  logging.getLogger("asyncio").disabled = True
14
14
  logging.getLogger("parso.cache").disabled = True
15
15
  logging.getLogger("parso.cache.pickle").disabled = True
16
16
  logging.getLogger("parso.python.diff").disabled = True
17
- logging.getLogger("humanfriendly.prompts").disabled = True
18
17
  logging.getLogger("blib2to3.pgen2.driver").disabled = True
19
18
  logging.getLogger("urllib3.connectionpool").disabled = True
20
19
 
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '1.8.3'
22
- __version_tuple__ = version_tuple = (1, 8, 3)
21
+ __version__ = version = '1.9.0'
22
+ __version_tuple__ = version_tuple = (1, 9, 0)
23
23
 
24
- __commit_id__ = commit_id = 'gc9b1581ba'
24
+ __commit_id__ = commit_id = 'g53f234674'
@@ -1,10 +1,10 @@
1
1
  import shutil
2
2
  import stat
3
- from collections.abc import Iterable
3
+ from collections.abc import Iterable, Sequence
4
4
  from dataclasses import dataclass
5
5
  from functools import cached_property
6
6
  from pathlib import Path
7
- from typing import BinaryIO, Protocol, Union
7
+ from typing import IO, Protocol, Union
8
8
  from zipfile import ZipFile, ZipInfo
9
9
 
10
10
 
@@ -17,11 +17,24 @@ class ArchiveMember:
17
17
  external_attr: int
18
18
 
19
19
 
20
+ class ArchiveEntry(Protocol):
21
+ """Metadata of an archive member: an ``ArchiveMember`` or a ``zipfile.ZipInfo``."""
22
+
23
+ @property
24
+ def filename(self) -> str: ...
25
+
26
+ @property
27
+ def file_size(self) -> int: ...
28
+
29
+ @property
30
+ def external_attr(self) -> int: ...
31
+
32
+
20
33
  class Archive(Protocol):
21
34
  """Protocol implemented by supported IPSW archive backends."""
22
35
 
23
36
  @property
24
- def filelist(self) -> list[ArchiveMember]:
37
+ def filelist(self) -> Sequence[ArchiveEntry]:
25
38
  """Return archive members with metadata."""
26
39
  ...
27
40
 
@@ -29,7 +42,7 @@ class Archive(Protocol):
29
42
  """Return archive member names."""
30
43
  ...
31
44
 
32
- def open(self, path: str) -> BinaryIO:
45
+ def open(self, path: str) -> IO[bytes]:
33
46
  """Open an archive member for binary reading."""
34
47
  ...
35
48
 
@@ -37,7 +50,7 @@ class Archive(Protocol):
37
50
  """Read an archive member into memory."""
38
51
  ...
39
52
 
40
- def extractall(self, path: Path, members: Iterable[Union[ArchiveMember, ZipInfo, str]]) -> None:
53
+ def extractall(self, path: Path, members: Iterable[Union[ArchiveEntry, str]]) -> None:
41
54
  """Extract the selected archive members into ``path``."""
42
55
  ...
43
56
 
@@ -58,7 +71,7 @@ class ZipArchive:
58
71
  """Return ZIP member names."""
59
72
  return self._archive.namelist()
60
73
 
61
- def open(self, path: str) -> BinaryIO:
74
+ def open(self, path: str) -> IO[bytes]:
62
75
  """Open a ZIP member for binary reading."""
63
76
  return self._archive.open(path)
64
77
 
@@ -66,9 +79,11 @@ class ZipArchive:
66
79
  """Read a ZIP member into memory."""
67
80
  return self._archive.read(path)
68
81
 
69
- def extractall(self, path: Path, members: Iterable[Union[ArchiveMember, ZipInfo, str]]) -> None:
82
+ def extractall(self, path: Path, members: Iterable[Union[ArchiveEntry, str]]) -> None:
70
83
  """Extract the selected ZIP members into ``path``."""
71
- self._archive.extractall(path=path, members=members)
84
+ self._archive.extractall(
85
+ path=path, members=[member if isinstance(member, str) else member.filename for member in members]
86
+ )
72
87
 
73
88
 
74
89
  class DirectoryArchive:
@@ -78,10 +93,14 @@ class DirectoryArchive:
78
93
  """Wrap an extracted IPSW directory."""
79
94
  self._root = root
80
95
 
81
- @cached_property
96
+ @property
82
97
  def filelist(self) -> list[ArchiveMember]:
83
98
  """Return filesystem entries as archive-style metadata."""
84
- result = []
99
+ return self._members
100
+
101
+ @cached_property
102
+ def _members(self) -> list[ArchiveMember]:
103
+ result: list[ArchiveMember] = []
85
104
  for file_path in sorted(path for path in self._root.rglob("*") if path.is_file()):
86
105
  file_stat = file_path.stat()
87
106
  relative_path = file_path.relative_to(self._root).as_posix()
@@ -99,7 +118,7 @@ class DirectoryArchive:
99
118
  """Return relative file paths under the archive root."""
100
119
  return [member.filename for member in self.filelist]
101
120
 
102
- def open(self, path: str) -> BinaryIO:
121
+ def open(self, path: str) -> IO[bytes]:
103
122
  """Open a file relative to the archive root."""
104
123
  return (self._root / path).open("rb")
105
124
 
@@ -107,7 +126,7 @@ class DirectoryArchive:
107
126
  """Read a file relative to the archive root."""
108
127
  return (self._root / path).read_bytes()
109
128
 
110
- def extractall(self, path: Path, members: Iterable[Union[ArchiveMember, ZipInfo, str]]) -> None:
129
+ def extractall(self, path: Path, members: Iterable[Union[ArchiveEntry, str]]) -> None:
111
130
  """Copy the selected members into ``path``."""
112
131
  for member in members:
113
132
  filename = member if isinstance(member, str) else member.filename
@@ -6,22 +6,27 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
6
6
  from functools import cached_property
7
7
  from pathlib import Path
8
8
  from tempfile import TemporaryDirectory
9
- from typing import Optional
9
+ from typing import TYPE_CHECKING, Any, Optional, Union
10
10
 
11
11
  import requests
12
- from pyimg4 import IM4P
12
+ from pyimg4 import IM4P # pyright: ignore[reportMissingTypeStubs]
13
13
 
14
14
  from ipsw_parser.archive import Archive
15
- from ipsw_parser.component import Component
15
+ from ipsw_parser.component import Component, SupportsPathByEntry
16
16
  from ipsw_parser.dsc import split_dsc
17
17
  from ipsw_parser.process import ProcessExecutionError, run
18
18
 
19
+ if TYPE_CHECKING:
20
+ from ipsw_parser.build_manifest import BuildManifest
21
+
19
22
  logger = logging.getLogger(__name__)
20
23
 
21
24
  AEA_MAGIC = b"AEA1"
22
25
 
23
26
 
24
- def extract_as(archive: Archive, member_name, output_path, chunk_size=64 * 1024):
27
+ def extract_as(
28
+ archive: Archive, member_name: str, output_path: Union[str, "os.PathLike[str]"], chunk_size: int = 64 * 1024
29
+ ) -> None:
25
30
  """Extract one archive member into a caller-provided path."""
26
31
  os.makedirs(os.path.dirname(output_path), exist_ok=True)
27
32
  with archive.open(member_name) as source, open(output_path, "wb") as target:
@@ -30,8 +35,8 @@ def extract_as(archive: Archive, member_name, output_path, chunk_size=64 * 1024)
30
35
 
31
36
  def _extract_dmg(dmg: Path, output: Path, sub_path: Optional[Path] = None, pem_db: Optional[str] = None) -> None:
32
37
  # darwin system statistically have problems cleaning up after detaching the mountpoint
33
- with TemporaryDirectory() as temp_dir:
34
- temp_dir = Path(temp_dir)
38
+ with TemporaryDirectory() as temp_dir_name:
39
+ temp_dir = Path(temp_dir_name)
35
40
  mnt = temp_dir / "mnt"
36
41
  mnt.mkdir()
37
42
 
@@ -42,14 +47,14 @@ def _extract_dmg(dmg: Path, output: Path, sub_path: Optional[Path] = None, pem_d
42
47
  aea_dmg = str(dmg.absolute()) + ".aea"
43
48
  dmg.rename(aea_dmg)
44
49
  dmg = temp_dir / Path(aea_dmg).name.rsplit(".", 1)[0]
45
- args = ["fw", "aea", aea_dmg, "-o", temp_dir]
50
+ args: list[Union[str, Path]] = ["fw", "aea", aea_dmg, "-o", temp_dir]
46
51
  if pem_db is not None:
52
+ pem_db_path: Union[str, Path] = pem_db
47
53
  if "://" in pem_db:
48
54
  # create a local file containing it
49
- temp_pem_db = temp_dir / "pem-db.json"
50
- temp_pem_db.write_text(requests.get(pem_db, verify=False).text)
51
- pem_db = temp_pem_db
52
- args += ["--pem-db", pem_db]
55
+ pem_db_path = temp_dir / "pem-db.json"
56
+ pem_db_path.write_text(requests.get(pem_db, verify=False).text)
57
+ args += ["--pem-db", pem_db_path]
53
58
  run("ipsw", *args)
54
59
 
55
60
  run("hdiutil", "attach", "-mountpoint", mnt, dmg)
@@ -65,7 +70,7 @@ def _extract_dmg(dmg: Path, output: Path, sub_path: Optional[Path] = None, pem_d
65
70
 
66
71
 
67
72
  def _decode_sandbox_profiles(kernel_output: Path, output: Path, profile_type: Optional[str] = None) -> None:
68
- args = ["sb", "list", kernel_output]
73
+ args: list[Union[str, Path]] = ["sb", "list", kernel_output]
69
74
  if profile_type is not None:
70
75
  args += ["--type", profile_type]
71
76
 
@@ -76,7 +81,7 @@ def _decode_sandbox_profiles(kernel_output: Path, output: Path, profile_type: Op
76
81
  # Not with_suffix(): it would cut a dotted name short, and com.apple.cloudd would share
77
82
  # com.apple.sb with every other com.apple.* profile
78
83
  profile_path = output / f"{profile_name}.sb"
79
- decode_args = ["sb", "dec", kernel_output, profile_name]
84
+ decode_args: list[Union[str, Path]] = ["sb", "dec", kernel_output, profile_name]
80
85
  if profile_type is not None:
81
86
  decode_args += ["--type", profile_type]
82
87
  try:
@@ -105,9 +110,7 @@ def _extract_kernelcache(build_identity: "BuildIdentity", output: Path) -> Path:
105
110
  output.mkdir(parents=True, exist_ok=True)
106
111
 
107
112
  logger.info(f"extracting kernel into: {kernel_output}")
108
- im4p = IM4P(kernel_component.data)
109
- im4p.payload.decompress()
110
- kernel_output.write_bytes(im4p.payload.output().data)
113
+ kernel_output.write_bytes(_im4p_payload(kernel_component.data))
111
114
  try:
112
115
  # In case the kernel is a FAT image, extract the arm64 macho
113
116
  run("ipsw", "macho", "lipo", "-a", "arm64", kernel_output)
@@ -118,10 +121,19 @@ def _extract_kernelcache(build_identity: "BuildIdentity", output: Path) -> Path:
118
121
  return kernel_output
119
122
 
120
123
 
121
- class BuildIdentity(UserDict):
124
+ def _im4p_payload(data: bytes) -> bytes:
125
+ """Return the decompressed payload of an IM4P."""
126
+ payload = IM4P(data).payload
127
+ if payload is None:
128
+ raise ValueError("The IM4P carries no payload.")
129
+ payload.decompress()
130
+ return payload.output().data
131
+
132
+
133
+ class BuildIdentity(UserDict[str, Any]):
122
134
  """Dictionary-backed wrapper for a single build identity."""
123
135
 
124
- def __init__(self, build_manifest, data):
136
+ def __init__(self, build_manifest: "BuildManifest", data: dict[str, Any]):
125
137
  """Wrap a single BuildIdentity entry from the manifest."""
126
138
  super().__init__(data)
127
139
  self.build_manifest = build_manifest
@@ -132,27 +144,27 @@ class BuildIdentity(UserDict):
132
144
  return self["Info"]["DeviceClass"].lower()
133
145
 
134
146
  @cached_property
135
- def restore_behavior(self) -> str:
147
+ def restore_behavior(self) -> Optional[str]:
136
148
  """Return the restore behavior declared by the build identity."""
137
149
  return self["Info"].get("RestoreBehavior")
138
150
 
139
151
  @cached_property
140
- def variant(self):
152
+ def variant(self) -> Optional[str]:
141
153
  """Return the variant string for this build identity."""
142
154
  return self["Info"].get("Variant")
143
155
 
144
156
  @cached_property
145
- def macos_variant(self) -> str:
157
+ def macos_variant(self) -> Optional[str]:
146
158
  """Return the macOS restore variant, if present."""
147
159
  return self["Info"].get("MacOSVariant")
148
160
 
149
161
  @cached_property
150
- def manifest(self) -> dict:
162
+ def manifest(self) -> dict[str, Any]:
151
163
  """Return the component manifest dictionary."""
152
164
  return self["Manifest"]
153
165
 
154
166
  @cached_property
155
- def minimum_system_partition(self):
167
+ def minimum_system_partition(self) -> Optional[int]:
156
168
  """Return the minimum system partition requirement, if present."""
157
169
  return self["Info"].get("MinimumSystemPartition")
158
170
 
@@ -164,9 +176,15 @@ class BuildIdentity(UserDict):
164
176
  """Return whether the build identity contains a named component."""
165
177
  return name in self.manifest
166
178
 
167
- def get_component(self, name: str, **args) -> Component:
179
+ def get_component(
180
+ self,
181
+ name: str,
182
+ tss: Optional[SupportsPathByEntry] = None,
183
+ data: Optional[bytes] = None,
184
+ path: Optional[str] = None,
185
+ ) -> Component:
168
186
  """Return a component wrapper for a named manifest entry."""
169
- return Component(self, name, **args)
187
+ return Component(self, name, tss=tss, data=data, path=path)
170
188
 
171
189
  def extract_dsc(self, output: Path, pem_db: Optional[str] = None, split: bool = True) -> None:
172
190
  """Extract the system cryptex DSC payloads into ``output``."""
@@ -187,14 +205,13 @@ class BuildIdentity(UserDict):
187
205
 
188
206
  def get_kernelcache_payload(self, arch: Optional[str] = None) -> bytes:
189
207
  """Return the decompressed kernelcache payload, optionally sliced by arch."""
190
- im4p = IM4P(self.build_manifest.build_identities[0].get_component("KernelCache").data)
191
- im4p.payload.decompress()
192
- payload = im4p.payload.output().data
208
+ payload = _im4p_payload(self.build_manifest.build_identities[0].get_component("KernelCache").data)
193
209
  if arch is None:
194
210
  return payload
195
211
 
196
212
  with TemporaryDirectory() as temp_dir:
197
213
  kernel_output = Path(temp_dir) / "kernel"
214
+ kernel_output.write_bytes(payload)
198
215
  run("ipsw", "macho", "lipo", "-a", arch, kernel_output)
199
216
  return Path(next(kernel_output.parent.glob(f"*.{arch}"))).read_bytes()
200
217
 
@@ -1,19 +1,24 @@
1
1
  import plistlib
2
2
  from functools import cached_property
3
- from typing import Optional
3
+ from typing import TYPE_CHECKING, Any, Optional
4
4
 
5
5
  from ipsw_parser.build_identity import BuildIdentity
6
6
  from ipsw_parser.exceptions import NoSuchBuildIdentityError
7
7
 
8
+ if TYPE_CHECKING:
9
+ from ipsw_parser.ipsw import IPSW
10
+
8
11
 
9
12
  class BuildManifest:
10
13
  """Parsed ``BuildManifest.plist`` wrapper with lookup helpers."""
11
14
 
12
- def __init__(self, ipsw, manifest: bytes):
15
+ def __init__(self, ipsw: "IPSW", manifest: bytes):
13
16
  """Parse a BuildManifest plist for the given IPSW."""
14
17
  self.ipsw = ipsw
15
- self._manifest = plistlib.loads(manifest)
16
- self._parse_build_identities()
18
+ self._manifest: dict[str, Any] = plistlib.loads(manifest)
19
+ self.build_identities: list[BuildIdentity] = [
20
+ BuildIdentity(self, build_identity) for build_identity in self._manifest["BuildIdentities"]
21
+ ]
17
22
 
18
23
  @cached_property
19
24
  def build_major(self) -> int:
@@ -60,7 +65,7 @@ class BuildManifest:
60
65
  ) -> BuildIdentity:
61
66
  """Return the first build identity matching the requested filters."""
62
67
  for build_identity in self.build_identities:
63
- if variant is not None and variant not in build_identity.variant:
68
+ if variant is not None and (build_identity.variant is None or variant not in build_identity.variant):
64
69
  continue
65
70
 
66
71
  if build_identity.device_class != device_class:
@@ -71,8 +76,3 @@ class BuildManifest:
71
76
 
72
77
  return build_identity
73
78
  raise NoSuchBuildIdentityError("failed to find the correct BuildIdentity from the BuildManifest")
74
-
75
- def _parse_build_identities(self) -> None:
76
- self.build_identities = []
77
- for build_identity in self._manifest["BuildIdentities"]:
78
- self.build_identities.append(BuildIdentity(self, build_identity))
@@ -1,16 +1,25 @@
1
1
  import logging
2
2
  import os.path
3
3
  from functools import cached_property
4
- from typing import Optional
4
+ from typing import TYPE_CHECKING, Any, Optional, Protocol
5
5
 
6
6
  from ipsw_parser.exceptions import IpswException
7
7
 
8
+ if TYPE_CHECKING:
9
+ from ipsw_parser.build_identity import BuildIdentity
8
10
 
9
- class TSSResponse(dict):
11
+
12
+ class SupportsPathByEntry(Protocol):
13
+ """A TSS response that may name the path of a component."""
14
+
15
+ def get_path_by_entry(self, component: str) -> Optional[str]: ...
16
+
17
+
18
+ class TSSResponse(dict[str, Any]):
10
19
  """Dictionary wrapper for TSS response payloads."""
11
20
 
12
21
  @property
13
- def ap_img4_ticket(self):
22
+ def ap_img4_ticket(self) -> bytes:
14
23
  """Return the AP IMG4 ticket from the TSS response."""
15
24
  ticket = self.get("ApImg4Ticket")
16
25
 
@@ -20,11 +29,11 @@ class TSSResponse(dict):
20
29
  return ticket
21
30
 
22
31
  @property
23
- def bb_ticket(self):
32
+ def bb_ticket(self) -> Optional[bytes]:
24
33
  """Return the baseband ticket from the TSS response, if present."""
25
34
  return self.get("BBTicket")
26
35
 
27
- def get_path_by_entry(self, component: str):
36
+ def get_path_by_entry(self, component: str) -> Optional[str]:
28
37
  """Return the path for a component entry in the TSS response."""
29
38
  node = self.get(component)
30
39
  if node is not None:
@@ -38,9 +47,9 @@ class Component:
38
47
 
39
48
  def __init__(
40
49
  self,
41
- build_identity,
50
+ build_identity: "BuildIdentity",
42
51
  name: str,
43
- tss: TSSResponse = None,
52
+ tss: Optional[SupportsPathByEntry] = None,
44
53
  data: Optional[bytes] = None,
45
54
  path: Optional[str] = None,
46
55
  ):
@@ -68,9 +77,6 @@ class Component:
68
77
  if path is None:
69
78
  path = self.build_identity.get_component_path(self.name)
70
79
 
71
- if path is None:
72
- raise IpswException(f"Failed to find component path for: {self.name}")
73
-
74
80
  return path
75
81
 
76
82
  @cached_property
@@ -0,0 +1,58 @@
1
+ from typing import TYPE_CHECKING, Optional
2
+
3
+ if TYPE_CHECKING:
4
+ from ipsw_parser.ipsw import IPSW
5
+
6
+ # filename prefix -> component name, as idevicerestore's get_component_name() maps them
7
+ _COMPONENT_NAME_PREFIXES = (
8
+ ("LLB", "LLB"),
9
+ ("iBoot", "iBoot"),
10
+ ("DeviceTree", "DeviceTree"),
11
+ ("applelogo", "AppleLogo"),
12
+ ("liquiddetect", "Liquid"),
13
+ ("lowpowermode", "LowPowerWallet0"),
14
+ ("recoverymode", "RecoveryMode"),
15
+ ("batterylow0", "BatteryLow0"),
16
+ ("batterylow1", "BatteryLow1"),
17
+ ("glyphcharging", "BatteryCharging"),
18
+ ("glyphplugin", "BatteryPlugin"),
19
+ ("batterycharging0", "BatteryCharging0"),
20
+ ("batterycharging1", "BatteryCharging1"),
21
+ ("batteryfull", "BatteryFull"),
22
+ ("needservice", "NeedService"),
23
+ ("SCAB", "SCAB"),
24
+ ("sep-firmware", "RestoreSEP"),
25
+ )
26
+
27
+
28
+ class Firmware:
29
+ """Helper for firmware manifests and component file mapping."""
30
+
31
+ def __init__(self, firmware_path: str, ipsw: "IPSW"):
32
+ """Index firmware manifest entries under a firmware directory."""
33
+ self._ipsw = ipsw
34
+ self._firmware_path = firmware_path
35
+ self._manifest_data = self._ipsw.read(self.get_relative_path("manifest"))
36
+ self._firmware_files: dict[str, str] = {}
37
+ for line in self._manifest_data.decode().splitlines():
38
+ filename = line.strip()
39
+ component_name = self.get_component_name(filename)
40
+ if component_name is None:
41
+ continue
42
+ self._firmware_files[component_name] = f"{firmware_path}/{filename}"
43
+
44
+ def get_relative_path(self, path: str) -> str:
45
+ """Return a firmware-relative archive path."""
46
+ return f"{self._firmware_path}/{path}"
47
+
48
+ def get_files(self) -> dict[str, str]:
49
+ """Return the indexed firmware component mapping."""
50
+ return self._firmware_files
51
+
52
+ @staticmethod
53
+ def get_component_name(filename: str) -> Optional[str]:
54
+ """Map a firmware filename (e.g. ``LLB.n61.RELEASE.img3``) to its component name by its prefix."""
55
+ for prefix, name in _COMPONENT_NAME_PREFIXES:
56
+ if filename.startswith(prefix):
57
+ return name
58
+ return None
@@ -1,15 +1,16 @@
1
1
  import logging
2
+ from collections.abc import Generator, Sequence
2
3
  from contextlib import contextmanager
3
4
  from dataclasses import dataclass, field
4
5
  from functools import cached_property
5
6
  from pathlib import Path
6
- from typing import Annotated, Optional
7
+ from typing import IO, Annotated, Optional
7
8
  from zipfile import ZipFile
8
9
 
9
10
  from bytestruct import BinaryStruct, Bytes, Const
10
- from remotezip2 import RemoteZip
11
+ from remotezip2 import RemoteZip # pyright: ignore[reportMissingTypeStubs]
11
12
 
12
- from ipsw_parser.archive import Archive, ArchiveMember, DirectoryArchive, ZipArchive
13
+ from ipsw_parser.archive import Archive, ArchiveEntry, DirectoryArchive, ZipArchive
13
14
  from ipsw_parser.build_manifest import BuildManifest
14
15
  from ipsw_parser.dsc import create_device_support_layout
15
16
  from ipsw_parser.firmware import Firmware
@@ -88,12 +89,12 @@ class IPSW:
88
89
  return self.read("SystemVersion.plist")
89
90
 
90
91
  @cached_property
91
- def filelist(self) -> list[ArchiveMember]:
92
+ def filelist(self) -> Sequence[ArchiveEntry]:
92
93
  """Return archive members for the IPSW."""
93
94
  return self.archive.filelist
94
95
 
95
96
  @contextmanager
96
- def open_path(self, path: str):
97
+ def open_path(self, path: str) -> Generator[IO[bytes], None, None]:
97
98
  """Open an IPSW member and close it automatically on exit."""
98
99
  file = self.archive.open(path)
99
100
  try:
@@ -152,7 +153,7 @@ class IPSW:
152
153
 
153
154
  def get_development_files(self) -> list[str]:
154
155
  """Return archive entries associated with development builds."""
155
- result = []
156
+ result: list[str] = []
156
157
  for entry in self.archive.namelist():
157
158
  for release in ("devel", "kasan", "research"):
158
159
  if release in entry.lower():
File without changes
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ipsw-parser
3
- Version: 1.8.3
3
+ Version: 1.9.0
4
4
  Summary: python3 utility for parsing and extracting data from IPSW
5
5
  Author-email: doronz88 <doron88@gmail.com>
6
6
  Maintainer-email: doronz88 <doron88@gmail.com>
@@ -695,8 +695,8 @@ Classifier: Programming Language :: Python :: 3 :: Only
695
695
  Requires-Python: >=3.9
696
696
  Description-Content-Type: text/markdown
697
697
  License-File: LICENSE
698
+ Requires-Dist: ansilogs>=1.1.0
698
699
  Requires-Dist: bytestruct>=0.1.0
699
- Requires-Dist: coloredlogs
700
700
  Requires-Dist: pyimg4>=0.8.8
701
701
  Requires-Dist: requests
702
702
  Requires-Dist: remotezip2
@@ -24,6 +24,7 @@ ipsw_parser/exceptions.py
24
24
  ipsw_parser/firmware.py
25
25
  ipsw_parser/ipsw.py
26
26
  ipsw_parser/process.py
27
+ ipsw_parser/py.typed
27
28
  ipsw_parser.egg-info/PKG-INFO
28
29
  ipsw_parser.egg-info/SOURCES.txt
29
30
  ipsw_parser.egg-info/dependency_links.txt
@@ -34,5 +35,7 @@ ipsw_parser.egg-info/scm_version.json
34
35
  ipsw_parser.egg-info/top_level.txt
35
36
  tests/test_archive_backends.py
36
37
  tests/test_dsc.py
38
+ tests/test_firmware.py
39
+ tests/test_kernelcache.py
37
40
  tests/test_process.py
38
41
  tests/test_sandbox_profiles.py
@@ -1,5 +1,5 @@
1
+ ansilogs>=1.1.0
1
2
  bytestruct>=0.1.0
2
- coloredlogs
3
3
  pyimg4>=0.8.8
4
4
  requests
5
5
  remotezip2
@@ -22,11 +22,14 @@
22
22
  "ipsw_parser/firmware.py",
23
23
  "ipsw_parser/ipsw.py",
24
24
  "ipsw_parser/process.py",
25
+ "ipsw_parser/py.typed",
25
26
  "pyproject.toml",
26
27
  "pytest.ini",
27
28
  "requirements.txt",
28
29
  "tests/test_archive_backends.py",
29
30
  "tests/test_dsc.py",
31
+ "tests/test_firmware.py",
32
+ "tests/test_kernelcache.py",
30
33
  "tests/test_process.py",
31
34
  "tests/test_sandbox_profiles.py"
32
35
  ]
@@ -0,0 +1,8 @@
1
+ {
2
+ "tag": "1.9.0",
3
+ "distance": 0,
4
+ "node": "g53f234674a3ecf6222b9041168f6c2f8e93e574d",
5
+ "dirty": false,
6
+ "branch": "HEAD",
7
+ "node_date": "2026-10-28"
8
+ }
@@ -38,6 +38,9 @@ ipsw-parser = "ipsw_parser.__main__:cli"
38
38
  [tool.setuptools.packages.find]
39
39
  exclude = ["docs*", "tests*"]
40
40
 
41
+ [tool.setuptools.package-data]
42
+ ipsw_parser = ["py.typed"]
43
+
41
44
  [tool.setuptools.dynamic]
42
45
  dependencies = { file = ["requirements.txt"] }
43
46
  version = { attr = "ipsw_parser._version.__version__" }
@@ -97,3 +100,9 @@ ignore = [
97
100
 
98
101
  [tool.ruff.format]
99
102
  preview = true
103
+
104
+ [tool.pyright]
105
+ include = ["ipsw_parser", "tests"]
106
+ pythonVersion = "3.9"
107
+ typeCheckingMode = "standard"
108
+ strict = ["ipsw_parser"]
@@ -1,5 +1,5 @@
1
+ ansilogs>=1.1.0
1
2
  bytestruct>=0.1.0
2
- coloredlogs
3
3
  pyimg4>=0.8.8
4
4
  requests
5
5
  remotezip2
@@ -0,0 +1,30 @@
1
+ import plistlib
2
+ from pathlib import Path
3
+
4
+ from ipsw_parser.archive import DirectoryArchive
5
+ from ipsw_parser.ipsw import IPSW
6
+
7
+
8
+ def test_firmware_maps_manifest_files_by_prefix(tmp_path: Path) -> None:
9
+ (tmp_path / "BuildManifest.plist").write_bytes(
10
+ plistlib.dumps({
11
+ "SupportedProductTypes": ["iPhone1,1"],
12
+ "ProductVersion": "1.0",
13
+ "ProductBuildVersion": "1A1",
14
+ "BuildIdentities": [],
15
+ })
16
+ )
17
+ firmware = tmp_path / "Firmware/all_flash/all_flash.n61ap.production"
18
+ firmware.mkdir(parents=True)
19
+ (firmware / "manifest").write_bytes(
20
+ b"LLB.n61.RELEASE.img3\napplelogo@2x.s5l8960x.img3\nunknown.img3\nsep-firmware.n61.RELEASE.im4p\n"
21
+ )
22
+
23
+ files = IPSW(DirectoryArchive(tmp_path)).get_firmware("Firmware/all_flash/all_flash.n61ap.production").get_files()
24
+
25
+ prefix = "Firmware/all_flash/all_flash.n61ap.production"
26
+ assert files == {
27
+ "LLB": f"{prefix}/LLB.n61.RELEASE.img3",
28
+ "AppleLogo": f"{prefix}/applelogo@2x.s5l8960x.img3",
29
+ "RestoreSEP": f"{prefix}/sep-firmware.n61.RELEASE.im4p",
30
+ }
@@ -0,0 +1,37 @@
1
+ import plistlib
2
+ from pathlib import Path
3
+
4
+ import pytest
5
+
6
+ from ipsw_parser import build_identity
7
+ from ipsw_parser.archive import DirectoryArchive
8
+ from ipsw_parser.ipsw import IPSW
9
+
10
+
11
+ def test_kernelcache_payload_is_sliced_by_arch(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
12
+ (tmp_path / "BuildManifest.plist").write_bytes(
13
+ plistlib.dumps({
14
+ "SupportedProductTypes": ["iPhone1,1"],
15
+ "ProductVersion": "1.0",
16
+ "ProductBuildVersion": "1A1",
17
+ "BuildIdentities": [
18
+ {"Info": {"DeviceClass": "N61AP"}, "Manifest": {"KernelCache": {"Info": {"Path": "kernelcache"}}}}
19
+ ],
20
+ })
21
+ )
22
+ (tmp_path / "kernelcache").write_bytes(b"im4p")
23
+ monkeypatch.setattr(build_identity, "_im4p_payload", lambda data: b"fat kernel")
24
+
25
+ def lipo(tool: str, *args: object) -> str:
26
+ assert (tool, *map(str, args[:4])) == ("ipsw", "macho", "lipo", "-a", "arm64e")
27
+ kernel = Path(str(args[4]))
28
+ # lipo slices the kernel it is given, so it must already hold the payload
29
+ assert kernel.read_bytes() == b"fat kernel"
30
+ kernel.with_name(f"{kernel.name}.arm64e").write_bytes(b"thin kernel")
31
+ return ""
32
+
33
+ monkeypatch.setattr(build_identity, "run", lipo)
34
+
35
+ ipsw = IPSW(DirectoryArchive(tmp_path))
36
+ assert ipsw.build_manifest.build_identities[0].get_kernelcache_payload() == b"fat kernel"
37
+ assert ipsw.build_manifest.build_identities[0].get_kernelcache_payload(arch="arm64e") == b"thin kernel"
@@ -1,45 +0,0 @@
1
- class Firmware:
2
- """Helper for firmware manifests and component file mapping."""
3
-
4
- def __init__(self, firmware_path: str, ipsw):
5
- """Index firmware manifest entries under a firmware directory."""
6
- self._ipsw = ipsw
7
- self._firmware_path = firmware_path
8
- self._manifest_data = self._ipsw.read(self.get_relative_path("manifest"))
9
- self._firmware_files = {}
10
- for filename in self._manifest_data.splitlines():
11
- filename = filename.strip()
12
- component_name = self.get_component_name(filename)
13
- self._firmware_files[component_name] = f"{firmware_path}/{filename}"
14
-
15
- def get_relative_path(self, path: str):
16
- """Return a firmware-relative archive path."""
17
- return f"{self._firmware_path}/{path}"
18
-
19
- def get_files(self):
20
- """Return the indexed firmware component mapping."""
21
- return self._firmware_files
22
-
23
- @staticmethod
24
- def get_component_name(filename):
25
- """Map a firmware filename to its logical component name."""
26
- names = {
27
- "LLB": "LLB",
28
- "iBoot": "iBoot",
29
- "DeviceTree": "DeviceTree",
30
- "applelogo": "AppleLogo",
31
- "liquiddetect": "Liquid",
32
- "lowpowermode": "LowPowerWallet0",
33
- "recoverymode": "RecoveryMode",
34
- "batterylow0": "BatteryLow0",
35
- "batterylow1": "BatteryLow1",
36
- "glyphcharging": "BatteryCharging",
37
- "glyphplugin": "BatteryPlugin",
38
- "batterycharging0": "BatteryCharging0",
39
- "batterycharging1": "BatteryCharging1",
40
- "batteryfull": "BatteryFull",
41
- "needservice": "NeedService",
42
- "SCAB": "SCAB",
43
- "sep-firmware": "RestoreSEP",
44
- }
45
- return names.get(filename)
@@ -1,8 +0,0 @@
1
- {
2
- "tag": "1.8.3",
3
- "distance": 0,
4
- "node": "gc9b1581ba6a4a572309d7cde07c1d0dba36c8c16",
5
- "dirty": false,
6
- "branch": "HEAD",
7
- "node_date": "2026-10-17"
8
- }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes