Skip to content
Source
Sign inSign up

desktopAppControl.ts

42 lines1.4 KB

1import { sha256 } from "@noble/hashes/sha2";
2​
3export interface DesktopAppControlAddress {
4 readonly address: string;
5 readonly directory: string | null;
6}
7​
8function shortHash(value: string): string {
9 return Array.from(sha256(new TextEncoder().encode(value)).slice(0, 12), (byte) =>
10 byte.toString(16).padStart(2, "0"),
11 ).join("");
13​
14/** Hash state directories to stay within Unix socket path limits. */
15export function resolveDesktopAppControlAddress(input: {
16 readonly stateDir: string;
17 readonly platform: NodeJS.Platform;
18 readonly tempDir: string;
19 readonly userId: number | undefined;
20 readonly joinPath: (...segments: readonly string[]) => string;
21}): DesktopAppControlAddress {
22 const stateHash = shortHash(input.stateDir);
23 if (input.platform === "win32") {
24 return {
25 address: `\\\\.\\pipe\\t3code-app-${stateHash}`,
26 directory: null,
27 };
28 }
29​
30 const userKey =
31 input.userId === undefined ? shortHash(input.stateDir).slice(0, 12) : input.userId;
32 const socketName = `${stateHash}.sock`;
33 const maxPathBytes = input.platform === "linux" ? 107 : 103;
34 let directory = input.joinPath(input.tempDir, `t3code-${userKey}`);
35 if (new TextEncoder().encode(input.joinPath(directory, socketName)).byteLength > maxPathBytes) {
36 directory = input.joinPath("/tmp", `t3code-${userKey}`);
37 }
38 return {
39 address: input.joinPath(directory, socketName),
40 directory,
41 };