File size: 5,900 Bytes
98c9143
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import consola from "consola"
import { randomUUID } from "node:crypto"
import path from "node:path"

const WINDOWS_DEVICE_ID_KEY = String.raw`\SOFTWARE\Microsoft\DeveloperTools`
const WINDOWS_DEVICE_ID_NAME = "deviceid"

type RegistryArch = "x86" | "x64"

interface WinregConstructor {
  new (options: {
    hive: string
    key: string
    arch?: RegistryArch
  }): WinregRegistry
  HKCU: string
  REG_SZ: string
}

interface WinregRegistry {
  get(
    name: string,
    callback: (error: RegistryError | null, item: RegistryItem | null) => void,
  ): void
  set(
    name: string,
    type: string,
    value: string,
    callback: (error: RegistryError | null) => void,
  ): void
}

interface RegistryItem {
  value?: string
}

interface RegistryError extends Error {
  code?: number | string
}

const windows64Architectures = new Set(["AMD64", "ARM64", "IA64"])

const getPosixHomeDir = (): string => {
  if (!process.env.HOME) {
    throw new Error("Home directory not found")
  }

  return process.env.HOME
}

const getDeviceIdFilePath = (): string => {
  let folder: string

  switch (process.platform) {
    case "darwin": {
      folder = path.posix.join(
        getPosixHomeDir(),
        "Library",
        "Application Support",
      )
      break
    }
    case "linux": {
      folder =
        process.env.XDG_CACHE_HOME
        ?? path.posix.join(getPosixHomeDir(), ".cache")
      break
    }
    default: {
      throw new Error("Unsupported platform")
    }
  }

  return path.posix.join(folder, "Microsoft", "DeveloperTools", "deviceid")
}

const isMissingFileError = (error: unknown): error is NodeJS.ErrnoException => {
  return error instanceof Error && "code" in error && error.code === "ENOENT"
}

const readStoredDeviceIdFile = async (
  filePath: string,
): Promise<string | undefined> => {
  const { readFile } = await import("node:fs/promises")

  try {
    return await readFile(filePath, "utf8")
  } catch (error) {
    if (isMissingFileError(error)) {
      return undefined
    }

    throw error
  }
}

const writeStoredDeviceIdFile = async (
  filePath: string,
  deviceId: string,
): Promise<void> => {
  const { mkdir, writeFile } = await import("node:fs/promises")

  await mkdir(path.posix.dirname(filePath), { recursive: true })
  await writeFile(filePath, deviceId, "utf8")
}

const getWindowsRegistryArch = (): RegistryArch | undefined => {
  const architecture = (
    process.env.PROCESSOR_ARCHITEW6432 ?? process.env.PROCESSOR_ARCHITECTURE
  )?.toUpperCase()

  return architecture && windows64Architectures.has(architecture) ?
      "x64"
    : undefined
}

const loadWinreg = async (): Promise<WinregConstructor> => {
  const module = await import("winreg")
  const winreg =
    "default" in module ? (module.default as unknown) : (module as unknown)

  return winreg as WinregConstructor
}

const isMissingRegistryError = (error: RegistryError | null): boolean => {
  if (!error) {
    return false
  }

  const errorCode = Number(error.code)

  return Number.isFinite(errorCode) && errorCode === 1
}

const createWindowsRegistry = async (): Promise<{
  registry: WinregRegistry
  regSz: string
}> => {
  const Winreg = await loadWinreg()

  return {
    registry: new Winreg({
      hive: Winreg.HKCU,
      key: WINDOWS_DEVICE_ID_KEY,
      arch: getWindowsRegistryArch(),
    }),
    regSz: Winreg.REG_SZ,
  }
}

const readRegistryString = async (
  registry: WinregRegistry,
  name: string,
): Promise<string | undefined> => {
  return new Promise((resolve, reject) => {
    registry.get(name, (error, item) => {
      if (isMissingRegistryError(error)) {
        resolve(undefined)
        return
      }

      if (error) {
        reject(
          error instanceof Error ? error : new Error("Unknown registry error"),
        )
        return
      }

      resolve(item?.value)
    })
  })
}

const writeRegistryString = async ({
  registry,
  regSz,
  name,
  value,
}: {
  registry: WinregRegistry
  regSz: string
  name: string
  value: string
}): Promise<void> => {
  return new Promise((resolve, reject) => {
    registry.set(name, regSz, value, (error) => {
      if (error) {
        reject(
          error instanceof Error ? error : new Error("Unknown registry error"),
        )
        return
      }

      resolve()
    })
  })
}

export const getStoredVSCodeDeviceId = async (): Promise<
  string | undefined
> => {
  switch (process.platform) {
    case "win32": {
      const { registry } = await createWindowsRegistry()

      return readRegistryString(registry, WINDOWS_DEVICE_ID_NAME)
    }
    case "darwin":
    case "linux": {
      return readStoredDeviceIdFile(getDeviceIdFilePath())
    }
    default: {
      throw new Error("Unsupported platform")
    }
  }
}

const setStoredVSCodeDeviceId = async (deviceId: string): Promise<void> => {
  switch (process.platform) {
    case "win32": {
      const { registry, regSz } = await createWindowsRegistry()

      await writeRegistryString({
        registry,
        regSz,
        name: WINDOWS_DEVICE_ID_NAME,
        value: deviceId,
      })
      return
    }
    case "darwin":
    case "linux": {
      await writeStoredDeviceIdFile(getDeviceIdFilePath(), deviceId)
      return
    }
    default: {
      throw new Error("Unsupported platform")
    }
  }
}

const createVSCodeDeviceId = (): string => randomUUID().toLowerCase()

export async function getVSCodeDeviceId(): Promise<string> {
  let deviceId: string | undefined

  try {
    deviceId = await getStoredVSCodeDeviceId()
  } catch (error) {
    consola.debug("Failed to read VSCode device id", error)
  }

  if (deviceId) {
    return deviceId
  }

  const newDeviceId = createVSCodeDeviceId()

  try {
    await setStoredVSCodeDeviceId(newDeviceId)
  } catch (error) {
    consola.warn(
      "Failed to persist VSCode device id, using ephemeral id",
      error,
    )
  }

  return newDeviceId
}