-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbrowser.go
More file actions
259 lines (239 loc) · 8.07 KB
/
Copy pathbrowser.go
File metadata and controls
259 lines (239 loc) · 8.07 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
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
package main
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/chromedp"
)
// errNoChrome is returned when no Chromium-family browser can be located.
var errNoChrome = errors.New("no Chromium-based browser found")
// browserSigninMsg is delivered to the TUI when the browser sign-in flow ends.
type browserSigninMsg struct {
token string
err error
}
// findChrome locates a Chromium-family browser across platforms, or returns ""
// if none is found. DISCORD_DELETE_CHROME overrides the search with an explicit
// path (useful for an unusual install or a flatpak wrapper).
func findChrome() string {
if p := strings.TrimSpace(os.Getenv("DISCORD_DELETE_CHROME")); p != "" {
return p
}
return pickBrowser(chromeCandidates())
}
// chromeCandidates returns every browser it can find, in preference order.
func chromeCandidates() []string {
var out []string
// Names commonly on PATH, which in practice means Linux and BSD: macOS casks
// and Windows installers do not add one.
for _, n := range []string{
"google-chrome", "google-chrome-stable", "chromium", "chromium-browser",
"brave-browser", "brave", "microsoft-edge", "microsoft-edge-stable",
"vivaldi", "vivaldi-stable", "opera", "chrome",
} {
if p, err := exec.LookPath(n); err == nil {
out = append(out, p)
}
}
if p := chromeFromRegistry(); p != "" {
out = append(out, p)
}
for _, p := range chromeInstallPaths() {
if fi, err := os.Stat(p); err == nil && !fi.IsDir() {
out = append(out, p)
}
}
return out
}
// pickBrowser takes the first candidate installed outside a sandbox, falling
// back to a sandboxed one only when nothing else is present. On Ubuntu the snap
// Chromium sits on PATH and would otherwise beat a working deb install.
func pickBrowser(candidates []string) string {
var sandboxed string
for _, p := range candidates {
if sandboxKind(p) == "" {
return p
}
if sandboxed == "" {
sandboxed = p
}
}
return sandboxed
}
// sandboxKind names the packaging of a browser that runs sandboxed, or returns
// "" for an ordinary install. Snap and Flatpak both give the app a private /tmp,
// so the sign-in profile this process creates there is invisible to it.
func sandboxKind(path string) string {
switch {
case strings.HasPrefix(path, "/snap/"):
return "snap"
case strings.Contains(path, "/flatpak/exports/bin/"):
return "Flatpak"
}
return ""
}
func chromeInstallPaths() []string {
home, _ := os.UserHomeDir()
return chromeInstallPathsFor(runtime.GOOS, home)
}
// chromeInstallPathsFor lists a platform's default install locations, in
// preference order. The home directory is a parameter rather than a lookup
// because os.UserHomeDir switches on the host's GOOS, which would make this
// depend on where it runs as well as on goos.
func chromeInstallPathsFor(goos, home string) []string {
switch goos {
case "darwin":
var out []string
// A drag-install by a user without admin rights lands in ~/Applications,
// not /Applications.
dirs := []string{"/Applications"}
if home != "" {
dirs = append(dirs, filepath.Join(home, "Applications"))
}
for _, base := range dirs {
for _, bundle := range []string{
"Google Chrome", "Chromium", "Microsoft Edge",
"Brave Browser", "Vivaldi", "Arc", "Opera",
} {
out = append(out, filepath.Join(base, bundle+".app", "Contents", "MacOS", bundle))
}
}
return out
case "windows":
var out []string
for _, env := range []string{"ProgramFiles", "ProgramFiles(x86)", "LocalAppData"} {
base := os.Getenv(env)
if base == "" {
continue
}
out = append(out,
filepath.Join(base, `Google\Chrome\Application\chrome.exe`),
filepath.Join(base, `Chromium\Application\chrome.exe`),
filepath.Join(base, `Microsoft\Edge\Application\msedge.exe`),
filepath.Join(base, `BraveSoftware\Brave-Browser\Application\brave.exe`),
filepath.Join(base, `Vivaldi\Application\vivaldi.exe`),
)
}
return out
default: // linux, *bsd
return []string{
"/usr/bin/google-chrome", "/usr/bin/google-chrome-stable",
"/opt/google/chrome/chrome",
"/usr/bin/chromium", "/usr/bin/chromium-browser", "/snap/bin/chromium",
"/usr/bin/brave-browser", "/usr/bin/brave", "/opt/brave.com/brave/brave",
"/usr/bin/microsoft-edge", "/usr/bin/microsoft-edge-stable",
"/opt/microsoft/msedge/msedge",
"/usr/bin/vivaldi", "/usr/bin/vivaldi-stable", "/opt/vivaldi/vivaldi",
"/usr/bin/opera", "/usr/local/bin/chrome", "/usr/local/bin/chromium",
}
}
}
// captureTokenFromBrowser launches a visible browser at discord.com/login, waits
// for the user to sign in, and lifts the Authorization header off the first
// authenticated Discord API request. The password is typed into the real
// browser, never through this process, and a throwaway profile keeps the
// user's real browser profile untouched. Honors ctx for cancellation.
func captureTokenFromBrowser(ctx context.Context) (string, error) {
chromePath := findChrome()
if chromePath == "" {
return "", errNoChrome
}
profile, err := os.MkdirTemp("", "discord-delete-signin-*")
if err != nil {
return "", fmt.Errorf("create temp profile: %w", err)
}
defer os.RemoveAll(profile)
opts := append([]chromedp.ExecAllocatorOption{}, chromedp.DefaultExecAllocatorOptions[:]...)
// Keep enable-automation as it blocks password saving.
opts = append(opts,
chromedp.ExecPath(chromePath),
chromedp.Flag("headless", false),
chromedp.Flag("hide-scrollbars", false),
chromedp.Flag("mute-audio", false),
chromedp.UserDataDir(profile),
)
allocCtx, cancelAlloc := chromedp.NewExecAllocator(ctx, opts...)
defer cancelAlloc()
browserCtx, cancelBrowser := chromedp.NewContext(allocCtx)
defer cancelBrowser()
tokenCh := make(chan string, 1)
chromedp.ListenTarget(browserCtx, func(ev any) {
e, ok := ev.(*network.EventRequestWillBeSent)
if !ok || e.Request == nil {
return
}
if !strings.Contains(e.Request.URL, "discord.com/api") {
return
}
if auth := userAuthHeader(e.Request.Headers); auth != "" {
select {
case tokenCh <- auth:
default:
}
}
})
if err := chromedp.Run(browserCtx,
network.Enable(),
chromedp.Navigate("https://discord.com/login"),
); err != nil {
return "", launchError(chromePath, err)
}
select {
case tok := <-tokenCh:
return tok, nil
case <-browserCtx.Done():
// The user closed the window, or our context was cancelled.
return "", context.Canceled
case <-ctx.Done():
return "", ctx.Err()
}
}
// userAuthHeader returns a plausible Discord *user* token from request headers
// (case-insensitive key), skipping bot ("Bot …") and OAuth ("Bearer …") values.
func userAuthHeader(h network.Headers) string {
for k, v := range h {
if !strings.EqualFold(k, "authorization") {
continue
}
s, ok := v.(string)
if !ok {
continue
}
s = strings.TrimSpace(s)
low := strings.ToLower(s)
if s == "" || strings.HasPrefix(low, "bot ") || strings.HasPrefix(low, "bearer ") {
continue
}
return s
}
return ""
}
// launchError reports a failed launch, naming the binary that was tried: a bad
// DISCORD_DELETE_CHROME and a broken install need different fixes. findChrome
// has already resolved a path, so "no such file" in the wrapped message is
// Chrome's stderr about a shared library, not an absent browser.
func launchError(path string, err error) error {
// The hint goes last so browserErrLine's tail-first truncation keeps it.
if kind := sandboxKind(path); kind != "" {
return fmt.Errorf("browser at %s failed to start: %w; %s builds cannot read the sign-in profile in %s, so point DISCORD_DELETE_CHROME at a browser installed outside a sandbox",
path, err, kind, os.TempDir())
}
return fmt.Errorf("browser at %s failed to start: %w", path, err)
}
// browserErrLine condenses err into a single status line. chromedp includes all
// of Chrome's stderr, which is multi-line and front-loaded with unrelated
// warnings, so truncation keeps the tail.
func browserErrLine(err error) string {
s := strings.Join(strings.Fields(err.Error()), " ")
const max = 200
if r := []rune(s); len(r) > max {
return "…" + string(r[len(r)-max+1:])
}
return s
}