| 1 | import { sha256 } from "@noble/hashes/sha2"; |
| 2 | |
| 3 | export interface DesktopAppControlAddress { |
| 4 | readonly address: string; |
| 5 | readonly directory: string | null; |
| 6 | } |
| 7 | |
| 8 | function 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(""); |
| 12 | } |
| 13 | |
| 14 | /** |
| 15 | * Returns the local-only socket address shared by the desktop shell and CLI. |
| 16 | * The state directory is hashed so custom T3 homes cannot exceed Unix socket |
| 17 | * path limits. |
| 18 | */ |
| 19 | export function resolveDesktopAppControlAddress(input: { |
| 20 | readonly stateDir: string; |
| 21 | readonly platform: NodeJS.Platform; |
| 22 | readonly tempDir: string; |
| 23 | readonly userId: number | undefined; |
| 24 | readonly joinPath: (...segments: readonly string[]) => string; |
| 25 | }): DesktopAppControlAddress { |
| 26 | const stateHash = shortHash(input.stateDir); |
| 27 | if (input.platform === "win32") { |
| 28 | return { |
| 29 | address: `\\\\.\\pipe\\t3code-app-${stateHash}`, |
| 30 | directory: null, |
| 31 | }; |
| 32 | } |
| 33 | |
| 34 | const userKey = |
| 35 | input.userId === undefined ? shortHash(input.stateDir).slice(0, 12) : input.userId; |
| 36 | const directory = input.joinPath(input.tempDir, `t3code-${userKey}`); |
| 37 | return { |
| 38 | address: input.joinPath(directory, `${stateHash}.sock`), |
| 39 | directory, |
| 40 | }; |
| 41 | } |