| 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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622 |
'use strict';
const { execFile } = require('child_process');
const fs = require('fs');
const path = require('path');
const os = require('os');
const HOME = os.homedir();
const VAR_APP = path.join(HOME, '.var', 'app');
const USER_OVERRIDES = path.join(HOME, '.local', 'share', 'flatpak', 'overrides');
const SYSTEM_OVERRIDES = '/var/lib/flatpak/overrides';
const SYSTEM_REPO = '/var/lib/flatpak/repo';
const ICON_ROOTS = [
path.join(HOME, '.local', 'share', 'flatpak', 'exports', 'share', 'icons', 'hicolor'),
'/var/lib/flatpak/exports/share/icons/hicolor',
];
const ICON_SIZES = ['128x128', '256x256', '64x64', '96x96', '48x48'];
const LONG_MS = 60 * 60 * 1000;
function run(cmd, args, opts = {}) {
return new Promise((resolve) => {
execFile(cmd, args, {
maxBuffer: 64 * 1024 * 1024,
timeout: opts.timeout || 120000,
env: { ...process.env, LC_ALL: 'C' },
}, (error, stdout, stderr) => {
resolve({
ok: !error,
code: error && typeof error.code === 'number' ? error.code : (error ? 1 : 0),
stdout: stdout || '',
stderr: stderr || '',
error: error ? (stderr || error.message).trim() : null,
});
});
});
}
function runLong(cmd, args) {
return run(cmd, args, { timeout: LONG_MS });
}
async function probe() {
const result = await run('flatpak', ['--version'], { timeout: 10000 });
if (!result.ok) {
return { present: false, version: null };
}
const version = (result.stdout.trim().split(/\s+/).pop() || '').trim();
return { present: true, version };
}
const LIST_COLUMNS = ['name', 'application', 'version', 'branch', 'arch', 'origin', 'installation'];
async function listApps() {
const result = await run('flatpak', [
'list', '--app', `--columns=${LIST_COLUMNS.join(',')}`,
]);
if (!result.ok) return { ok: false, error: result.error, apps: [] };
const apps = [];
for (const line of result.stdout.split('\n')) {
if (!line.trim()) continue;
const cells = line.split('\t');
if (cells.length < LIST_COLUMNS.length) continue;
const [name, id, version, branch, arch, origin, installation] = cells.map((c) => c.trim());
if (!id) continue;
apps.push({
id,
name: name || id,
version: version || '',
branch: branch || 'stable',
arch: arch || (process.arch === 'arm64' ? 'aarch64' : 'x86_64'),
origin: origin || '',
scope: installation === 'user' ? 'user' : 'system',
});
}
const byId = new Map();
for (const app of apps) {
const existing = byId.get(app.id);
if (!existing || (existing.scope === 'system' && app.scope === 'user')) byId.set(app.id, app);
}
return { ok: true, apps: [...byId.values()].sort((a, b) => a.name.localeCompare(b.name)) };
}
async function runningApps() {
const result = await run('flatpak', ['ps', '--columns=application']);
if (!result.ok) return [];
const ids = result.stdout.split('\n').map((l) => l.trim()).filter(Boolean);
return [...new Set(ids)];
}
async function ensureUserRemote(name, url) {
if (!name) return { ok: false, error: 'No remote was recorded for this app.' };
const userRemotes = await listRemotes('user');
if (userRemotes.some((r) => r.name === name)) return { ok: true, remote: name, added: false };
const systemRemotes = await listRemotes('system');
const clashes = systemRemotes.some((r) => r.name === name);
const localName = clashes ? `${name}-user` : name;
if (userRemotes.some((r) => r.name === localName)) {
return { ok: true, remote: localName, added: false };
}
if (name === FLATHUB.name) {
const added = await run('flatpak', [
'remote-add', '--if-not-exists', '--user', localName, FLATHUB.url,
], { timeout: 120000 });
return added.ok
? { ok: true, remote: localName, added: true }
: { ok: false, error: added.error };
}
let address = url;
if (!address) {
const match = systemRemotes.find((r) => r.name === name);
address = match && match.url;
}
if (!address) {
return { ok: false, error: `The ${name} remote is not on this machine and no address for it was recorded.` };
}
const args = ['remote-add', '--if-not-exists', '--user'];
const key = path.join(SYSTEM_REPO, `${name}.trustedkeys.gpg`);
try {
fs.accessSync(key, fs.constants.R_OK);
args.push(`--gpg-import=${key}`);
} catch { }
args.push(localName, address);
const result = await run('flatpak', args, { timeout: 120000 });
return result.ok
? { ok: true, remote: localName, added: true }
: { ok: false, error: result.error };
}
async function killApp(id) {
return run('flatpak', ['kill', id], { timeout: 20000 });
}
async function listRemotes(scope) {
const args = ['remotes'];
if (scope === 'user' || scope === 'system') args.push(`--${scope}`);
args.push('--columns=name,url,options');
const result = await run('flatpak', args);
if (!result.ok) return [];
const remotes = [];
for (const line of result.stdout.split('\n')) {
if (!line.trim()) continue;
const [name, url, options] = line.split('\t').map((c) => (c || '').trim());
if (!name || !url) continue;
if (remotes.some((r) => r.name === name)) continue;
remotes.push({ name, url, options: options || '' });
}
return remotes;
}
function dataDir(id) {
return path.join(VAR_APP, id);
}
function hasData(id) {
try {
return fs.statSync(dataDir(id)).isDirectory();
} catch {
return false;
}
}
function hasSettings(id) {
const root = dataDir(id);
const stack = [];
try {
for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
if (entry.name === 'cache') continue;
stack.push({ dir: root, entry });
}
} catch {
return false;
}
let looked = 0;
while (stack.length) {
const { dir, entry } = stack.pop();
const full = path.join(dir, entry.name);
if (entry.isFile()) return true;
if (entry.isDirectory() && !entry.isSymbolicLink()) {
looked += 1;
if (looked > 5000) return true;
try {
for (const child of fs.readdirSync(full, { withFileTypes: true })) {
stack.push({ dir: full, entry: child });
}
} catch { }
}
}
return false;
}
const CHROMIUM_ROOT_JUNK = [
'extensions_crx_cache', 'component_crx_cache', 'Safe Browsing',
'OnDeviceHeadSuggestModel', 'GPUPersistentCache', 'GrShaderCache', 'ShaderCache',
'GraphiteDawnCache', 'hyphen-data', 'ZxcvbnData', 'CertificateRevocation',
'PKIMetadata', 'Crashpad', 'Crash Reports', 'screen_ai', 'WasmTtsEngine',
'OptimizationGuidePredictionModels', 'optimization_guide_model_store',
'TrustTokenKeyCommitments', 'FirstPartySetsPreloaded', 'OriginTrials',
'SSLErrorAssistant', 'MEIPreload', 'Subresource Filter', 'FileTypePolicies',
'BrowserMetrics', 'DeferredBrowserMetrics',
];
const CHROMIUM_PROFILE_JUNK = [
'Service Worker/CacheStorage', 'Service Worker/ScriptCache',
'Cache', 'Code Cache', 'GPUCache', 'DawnCache', 'DawnWebGPUCache', 'DawnGraphiteCache',
'adblock_cache', 'Shared Dictionary', 'blob_storage',
'optimization_guide_hint_cache_store', 'optimization_guide_model_metadata_store',
];
const FIREFOX_PROFILE_JUNK = [
'cache2', 'startupCache', 'thumbnails', 'crashes', 'minidumps', 'datareporting',
'saved-telemetry-pings', 'safebrowsing', 'shader-cache', 'OfflineCache', 'jumpListCache',
];
const COMPONENT_DIR = /^[a-p]{32}$/;
function isFile(file) {
try { return fs.statSync(file).isFile(); } catch { return false; }
}
function isDir(dir) {
try { return fs.statSync(dir).isDirectory(); } catch { return false; }
}
function childDirs(dir) {
try {
return fs.readdirSync(dir, { withFileTypes: true })
.filter((d) => d.isDirectory() && !d.isSymbolicLink())
.map((d) => d.name);
} catch {
return [];
}
}
function throwawayPaths(root) {
const found = new Set();
const add = (abs) => { if (isDir(abs)) found.add(path.relative(root, abs)); };
const walk = (dir, depth) => {
if (depth > 7) return;
if (isFile(path.join(dir, 'Local State'))) {
for (const name of CHROMIUM_ROOT_JUNK) add(path.join(dir, name));
for (const name of childDirs(dir)) if (COMPONENT_DIR.test(name)) add(path.join(dir, name));
for (const name of CHROMIUM_PROFILE_JUNK) add(path.join(dir, name));
for (const name of childDirs(dir)) {
const profile = path.join(dir, name);
if (isFile(path.join(profile, 'Preferences'))) {
for (const junk of CHROMIUM_PROFILE_JUNK) add(path.join(profile, junk));
}
}
return;
}
if (isFile(path.join(dir, 'prefs.js'))) {
for (const name of FIREFOX_PROFILE_JUNK) add(path.join(dir, name));
const sites = path.join(dir, 'storage', 'default');
for (const site of childDirs(sites)) add(path.join(sites, site, 'cache'));
return;
}
for (const name of childDirs(dir)) {
if (depth === 0 && name === 'cache') continue;
walk(path.join(dir, name), depth + 1);
}
};
walk(root, 0);
const list = [...found].sort();
return list.filter((p) => !list.some((q) => q !== p && p.startsWith(`${q}${path.sep}`)));
}
async function bytesOf(abs) {
const result = await run('du', ['-sb', abs], { timeout: 120000 });
const bytes = parseInt((result.stdout || '').split(/\s+/)[0], 10);
return Number.isFinite(bytes) ? bytes : 0;
}
async function settingsSizes(id, root = dataDir(id)) {
if (!isDir(root)) return { full: 0, trimmed: 0, trimmable: false };
const full = await bytesOf(root);
const cache = isDir(path.join(root, 'cache')) ? await bytesOf(path.join(root, 'cache')) : 0;
let saved = 0;
for (const rel of throwawayPaths(root)) saved += await bytesOf(path.join(root, rel));
const trimmed = Math.max(0, full - cache - saved);
return { full, trimmed, trimmable: full > trimmed };
}
function readOverrideFile(id) {
const user = path.join(USER_OVERRIDES, id);
const system = path.join(SYSTEM_OVERRIDES, id);
for (const [scope, file] of [['user', user], ['system', system]]) {
try {
return { scope, text: fs.readFileSync(file, 'utf8') };
} catch { }
}
return null;
}
function readGlobalOverride() {
try {
return fs.readFileSync(path.join(USER_OVERRIDES, 'global'), 'utf8');
} catch {
return null;
}
}
async function showPermissions(id) {
const result = await run('flatpak', ['info', '--show-permissions', id], { timeout: 30000 });
return result.ok ? result.stdout : '';
}
const CONTEXT_FLAGS = {
shared: ['--share=', '--unshare='],
sockets: ['--socket=', '--nosocket='],
devices: ['--device=', '--nodevice='],
features: ['--allow=', '--disallow='],
filesystems: ['--filesystem=', '--nofilesystem='],
};
function permissionsToArgs(text) {
const args = [];
let section = '';
for (const rawLine of String(text).split('\n')) {
const line = rawLine.trim();
if (!line || line.startsWith('#')) continue;
if (line.startsWith('[') && line.endsWith(']')) {
section = line.slice(1, -1);
continue;
}
const eq = line.indexOf('=');
if (eq === -1) continue;
const key = line.slice(0, eq).trim();
const value = line.slice(eq + 1).trim();
if (section === 'Context') {
const flags = CONTEXT_FLAGS[key];
if (!flags) continue;
for (const item of value.split(';')) {
const entry = item.trim();
if (!entry) continue;
args.push(entry.startsWith('!')
? `${flags[1]}${entry.slice(1)}`
: `${flags[0]}${entry}`);
}
} else if (section === 'Session Bus Policy' || section === 'System Bus Policy') {
const system = section.startsWith('System') ? '--system-' : '--';
if (value === 'talk') args.push(`${system}talk-name=${key}`);
else if (value === 'own') args.push(`${system}own-name=${key}`);
else if (value === 'none') args.push(`${system}no-talk-name=${key}`);
} else if (section === 'Environment') {
args.push(`--env=${key}=${value}`);
}
}
return args;
}
async function applyOverrideArgs(id, args) {
if (!args.length) return { ok: true };
return run('flatpak', ['override', '--user', ...args, id], { timeout: 60000 });
}
function writeOverrideFile(id, text) {
fs.mkdirSync(USER_OVERRIDES, { recursive: true });
fs.writeFileSync(path.join(USER_OVERRIDES, id), text, 'utf8');
}
function iconDataUrl(id) {
for (const root of ICON_ROOTS) {
for (const size of ICON_SIZES) {
const file = path.join(root, size, 'apps', `${id}.png`);
try {
const data = fs.readFileSync(file);
if (data.length && data.length < 2 * 1024 * 1024) {
return `data:image/png;base64,${data.toString('base64')}`;
}
} catch { }
}
const svg = path.join(root, 'scalable', 'apps', `${id}.svg`);
try {
const data = fs.readFileSync(svg);
if (data.length && data.length < 512 * 1024) {
return `data:image/svg+xml;base64,${data.toString('base64')}`;
}
} catch { }
}
return null;
}
const FLATHUB = { name: 'flathub', url: 'https://dl.flathub.org/repo/flathub.flatpakrepo' };
async function addFlathub() {
const ready = await ensureUserRemote(FLATHUB.name);
return ready.ok ? { ok: true, remote: ready.remote } : { ok: false, error: ready.error };
}
const NOT_AN_APP = [
/^org\.gtk\.Gtk3theme\./,
/^org\.kde\.(Platform|Sdk|KStyle)/,
/^org\.freedesktop\.(Platform|Sdk)/,
/^org\.gnome\.(Platform|Sdk)/,
/\.(Locale|Debug|Sources|BaseApp|Extension)$/,
/\.Plugin\./,
];
async function searchApps(term) {
const text = String(term || '').trim();
if (text.length < 2) return [];
const result = await run('flatpak', [
'search', '--columns=name,application,remotes,description', text,
], { timeout: 60000 });
if (!result.ok) return [];
const found = [];
for (const line of result.stdout.split('\n')) {
if (!line.trim()) continue;
const [name, id, remotes, description] = line.split('\t').map((c) => (c || '').trim());
if (!id || NOT_AN_APP.some((pattern) => pattern.test(id))) continue;
if (found.some((f) => f.id === id)) continue;
found.push({
id,
name: name || id,
remote: (remotes || 'flathub').split(',')[0].trim(),
description: description || '',
});
if (found.length >= 30) break;
}
const lower = text.toLowerCase();
found.sort((a, b) => {
const score = (x) => (x.id.toLowerCase() === lower ? 0
: x.name.toLowerCase() === lower ? 1
: x.name.toLowerCase().startsWith(lower) ? 2 : 3);
return score(a) - score(b) || a.name.localeCompare(b.name);
});
return found;
}
async function installLatest({ id, remote }) {
const ready = await ensureUserRemote(remote);
if (!ready.ok) return { ok: false, error: ready.error };
const result = await runLong('flatpak', [
'install', '--user', '--noninteractive', '-y', ready.remote, id,
]);
if (result.ok) return { ok: true };
return { ok: false, error: result.error || 'install failed' };
}
async function isInstalled(id) {
const result = await run('flatpak', ['info', id], { timeout: 30000 });
return result.ok;
}
async function installApp({ id, remote, branch, remoteUrl }) {
const ready = await ensureUserRemote(remote, remoteUrl);
if (!ready.ok) return { ok: false, error: ready.error };
const exact = await runLong('flatpak', [
'install', '--user', '--noninteractive', '-y', ready.remote, `${id}//${branch}`,
]);
if (exact.ok) return { ok: true, branch, fellBack: false };
const fallback = await runLong('flatpak', [
'install', '--user', '--noninteractive', '-y', ready.remote, id,
]);
if (fallback.ok) return { ok: true, branch: null, fellBack: true };
return { ok: false, error: (exact.error || fallback.error || 'install failed') };
}
module.exports = {
VAR_APP,
USER_OVERRIDES,
run,
runLong,
probe,
listApps,
runningApps,
killApp,
listRemotes,
dataDir,
hasData,
hasSettings,
throwawayPaths,
settingsSizes,
readOverrideFile,
readGlobalOverride,
showPermissions,
permissionsToArgs,
applyOverrideArgs,
writeOverrideFile,
iconDataUrl,
isInstalled,
installApp,
addFlathub,
ensureUserRemote,
searchApps,
installLatest,
}; |