dion: add email/password to fix cookie expiration
This commit is contained in:
1 parent
a7b7fba0a6
commit
6c732f34e3
12 files changed
+388
-63
No files matched your search
@@ -49,6 +49,11 @@
|
||||
<div class="headless-start-error" id="headlessStartError"></div>
|
||||
<button class="headless-start-btn" id="btnHeadlessJoin">Join existing</button>
|
||||
</div>
|
||||
<div class="headless-start-card" id="headlessDionAccountCard" style="display:none">
|
||||
<div class="headless-start-card-title">DION account</div>
|
||||
<div class="headless-start-card-desc">Store an email and password so the session renews itself and never asks for a browser login.</div>
|
||||
<button class="headless-start-btn" id="btnDionAccount">Edit credentials</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="headless-status" id="headlessStatus">Starting...</div>
|
||||
<div class="headless-call-info" id="headlessCallInfo">
|
||||
@@ -110,6 +115,20 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="popup-overlay" id="dionAccountPopup">
|
||||
<div class="popup">
|
||||
<h2>DION account</h2>
|
||||
<label for="dionEmail">Email</label>
|
||||
<input type="text" id="dionEmail" placeholder="you@example.com">
|
||||
<label for="dionPassword">Password</label>
|
||||
<input type="text" id="dionPassword" placeholder="">
|
||||
<div class="clear-cookies-status" id="dionAccountStatus"></div>
|
||||
<div class="popup-buttons">
|
||||
<button class="btn-cancel" id="btnDionAccountCancel">Cancel</button>
|
||||
<button class="btn-save" id="btnDionAccountSave">Save</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="popup-overlay" id="errorPopup">
|
||||
<div class="popup" style="padding:16px">
|
||||
<h2 class="error-title">Bot error</h2>
|
||||
|
||||
@@ -61,6 +61,8 @@ export enum IPC {
|
||||
SET_UPSTREAM_PROXY = 'set-upstream-proxy',
|
||||
SET_DEBUG_LOGGING = 'set-debug-logging',
|
||||
CLEAR_COOKIES = 'clear-cookies',
|
||||
GET_DION_CREDENTIALS = 'get-dion-credentials',
|
||||
SET_DION_CREDENTIALS = 'set-dion-credentials',
|
||||
EXPORT_COOKIES_ZIP = 'export-cookies-zip',
|
||||
RELAY_LOG = 'relay-log',
|
||||
CREATE_BOT_TAB = 'create-bot-tab',
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import * as fs from 'fs/promises';
|
||||
import { CookieFileContent, DionCredentials } from '../types';
|
||||
import { DION_AUTH_COOKIE } from '../constants';
|
||||
|
||||
export class DionCookieFile {
|
||||
private filePath: string;
|
||||
|
||||
constructor(filePath: string) {
|
||||
this.filePath = filePath;
|
||||
}
|
||||
|
||||
async hasSession(): Promise<boolean> {
|
||||
const content = await this.readContent();
|
||||
if (!content) return false;
|
||||
if (content.email && content.password) return true;
|
||||
return content.cookies.some((cookie) => cookie.name === DION_AUTH_COOKIE && !!cookie.value);
|
||||
}
|
||||
|
||||
async readCredentials(): Promise<DionCredentials> {
|
||||
const content = await this.readContent();
|
||||
return { email: content?.email || '', password: content?.password || '' };
|
||||
}
|
||||
|
||||
async writeCredentials(email: string, password: string): Promise<void> {
|
||||
const content = await this.readContent();
|
||||
const updated: CookieFileContent = {
|
||||
email: email || undefined,
|
||||
password: password || undefined,
|
||||
cookies: content?.cookies || [],
|
||||
};
|
||||
await fs.writeFile(this.filePath, JSON.stringify(updated));
|
||||
}
|
||||
|
||||
async clearTokens(): Promise<void> {
|
||||
const content = await this.readContent();
|
||||
if (!content) return;
|
||||
if (!content.email || !content.password) {
|
||||
await fs.unlink(this.filePath).catch(() => {});
|
||||
return;
|
||||
}
|
||||
const credentialsOnly: CookieFileContent = {
|
||||
email: content.email,
|
||||
password: content.password,
|
||||
cookies: [],
|
||||
};
|
||||
await fs.writeFile(this.filePath, JSON.stringify(credentialsOnly));
|
||||
}
|
||||
|
||||
async readContent(): Promise<CookieFileContent | null> {
|
||||
try {
|
||||
const raw = await fs.readFile(this.filePath, 'utf8');
|
||||
const parsed = JSON.parse(raw);
|
||||
if (Array.isArray(parsed)) return { cookies: parsed };
|
||||
return {
|
||||
email: typeof parsed.email === 'string' ? parsed.email : undefined,
|
||||
password: typeof parsed.password === 'string' ? parsed.password : undefined,
|
||||
cookies: Array.isArray(parsed.cookies) ? parsed.cookies : [],
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -98,6 +98,14 @@ export function registerIpcHandlers(tabManager: TabManager): void {
|
||||
return tabManager.clearPlatformCookies(platform as Platform);
|
||||
});
|
||||
|
||||
ipcMain.handle(IPC.GET_DION_CREDENTIALS, () => {
|
||||
return tabManager.getDionCredentials();
|
||||
});
|
||||
|
||||
ipcMain.handle(IPC.SET_DION_CREDENTIALS, (_e, email: string, password: string) => {
|
||||
return tabManager.setDionCredentials(email, password);
|
||||
});
|
||||
|
||||
ipcMain.handle(IPC.SEND_BOT_CALL_LINK, (_e, tabId: string, link: string) => {
|
||||
tabManager.sendBotCallLink(tabId, link);
|
||||
});
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
HeadlessStartArgs,
|
||||
HeadlessMode,
|
||||
UpstreamProxy,
|
||||
DionCredentials,
|
||||
} from '../types';
|
||||
import {
|
||||
INITIAL_PORT_BASE,
|
||||
@@ -36,6 +37,7 @@ import {
|
||||
LOG_CAPTURE_SNIPPET,
|
||||
} from '../constants';
|
||||
import { BotManager } from '../bot/bot-manager';
|
||||
import { DionCookieFile } from './dion-cookie-file';
|
||||
import { buildStoredZip } from './util/zip';
|
||||
import { resolveResourcePath, binaryName } from './util/paths';
|
||||
|
||||
@@ -336,9 +338,12 @@ export class TabManager {
|
||||
return;
|
||||
}
|
||||
tab.tunnelMode = config.tunnelMode;
|
||||
let cookies = await this.getCookiesForDomains(config.cookieDomains);
|
||||
const cookiesPath = this.cookieFilePath(platform);
|
||||
const refreshCookie = platform === Platform.WBStream ? 'wbx-refresh' : config.authCookie;
|
||||
const needsLogin = !cookies.some((c) => c.name === refreshCookie);
|
||||
const dionCookieFile = platform === Platform.Dion ? new DionCookieFile(cookiesPath) : null;
|
||||
const fileHasSession = dionCookieFile != null && await dionCookieFile.hasSession();
|
||||
let cookies = await this.getCookiesForDomains(config.cookieDomains);
|
||||
const needsLogin = !fileHasSession && !cookies.some((c) => c.name === refreshCookie);
|
||||
if (needsLogin) {
|
||||
if (tab.isBot) {
|
||||
const reply = `Please log into ${config.platformName} in the creator app first, then try again.`;
|
||||
@@ -367,9 +372,12 @@ export class TabManager {
|
||||
this.sendLog(tabId, `${config.platformName} login captured.`);
|
||||
cookies = await this.getCookiesForDomains(config.cookieDomains);
|
||||
}
|
||||
this.sendLog(tabId, `${config.platformName} cookies (${cookies.length}): ${cookies.map((c) => c.name).join(', ')}`);
|
||||
const cookiesPath = path.join(app.getPath('userData'), `cookies-${platform}.json`);
|
||||
await fs.writeFile(cookiesPath, JSON.stringify(cookies));
|
||||
if (fileHasSession) {
|
||||
this.sendLog(tabId, `${config.platformName} session file is still active, keeping it as is.`);
|
||||
} else {
|
||||
this.sendLog(tabId, `${config.platformName} cookies (${cookies.length}): ${cookies.map((c) => c.name).join(', ')}`);
|
||||
await fs.writeFile(cookiesPath, JSON.stringify(cookies));
|
||||
}
|
||||
const spawnArgs = ['--resources', 'default', '--cookies', cookiesPath];
|
||||
this.killRelay(tabId, tab);
|
||||
if (joinTarget) {
|
||||
@@ -383,7 +391,11 @@ export class TabManager {
|
||||
});
|
||||
tab.relay = proc;
|
||||
let sawAuthFailure = false;
|
||||
let sawInvalidCredentials = false;
|
||||
this.attachProcessOutput(proc, tabId, (msg) => {
|
||||
if (dionCookieFile && (msg.includes('"code":1086') || msg.includes('Invalid credentials'))) {
|
||||
sawInvalidCredentials = true;
|
||||
}
|
||||
if (
|
||||
msg.includes('status 401') ||
|
||||
msg.includes('"UnauthorizedError"') ||
|
||||
@@ -395,7 +407,12 @@ export class TabManager {
|
||||
});
|
||||
proc.on('close', async (code) => {
|
||||
this.sendLog(tabId, `Headless exited with code ${code}`);
|
||||
if (sawInvalidCredentials) {
|
||||
this.sendLog(tabId, `${config.platformName} rejected the email and password stored in ${cookiesPath}, fix them or clear cookies to log in through the browser.`);
|
||||
return;
|
||||
}
|
||||
if (sawAuthFailure) {
|
||||
if (dionCookieFile) await dionCookieFile.clearTokens();
|
||||
await this.clearAuthCookies(config.cookieDomains, config.authCookie);
|
||||
if (this.tabs.get(tabId) === tab) this.startHeadless(tabId, platform, args);
|
||||
}
|
||||
@@ -417,6 +434,18 @@ export class TabManager {
|
||||
}
|
||||
}
|
||||
|
||||
private cookieFilePath(platform: Platform): string {
|
||||
return path.join(app.getPath('userData'), `cookies-${platform}.json`);
|
||||
}
|
||||
|
||||
async getDionCredentials(): Promise<DionCredentials> {
|
||||
return new DionCookieFile(this.cookieFilePath(Platform.Dion)).readCredentials();
|
||||
}
|
||||
|
||||
async setDionCredentials(email: string, password: string): Promise<void> {
|
||||
await new DionCookieFile(this.cookieFilePath(Platform.Dion)).writeCredentials(email, password);
|
||||
}
|
||||
|
||||
async clearPlatformCookies(platform: Platform): Promise<number> {
|
||||
const config = this.headlessConfig(platform);
|
||||
if (!config) return 0;
|
||||
@@ -434,7 +463,7 @@ export class TabManager {
|
||||
console.log(`[COOKIES] failed to remove ${cookie.name} on ${url}:`, err);
|
||||
}
|
||||
}
|
||||
await fs.unlink(path.join(app.getPath('userData'), `cookies-${platform}.json`)).catch(() => {});
|
||||
await fs.unlink(this.cookieFilePath(platform)).catch(() => {});
|
||||
console.log(`[COOKIES] cleared ${removed} cookies for ${platform}`);
|
||||
return removed;
|
||||
}
|
||||
@@ -549,17 +578,18 @@ export class TabManager {
|
||||
}
|
||||
|
||||
async buildCookiesZip(): Promise<Buffer> {
|
||||
const platforms: { filename: string; domains: string[] }[] = [
|
||||
{ filename: 'cookies-vk.json', domains: VK_COOKIE_DOMAINS },
|
||||
{ filename: 'cookies-yandex.json', domains: YANDEX_COOKIE_DOMAINS },
|
||||
{ filename: 'cookies-dion.json', domains: DION_COOKIE_DOMAINS },
|
||||
{ filename: 'cookies-wbstream.json', domains: WBSTREAM_COOKIE_DOMAINS },
|
||||
const platforms: { filename: string; domains: string[]; platform: Platform }[] = [
|
||||
{ filename: 'cookies-vk.json', domains: VK_COOKIE_DOMAINS, platform: Platform.VK },
|
||||
{ filename: 'cookies-yandex.json', domains: YANDEX_COOKIE_DOMAINS, platform: Platform.Telemost },
|
||||
{ filename: 'cookies-dion.json', domains: DION_COOKIE_DOMAINS, platform: Platform.Dion },
|
||||
{ filename: 'cookies-wbstream.json', domains: WBSTREAM_COOKIE_DOMAINS, platform: Platform.WBStream },
|
||||
];
|
||||
const cookies = await Promise.all(platforms.map((p) => this.getCookiesForDomains(p.domains)));
|
||||
const entries = platforms.map((p, i) => ({
|
||||
name: p.filename,
|
||||
data: Buffer.from(JSON.stringify(cookies[i], null, 2), 'utf8'),
|
||||
}));
|
||||
const dionContent = await new DionCookieFile(this.cookieFilePath(Platform.Dion)).readContent();
|
||||
const entries = platforms.map((p, i) => {
|
||||
const content = p.platform === Platform.Dion && dionContent ? dionContent : cookies[i];
|
||||
return { name: p.filename, data: Buffer.from(JSON.stringify(content, null, 2), 'utf8') };
|
||||
});
|
||||
return buildStoredZip(entries);
|
||||
}
|
||||
|
||||
|
||||
@@ -32,6 +32,12 @@ import { IPC } from '../constants';
|
||||
clearCookies(platform: string) {
|
||||
return ipcRenderer.invoke(IPC.CLEAR_COOKIES, platform);
|
||||
},
|
||||
getDionCredentials() {
|
||||
return ipcRenderer.invoke(IPC.GET_DION_CREDENTIALS);
|
||||
},
|
||||
setDionCredentials(email: string, password: string) {
|
||||
return ipcRenderer.invoke(IPC.SET_DION_CREDENTIALS, email, password);
|
||||
},
|
||||
onCreateBotTab(cb: (data: any) => void) {
|
||||
ipcRenderer.on(IPC.CREATE_BOT_TAB, (_e, data) => cb(data));
|
||||
},
|
||||
|
||||
@@ -68,6 +68,8 @@ export function renderContent(tm: RendererTabManager): void {
|
||||
targetInput.value = activeTab.headlessStartTarget || '';
|
||||
targetInput.classList.remove('invalid');
|
||||
errorEl.textContent = '';
|
||||
const dionAccountCard = document.getElementById('headlessDionAccountCard')!;
|
||||
dionAccountCard.style.display = activeTab.platform === Platform.Dion ? '' : 'none';
|
||||
if (activeTab.platform === Platform.WBStream) {
|
||||
targetLabel.textContent = 'Paste a room id or stream.wb.ru/room/<id> link.';
|
||||
targetInput.placeholder = 'https://stream.wb.ru/room/<id>';
|
||||
|
||||
@@ -108,6 +108,41 @@ function bindSettingsEvents(): void {
|
||||
});
|
||||
}
|
||||
|
||||
function bindDionAccountEvents(): void {
|
||||
document.getElementById('btnDionAccount')!.addEventListener('click', openDionAccount);
|
||||
document.getElementById('dionAccountPopup')!.addEventListener('click', closeDionAccount);
|
||||
document.querySelector('#dionAccountPopup .popup')!.addEventListener('click', (event) => event.stopPropagation());
|
||||
document.getElementById('btnDionAccountCancel')!.addEventListener('click', closeDionAccount);
|
||||
document.getElementById('btnDionAccountSave')!.addEventListener('click', async () => {
|
||||
const email = (document.getElementById('dionEmail') as HTMLInputElement).value.trim();
|
||||
const password = (document.getElementById('dionPassword') as HTMLInputElement).value;
|
||||
const status = document.getElementById('dionAccountStatus')!;
|
||||
try {
|
||||
await window.bridge.setDionCredentials(email, password);
|
||||
closeDionAccount();
|
||||
} catch {
|
||||
status.textContent = 'Failed to save the credentials.';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function openDionAccount(): Promise<void> {
|
||||
const status = document.getElementById('dionAccountStatus')!;
|
||||
status.textContent = '';
|
||||
document.getElementById('dionAccountPopup')!.classList.add('visible');
|
||||
try {
|
||||
const credentials = await window.bridge.getDionCredentials();
|
||||
(document.getElementById('dionEmail') as HTMLInputElement).value = credentials.email;
|
||||
(document.getElementById('dionPassword') as HTMLInputElement).value = credentials.password;
|
||||
} catch {
|
||||
status.textContent = 'Failed to read the session file.';
|
||||
}
|
||||
}
|
||||
|
||||
function closeDionAccount(): void {
|
||||
document.getElementById('dionAccountPopup')!.classList.remove('visible');
|
||||
}
|
||||
|
||||
function bindErrorPopup(): void {
|
||||
document.getElementById('errorPopup')!.addEventListener('click', closeError);
|
||||
document.querySelector('#errorPopup .popup')!.addEventListener('click', (event) => event.stopPropagation());
|
||||
@@ -189,6 +224,7 @@ function init(): void {
|
||||
bindToolbarEvents();
|
||||
bindActionBarEvents();
|
||||
bindSettingsEvents();
|
||||
bindDionAccountEvents();
|
||||
bindErrorPopup();
|
||||
bindLogEvents();
|
||||
bindHeadlessEvents();
|
||||
|
||||
@@ -71,6 +71,22 @@ export interface UpstreamProxy {
|
||||
pass: string;
|
||||
}
|
||||
|
||||
export interface CookieEntry {
|
||||
name: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
export interface CookieFileContent {
|
||||
email?: string;
|
||||
password?: string;
|
||||
cookies: CookieEntry[];
|
||||
}
|
||||
|
||||
export interface DionCredentials {
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface TabConfig {
|
||||
mode: TunnelMode;
|
||||
peerId: number;
|
||||
@@ -153,6 +169,8 @@ export interface Bridge {
|
||||
setUpstreamProxy(proxy: UpstreamProxy): Promise<void>;
|
||||
setDebugLogging(enabled: boolean): Promise<void>;
|
||||
clearCookies(platform: string): Promise<number>;
|
||||
getDionCredentials(): Promise<DionCredentials>;
|
||||
setDionCredentials(email: string, password: string): Promise<void>;
|
||||
onCreateBotTab(cb: (data: BotTabData) => void): void;
|
||||
getCallCreatorCode(scriptFile: string): Promise<string>;
|
||||
onBotError(cb: (msg: string) => void): void;
|
||||
|
||||
@@ -56,6 +56,12 @@ func main() {
|
||||
if err := auth.LoadCookiesFromFile(*cookiesPath); err != nil {
|
||||
log.Fatalf("[FATAL] LoadCookiesFromFile: %v", err)
|
||||
}
|
||||
if !auth.HasCredentials() && !auth.HasRefreshCookie() {
|
||||
log.Fatalf("[FATAL] %s has neither cookies nor credentials, add \"email\" and \"password\" fields to it", *cookiesPath)
|
||||
}
|
||||
if auth.HasCredentials() {
|
||||
log.Printf("[auth] credentials present, session will re-login automatically when the refresh token dies")
|
||||
}
|
||||
if err := auth.EnsureValidToken(); err != nil {
|
||||
log.Fatalf("[FATAL] EnsureValidToken: %v", err)
|
||||
}
|
||||
|
||||
+97
-2
@@ -18,6 +18,16 @@ import (
|
||||
|
||||
var ErrSessionExpired = errors.New("dion: session expired, re-login required")
|
||||
|
||||
var errLoginEndpointMissing = errors.New("dion: login endpoint not available")
|
||||
|
||||
const (
|
||||
accessCookieName = "vc-access-token"
|
||||
refreshCookieName = "vc-refresh-token"
|
||||
|
||||
loginClientsPath = "/v2/users/login/web"
|
||||
loginPlatformPath = "/platform/v2/auth/auth-providers/dion/login/password"
|
||||
)
|
||||
|
||||
const (
|
||||
refreshSkewSeconds = 60
|
||||
refreshMaxAttempts = 3
|
||||
@@ -30,6 +40,7 @@ const (
|
||||
APIClientsBase = "https://api-clients.dion.vc"
|
||||
WebBase = "https://dion.vc"
|
||||
Origin = "https://dion.vc"
|
||||
CookieDomain = "dion.vc"
|
||||
)
|
||||
|
||||
// ParseRoom accepts a bare room id, a dion://<id> link, or a
|
||||
@@ -72,6 +83,14 @@ type GuestAuthResponse struct {
|
||||
User GuestUser `json:"user"`
|
||||
}
|
||||
|
||||
type LoginResponse struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
AuthProvider string `json:"auth_provider"`
|
||||
IsAuthBySSO bool `json:"is_auth_by_sso"`
|
||||
User GuestUser `json:"user"`
|
||||
}
|
||||
|
||||
type EventInfo struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
@@ -101,6 +120,8 @@ type Session struct {
|
||||
UserID string
|
||||
SessionID string
|
||||
cookiesPath string
|
||||
email string
|
||||
password string
|
||||
refreshMu sync.Mutex
|
||||
}
|
||||
|
||||
@@ -220,12 +241,80 @@ func (s *Session) RegisterAnonymousGuest(eventID, displayName string) (*GuestAut
|
||||
return &auth, nil
|
||||
}
|
||||
|
||||
// LoginWithPassword exchanges credentials for a fresh token pair. The web
|
||||
// front-end posts to api-clients, and switches to the platform endpoint when
|
||||
// the DION_PLATFORM_COOKIE_AUTH_ENABLED toggle is on, so both are tried.
|
||||
func (s *Session) LoginWithPassword(email, password string) error {
|
||||
if email == "" || password == "" {
|
||||
return fmt.Errorf("login: email and password are required")
|
||||
}
|
||||
body, _ := json.Marshal(map[string]string{"email": email, "password": password})
|
||||
login, err := s.postLogin(APIClientsBase+loginClientsPath, body)
|
||||
if errors.Is(err, errLoginEndpointMissing) {
|
||||
login, err = s.postLogin(APIBase+loginPlatformPath, body)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.email = email
|
||||
s.password = password
|
||||
s.applyLoginResult(login)
|
||||
if s.cookiesPath != "" {
|
||||
if saveErr := s.SaveCookiesToFile(s.cookiesPath); saveErr != nil {
|
||||
return fmt.Errorf("login ok but save cookies failed: %w", saveErr)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Session) postLogin(target string, body []byte) (*LoginResponse, error) {
|
||||
req, err := http.NewRequest(http.MethodPost, target, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.setBaseHeaders(req, "")
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := s.HTTPClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("login: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusMethodNotAllowed {
|
||||
return nil, errLoginEndpointMissing
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
|
||||
return nil, fmt.Errorf("login: status %d: %s", resp.StatusCode, string(raw))
|
||||
}
|
||||
var login LoginResponse
|
||||
if err := json.Unmarshal(raw, &login); err != nil {
|
||||
return nil, fmt.Errorf("login decode: %w", err)
|
||||
}
|
||||
if login.AccessToken == "" {
|
||||
return nil, fmt.Errorf("login: empty access_token: %s", string(raw))
|
||||
}
|
||||
return &login, nil
|
||||
}
|
||||
|
||||
func (s *Session) applyLoginResult(login *LoginResponse) {
|
||||
s.AccessToken = login.AccessToken
|
||||
s.UserID = login.User.ID
|
||||
if exp, err := parseJWTExpiry(login.AccessToken); err == nil {
|
||||
s.AccessTokenExp = exp
|
||||
}
|
||||
if login.RefreshToken != "" {
|
||||
s.SetCookieInJar(refreshCookieName, login.RefreshToken)
|
||||
}
|
||||
s.SetCookieInJar(accessCookieName, login.AccessToken)
|
||||
}
|
||||
|
||||
func (s *Session) callRefreshOnce() (*GuestAuthResponse, error) {
|
||||
req, err := http.NewRequest(http.MethodPost, APIBase+"/platform/v1/auth/refresh/web", bytes.NewReader(nil))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.setBaseHeaders(req, s.AccessToken)
|
||||
s.setBaseHeaders(req, "")
|
||||
req.Header.Set("Content-Length", "0")
|
||||
|
||||
resp, err := s.HTTPClient.Do(req)
|
||||
@@ -256,7 +345,7 @@ func (s *Session) applyRefreshResult(auth *GuestAuthResponse) {
|
||||
if exp, err := parseJWTExpiry(auth.AccessToken); err == nil {
|
||||
s.AccessTokenExp = exp
|
||||
}
|
||||
s.SetCookieInJar("vc-access-token", auth.AccessToken)
|
||||
s.SetCookieInJar(accessCookieName, auth.AccessToken)
|
||||
}
|
||||
|
||||
// Refresh runs /auth/refresh/web with single-flight locking, retries on
|
||||
@@ -269,6 +358,9 @@ func (s *Session) Refresh() error {
|
||||
}
|
||||
|
||||
func (s *Session) refreshLocked() error {
|
||||
if !s.HasRefreshCookie() && s.HasCredentials() {
|
||||
return s.LoginWithPassword(s.email, s.password)
|
||||
}
|
||||
var lastErr error
|
||||
delay := refreshBaseDelay
|
||||
for attempt := 1; attempt <= refreshMaxAttempts; attempt++ {
|
||||
@@ -283,6 +375,9 @@ func (s *Session) refreshLocked() error {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, ErrSessionExpired) {
|
||||
if s.HasCredentials() {
|
||||
return s.LoginWithPassword(s.email, s.password)
|
||||
}
|
||||
return err
|
||||
}
|
||||
lastErr = err
|
||||
|
||||
+86
-46
@@ -16,26 +16,66 @@ type CookieEntry struct {
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
type CookieFile struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
Cookies []CookieEntry `json:"cookies"`
|
||||
}
|
||||
|
||||
func parseCookieFile(raw []byte) (CookieFile, error) {
|
||||
var file CookieFile
|
||||
if err := json.Unmarshal(raw, &file); err == nil {
|
||||
return file, nil
|
||||
}
|
||||
var entries []CookieEntry
|
||||
if err := json.Unmarshal(raw, &entries); err != nil {
|
||||
return CookieFile{}, fmt.Errorf("parse cookies: %w", err)
|
||||
}
|
||||
return CookieFile{Cookies: entries}, nil
|
||||
}
|
||||
|
||||
func (s *Session) LoadCookiesFromFile(path string) error {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read cookies: %w", err)
|
||||
}
|
||||
var entries []CookieEntry
|
||||
if err := json.Unmarshal(raw, &entries); err != nil {
|
||||
return fmt.Errorf("parse cookies: %w", err)
|
||||
file, err := parseCookieFile(raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.LoadCookies(entries); err != nil {
|
||||
if err := s.LoadCookies(file.Cookies); err != nil {
|
||||
return err
|
||||
}
|
||||
s.cookiesPath = path
|
||||
s.seedAccessTokenFromCookies(entries)
|
||||
s.email = strings.TrimSpace(file.Email)
|
||||
s.password = file.Password
|
||||
s.seedAccessTokenFromCookies(file.Cookies)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Session) HasCredentials() bool {
|
||||
return s.email != "" && s.password != ""
|
||||
}
|
||||
|
||||
func (s *Session) HasRefreshCookie() bool {
|
||||
if s.HTTPClient == nil || s.HTTPClient.Jar == nil {
|
||||
return false
|
||||
}
|
||||
web, err := url.Parse(WebBase)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for _, c := range s.HTTPClient.Jar.Cookies(web) {
|
||||
if c.Name == refreshCookieName && c.Value != "" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Session) seedAccessTokenFromCookies(entries []CookieEntry) {
|
||||
for _, entry := range entries {
|
||||
if entry.Name != "vc-access-token" || entry.Value == "" {
|
||||
if entry.Name != accessCookieName || entry.Value == "" {
|
||||
continue
|
||||
}
|
||||
exp, err := parseJWTExpiry(entry.Value)
|
||||
@@ -52,23 +92,17 @@ func (s *Session) SaveCookiesToFile(path string) error {
|
||||
if s.HTTPClient == nil || s.HTTPClient.Jar == nil {
|
||||
return fmt.Errorf("no cookiejar")
|
||||
}
|
||||
web, err := url.Parse(WebBase)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse target %s: %w", WebBase, err)
|
||||
}
|
||||
seen := make(map[string]string)
|
||||
for _, target := range []string{WebBase, APIBase, APIClientsBase} {
|
||||
parsed, err := url.Parse(target)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, c := range s.HTTPClient.Jar.Cookies(parsed) {
|
||||
if _, exists := seen[c.Name]; exists {
|
||||
continue
|
||||
}
|
||||
seen[c.Name] = c.Value
|
||||
}
|
||||
for _, c := range s.HTTPClient.Jar.Cookies(web) {
|
||||
seen[c.Name] = c.Value
|
||||
}
|
||||
if existing, err := os.ReadFile(path); err == nil {
|
||||
var prev []CookieEntry
|
||||
if json.Unmarshal(existing, &prev) == nil {
|
||||
for _, entry := range prev {
|
||||
if prev, err := parseCookieFile(existing); err == nil {
|
||||
for _, entry := range prev.Cookies {
|
||||
if _, exists := seen[entry.Name]; !exists {
|
||||
seen[entry.Name] = entry.Value
|
||||
}
|
||||
@@ -79,7 +113,16 @@ func (s *Session) SaveCookiesToFile(path string) error {
|
||||
for name, value := range seen {
|
||||
entries = append(entries, CookieEntry{Name: name, Value: value})
|
||||
}
|
||||
raw, err := json.MarshalIndent(entries, "", " ")
|
||||
var raw []byte
|
||||
if s.HasCredentials() {
|
||||
raw, err = json.MarshalIndent(CookieFile{
|
||||
Email: s.email,
|
||||
Password: s.password,
|
||||
Cookies: entries,
|
||||
}, "", " ")
|
||||
} else {
|
||||
raw, err = json.MarshalIndent(entries, "", " ")
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal cookies: %w", err)
|
||||
}
|
||||
@@ -97,14 +140,13 @@ func (s *Session) SetCookieInJar(name, value string) {
|
||||
if s.HTTPClient == nil || s.HTTPClient.Jar == nil {
|
||||
return
|
||||
}
|
||||
cookie := &http.Cookie{Name: name, Value: value, Path: "/"}
|
||||
for _, target := range []string{WebBase, APIBase, APIClientsBase} {
|
||||
parsed, err := url.Parse(target)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
s.HTTPClient.Jar.SetCookies(parsed, []*http.Cookie{cookie})
|
||||
web, err := url.Parse(WebBase)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.HTTPClient.Jar.SetCookies(web, []*http.Cookie{
|
||||
{Name: name, Value: value, Path: "/", Domain: CookieDomain},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Session) LoadCookieString(cookieStr string) error {
|
||||
@@ -135,25 +177,23 @@ func (s *Session) LoadCookies(entries []CookieEntry) error {
|
||||
}
|
||||
s.HTTPClient.Jar = jar
|
||||
}
|
||||
targets := []string{WebBase, APIBase, APIClientsBase}
|
||||
for _, target := range targets {
|
||||
u, err := url.Parse(target)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse target %s: %w", target, err)
|
||||
}
|
||||
cookies := make([]*http.Cookie, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
if entry.Name == "" {
|
||||
continue
|
||||
}
|
||||
cookies = append(cookies, &http.Cookie{
|
||||
Name: entry.Name,
|
||||
Value: entry.Value,
|
||||
Path: "/",
|
||||
})
|
||||
}
|
||||
s.HTTPClient.Jar.SetCookies(u, cookies)
|
||||
web, err := url.Parse(WebBase)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse target %s: %w", WebBase, err)
|
||||
}
|
||||
cookies := make([]*http.Cookie, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
if entry.Name == "" {
|
||||
continue
|
||||
}
|
||||
cookies = append(cookies, &http.Cookie{
|
||||
Name: entry.Name,
|
||||
Value: entry.Value,
|
||||
Path: "/",
|
||||
Domain: CookieDomain,
|
||||
})
|
||||
}
|
||||
s.HTTPClient.Jar.SetCookies(web, cookies)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user