/
mod.ts
98 lines (87 loc) · 2.09 KB
/
mod.ts
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
export default async function machineId(original = false): Promise<string> {
let guid: string;
switch (Deno.build.os) {
case "linux": {
let output = "";
try {
output = await exec([
"cat",
"/var/lib/dbus/machine-id",
"/etc/machine-id",
]);
} catch {
output = await exec(["hostname"]);
}
guid = output
.substring(0, output.indexOf("\n"))
.replace(/\r+|\n+|\s+/gi, "")
.toLowerCase();
break;
}
case "darwin": {
const output = await exec([
"ioreg",
"-rd1",
"-c",
"IOPlatformExpertDevice",
]);
guid = output
.split("IOPlatformUUID")[1]
.split("\n")[0]
.replace(/\=|\s+|\"/gi, "")
.toLowerCase();
break;
}
case "windows": {
const output = await exec([
"REG",
"QUERY",
"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography",
"/v",
"MachineGuid",
]);
guid = output
.split("REG_SZ")[1]
.replace(/\r+|\n+|\s+/gi, "")
.toLowerCase();
break;
}
}
if (original) {
return guid;
}
return hash(guid);
}
async function exec(cmd: string[]): Promise<string> {
let p: Deno.Process;
try {
p = Deno.run({
cmd,
stdout: "piped",
stderr: "piped",
});
const { code } = await p.status();
if (code === 0) {
const rawOutput = await p.output();
const outputString = new TextDecoder().decode(rawOutput);
return outputString;
} else {
const rawError = await p.stderrOutput();
const errorString = new TextDecoder().decode(rawError);
throw new Error(errorString);
}
} finally {
p!.stderr?.close();
p!.close();
}
}
async function hash(guid: string): Promise<string> {
const data = new TextEncoder().encode(guid);
const buf = await crypto.subtle.digest("SHA-256", data);
return Array.from(new Uint8Array(buf))
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
if (import.meta.main) {
console.log(await machineId());
}