Repository navigation
Expand file tree
/
Copy pathwindow-preview.ts
More file actions
209 lines (200 loc) · 8.81 KB
/
Copy pathwindow-preview.ts
File metadata and controls
209 lines (200 loc) · 8.81 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
#!/usr/bin/env bun
import {
chmodSync,
closeSync,
constants,
fsyncSync,
lstatSync,
mkdtempSync,
openSync,
readdirSync,
rmSync,
writeSync,
} from "fs";
import { tmpdir } from "os";
import { basename, dirname, join } from "path";
const MAX_PREVIEW_BYTES = 4 * 1024 * 1024;
const MAX_RAW_CAPTURE_BYTES = 32 * 1024 * 1024;
export interface PreviewTarget {
directory: string;
path: string;
fd: number;
}
export function validWindowAddress(value: unknown): string | null {
const address = String(value || "").toLowerCase();
return /^0x[0-9a-f]+$/.test(address) ? address : null;
}
export const PREVIEW_PREFIX = "infomarchy-preview-";
export const PREVIEW_TTL_MS = 5 * 60 * 1000;
// Only names mkdtemp could have produced: prefix + exactly six [A-Za-z0-9].
// A prefix-only check would have recursively deleted any same-prefix
// directory the user happened to own.
export const PREVIEW_DIR_NAME = /^infomarchy-preview-[A-Za-z0-9]{6}$/;
export function expiredPreviewDirectories(names: string[], ages: Record<string, number>, ttlMs = PREVIEW_TTL_MS): string[] {
return names.filter(name => PREVIEW_DIR_NAME.test(name) && Number(ages[name] ?? 0) > ttlMs);
}
// A directory is ours only if it holds nothing but the preview file we write.
export function looksLikeOurPreviewDirectory(entries: string[]): boolean {
return entries.length <= 1 && entries.every(entry => entry === "preview.png");
}
// A successful capture keeps its directory so QML can load the PNG; nothing
// used to delete it, so sustained hover leaked one directory every few seconds.
// Sweep our own stale ones on each run instead of holding a daemon.
export const MAX_SWEEP_REMOVALS = 32;
// Is this path one of OUR preview directories? Exact parent, exact mkdtemp
// name shape, a real directory (not a symlink) owned by us, holding nothing
// but preview.png. Used by both the sweep and the explicit removal path.
export function ownedPreviewDirectory(path: string, baseDirectory = tmpdir()): boolean {
const name = basename(path);
if (!PREVIEW_DIR_NAME.test(name) || dirname(path) !== baseDirectory) return false;
try {
const stat = lstatSync(path);
if (!stat.isDirectory() || stat.isSymbolicLink()) return false;
const uid = process.getuid?.();
if (uid !== undefined && stat.uid !== uid) return false;
return looksLikeOurPreviewDirectory(readdirSync(path));
} catch { return false; }
}
// Explicit removal when a preview is replaced, previews are disabled, or the
// view is destroyed. Accepts the preview.png path the shell holds, or the
// directory itself.
export function removePreviewArtifact(target: string, baseDirectory = tmpdir()): boolean {
const directory = basename(target) === "preview.png" ? dirname(target) : target;
if (!ownedPreviewDirectory(directory, baseDirectory)) return false;
try { rmSync(directory, { recursive: true, force: true }); return true; } catch { return false; }
}
// Bounded stale sweep: at most MAX_SWEEP_REMOVALS directories per run, so a
// pathological /tmp cannot turn one hover into a long delete loop.
export function reapPreviewDirectories(baseDirectory = tmpdir(), ttlMs = PREVIEW_TTL_MS, stamp = Date.now(), limit = MAX_SWEEP_REMOVALS): number {
let removed = 0;
let names: string[] = [];
try { names = readdirSync(baseDirectory); } catch { return 0; }
for (const name of names) {
if (removed >= limit) break;
if (!PREVIEW_DIR_NAME.test(name)) continue;
const path = join(baseDirectory, name);
try {
const stat = lstatSync(path);
if (stamp - stat.mtimeMs <= ttlMs) continue;
if (!ownedPreviewDirectory(path, baseDirectory)) continue;
rmSync(path, { recursive: true, force: true });
removed++;
} catch {}
}
return removed;
}
export function createPreviewTarget(baseDirectory = tmpdir()): PreviewTarget {
const directory = mkdtempSync(join(baseDirectory, "infomarchy-preview-"));
try {
chmodSync(directory, 0o700);
const stat = lstatSync(directory);
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== (process.getuid?.() ?? stat.uid) || (stat.mode & 0o777) !== 0o700) {
throw new Error("unsafe preview directory");
}
const path = join(directory, "preview.png");
const fd = openSync(
path,
constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,
0o600,
);
return { directory, path, fd };
} catch (error) {
rmSync(directory, { recursive: true, force: true });
throw error;
}
}
const STAGE_TIMEOUT_MS = 4000;
// A hung hyprctl/grim/magick used to leave the QML preview Process running
// forever. Every stage gets a deadline; on expiry the child is killed and the
// helper exits non-zero.
type Child = { kill: (signal?: any) => void; exited: Promise<number>; exitCode: number | null; signalCode: string | null };
// TERM, bounded grace, KILL, reap — the same firm contract as the collector.
export async function terminate(proc: Child, graceMs = 250): Promise<void> {
const alive = () => proc.exitCode === null && proc.signalCode === null;
if (!alive()) return;
try { proc.kill("SIGTERM"); } catch {}
await Promise.race([proc.exited, new Promise(resolve => setTimeout(resolve, graceMs))]);
if (alive()) {
try { proc.kill("SIGKILL"); } catch {}
await Promise.race([proc.exited, new Promise(resolve => setTimeout(resolve, graceMs))]);
}
}
async function withDeadline<T>(promise: Promise<T>, proc: Child, ms = STAGE_TIMEOUT_MS): Promise<T | null> {
let timer: ReturnType<typeof setTimeout> | null = null;
const expiry = new Promise<null>(resolve => { timer = setTimeout(() => resolve(null), ms); });
try {
const result = await Promise.race([promise, expiry]);
if (result === null) await terminate(proc);
return result;
} finally { if (timer) clearTimeout(timer); }
}
async function readBounded(stream: ReadableStream<Uint8Array>, limit = MAX_PREVIEW_BYTES): Promise<Uint8Array> {
const reader = stream.getReader();
const chunks: Uint8Array[] = [];
let length = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
length += value.byteLength;
if (length > limit) throw new Error("preview output limit exceeded");
chunks.push(value);
}
} finally {
reader.releaseLock();
}
const output = new Uint8Array(length);
let offset = 0;
for (const chunk of chunks) {
output.set(chunk, offset);
offset += chunk.byteLength;
}
return output;
}
if (import.meta.main) {
// `--remove <preview.png|dir>`: ownership-checked deletion of one artifact.
if (process.argv[2] === "--remove") {
const removed = removePreviewArtifact(String(process.argv[3] || ""));
reapPreviewDirectories();
process.exit(removed ? 0 : 7);
}
const address = validWindowAddress(process.argv[2]);
if (!address || !Bun.which("grim") || !Bun.which("magick")) process.exit(2);
const clientsProc = Bun.spawn(["hyprctl", "clients", "-j"], { stdout: "pipe", stderr: "ignore" });
const clientsRaw = await withDeadline(readBounded(clientsProc.stdout, MAX_PREVIEW_BYTES), clientsProc);
if (!clientsRaw) process.exit(6);
let clients: any[] = [];
try { const parsed = JSON.parse(new TextDecoder().decode(clientsRaw)); clients = Array.isArray(parsed) ? parsed : []; } catch { process.exit(6); }
const client = clients.find((item: any) => item && typeof item === "object" && String(item.address || "").toLowerCase() === address);
const at = client?.at, size = client?.size;
if (!Array.isArray(at) || !Array.isArray(size) || size[0] < 20 || size[1] < 20) process.exit(3);
reapPreviewDirectories();
const target = createPreviewTarget();
let keepTarget = false;
try {
const geometry = `${at[0]},${at[1]} ${size[0]}x${size[1]}`;
const grim = Bun.spawn(["grim", "-g", geometry, "-"], { stdout: "pipe", stderr: "ignore" });
const grimResult = await withDeadline(Promise.all([grim.exited, readBounded(grim.stdout, MAX_RAW_CAPTURE_BYTES)]), grim);
const [grimExit, raw] = grimResult || [1, new Uint8Array(0)];
if (grimExit !== 0 || raw.byteLength === 0) process.exitCode = 4;
else {
const magick = Bun.spawn(
["magick", "png:-", "-resize", "160x90!", "-blur", "0x10", "-scale", "320x180!", "png:-"],
{ stdin: new Blob([raw]), stdout: "pipe", stderr: "ignore" },
);
const magickResult = await withDeadline(Promise.all([magick.exited, readBounded(magick.stdout)]), magick);
const [magickExit, preview] = magickResult || [1, new Uint8Array(0)];
if (magickExit !== 0 || preview.byteLength === 0) process.exitCode = 5;
else {
let offset = 0;
while (offset < preview.byteLength) offset += writeSync(target.fd, preview, offset);
fsyncSync(target.fd);
keepTarget = true;
console.log(target.path);
}
}
} finally {
closeSync(target.fd);
if (!keepTarget) rmSync(target.directory, { recursive: true, force: true });
}
}