mirror of
https://github.com/Mak5er/AirCard
synced 2026-11-26 08:57:55 +08:00
fix: invalidate stale Wallet artwork on iOS 27
This commit is contained in:
1 parent
02b5ba8b87
commit
7e8979b7a7
4 files changed
+184
-27
No files matched your search
@@ -969,6 +969,43 @@ static NSDictionary *FinishWrite(DeviceSession *session, NSArray<NSString *> *ar
|
||||
@"booksRestore": booksRestore };
|
||||
}
|
||||
|
||||
static NSDictionary *FinishMovedRemoval(DeviceSession *session, NSArray<NSString *> *args) {
|
||||
NSString *source = args[0];
|
||||
NSString *linkDestination = args[1];
|
||||
NSString *recovered = args[2];
|
||||
NSString *snapshotRoot = args[3];
|
||||
NSInteger expectedCount = [args[4] integerValue];
|
||||
BOOL safeArguments = GeneratedNamesMatch(source, linkDestination, recovered) &&
|
||||
expectedCount > 0 && expectedCount <= 32;
|
||||
if (!safeArguments) return @{ @"ok": @NO, @"safeArguments": @NO };
|
||||
|
||||
NSMutableArray<NSString *> *missing = NSMutableArray.array;
|
||||
for (NSInteger index = 0; index < expectedCount; index++) {
|
||||
NSString *path = [source stringByAppendingPathComponent:
|
||||
[NSString stringWithFormat:@"removed-%ld", (long)index]];
|
||||
if (!AFCExists(session->afc, path)) [missing addObject:path];
|
||||
}
|
||||
NSMutableArray<NSString *> *failures = NSMutableArray.array;
|
||||
if (!RemoveIfPresent(session->afc, linkDestination)) [failures addObject:@"relocated link"];
|
||||
if (!RemoveIfPresent(session->afc, recovered)) [failures addObject:@"recovered file"];
|
||||
if (!RemoveGeneratedTree(session->afc, source, 0)) [failures addObject:@"StreamingZip tree"];
|
||||
NSDictionary *booksRestore = RestoreBooksState(session->afc, snapshotRoot);
|
||||
if (![booksRestore[@"ok"] boolValue]) [failures addObject:@"Books preimage"];
|
||||
BOOL cleanupComplete = failures.count == 0;
|
||||
// A missing source is already an invalidated cache entry. Report success
|
||||
// when cleanup and Books restoration succeed, while exposing how many
|
||||
// entries were actually moved for diagnostics.
|
||||
return @{ @"ok": @(cleanupComplete),
|
||||
@"safeArguments": @YES,
|
||||
@"movedCount": @(expectedCount - missing.count),
|
||||
@"alreadyAbsentCount": @(missing.count),
|
||||
@"allTargetsMoved": @(missing.count == 0),
|
||||
@"missing": missing,
|
||||
@"cleanupComplete": @(cleanupComplete),
|
||||
@"failures": failures,
|
||||
@"booksRestore": booksRestore };
|
||||
}
|
||||
|
||||
int main(int argc, const char *argv[]) {
|
||||
@autoreleasepool {
|
||||
signal(SIGPIPE, SIG_IGN);
|
||||
@@ -1047,6 +1084,14 @@ int main(int argc, const char *argv[]) {
|
||||
[NSString stringWithUTF8String:argv[5]],
|
||||
[NSString stringWithUTF8String:argv[6]],
|
||||
]);
|
||||
} else if ([command isEqual:@"finish-moved-removal"] && argc == 8) {
|
||||
operation = FinishMovedRemoval(&session, @[
|
||||
[NSString stringWithUTF8String:argv[3]],
|
||||
[NSString stringWithUTF8String:argv[4]],
|
||||
[NSString stringWithUTF8String:argv[5]],
|
||||
[NSString stringWithUTF8String:argv[6]],
|
||||
[NSString stringWithUTF8String:argv[7]],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+14
-9
@@ -45,6 +45,7 @@ from apply_card_skin import (
|
||||
operation_ok,
|
||||
write_file,
|
||||
write_files_batch,
|
||||
remove_files,
|
||||
build_archive_multi,
|
||||
ROOT,
|
||||
DEVICE_HELPER,
|
||||
@@ -143,7 +144,7 @@ def cmd_flash(udid: str, card_hash: str, image_path: str) -> bool:
|
||||
|
||||
pkpass_dir = f"/var/mobile/Library/Passes/Cards/{card_hash}.pkpass"
|
||||
|
||||
total_steps = len(asset_payloads) + (len(CACHE_FILES) * 2) + 1
|
||||
total_steps = 4
|
||||
step = 0
|
||||
all_ok = True
|
||||
|
||||
@@ -172,8 +173,8 @@ def cmd_flash(udid: str, card_hash: str, image_path: str) -> bool:
|
||||
if not ok_single:
|
||||
all_ok = False
|
||||
|
||||
# Clear cache with batch
|
||||
cache_leaves = [(leaf, b"corrupted") for leaf in CACHE_FILES]
|
||||
# Wallet v2: genuinely unlink rendered faces. Writing corrupt bytes here can
|
||||
# leave the previous artwork resident indefinitely on iOS 27.
|
||||
for ext in [".cache", ".pkcache"]:
|
||||
cache_dir = f"/var/mobile/Library/Passes/Cards/{card_hash}{ext}"
|
||||
step += 1
|
||||
@@ -186,15 +187,19 @@ def cmd_flash(udid: str, card_hash: str, image_path: str) -> bool:
|
||||
}))
|
||||
sys.stdout.flush()
|
||||
try:
|
||||
ok_cache = write_files_batch(udid, cache_dir, cache_leaves)
|
||||
ok_cache = remove_files(udid, cache_dir, list(CACHE_FILES))
|
||||
except Exception:
|
||||
ok_cache = False
|
||||
if not ok_cache:
|
||||
for leaf, payload in cache_leaves:
|
||||
try:
|
||||
write_file(udid, cache_dir, leaf, payload)
|
||||
except Exception:
|
||||
pass
|
||||
all_ok = False
|
||||
print(json.dumps({
|
||||
"type": "error",
|
||||
"card": card_hash,
|
||||
"step": step,
|
||||
"total": total_steps,
|
||||
"message": f"Could not clear Wallet cache ({ext}); card was not reported as updated."
|
||||
}))
|
||||
sys.stdout.flush()
|
||||
|
||||
step += 1
|
||||
if not all_ok:
|
||||
|
||||
+83
-11
@@ -344,22 +344,94 @@ def write_files_batch(
|
||||
return False
|
||||
|
||||
|
||||
def remove_files(udid: str, target: str, leaves: list[str], retries: int = 3) -> bool:
|
||||
"""Remove specific files through the relocated Airlift symlink.
|
||||
|
||||
Wallet only rebuilds its rendered card faces when the old cache entries are
|
||||
absent. Overwriting them with arbitrary bytes leaves stale artwork active on
|
||||
recent iOS releases, so cache invalidation must be a real unlink operation.
|
||||
"""
|
||||
if not leaves:
|
||||
return True
|
||||
if any(not leaf or "/" in leaf or leaf in {".", ".."} for leaf in leaves):
|
||||
raise ValueError("cache leaves must be plain file names")
|
||||
|
||||
for attempt in range(1, max(1, retries) + 1):
|
||||
try:
|
||||
token = secrets.token_hex(10)
|
||||
source = f"{SOURCE_PREFIX}{token}"
|
||||
link_destination = f"{LINK_PREFIX}{token}"
|
||||
recovered = f"{RECOVERED_PREFIX}{token}"
|
||||
link_identifier = f"../../{source}/p0/p1/p2/link"
|
||||
protected_identifiers = [
|
||||
f"../../{link_destination}/{leaf}" for leaf in leaves
|
||||
]
|
||||
removed_destinations = [
|
||||
f"{source}/removed-{index}" for index in range(len(leaves))
|
||||
]
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="airlift-remove-") as temporary:
|
||||
work = Path(temporary)
|
||||
archive_path = work / "payload.zip"
|
||||
books_path = work / "Books.plist"
|
||||
snapshot_root = work / "books-snapshot"
|
||||
snapshot_root.mkdir()
|
||||
|
||||
# Relocate the symlink first, then have AirTraffic move each
|
||||
# protected cache file out through it. This is a real unlink;
|
||||
# AFCRemovePath cannot traverse the protected link on iOS 27.
|
||||
archive_path.write_bytes(build_archive(target, b"aircard-v2"))
|
||||
books_path.write_bytes(build_books(
|
||||
[link_identifier, *protected_identifiers]
|
||||
))
|
||||
|
||||
snapshot = native("snapshot-books", udid, os.fspath(snapshot_root))
|
||||
if not operation_ok(snapshot):
|
||||
raise RuntimeError("could not snapshot Books state")
|
||||
stage = native(
|
||||
"stage", udid, source, link_destination, recovered,
|
||||
os.fspath(archive_path), os.fspath(books_path),
|
||||
os.fspath(snapshot_root),
|
||||
)
|
||||
if not operation_ok(stage):
|
||||
raise RuntimeError("could not stage cache removal")
|
||||
|
||||
atc = run_json(
|
||||
[os.fspath(AIRTRAFFIC_HOST), udid,
|
||||
link_identifier, link_destination,
|
||||
*[part for pair in zip(protected_identifiers, removed_destinations)
|
||||
for part in pair]],
|
||||
timeout=120,
|
||||
)
|
||||
if atc.get("exitCode") != 0 or not atc.get("ok"):
|
||||
native("finish-write", udid, source, link_destination,
|
||||
recovered, os.fspath(snapshot_root))
|
||||
raise RuntimeError("could not relocate cache link")
|
||||
|
||||
finish = native(
|
||||
"finish-moved-removal", udid, source, link_destination,
|
||||
recovered, os.fspath(snapshot_root), str(len(leaves)),
|
||||
)
|
||||
if operation_ok(finish):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
if attempt < retries:
|
||||
time.sleep(0.4 * attempt)
|
||||
return False
|
||||
|
||||
|
||||
def invalidate_cache(udid: str, card_hash: str) -> bool:
|
||||
"""Invalidates card image cache by corrupting cache leaves in .cache and .pkcache."""
|
||||
any_ok = False
|
||||
cache_leaves = [("FrontFace", b"corrupted"), ("PlaceHolder", b"corrupted"), ("Preview", b"corrupted")]
|
||||
"""Remove every rendered card face so Wallet must rebuild from the pass."""
|
||||
all_ok = True
|
||||
cache_leaves = ["FrontFace", "PlaceHolder", "Preview"]
|
||||
for ext in [".cache", ".pkcache"]:
|
||||
cache_dir = f"/var/mobile/Library/Passes/Cards/{card_hash}{ext}"
|
||||
try:
|
||||
if write_files_batch(udid, cache_dir, cache_leaves):
|
||||
any_ok = True
|
||||
else:
|
||||
for leaf, payload in cache_leaves:
|
||||
if write_file(udid, cache_dir, leaf, payload):
|
||||
any_ok = True
|
||||
all_ok = remove_files(udid, cache_dir, cache_leaves) and all_ok
|
||||
except Exception:
|
||||
pass
|
||||
return any_ok
|
||||
all_ok = False
|
||||
return all_ok
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
@@ -9,6 +9,7 @@ from pathlib import Path
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import aircard_backend
|
||||
import apply_card_skin
|
||||
|
||||
|
||||
PNG_1X1 = base64.b64decode(
|
||||
@@ -17,14 +18,37 @@ PNG_1X1 = base64.b64decode(
|
||||
|
||||
|
||||
class CardFlashTests(unittest.TestCase):
|
||||
def test_flash_writes_pdf_and_invalidates_placeholder(self) -> None:
|
||||
def test_cache_removal_moves_link_and_required_companion_payload(self) -> None:
|
||||
successful = {
|
||||
"exitCode": 0,
|
||||
"targetGatePassed": True,
|
||||
"operation": {"ok": True},
|
||||
}
|
||||
with (
|
||||
patch.object(apply_card_skin, "native", return_value=successful),
|
||||
patch.object(apply_card_skin, "run_json", return_value={"exitCode": 0, "ok": True}) as transfer,
|
||||
):
|
||||
result = apply_card_skin.remove_files(
|
||||
"device", "/protected/card.cache", ["FrontFace"], retries=1
|
||||
)
|
||||
|
||||
self.assertTrue(result)
|
||||
command = transfer.call_args.args[0]
|
||||
self.assertEqual(len(command), 6)
|
||||
self.assertIn("/airlift-link-", command[4])
|
||||
self.assertTrue(command[5].endswith("/removed-0"))
|
||||
|
||||
def test_flash_writes_pdf_and_removes_rendered_cache(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
image_path = Path(temporary) / "card.png"
|
||||
image_path.write_bytes(PNG_1X1)
|
||||
write_file = Mock(return_value=True)
|
||||
remove_files = Mock(return_value=True)
|
||||
|
||||
with (
|
||||
patch.object(aircard_backend, "write_file", write_file),
|
||||
patch.object(aircard_backend, "write_files_batch", Mock(return_value=False)),
|
||||
patch.object(aircard_backend, "remove_files", remove_files),
|
||||
redirect_stdout(io.StringIO()),
|
||||
):
|
||||
result = aircard_backend.cmd_flash("device", "card", str(image_path))
|
||||
@@ -47,13 +71,24 @@ class CardFlashTests(unittest.TestCase):
|
||||
)
|
||||
self.assertTrue(pass_assets["cardBackgroundCombined.pdf"].startswith(b"%PDF-"))
|
||||
|
||||
cache_entries = {(target, leaf) for _, target, leaf, _ in writes}
|
||||
removals = [call.args for call in remove_files.call_args_list]
|
||||
for extension in (".cache", ".pkcache"):
|
||||
for leaf in aircard_backend.CACHE_FILES:
|
||||
self.assertIn(
|
||||
(f"/var/mobile/Library/Passes/Cards/card{extension}", leaf),
|
||||
cache_entries,
|
||||
)
|
||||
self.assertIn(("device", f"/var/mobile/Library/Passes/Cards/card{extension}", list(aircard_backend.CACHE_FILES)), removals)
|
||||
|
||||
def test_flash_fails_when_wallet_cache_cannot_be_removed(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
image_path = Path(temporary) / "card.png"
|
||||
image_path.write_bytes(PNG_1X1)
|
||||
output = io.StringIO()
|
||||
with (
|
||||
patch.object(aircard_backend, "write_files_batch", return_value=True),
|
||||
patch.object(aircard_backend, "remove_files", side_effect=[True, False]),
|
||||
redirect_stdout(output),
|
||||
):
|
||||
result = aircard_backend.cmd_flash("device", "card", str(image_path))
|
||||
messages = [json.loads(line) for line in output.getvalue().splitlines()]
|
||||
self.assertFalse(result)
|
||||
self.assertEqual(messages[-1]["type"], "error")
|
||||
|
||||
def test_flash_reports_failure_when_an_asset_write_fails(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
|
||||
Reference in new issue
Block a user