-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathbrave.ts
More file actions
185 lines (161 loc) · 5.03 KB
/
brave.ts
File metadata and controls
185 lines (161 loc) · 5.03 KB
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
import { execFileSync } from "node:child_process";
import { existsSync } from "node:fs";
import { homedir, platform } from "node:os";
import { join } from "node:path";
import { queryReadonlySqlite } from "./firefox-profile.ts";
import { decryptChromiumCookieValue } from "./chromium-cookie.ts";
import { isRecord } from "../lib/object-type-guards.ts";
type BraveExtractedTeam = { url: string; name?: string; token: string };
export type BraveExtracted = {
cookie_d: string;
teams: BraveExtractedTeam[];
};
const IS_MACOS = platform() === "darwin";
// --- AppleScript helpers (for extracting teams from Brave tabs) ---
function osascript(script: string): string {
return execFileSync("osascript", ["-e", script], {
encoding: "utf8",
timeout: 7000,
stdio: ["ignore", "pipe", "pipe"],
}).trim();
}
const TEAM_JSON_PATHS = [
"JSON.stringify(JSON.parse(localStorage.localConfig_v2).teams)",
"JSON.stringify(JSON.parse(localStorage.localConfig_v3).teams)",
"JSON.stringify(JSON.parse(localStorage.getItem('reduxPersist:localConfig'))?.teams || {})",
"JSON.stringify(window.boot_data?.teams || {})",
];
function teamsScript(): string {
const tryPaths = TEAM_JSON_PATHS.map(
(expr) => `try { var v = ${expr}; if (v && v !== '{}' && v !== 'null') return v; } catch(e) {}`,
);
return `
tell application "Brave Browser"
repeat with w in windows
repeat with t in tabs of w
if URL of t contains "slack.com" then
return execute t javascript "(function(){ ${tryPaths.join(" ")} return '{}'; })()"
end if
end repeat
end repeat
return "{}"
end tell
`;
}
function toBraveTeam(value: unknown): BraveExtractedTeam | null {
if (!isRecord(value)) {
return null;
}
const token = typeof value.token === "string" ? value.token : null;
const url = typeof value.url === "string" ? value.url : null;
if (!token || !url || !token.startsWith("xoxc-")) {
return null;
}
const name = typeof value.name === "string" ? value.name : undefined;
return { url, name, token };
}
function extractTeamsFromBraveTab(): BraveExtractedTeam[] {
const teamsRaw = osascript(teamsScript());
let teamsObj: unknown = {};
try {
teamsObj = JSON.parse(teamsRaw || "{}");
} catch {
teamsObj = {};
}
const teamsRecord = isRecord(teamsObj) ? teamsObj : {};
return Object.values(teamsRecord)
.map((t) => toBraveTeam(t))
.filter((t): t is BraveExtractedTeam => t !== null);
}
// --- Cookie extraction from Brave's SQLite database ---
const BRAVE_COOKIES_DB = join(
homedir(),
"Library",
"Application Support",
"BraveSoftware",
"Brave-Browser",
"Default",
"Cookies",
);
function getSafeStoragePasswords(): string[] {
const services = [
"Brave Safe Storage",
"Brave Browser Safe Storage",
"Chrome Safe Storage",
"Chromium Safe Storage",
];
const passwords: string[] = [];
for (const service of services) {
try {
const out = execFileSync("security", ["find-generic-password", "-w", "-s", service], {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
}).trim();
if (out) {
passwords.push(out);
}
} catch {
// continue
}
}
return passwords;
}
async function extractCookieDFromBrave(): Promise<string> {
if (!existsSync(BRAVE_COOKIES_DB)) {
throw new Error(`Brave Cookies DB not found: ${BRAVE_COOKIES_DB}`);
}
const rows = (await queryReadonlySqlite(
BRAVE_COOKIES_DB,
"select host_key, name, value, encrypted_value from cookies where name = 'd' and host_key like '%slack.com' order by length(encrypted_value) desc",
)) as {
host_key: string;
name: string;
value: string;
encrypted_value: Uint8Array;
}[];
if (!rows || rows.length === 0) {
throw new Error("No Slack 'd' cookie found in Brave");
}
const row = rows[0]!;
if (row.value && row.value.startsWith("xoxd-")) {
return row.value;
}
const encrypted = Buffer.from(row.encrypted_value || []);
if (encrypted.length === 0) {
throw new Error("Brave Slack 'd' cookie had no encrypted_value");
}
const prefix = encrypted.subarray(0, 3).toString("utf8");
const data = prefix === "v10" || prefix === "v11" ? encrypted.subarray(3) : encrypted;
const passwords = getSafeStoragePasswords();
for (const password of passwords) {
try {
const decrypted = decryptChromiumCookieValue(data, password, 1003);
const match = decrypted.match(/xoxd-[A-Za-z0-9%/+_=.-]+/);
if (match) {
return match[0]!;
}
} catch {
// continue
}
}
throw new Error("Could not decrypt Slack 'd' cookie from Brave");
}
// --- Main export ---
export async function extractFromBrave(): Promise<BraveExtracted | null> {
if (!IS_MACOS) {
return null;
}
try {
const teams = extractTeamsFromBraveTab();
if (teams.length === 0) {
return null;
}
const cookie_d = await extractCookieDFromBrave();
if (!cookie_d || !cookie_d.startsWith("xoxd-")) {
return null;
}
return { cookie_d, teams };
} catch {
return null;
}
}