Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopBackendRecovery.ts

313 lines11.3 KB

1// @effect-diagnostics nodeBuiltinImport:off - Secure record opens require O_NOFOLLOW and fstat.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeCrypto from "node:crypto";
4import * as NodeFS from "node:fs";
5import * as NodeFSP from "node:fs/promises";
6import * as NodePath from "node:path";
7import * as NodeProcess from "node:process";
8import * as NodeTimersPromises from "node:timers/promises";
9import * as NodeUtil from "node:util";
10​
11import {
12 auditTokenPid,
13 isProcessAuditToken,
14 loadMacProcessAuditToken,
15 type MacProcessAuditToken,
16} from "./MacProcessAuditToken.ts";
17import { linuxProcessIdentity } from "./LinuxProcessIdentity.ts";
18​
19const exec = NodeUtil.promisify(NodeChildProcess.execFile);
20const directoryName = "t3code-backend-recovery";
21const maxRecordBytes = 512;
22const isDarwin = NodeProcess.platform === "darwin";
23// Darwin sys/fcntl.h. Node accepts these open flags but does not export them. Linux has no
24// open-time locks, so there a record is written under a temporary name and renamed into place.
25const O_SHLOCK = isDarwin ? 0x10 : 0;
26const O_EXLOCK = isDarwin ? 0x20 : 0;
27const observedFileName = /^[0-9a-f]{64}\.[0-9a-f-]{36}\.json$/;
28const scopePattern = /^[0-9a-f]{64}$/;
29const bootIdPattern = /^[0-9a-f-]{36}$/i;
30const terminateGraceMs = 5_000;
31const killGraceMs = 1_000;
32const pollIntervalMs = 250;
33​
34interface RecoveryRecord {
35 readonly version: 1;
36 readonly bootId: string;
37 readonly scope: string;
38 readonly launcher: string;
39 readonly backend: string;
41​
42type RecordReadResult = RecoveryRecord | "incomplete" | undefined;
43​
44function decodeRecord(raw: string): RecordReadResult {
45 try {
46 const value = JSON.parse(raw) as Partial<RecoveryRecord> | null;
47 if (
48 value?.version !== 1 ||
49 typeof value.bootId !== "string" ||
50 !bootIdPattern.test(value.bootId) ||
51 typeof value.scope !== "string" ||
52 !scopePattern.test(value.scope) ||
53 !isProcessAuditToken(value.launcher) ||
54 !isProcessAuditToken(value.backend)
55 ) {
56 return undefined;
57 }
58 const owner = auditTokenPid(value.launcher);
59 const child = auditTokenPid(value.backend);
60 if (owner <= 1 || child <= 1 || owner > 0x7fff_ffff || child > 0x7fff_ffff || owner === child) {
61 return undefined;
62 }
63 return {
64 version: 1,
65 bootId: value.bootId,
66 scope: value.scope,
67 launcher: value.launcher,
68 backend: value.backend,
69 };
70 } catch {
71 return "incomplete";
72 }
74​
75const isErrorCode = (error: unknown, code: string) =>
76 (error as NodeJS.ErrnoException)?.code === code;
77​
78function ownsPrivateFile(info: { uid: number; mode: number }): boolean {
79 return info.uid === NodeProcess.getuid?.() && (info.mode & 0o077) === 0;
81​
82async function readRecord(path: string): Promise<RecordReadResult> {
83 const file = await NodeFSP.open(
84 path,
85 NodeFS.constants.O_RDONLY |
86 NodeFS.constants.O_NOFOLLOW |
87 NodeFS.constants.O_NONBLOCK |
88 O_SHLOCK,
89 );
90 try {
91 const info = await file.stat();
92 if (
93 !info.isFile() ||
94 info.nlink !== 1 ||
95 !ownsPrivateFile(info) ||
96 info.size > maxRecordBytes
97 ) {
98 return undefined;
99 }
100 const bytes = Buffer.alloc(maxRecordBytes + 1);
101 const { bytesRead } = await file.read(bytes);
102 return bytesRead > maxRecordBytes
103 ? undefined
104 : decodeRecord(bytes.toString("utf8", 0, bytesRead));
105 } finally {
106 await file.close();
107 }
109​
110type ProcessStatus = "same" | "gone" | "unknown";
111​
112function status(native: MacProcessAuditToken, token: string): ProcessStatus {
113 const target = auditTokenPid(token);
114 const observed = native.read(target);
115 if (observed !== undefined) return observed === token ? "same" : "gone";
116 try {
117 NodeProcess.kill(target, 0);
118 return "unknown";
119 } catch (error) {
120 return isErrorCode(error, "ESRCH") ? "gone" : "unknown";
121 }
123​
124async function waitForExit(
125 native: MacProcessAuditToken,
126 token: string,
127 graceMs: number,
128 signal: AbortSignal,
129): Promise<boolean> {
130 const deadline = performance.now() + graceMs;
131 while (performance.now() < deadline) {
132 if (status(native, token) === "gone") return true;
133 await NodeTimersPromises.setTimeout(pollIntervalMs, undefined, { signal });
134 }
135 return status(native, token) === "gone";
137​
138async function recoverRecord(
139 native: MacProcessAuditToken,
140 record: RecoveryRecord,
141 options: { launcherPid: number; signal: AbortSignal; onRecovery: (pid: number) => void },
142): Promise<boolean> {
143 const backendPid = auditTokenPid(record.backend);
144 if (backendPid === options.launcherPid) return false;
145 // The launch record already binds the executable. Its vnode may be gone after
146 // a volume disconnect, but the kernel still knows the recorded audit token.
147 const ownsOrphan = () =>
148 status(native, record.launcher) === "gone" &&
149 status(native, record.backend) === "same" &&
150 // macOS reparents orphans to launchd; Linux may pick a subreaper such as systemd --user.
151 native.parent(backendPid) !== auditTokenPid(record.launcher);
152​
153 if (status(native, record.backend) === "gone") return true;
154 if (!ownsOrphan()) return false;
155​
156 options.signal.throwIfAborted();
157 options.onRecovery(backendPid);
158 native.signal(record.backend, "SIGTERM");
159 if (await waitForExit(native, record.backend, terminateGraceMs, options.signal)) return true;
160 if (!ownsOrphan()) return false;
161 options.signal.throwIfAborted();
162 native.signal(record.backend, "SIGKILL");
163 return waitForExit(native, record.backend, killGraceMs, options.signal);
165​
166async function readBootId(): Promise<string> {
167 const bootId = isDarwin
168 ? (
169 await exec("/usr/sbin/sysctl", ["-n", "kern.bootsessionuuid"], { timeout: 1_000 })
170 ).stdout.trim()
171 : (await NodeFSP.readFile("/proc/sys/kernel/random/boot_id", "utf8")).trim();
172 if (!bootIdPattern.test(bootId)) throw new Error("Could not identify the current boot");
173 return bootId;
175​
176const loadProcessIdentity = (): Promise<MacProcessAuditToken> =>
177 isDarwin ? loadMacProcessAuditToken() : Promise.resolve(linuxProcessIdentity);
178​
179// A first launch can precede creation of the state directory. Resolve existing
180// ancestors so a symlinked home keeps the same key after that directory appears.
181async function canonicalHome(path: string): Promise<string> {
182 try {
183 return await NodeFSP.realpath(path);
184 } catch (error) {
185 if (!isErrorCode(error, "ENOENT") || NodePath.dirname(path) === path) throw error;
186 return NodePath.join(await canonicalHome(NodePath.dirname(path)), NodePath.basename(path));
187 }
189​
190export function make(input: {
191 readonly appDataDirectory: string;
192 readonly stateDir: string;
193 /** The desktop main process; this module runs in a helper so native calls stay off main. */
194 readonly launcherPid: number;
195 readonly onRecovery: (pid: number) => void;
196 readonly onError: (operation: string, error: unknown) => void;
197}) {
198 // Use Application Support even when the T3 home or the app lives on removable storage.
199 const directory = NodePath.join(input.appDataDirectory, directoryName);
200 const scope = async () => {
201 const appImage = isDarwin ? undefined : NodeProcess.env.APPIMAGE?.trim();
202 const [home, executable, installation] = await Promise.all([
203 canonicalHome(input.stateDir),
204 NodeFSP.realpath(NodeProcess.execPath),
205 // An AppImage runs from a new mount path each launch; its file path is the stable install.
206 appImage ? NodeFSP.realpath(appImage) : undefined,
207 ]);
208 const prefix = NodeCrypto.createHash("sha256")
209 .update(JSON.stringify([home, installation ?? executable]))
210 .digest("hex");
211 return { prefix, executable };
212 };
213 const privateDirectory = async () => {
214 const info = await NodeFSP.lstat(directory);
215 if (!info.isDirectory() || !ownsPrivateFile(info)) {
216 throw new Error("Backend recovery records must be in an owner-only directory");
217 }
218 };
219​
220 return {
221 /** Returns the record path, which the launcher removes after observing the backend exit. */
222 async track(backendPid: number): Promise<string | undefined> {
223 try {
224 const [native, bootId, { prefix, executable }] = await Promise.all([
225 loadProcessIdentity(),
226 readBootId(),
227 scope(),
228 ]);
229 const launcher = native.read(input.launcherPid);
230 const backend = native.read(backendPid);
231 // A token and executable alone do not prove this desktop actually spawned this process.
232 if (
233 launcher === undefined ||
234 backend === undefined ||
235 native.parent(backendPid) !== input.launcherPid ||
236 native.executable(backendPid) !== executable ||
237 native.read(backendPid) !== backend
238 ) {
239 throw new Error("Could not verify desktop ownership of the backend");
240 }
241 await NodeFSP.mkdir(directory, { mode: 0o700 }).catch((error) => {
242 if (!isErrorCode(error, "EEXIST")) throw error;
243 });
244 await privateDirectory();
245 const path = NodePath.join(directory, `${prefix}.${NodeCrypto.randomUUID()}.json`);
246 const writePath = isDarwin ? path : `${path}.partial`;
247 // Take the lock at creation so recovery can distinguish a partial write from a crash.
248 {
249 await using file = await NodeFSP.open(
250 writePath,
251 NodeFS.constants.O_WRONLY |
252 NodeFS.constants.O_CREAT |
253 NodeFS.constants.O_EXCL |
254 O_EXLOCK,
255 0o600,
256 );
257 await file.writeFile(
258 JSON.stringify({ version: 1, bootId, scope: prefix, launcher, backend }),
259 );
260 }
261 if (writePath !== path) await NodeFSP.rename(writePath, path);
262 return path;
263 } catch (error) {
264 input.onError("record backend", error);
265 return undefined;
266 }
267 },
268 async recover(signal: AbortSignal = new AbortController().signal): Promise<void> {
269 try {
270 await privateDirectory();
271 const { prefix } = await scope();
272 const records = (await NodeFSP.readdir(directory)).filter(
273 (name) => name.startsWith(`${prefix}.`) && observedFileName.test(name),
274 );
275 if (records.length === 0) return;
276​
277 const [bootId, native] = await Promise.all([readBootId(), loadProcessIdentity()]);
278 await Promise.all(
279 records.map(async (name) => {
280 const path = NodePath.join(directory, name);
281 try {
282 const record = await readRecord(path);
283 if (
284 record === "incomplete" ||
285 (record !== undefined &&
286 record.scope === prefix &&
287 (record.bootId !== bootId ||
288 (await recoverRecord(native, record, {
289 launcherPid: input.launcherPid,
290 signal,
291 onRecovery: input.onRecovery,
292 }))))
293 ) {
294 await NodeFSP.unlink(path);
295 }
296 } catch (error) {
297 // EAGAIN means the launcher is still writing this record.
298 if (
299 !signal.aborted &&
300 !isErrorCode(error, "ENOENT") &&
301 !isErrorCode(error, "EAGAIN")
302 ) {
303 input.onError("recover backend", error);
304 }
305 }
306 }),
307 );
308 } catch (error) {
309 if (!isErrorCode(error, "ENOENT")) input.onError("read backend records", error);
310 }
311 },
312 };