@androperator/emulator-macos-tweaks 0.0.0-stage → 1.0.0

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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Action Launcher Pty Ltd
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE.md ADDED
@@ -0,0 +1,12 @@
1
+ # Artwork and third-party notices
2
+
3
+ The Android robot is reproduced or modified from work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License.
4
+
5
+ - Original robot: Google, https://developer.android.com/distribute/marketing-tools/brand-guidelines
6
+ - License: https://creativecommons.org/licenses/by/3.0/
7
+ - Modifications: a partial Android robot inside a newly drawn blue phone frame, on a white background rendered with Apple's macOS icon mask, lighting and shadows. PNGs are palette-compressed to fit existing image allocations.
8
+ - The device-frame vector code is licensed under Apache 2.0. Android robot portions and their derivatives remain subject to CC BY 3.0 attribution; they are not relicensed by the code license.
9
+
10
+ Android is a trademark of Google LLC. Google retains trademark rights in the robot. Apple, macOS, Icon Composer, and Xcode are trademarks of Apple Inc. This independent project claims no affiliation or endorsement.
11
+
12
+ The package includes no Android Emulator executables, Apple design templates, or Apple software. The editable icon contains this project's artwork and Icon Composer document settings. The PNGs are output rendered from that artwork with Xcode.
package/README.md CHANGED
@@ -1,3 +1,113 @@
1
- # Temporary Holding Version
1
+ # @androperator/emulator-macos-tweaks
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A completely and utterly unessential utility that makes Android™ emulators feel more at home on macOS. Give your phone, tablet, TV, watch and automotive emulators distinct icons that fit in with the rest of your apps, with safe backups and an easy way to undo the changes.
4
+
5
+ **With `androperator-emulator-tweaks`:**
6
+
7
+ ![With androperator-emulator-tweaks: distinct tablet, phone and watch icons, with Pixel_9 selected](docs/images/emulator-app-switcher-after.png)
8
+
9
+ **Without `androperator-emulator-tweaks`:**
10
+
11
+ ![Without androperator-emulator-tweaks: three identical circular emulator icons, with qemu-system-aarch64 selected](docs/images/emulator-app-switcher-before.png)
12
+
13
+ Per-device icons are supported by the CLI. The `Pixel_9` label in the screenshot uses the [experimental AVD naming launcher](experimental/README.md); ordinary CLI-patched launches keep their executable label.
14
+
15
+ This is an independent CLI. It does not depend on ADBuddy or change emulator launch arguments, virtual devices, headless emulators, or Android Studio itself.
16
+
17
+ ## Requirements and supported builds
18
+
19
+ - macOS 14 or newer and Node.js 22 or newer.
20
+ - Write access to your Android SDK and backup location; do not run with sudo.
21
+ - Android Emulator **37.1.11, build 15917651, Apple Silicon GUI binary**.
22
+ - Executable SHA-256: `eaa97a970b81f81640db73ed79e19ee173323653a0a1203217e1199d078011f3`.
23
+
24
+ This first release intentionally supports one verified binary. Intel and other emulator builds are reported as unsupported and refused. Matching the version number alone is insufficient: the entire original executable and its embedded icon images must match the support profile.
25
+
26
+ Patching replaces Google's signature with a **local ad-hoc signature**, preserving the original entitlements and hardened runtime. The modified emulator is no longer Google-signed or notarized. No developer certificate or private key is used. Gatekeeper may treat the patched emulator differently. The CLI does not disable Gatekeeper or change system security settings.
27
+
28
+ Automatic icons use a bundled arm64 AppKit helper loaded by a verified weak dependency added to the supported GUI executable. No Xcode, background service or launch wrapper is needed for CLI users. The helper selects artwork from the AVD metadata separately for each process and keeps it through Qt icon updates.
29
+
30
+ Every `apply` invocation requires `--accept-adhoc-signing` to acknowledge this tradeoff, including repeated calls and reapplying a saved patch. Without it, the CLI explains the change and exits before SDK discovery or file modification. `status` and `restore` do not require the flag. Restore reinstates the exact original executable and Google’s original signature.
31
+
32
+ ## Install and use
33
+
34
+ Once published:
35
+
36
+ ```sh
37
+ npm install -g @androperator/emulator-macos-tweaks
38
+ androperator-emulator-tweaks status
39
+ androperator-emulator-tweaks apply --accept-adhoc-signing
40
+ androperator-emulator-tweaks restore
41
+ ```
42
+
43
+ For a local checkout before publication:
44
+
45
+ ```sh
46
+ npm test
47
+ node bin/androperator-emulator-tweaks.js status
48
+ node bin/androperator-emulator-tweaks.js apply --accept-adhoc-signing
49
+ node bin/androperator-emulator-tweaks.js restore
50
+ ```
51
+
52
+ SDK discovery checks `--sdk`, then `ANDROID_HOME`, `ANDROID_SDK_ROOT`, and `~/Library/Android/sdk`. Automatic discovery selects the first existing SDK; an explicit `--sdk` never falls back to another SDK.
53
+
54
+ ```sh
55
+ androperator-emulator-tweaks apply --accept-adhoc-signing --sdk "$HOME/Library/Android/sdk"
56
+ androperator-emulator-tweaks status --json
57
+ # Optional fixed phone artwork instead of automatic device selection:
58
+ androperator-emulator-tweaks apply --accept-adhoc-signing --icons phone
59
+ ```
60
+
61
+ Restart your emulator after applying or restoring. Existing running processes keep their current icon. Future standalone launches through Android Studio, the terminal, or other apps use the patched executable in that SDK. The artwork uses Apple's macOS 27 icon shape and lighting; it does not dynamically switch Liquid Glass appearances. Automatic selection reads initial AVD configuration, not live rotation or folding. Wear, TV and automotive tags take precedence; known tablet profiles or a configured minimum width of 600 density-independent pixels select tablet. Foldable profiles remain phone. Unknown or missing metadata falls back to phone. AVD metadata follows Android environment roots and custom `.ini` pointers; `-datadir` does not replace the named AVD's metadata. Android Studio embedded mode has not been validated.
62
+
63
+ ## Backups and restoration
64
+
65
+ Backups live in `~/Library/Application Support/emulator-icon-macos/backups`. This existing directory name is retained across the rename so earlier backups remain usable. The CLI prints the specific backup directory. Each SDK executable has its own directory, with separate records for each original executable hash and automatic runtime generation. Each record contains the untouched original executable, signed patched executable, original entitlements, the automatic runtime where applicable, and a receipt with hashes and image locations. No emulator binaries are distributed in the npm package.
66
+
67
+ Automatic backups contain the exact helper and five artwork files used by that generation. Their hashes are checked before apply or reapply; `status` reports the selected icon mode and runtime health. The executable uses an absolute helper path within that backup. Keep the backup at its original location while the patch is installed. Removing the helper allows startup through its weak dependency, with the fixed phone artwork as fallback; a corrupt helper may prevent startup. `restore` remains available when runtime files are missing or corrupt.
68
+
69
+ `restore` verifies both the current patch and the original backup before atomically replacing the executable. Repeated apply or restore commands are safe. Restore removes the loading hook by reinstating the exact original executable; retained backups include the runtime for reapplication and processes that are still running. Runtime upgrades create a new generation without overwriting earlier backups. Applying automatic icons over a CLI-managed phone patch preserves that patch and builds from its verified original. `--icons phone` can switch back to the earlier fixed-icon behavior. SDK updates may remove the patch: the tool keeps the old backup and refuses to restore it over an updated binary. You can apply again only once that new build is supported.
70
+
71
+ You may choose a backup location with `--backup-dir PATH`. Use the same location for status, apply, and restore. Moving or deleting backups prevents automatic restoration. Treat the receipt and backup files as part of the backup, not disposable cache files.
72
+
73
+ The SDK directory lock prevents overlapping mutations, even with different backup directories. Its existing `.emulator-icon-macos.lock` name is retained so old and renamed CLI copies share the same lock. If a process is forcibly killed, it may leave `.emulator-icon-macos.lock` beside the executable. Check `owner.json` and confirm the process is no longer running before removing that specific lock directory. There is no automatic stale-lock deletion.
74
+
75
+ An interrupted run after signing has a prepared receipt and can recover on the next apply or restore. Earlier failures leave a `.prepare-*` folder in the backup directory for inspection; it is not used as a completed backup. Never delete backups until you have verified the SDK is restored or replaced by an SDK update.
76
+
77
+ ### Migrating the earlier local prototype
78
+
79
+ If you installed the prototype from a previous experiment, first run its own restore command. The CLI refuses to adopt an unrecognized pre-existing patch, even if it looks identical. Then run this CLI's `apply --accept-adhoc-signing` to create a managed backup.
80
+
81
+ ## Experimental AVD names
82
+
83
+ [Experimental tooling](experimental/README.md) provides optional per-AVD named
84
+ preview launchers in temporary SDK copies. Naming is excluded from the npm
85
+ package and has not been integrated with ordinary installed-SDK launches.
86
+ The main CLI changes icons only; it does not rename Dock entries.
87
+
88
+ ## Development and release
89
+
90
+ ```sh
91
+ npm test
92
+ npm pack --dry-run
93
+ # Developers with Xcode and a graphical macOS session:
94
+ node scripts/verify-icons.mjs
95
+ ```
96
+
97
+ Tests use synthetic executables and fake process integrations. They require neither an Android SDK nor a device. macOS CI runs on Node.js 22 and 24. Real signing and boot checks supplement these tests for the supported build.
98
+
99
+ To add support for a build, use an untouched, signature-verified vendor executable. Record its revision, build ID, architecture, full SHA-256, and each original PNG hash and allocation length in `src/profiles.json`. The patcher discovers images by content rather than fixed offsets. Provide replacement PNGs that fit those allocations exactly, with valid chunks and checksums. Verify signing, boot, Dock appearance, and exact restore on that build before adding it to the support table. Do not loosen hash checks to accept a new build.
100
+
101
+ The editable `assets/Emulator.icon` source uses a vector phone/Android symbol, white background, and Apple's native icon renderer. The bundled 32, 128 and 256 pixel PNGs were compiled with Xcode's asset compiler and palette-compressed to fit the emulator's allocations. Xcode is not required by CLI users. Native helper source is in `native/`; `node scripts/build-runtime.mjs` rebuilds the packaged arm64 helper and all five icons and writes their content manifest. Rebuild and run native verification after changing those sources; review the regenerated manifest and runtime files together.
102
+
103
+ Before publishing, run the tests and inspect the package contents, update the version and release notes, and publish explicitly with `npm publish --access public`. This repository has no automatic publishing workflow.
104
+
105
+ ## License and attribution
106
+
107
+ Code is licensed under [Apache 2.0](LICENSE). See [LICENSE](LICENSE) and [NOTICE.md](NOTICE.md) for artwork attribution and third-party notices.
108
+
109
+ Android is a trademark of Google LLC. This project is not affiliated with or endorsed by Google or Apple.
110
+
111
+ Written by clankers. Engineered by [@chrismlacy](https://x.com/chrismlacy).
112
+
113
+ Copyright (C) 2026 Action Launcher Pty Ltd
package/assets/128.png ADDED
Binary file
package/assets/256.png ADDED
Binary file
package/assets/32.png ADDED
Binary file
@@ -0,0 +1,11 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 256 256">
2
+ <defs><clipPath id="screen"><rect x="92" y="63" width="72" height="130"/></clipPath></defs>
3
+ <g transform="translate(128 128) scale(1.15) translate(-128 -128)">
4
+ <g clip-path="url(#screen)">
5
+ <path fill="#35D780" d="M92 76 C119 79 140 101 140 128 C140 155 119 178 92 180 Z"/>
6
+ <path stroke="#35D780" stroke-width="3" stroke-linecap="round" d="M132 99 L149 88 M132 154 L149 165"/>
7
+ <circle cx="111" cy="104" r="4.5" fill="white"/><circle cx="111" cy="152" r="4.5" fill="white"/>
8
+ </g>
9
+ <path fill="#4083F7" fill-rule="evenodd" d="M93 48 H163 Q179 48 179 64 V192 Q179 208 163 208 H93 Q77 208 77 192 V64 Q77 48 93 48 Z M92 63 V193 H164 V63 Z"/>
10
+ </g>
11
+ </svg>
@@ -0,0 +1,28 @@
1
+ {
2
+ "fill": {
3
+ "solid": "extended-srgb:1.00000,1.00000,1.00000,1.00000"
4
+ },
5
+ "groups": [
6
+ {
7
+ "layers": [
8
+ {
9
+ "image-name": "emulator-symbol.svg",
10
+ "name": "emulator-symbol"
11
+ }
12
+ ],
13
+ "shadow": {
14
+ "kind": "neutral",
15
+ "opacity": 0.5
16
+ },
17
+ "translucency": {
18
+ "enabled": true,
19
+ "value": 0.3
20
+ }
21
+ }
22
+ ],
23
+ "supported-platforms": {
24
+ "squares": [
25
+ "macOS"
26
+ ]
27
+ }
28
+ }
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,12 @@
1
+ {
2
+ "schema": 1,
3
+ "architecture": "arm64",
4
+ "files": {
5
+ "helper.dylib": "6fe880bcb1767cca55695f72503c21427cdbb74280a6dc676ab28b71e35da95a",
6
+ "icons/phone.png": "968f9a96e5d01f5872d1b9255ed35bebe43f5236bf9c4b8e9c95e5d247318941",
7
+ "icons/tablet.png": "eb74a4cd3ba55b73bc45e5a83157c16779386d37cae4a10ff008342598fdaecd",
8
+ "icons/tv.png": "398ae5320e27803f24a3c73d4e9def98a0fafa71943e378e6f0a2d999545e6df",
9
+ "icons/watch.png": "5177c315a89b27901c36f5d061dc4d488cea7499e23390e39cd493f52446ae13",
10
+ "icons/automotive.png": "9bd6574c7aa8863b490941cc649fc2e0ffba213ec6954d644f65fbc9b8bcf5ac"
11
+ }
12
+ }
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from 'node:util';
3
+ import { apply, restore, inspect } from '../src/core.js';
4
+ const help = `Usage: androperator-emulator-tweaks <status|apply|restore> [--accept-adhoc-signing] [--icons auto|phone] [--sdk PATH] [--backup-dir PATH] [--json]
5
+
6
+ status Detect the SDK, version, executable support and backup state.
7
+ apply Install automatic per-device icons; requires --accept-adhoc-signing.
8
+ restore Restore the exact original executable if the current patch matches.
9
+
10
+ SDK discovery: --sdk, ANDROID_HOME, ANDROID_SDK_ROOT, ~/Library/Android/sdk.
11
+ Backups: ~/Library/Application Support/emulator-icon-macos/backups.
12
+ Patching replaces Google's signature with a local ad-hoc signature while retaining
13
+ its entitlements and hardened runtime. No developer certificate or private key is
14
+ used. Gatekeeper may treat the patched emulator differently. Restore reinstates
15
+ the original executable and Google's signature.
16
+ Example: androperator-emulator-tweaks apply --accept-adhoc-signing
17
+ Icons: auto (default) selects phone, tablet, TV, watch or automotive from AVD metadata.
18
+ Use --icons phone with apply for the fixed phone icon. AVD names remain experimental.
19
+ Restart emulators after apply or restore.
20
+ SDK updates may remove the patch; unsupported builds are never modified.`;
21
+ try {
22
+ const { values, positionals } = parseArgs({ allowPositionals: true, options: {
23
+ 'accept-adhoc-signing': { type: 'boolean' }, icons: { type: 'string' }, sdk: { type: 'string' }, 'backup-dir': { type: 'string' }, json: { type: 'boolean' }, help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' }
24
+ }});
25
+ if (values.help || !positionals.length && !values.version) console.log(help);
26
+ else if (values.version) console.log('1.0.0');
27
+ else {
28
+ if (positionals.length !== 1 || !['status', 'apply', 'restore'].includes(positionals[0])) throw new Error('Expected status, apply, or restore. Use --help.');
29
+ const command = positionals[0];
30
+ if (values.icons && (command !== 'apply' || !['auto', 'phone'].includes(values.icons))) throw new Error('--icons auto|phone is only valid with apply');
31
+ if (command === 'apply' && !values['accept-adhoc-signing']) {
32
+ throw new Error("apply requires --accept-adhoc-signing. Applying this patch replaces Google's signature with a local ad-hoc signature while preserving its entitlements and hardened runtime. No developer certificate or private key is used. Gatekeeper may treat the patched emulator differently. Restore reinstates the original executable and Google's signature. No files changed.\nRun: androperator-emulator-tweaks apply --accept-adhoc-signing");
33
+ }
34
+ const result = await ({ status: inspect, apply, restore }[command])({ sdk: values.sdk, backupDir: values['backup-dir'], icons: values.icons });
35
+ const output = { command, icons: result.icons, runtimeHealthy: result.runtimeHealthy, sdk: result.sdk, revision: result.revision, state: result.state, changed: result.changed ?? false, executable: result.target, sha256: result.targetHash, backup: result.backup ?? result.receipt?.directory ?? null };
36
+ // Refresh the reported hash after a successful mutation.
37
+ if (result.changed) output.sha256 = (await inspect({ sdk: values.sdk, backupDir: values['backup-dir'] })).targetHash;
38
+ console.log(values.json ? JSON.stringify(output, null, 2) : `${result.state}${result.icons ? ` (${result.icons} icons${result.runtimeHealthy === false ? ', runtime missing or corrupt; restore remains available' : ''})` : ''}: Android Emulator ${result.revision}\n${result.target}${output.backup ? `\nBackup: ${output.backup}` : ''}${result.changed ? '\nRestart emulators to see the change.' : ''}`);
39
+ }
40
+ } catch (error) { console.error(`androperator-emulator-tweaks: ${error.message}`); process.exitCode = 1; }
package/package.json CHANGED
@@ -1,6 +1,13 @@
1
1
  {
2
2
  "name": "@androperator/emulator-macos-tweaks",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Reversible macOS tweaks for supported Android Emulator builds",
5
+ "type": "module",
6
+ "bin": { "androperator-emulator-tweaks": "bin/androperator-emulator-tweaks.js" },
7
+ "engines": { "node": ">=22" },
8
+ "os": ["darwin"],
9
+ "license": "Apache-2.0",
10
+ "publishConfig": { "access": "public" },
11
+ "files": ["bin", "src", "assets", "NOTICE.md", "LICENSE"],
12
+ "scripts": { "test": "node --test", "prepack": "npm test", "build:runtime": "node scripts/build-runtime.mjs", "verify:icons": "node scripts/verify-icons.mjs" }
13
+ }
package/src/core.js ADDED
@@ -0,0 +1,187 @@
1
+ import { readFile, writeFile, mkdir, realpath, lstat, readdir, rename, rm, open } from 'node:fs/promises';
2
+ import { resolve, join, dirname } from 'node:path';
3
+ import { homedir } from 'node:os';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { sha256, patchImages } from './png.js';
7
+ import { macOS } from './platform.js';
8
+ import { addIconHelper } from './macho.js';
9
+ import { readRuntime, copyRuntime, verifyRuntime, runtimeHash } from './runtime.js';
10
+ const packageRoot = fileURLToPath(new URL('../', import.meta.url));
11
+ const bundledProfiles = JSON.parse(await readFile(new URL('./profiles.json', import.meta.url)));
12
+ const hashFile = async file => sha256(await readFile(file));
13
+
14
+ async function atomicJSON(file, value) {
15
+ const temporary = `${file}.${randomUUID()}.tmp`;
16
+ const handle = await open(temporary, 'wx', 0o600);
17
+ try { await handle.writeFile(JSON.stringify(value, null, 2) + '\n'); await handle.sync(); }
18
+ finally { await handle.close(); }
19
+ await rename(temporary, file);
20
+ }
21
+
22
+ export async function discoverSDK(explicit, environment = process.env, home = homedir()) {
23
+ const candidates = explicit ? [explicit] : [environment.ANDROID_HOME, environment.ANDROID_SDK_ROOT, join(home, 'Library/Android/sdk')].filter(Boolean);
24
+ for (const candidate of candidates) {
25
+ try {
26
+ const sdk = await realpath(resolve(candidate));
27
+ if ((await lstat(join(sdk, 'emulator/source.properties'))).isFile()) return sdk;
28
+ } catch (error) {
29
+ if (!['ENOENT', 'ENOTDIR'].includes(error.code)) throw error;
30
+ }
31
+ }
32
+ throw new Error('Android SDK not found. Pass --sdk /path/to/sdk.');
33
+ }
34
+
35
+ export async function inspect({ sdk: explicit, backupDir, profiles = bundledProfiles, adapter = macOS } = {}) {
36
+ const sdk = await discoverSDK(explicit);
37
+ const properties = await readFile(join(sdk, 'emulator/source.properties'), 'utf8');
38
+ const revision = properties.match(/^Pkg\.Revision\s*=\s*(\S+)\s*$/m)?.[1];
39
+ const supportedProfile = profiles.find(profile => profile.revision === revision);
40
+ // Inspect only known GUI binary paths. Do not execute unknown emulator builds.
41
+ let entry = join(sdk, 'emulator', supportedProfile?.binary ?? 'qemu/darwin-aarch64/qemu-system-aarch64');
42
+ let info;
43
+ try { info = await lstat(entry); }
44
+ catch (error) {
45
+ if (error.code !== 'ENOENT') throw error;
46
+ entry = join(sdk, 'emulator/qemu/darwin-x86_64/qemu-system-x86_64');
47
+ info = await lstat(entry);
48
+ }
49
+ if (!info.isFile() || info.isSymbolicLink()) throw new Error('Emulator executable must be a regular file, not a symlink');
50
+ const target = await realpath(entry);
51
+ if (!target.startsWith(`${sdk}/emulator/`)) throw new Error('Emulator executable resolves outside the SDK');
52
+ const targetHash = await hashFile(target);
53
+ const storage = resolve(backupDir ?? join(homedir(), 'Library/Application Support/emulator-icon-macos/backups'));
54
+ const targetId = sha256(Buffer.from(target));
55
+ const folder = join(storage, targetId);
56
+ let receipts = [];
57
+ try {
58
+ for (const name of await readdir(folder)) {
59
+ if (!/^[a-f0-9]{64}(?:-automatic-[a-f0-9]{64})?$/.test(name)) continue;
60
+ const receiptPath = join(folder, name, 'receipt.json');
61
+ try {
62
+ if (!(await lstat(receiptPath)).isFile()) throw new Error('Invalid backup receipt');
63
+ const receipt = JSON.parse(await readFile(receiptPath, 'utf8'));
64
+ if (![1, 2].includes(receipt.schema) || receipt.target !== target || receipt.originalHash !== name.slice(0, 64) || !/^[a-f0-9]{64}$/.test(receipt.patchedHash ?? '') || !['prepared','applied','restored'].includes(receipt.state)) throw new Error('Invalid backup receipt');
65
+ if (receipt.schema === 1 && name !== receipt.originalHash) throw new Error('Invalid legacy backup directory');
66
+ if (receipt.schema === 2 && (receipt.icons !== 'auto' || name !== `${receipt.originalHash}-automatic-${runtimeHash(receipt.runtime)}`)) throw new Error('Invalid automatic backup directory');
67
+ receipts.push({ ...receipt, directory: join(folder, name) });
68
+ } catch (error) {
69
+ throw new Error(`Cannot read backup receipt ${receiptPath}: ${error.message}`);
70
+ }
71
+ }
72
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
73
+ const receipt = receipts.find(record => record.patchedHash === targetHash) ?? receipts.find(record => record.originalHash === targetHash);
74
+ const profile = profiles.find(item => item.revision === revision && item.sha256 === targetHash);
75
+ const state = receipt?.patchedHash === targetHash ? 'patched' : profile ? 'original' : 'unsupported';
76
+ let runtimeHealthy = null;
77
+ if (receipt?.schema === 2 && state === 'patched') {
78
+ try { await verifyRuntime(join(receipt.directory, 'runtime'), receipt.runtime); runtimeHealthy = true; }
79
+ catch { runtimeHealthy = false; }
80
+ }
81
+ const icons = state === 'patched' ? (receipt.schema === 2 ? 'auto' : 'phone') : null;
82
+ return { icons, runtimeHealthy, sdk, revision, target, targetHash, storage, folder, targetId, state, receipt, profile, adapter, mode: info.mode & 0o777, receipts };
83
+ }
84
+
85
+ async function withLock(context, operation) {
86
+ if (context.adapter.platform !== 'darwin') throw new Error('Apply and restore require macOS');
87
+ const lock = join(dirname(context.target), '.emulator-icon-macos.lock');
88
+ try { await mkdir(lock, { mode: 0o700 }); }
89
+ catch (error) {
90
+ if (error.code === 'EEXIST') throw new Error(`Another operation or interrupted run holds ${lock}. Inspect it before removing the lock.`);
91
+ throw error;
92
+ }
93
+ try {
94
+ await writeFile(join(lock, 'owner.json'), JSON.stringify({ pid: process.pid, started: new Date().toISOString() }));
95
+ if (await hashFile(context.target) !== context.targetHash) throw new Error('Emulator changed after inspection; no files replaced');
96
+ return await operation();
97
+ } finally { await rm(lock, { recursive: true, force: true }); }
98
+ }
99
+
100
+ async function replace(context, source, expectedHash) {
101
+ // Stage on the target filesystem and rename. Running processes retain the old inode.
102
+ const staged = join(dirname(context.target), `.emulator-icon-${randomUUID()}`);
103
+ try {
104
+ await context.adapter.copy(source, staged);
105
+ if (await hashFile(staged) !== expectedHash) throw new Error('Staged executable hash mismatch');
106
+ await context.adapter.verify(staged);
107
+ const handle = await open(staged, 'r');
108
+ try { await handle.sync(); } finally { await handle.close(); }
109
+ if (await hashFile(context.target) !== context.targetHash) throw new Error('SDK changed during operation; refusing to overwrite');
110
+ await rename(staged, context.target);
111
+ } finally { await rm(staged, { force: true }); }
112
+ }
113
+
114
+ export async function apply(options = {}) {
115
+ const icons = options.icons ?? 'auto';
116
+ if (!['auto', 'phone'].includes(icons)) throw new Error('Expected --icons auto or phone');
117
+ const context = await inspect(options);
118
+ const runtimeDirectory = options.runtimeDir ?? join(packageRoot, 'assets/runtime');
119
+ const originalHash = context.state === 'patched' ? context.receipt.originalHash : context.targetHash;
120
+ const profile = (options.profiles ?? bundledProfiles).find(item => item.revision === context.revision && item.sha256 === originalHash);
121
+ if (!profile) throw new Error(`Unsupported emulator ${context.revision ?? 'version'} (${context.targetHash}). No files changed. See supported builds in README.`);
122
+ const bundle = icons === 'auto' ? await readRuntime(runtimeDirectory, context.adapter) : null;
123
+ const directory = join(context.folder, icons === 'auto' ? `${originalHash}-automatic-${bundle.hash}` : originalHash);
124
+ return withLock(context, async () => {
125
+ await context.adapter.verify(context.target);
126
+ const existing = context.receipts.find(record => record.directory === directory);
127
+ if (existing) {
128
+ if (await hashFile(join(directory, 'original')) !== originalHash) throw new Error('Original backup is corrupt; refusing to replace it');
129
+ if (await hashFile(join(directory, 'patched')) !== existing.patchedHash) throw new Error('Patched backup is corrupt');
130
+ if (existing.schema === 2) {
131
+ await verifyRuntime(join(directory, 'runtime'), existing.runtime);
132
+ await context.adapter.verify(join(directory, 'runtime/helper.dylib'));
133
+ }
134
+ if (context.targetHash === existing.patchedHash) return { ...context, changed: false };
135
+ await replace(context, join(directory, 'patched'), existing.patchedHash);
136
+ await atomicJSON(join(directory, 'receipt.json'), { ...existing, directory: undefined, state: 'applied' });
137
+ return { ...context, state: 'patched', icons, runtimeHealthy: bundle ? true : null, changed: true, backup: directory };
138
+ }
139
+ // Always derive a new patch from the verified original, including legacy upgrades.
140
+ const originalSource = context.state === 'patched' ? join(context.receipt.directory, 'original') : context.target;
141
+ if (await hashFile(originalSource) !== originalHash) throw new Error('Original backup is corrupt');
142
+ await context.adapter.verify(originalSource);
143
+ const original = await readFile(originalSource);
144
+ const replacements = new Map();
145
+ for (const slot of profile.slots) replacements.set(slot.size, await readFile(join(options.assetsDir ?? join(packageRoot, 'assets'), `${slot.size}.png`)));
146
+ const { patched, slots } = patchImages(original, profile, replacements);
147
+ await mkdir(context.folder, { recursive: true, mode: 0o700 });
148
+ const preparation = join(context.folder, `.prepare-${randomUUID()}`);
149
+ await mkdir(preparation, { mode: 0o700 });
150
+ const backup = join(preparation, 'original');
151
+ const candidate = join(preparation, 'patched');
152
+ await context.adapter.copy(originalSource, backup);
153
+ if (await hashFile(backup) !== originalHash) throw new Error('Original backup hash mismatch');
154
+ await context.adapter.copy(backup, candidate);
155
+ if (bundle) await copyRuntime(runtimeDirectory, join(preparation, 'runtime'), bundle.manifest);
156
+ await writeFile(candidate, bundle ? addIconHelper(patched, join(directory, 'runtime/helper.dylib')) : patched);
157
+ await context.adapter.sign(backup, candidate, preparation);
158
+ const patchedHash = await hashFile(candidate);
159
+ const receipt = { schema: bundle ? 2 : 1, target: context.target, revision: context.revision, build: profile.build, originalHash, patchedHash, state: 'prepared', created: new Date().toISOString(), slots, ...(bundle ? { icons, runtime: bundle.manifest } : {}) };
160
+ for (const file of [backup, candidate]) {
161
+ const handle = await open(file, 'r');
162
+ try { await handle.sync(); } finally { await handle.close(); }
163
+ }
164
+ await atomicJSON(join(preparation, 'receipt.json'), receipt);
165
+ await rename(preparation, directory);
166
+ if (bundle) {
167
+ await verifyRuntime(join(directory, 'runtime'), bundle.manifest);
168
+ await context.adapter.verify(join(directory, 'runtime/helper.dylib'));
169
+ }
170
+ await replace(context, join(directory, 'patched'), patchedHash);
171
+ await atomicJSON(join(directory, 'receipt.json'), { ...receipt, state: 'applied' });
172
+ return { ...context, state: 'patched', icons, runtimeHealthy: bundle ? true : null, changed: true, backup: directory };
173
+ });
174
+ }
175
+
176
+ export async function restore(options = {}) {
177
+ const context = await inspect(options);
178
+ if (context.receipt?.originalHash === context.targetHash) return { ...context, changed: false };
179
+ if (context.state !== 'patched') throw new Error('No matching applied backup for this executable. Refusing to overwrite an SDK update or unrecognized patch.');
180
+ return withLock(context, async () => {
181
+ const backup = join(context.receipt.directory, 'original');
182
+ if (await hashFile(backup) !== context.receipt.originalHash) throw new Error('Original backup is corrupt; nothing restored');
183
+ await replace(context, backup, context.receipt.originalHash);
184
+ await atomicJSON(join(context.receipt.directory, 'receipt.json'), { ...context.receipt, directory: undefined, state: 'restored' });
185
+ return { ...context, state: 'original', icons: null, runtimeHealthy: null, changed: true, backup: context.receipt.directory };
186
+ });
187
+ }
package/src/macho.js ADDED
@@ -0,0 +1,44 @@
1
+ // Only add a weak dependency in existing, zero-filled load-command padding.
2
+ // A missing helper does not prevent the emulator from starting.
3
+ export function addIconHelper(original, libraryPath) {
4
+ if (original.length < 32 || original.readUInt32LE(0) !== 0xfeedfacf || original.readUInt32LE(4) !== 0x100000c || original.readUInt32LE(12) !== 2) throw new Error('Expected a thin arm64 Mach-O executable');
5
+ if (!libraryPath.startsWith('/') || libraryPath.includes('\0')) throw new Error('Helper library path must be absolute');
6
+ const count = original.readUInt32LE(16), commandBytes = original.readUInt32LE(20), end = 32 + commandBytes;
7
+ if (end > original.length) throw new Error('Invalid Mach-O command table');
8
+ let cursor = 32, firstData = original.length;
9
+ for (let index = 0; index < count; index++) {
10
+ if (cursor + 8 > end) throw new Error('Truncated load command');
11
+ const command = original.readUInt32LE(cursor), size = original.readUInt32LE(cursor + 4);
12
+ if (size < 8 || size % 8 || cursor + size > end) throw new Error('Invalid load command size');
13
+ if ([0xc, 0x80000018].includes(command) && size >= 24) {
14
+ const nameOffset = original.readUInt32LE(cursor + 8);
15
+ if (nameOffset < 24 || nameOffset >= size) throw new Error('Invalid library load command');
16
+ const name = original.subarray(cursor + nameOffset, cursor + size).toString('utf8').split('\0')[0];
17
+ if (name === libraryPath) throw new Error('Helper dependency is already installed');
18
+ }
19
+ if (command === 0x19) {
20
+ if (size < 72) throw new Error('Invalid segment command');
21
+ const sections = original.readUInt32LE(cursor + 64);
22
+ if (72 + sections * 80 > size) throw new Error('Invalid segment sections');
23
+ for (let section = 0; section < sections; section++) {
24
+ const offset = original.readUInt32LE(cursor + 72 + section * 80 + 48);
25
+ if (offset) firstData = Math.min(firstData, offset);
26
+ }
27
+ const fileOffset = original.readBigUInt64LE(cursor + 40);
28
+ if (fileOffset > 0n && fileOffset <= BigInt(original.length)) firstData = Math.min(firstData, Number(fileOffset));
29
+ }
30
+ cursor += size;
31
+ }
32
+ if (cursor !== end || firstData === original.length || firstData < end) throw new Error('Could not verify load-command padding');
33
+ const name = Buffer.from(libraryPath + '\0');
34
+ const size = Math.ceil((24 + name.length) / 8) * 8;
35
+ if (end + size > firstData || original.subarray(end, end + size).some(byte => byte !== 0)) throw new Error('Insufficient zero-filled load-command padding');
36
+ const patched = Buffer.from(original);
37
+ patched.writeUInt32LE(0x80000018, end); // LC_LOAD_WEAK_DYLIB
38
+ patched.writeUInt32LE(size, end + 4);
39
+ patched.writeUInt32LE(24, end + 8);
40
+ name.copy(patched, end + 24);
41
+ patched.writeUInt32LE(count + 1, 16);
42
+ patched.writeUInt32LE(commandBytes + size, 20);
43
+ return patched;
44
+ }
@@ -0,0 +1,27 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { writeFile } from 'node:fs/promises';
4
+ const execute = promisify(execFile);
5
+ export async function run(executable, args) {
6
+ try {
7
+ return await execute(executable, args, { timeout: 60000, maxBuffer: 1024 * 1024 });
8
+ } catch (error) {
9
+ throw new Error(`${executable.split('/').at(-1)} failed: ${(error.stderr || error.message).trim()}`);
10
+ }
11
+ }
12
+ export const macOS = {
13
+ platform: process.platform,
14
+ copy: (from, to) => run('/usr/bin/ditto', [from, to]),
15
+ verify: file => run('/usr/bin/codesign', ['--verify', '--strict', file]),
16
+ async sign(original, candidate, folder) {
17
+ const { stdout } = await run('/usr/bin/codesign', ['-d', '--entitlements', ':-', original]);
18
+ if (!stdout.trim().startsWith('<?xml') || !stdout.includes('<plist')) throw new Error('Could not extract original entitlements');
19
+ const entitlements = `${folder}/entitlements.plist`;
20
+ await writeFile(entitlements, stdout, { mode: 0o600 });
21
+ await run('/usr/bin/plutil', ['-lint', entitlements]);
22
+ await run('/usr/bin/codesign', ['--force', '--sign', '-', '--options', 'runtime', '--identifier', 'qemu-system-aarch64', '--entitlements', entitlements, candidate]);
23
+ const result = await run('/usr/bin/codesign', ['-d', '--entitlements', ':-', candidate]);
24
+ if (result.stdout.trim() !== stdout.trim()) throw new Error('Signing changed the original entitlements');
25
+ await macOS.verify(candidate);
26
+ }
27
+ };
package/src/png.js ADDED
@@ -0,0 +1,60 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ export const sha256 = bytes => createHash('sha256').update(bytes).digest('hex');
4
+ const signature = Buffer.from('89504e470d0a1a0a', 'hex');
5
+ function crc32(bytes) {
6
+ let crc = 0xffffffff;
7
+ for (const byte of bytes) {
8
+ crc ^= byte;
9
+ for (let bit = 0; bit < 8; bit++) crc = (crc >>> 1) ^ ((crc & 1) ? 0xedb88320 : 0);
10
+ }
11
+ return (crc ^ 0xffffffff) >>> 0;
12
+ }
13
+
14
+ export function pngLength(bytes, offset = 0, expectedSize) {
15
+ if (!bytes.subarray(offset, offset + 8).equals(signature)) throw new Error('Invalid PNG signature');
16
+ let cursor = offset + 8;
17
+ let chunks = 0;
18
+ let hasImage = false;
19
+ while (cursor + 12 <= bytes.length) {
20
+ const length = bytes.readUInt32BE(cursor);
21
+ const end = cursor + 12 + length;
22
+ if (end > bytes.length) throw new Error('Truncated PNG');
23
+ const type = bytes.toString('ascii', cursor + 4, cursor + 8);
24
+ if (crc32(bytes.subarray(cursor + 4, end - 4)) !== bytes.readUInt32BE(end - 4)) throw new Error('PNG CRC mismatch');
25
+ if (chunks++ === 0) {
26
+ if (type !== 'IHDR' || length !== 13) throw new Error('Invalid PNG header');
27
+ if (expectedSize && (bytes.readUInt32BE(cursor + 8) !== expectedSize || bytes.readUInt32BE(cursor + 12) !== expectedSize)) throw new Error('Unexpected icon dimensions');
28
+ }
29
+ if (type === 'IDAT') hasImage = true;
30
+ if (type === 'IEND') {
31
+ if (length !== 0 || !hasImage) throw new Error('Invalid PNG end');
32
+ return end - offset;
33
+ }
34
+ cursor = end;
35
+ }
36
+ throw new Error('Missing PNG end');
37
+ }
38
+
39
+ export function patchImages(original, profile, replacements) {
40
+ if (sha256(original) !== profile.sha256) throw new Error('Unsupported executable hash; no files changed');
41
+ const patched = Buffer.from(original);
42
+ const slots = [];
43
+ for (const slot of profile.slots) {
44
+ const replacement = replacements.get(slot.size);
45
+ if (!replacement || replacement.length !== slot.length || sha256(replacement) !== slot.replacementSha256 || pngLength(replacement, 0, slot.size) !== slot.length) throw new Error('Replacement artwork failed validation');
46
+ const matches = [];
47
+ for (let offset = original.indexOf(signature); offset !== -1; offset = original.indexOf(signature, offset + 8)) {
48
+ if (sha256(original.subarray(offset, offset + slot.length)) === slot.sha256) {
49
+ if (pngLength(original, offset, slot.size) !== slot.length) throw new Error('Original icon failed validation');
50
+ matches.push(offset);
51
+ }
52
+ }
53
+ if (matches.length !== 1) throw new Error(`Expected exactly one ${slot.size}px icon; found ${matches.length}`);
54
+ const offset = matches[0];
55
+ if (slots.some(other => offset < other.offset + other.length && other.offset < offset + slot.length)) throw new Error('Overlapping icon allocations');
56
+ replacement.copy(patched, offset);
57
+ slots.push({ offset, length: slot.length, size: slot.size });
58
+ }
59
+ return { patched, slots };
60
+ }
@@ -0,0 +1,29 @@
1
+ [
2
+ {
3
+ "revision": "37.1.11",
4
+ "build": "15917651",
5
+ "architecture": "arm64",
6
+ "binary": "qemu/darwin-aarch64/qemu-system-aarch64",
7
+ "sha256": "eaa97a970b81f81640db73ed79e19ee173323653a0a1203217e1199d078011f3",
8
+ "slots": [
9
+ {
10
+ "size": 32,
11
+ "length": 1265,
12
+ "sha256": "1ca1a82332cbb2a3cb0228dd12430134a92e84de1e5954d3a9a173241e81b846",
13
+ "replacementSha256": "3e76899cc4cc8fcd28b915f8d35456021a65bd6595436ebeb893298799d776bd"
14
+ },
15
+ {
16
+ "size": 128,
17
+ "length": 3761,
18
+ "sha256": "6f18ce79178f35186f0139a9299a9eefa4b1fc6bfe3d57d46cb0b58ee0d58728",
19
+ "replacementSha256": "d5b84255b773ceea097b154b7e7561269a40c8a4ecc4d12cdc2581133acfd204"
20
+ },
21
+ {
22
+ "size": 256,
23
+ "length": 7534,
24
+ "sha256": "4c3b9dbde6487e5ece1e606af8876c73365ec2ef4340926a283397cd941ee14e",
25
+ "replacementSha256": "968f9a96e5d01f5872d1b9255ed35bebe43f5236bf9c4b8e9c95e5d247318941"
26
+ }
27
+ ]
28
+ }
29
+ ]
package/src/runtime.js ADDED
@@ -0,0 +1,43 @@
1
+ import { readFile, lstat, realpath, mkdir, copyFile, open } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { sha256, pngLength } from './png.js';
4
+ export const runtimeFiles = ['helper.dylib', ...['phone', 'tablet', 'tv', 'watch', 'automotive'].map(name => `icons/${name}.png`)];
5
+ export function validateRuntimeManifest(manifest) {
6
+ if (manifest?.schema !== 1 || manifest.architecture !== 'arm64' || !manifest.files || Object.keys(manifest.files).length !== runtimeFiles.length || runtimeFiles.some(file => !/^[a-f0-9]{64}$/.test(manifest.files[file] ?? ''))) throw new Error('Invalid automatic icon runtime manifest');
7
+ }
8
+ export function runtimeHash(manifest) {
9
+ validateRuntimeManifest(manifest);
10
+ return sha256(Buffer.from(JSON.stringify(runtimeFiles.map(file => [file, manifest.files[file]]))));
11
+ }
12
+ export async function verifyRuntime(directory, manifest) {
13
+ validateRuntimeManifest(manifest);
14
+ const root = await realpath(directory);
15
+ const directoryInfo = await lstat(directory);
16
+ if (!directoryInfo.isDirectory() || directoryInfo.isSymbolicLink()) throw new Error('Automatic icon runtime must be a regular directory');
17
+ for (const file of runtimeFiles) {
18
+ const path = join(directory, file);
19
+ const info = await lstat(path);
20
+ if (!info.isFile() || info.isSymbolicLink() || !(await realpath(path)).startsWith(`${root}/`)) throw new Error(`Invalid automatic icon runtime file: ${file}`);
21
+ const bytes = await readFile(path);
22
+ if (sha256(bytes) !== manifest.files[file]) throw new Error(`Automatic icon runtime is missing or corrupt: ${file}`);
23
+ if (file.endsWith('.png')) pngLength(bytes, 0, 256);
24
+ else if (bytes.length < 32 || bytes.readUInt32LE(0) !== 0xfeedfacf || bytes.readUInt32LE(4) !== 0x100000c || bytes.readUInt32LE(12) !== 6) throw new Error('Automatic icon helper must be a thin arm64 Mach-O library');
25
+ }
26
+ }
27
+ export async function readRuntime(directory, adapter) {
28
+ const manifest = JSON.parse(await readFile(join(directory, 'manifest.json'), 'utf8'));
29
+ await verifyRuntime(directory, manifest);
30
+ await adapter.verify(join(directory, 'helper.dylib'));
31
+ return { manifest, hash: runtimeHash(manifest) };
32
+ }
33
+ export async function copyRuntime(source, destination, manifest) {
34
+ await mkdir(destination);
35
+ await mkdir(join(destination, 'icons'));
36
+ for (const file of runtimeFiles) {
37
+ const target = join(destination, file);
38
+ await copyFile(join(source, file), target);
39
+ const handle = await open(target, 'r');
40
+ try { await handle.sync(); } finally { await handle.close(); }
41
+ }
42
+ await verifyRuntime(destination, manifest);
43
+ }