-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathasar-utils.ts
More file actions
268 lines (217 loc) · 7.07 KB
/
asar-utils.ts
File metadata and controls
268 lines (217 loc) · 7.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
import { execFileSync } from 'node:child_process';
import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import * as asar from '@electron/asar';
import { minimatch } from 'minimatch';
import { d } from './debug.js';
const LIPO = 'lipo';
export enum AsarMode {
NO_ASAR,
HAS_ASAR,
}
export type MergeASARsOptions = {
x64AsarPath: string;
arm64AsarPath: string;
outputAsarPath: string;
singleArchFiles?: string;
};
// See: https://github.com/apple-opensource-mirror/llvmCore/blob/0c60489d96c87140db9a6a14c6e82b15f5e5d252/include/llvm/Object/MachOFormat.h#L108-L112
const MACHO_MAGIC = new Set([
// 32-bit Mach-O
0xfeedface, 0xcefaedfe,
// 64-bit Mach-O
0xfeedfacf, 0xcffaedfe,
]);
const MACHO_UNIVERSAL_MAGIC = new Set([
// universal
0xcafebabe, 0xbebafeca,
]);
export const detectAsarMode = async (appPath: string) => {
d('checking asar mode of', appPath);
const asarPath = path.resolve(appPath, 'Contents', 'Resources', 'app.asar');
if (!fs.existsSync(asarPath)) {
d('determined no asar');
return AsarMode.NO_ASAR;
}
d('determined has asar');
return AsarMode.HAS_ASAR;
};
export const generateAsarIntegrity = (asarPath: string) => {
return {
algorithm: 'SHA256' as const,
hash: crypto
.createHash('SHA256')
.update(asar.getRawHeader(asarPath).headerString)
.digest('hex'),
};
};
function toRelativePath(file: string): string {
return file.replace(/^\//, '');
}
function isDirectory(a: string, file: string): boolean {
return Boolean('files' in asar.statFile(a, file));
}
function checkSingleArch(archive: string, file: string, allowList?: string): void {
if (allowList === undefined || !minimatch(file, allowList, { matchBase: true })) {
throw new Error(
`Detected unique file "${file}" in "${archive}" not covered by ` +
`allowList rule: "${allowList}"`,
);
}
}
export const mergeASARs = async ({
x64AsarPath,
arm64AsarPath,
outputAsarPath,
singleArchFiles,
}: MergeASARsOptions): Promise<void> => {
d(`merging ${x64AsarPath} and ${arm64AsarPath}`);
const x64Files = new Set(asar.listPackage(x64AsarPath, { isPack: false }).map(toRelativePath));
const arm64Files = new Set(
asar.listPackage(arm64AsarPath, { isPack: false }).map(toRelativePath),
);
//
// Build set of unpacked directories and files
//
const unpackedFiles = new Set<string>();
function buildUnpacked(a: string, fileList: Set<string>): void {
for (const file of fileList) {
const stat = asar.statFile(a, file);
if (!('unpacked' in stat) || !stat.unpacked) {
continue;
}
if ('files' in stat) {
continue;
}
unpackedFiles.add(file);
}
}
buildUnpacked(x64AsarPath, x64Files);
buildUnpacked(arm64AsarPath, arm64Files);
//
// Build list of files/directories unique to each asar
//
for (const file of x64Files) {
if (!arm64Files.has(file)) {
checkSingleArch(x64AsarPath, file, singleArchFiles);
}
}
const arm64Unique = [];
for (const file of arm64Files) {
if (!x64Files.has(file)) {
checkSingleArch(arm64AsarPath, file, singleArchFiles);
arm64Unique.push(file);
}
}
//
// Find common bindings with different content
//
const commonBindings = [];
for (const file of x64Files) {
if (!arm64Files.has(file)) {
continue;
}
// Skip directories
if (isDirectory(x64AsarPath, file)) {
continue;
}
const x64Content = asar.extractFile(x64AsarPath, file);
const arm64Content = asar.extractFile(arm64AsarPath, file);
// Skip file if the same content
if (x64Content.compare(arm64Content) === 0) {
continue;
}
// Skip universal Mach-O files.
if (isUniversalMachO(x64Content)) {
continue;
}
if (!MACHO_MAGIC.has(x64Content.readUInt32LE(0))) {
throw new Error(`Can't reconcile two non-macho files ${file}`);
}
commonBindings.push(file);
}
//
// Extract both
//
const x64Dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'x64-'));
const arm64Dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'arm64-'));
try {
d(`extracting ${x64AsarPath} to ${x64Dir}`);
asar.extractAll(x64AsarPath, x64Dir);
d(`extracting ${arm64AsarPath} to ${arm64Dir}`);
asar.extractAll(arm64AsarPath, arm64Dir);
for (const file of arm64Unique) {
const source = path.resolve(arm64Dir, file);
const destination = path.resolve(x64Dir, file);
if (isDirectory(arm64AsarPath, file)) {
d(`creating unique directory: ${file}`);
await fs.promises.mkdir(destination, { recursive: true });
continue;
}
d(`copying unique file: ${file}`);
await fs.promises.mkdir(path.dirname(destination), { recursive: true });
await fs.promises.cp(source, destination, {
force: true,
recursive: true,
verbatimSymlinks: true,
});
}
for (const binding of commonBindings) {
const source = await fs.promises.realpath(path.resolve(arm64Dir, binding));
const destination = await fs.promises.realpath(path.resolve(x64Dir, binding));
d(`merging binding: ${binding}`);
execFileSync(LIPO, [source, destination, '-create', '-output', destination]);
}
d(`creating archive at ${outputAsarPath}`);
// Build a compact unpack pattern from directory prefixes instead of
// listing every file individually. When there are many unpacked files
// (e.g. auto-unpacked native modules) the old brace-expansion approach
// can exceed minimatch's 64 KiB pattern-length limit.
// See: https://github.com/electron/universal/issues/XXX
const unpackDirs = new Set<string>();
for (const file of unpackedFiles) {
const parts = file.replace(/^\//, '').split('/');
let dir: string;
if (parts[0] === 'node_modules' && parts.length > 1) {
// Handle scoped packages (e.g. @img/sharp-darwin-arm64)
dir =
parts[1].startsWith('@') && parts.length > 2
? parts.slice(0, 3).join('/')
: parts.slice(0, 2).join('/');
} else if (parts.length > 1) {
dir = parts.slice(0, 2).join('/');
} else {
dir = parts[0];
}
unpackDirs.add(dir);
}
const dirPatterns = Array.from(unpackDirs).map((dir) =>
path.join(x64Dir, dir, '**'),
);
let unpack: string | undefined;
if (dirPatterns.length > 1) {
unpack = `{${dirPatterns.join(',')}}`;
} else if (dirPatterns.length === 1) {
unpack = dirPatterns[0];
}
d(
`unpack pattern (${unpackedFiles.size} files, ${unpackDirs.size} dirs): ${
unpack ? unpack.substring(0, 200) + '...' : 'none'
}`,
);
await asar.createPackageWithOptions(x64Dir, outputAsarPath, {
unpack,
});
d('done merging');
} finally {
await Promise.all([
fs.promises.rm(x64Dir, { recursive: true, force: true }),
fs.promises.rm(arm64Dir, { recursive: true, force: true }),
]);
}
};
export const isUniversalMachO = (fileContent: Buffer) => {
return MACHO_UNIVERSAL_MAGIC.has(fileContent.readUInt32LE(0));
};