// The Google sign-in that Google Voice requests ride on: a persistent Electron // session (cookies live in userData, outside the backed-up data folder, like // the voip.ms password). Chromium keeps the cookie jar, including the rotation // Google does through Set-Cookie, so we never handle most cookies ourselves. import { BrowserWindow, session, type Session } from 'electron' import { ORIGIN, USER_AGENT, type Transport } from './client' const PARTITION = 'persist:gvoice' const SIGN_IN_URL = 'https://voice.google.com/u/0/messages' let ses: Session | undefined export function gvSession(): Session { if (!ses) { ses = session.fromPartition(PARTITION) // Google turns away sign-ins from browsers that say they're Electron. ses.setUserAgent(USER_AGENT) // The API only answers requests from voice.google.com. fetch() won't let // us set Origin ourselves, so add it on the way out. ses.webRequest.onBeforeSendHeaders( { urls: ['https://clients6.google.com/*', 'https://*.clients6.google.com/*', 'https://voice.google.com/u/*'] }, (d, cb) => cb({ requestHeaders: d.requestHeaders['Origin'] ? d.requestHeaders : { ...d.requestHeaders, Origin: ORIGIN } }) ) } return ses } export function gvTransport(): Transport { return { fetch: (url, init) => gvSession().fetch(url, init), cookie: async (name) => { const jar = await gvSession().cookies.get({ domain: 'google.com' }) const find = (n: string): string | undefined => jar.find((c) => c.name === n)?.value // SAPISID and __Secure-3PAPISID carry the same value; Google sometimes // only sets the latter. return find(name) ?? (name === 'SAPISID' ? find('__Secure-3PAPISID') : undefined) } } } export async function hasGvSession(): Promise { return !!(await gvTransport().cookie('SAPISID')) } // Sign in with Google in a window of our own. Resolves once the sign-in // cookies exist and Google Voice has loaded; rejects if the window is closed. export function signInWindow(parent?: BrowserWindow): Promise { return new Promise((resolve, reject) => { const win = new BrowserWindow({ parent, width: 520, height: 720, title: 'Sign in to Google Voice', autoHideMenuBar: true, webPreferences: { partition: PARTITION, sandbox: true, contextIsolation: true, nodeIntegration: false } }) let done = false const check = async (): Promise => { if (done || win.isDestroyed()) return const url = win.webContents.getURL() if (url.startsWith('https://voice.google.com/') && (await hasGvSession())) { done = true clearInterval(timer) resolve() win.close() } } // Navigation events don't reliably fire as Google's pages hand off, so // also just look every second. const timer = setInterval(() => void check(), 1000) win.webContents.on('did-navigate', () => void check()) win.webContents.on('did-navigate-in-page', () => void check()) // Closing the window by hand once signed in counts as done too. win.on('closed', () => { clearInterval(timer) if (done) return void hasGvSession().then((ok) => (ok ? resolve() : reject(new Error('Sign-in was cancelled before it finished.')))) }) void win.loadURL(SIGN_IN_URL, { userAgent: USER_AGENT }) }) } // Fallback for when Google refuses to sign in inside the app: cookies copied // from a browser where you're signed in, as a "Copy as cURL" command, a raw // Cookie header, or a JSON object of name → value. export function parseCookies(input: string): Record { const text = input.trim() if (text.startsWith('{')) { const obj = JSON.parse(text) as Record return Object.fromEntries(Object.entries(obj).filter(([, v]) => typeof v === 'string')) as Record } let header = text const curl = /(?:-H|--header)\s+(['"])cookie:\s*(.*?)\1/is.exec(text) ?? /(?:-b|--cookie)\s+(['"])(.*?)\1/s.exec(text) if (curl) header = curl[2] else header = header.replace(/^cookie:\s*/i, '') const out: Record = {} for (const part of header.split(';')) { const eq = part.indexOf('=') if (eq <= 0) continue out[part.slice(0, eq).trim()] = part.slice(eq + 1).trim() } return out } export async function importCookies(cookies: Record): Promise { if (!cookies['SAPISID']) throw new Error("Those cookies don't include SAPISID. Copy a request to voice.google.com while signed in.") const jar = gvSession().cookies const expirationDate = Date.now() / 1000 + 365 * 86400 for (const [name, value] of Object.entries(cookies)) { // OSID belongs to voice.google.com itself; __Host- cookies can't carry a domain. const hostOnly = name === 'OSID' || name.startsWith('__Host-') await jar.set({ url: hostOnly ? 'https://voice.google.com' : 'https://google.com', ...(hostOnly ? {} : { domain: '.google.com' }), path: '/', name, value, secure: true, sameSite: 'no_restriction', expirationDate }) } await jar.flushStore() } // The sign-in cookies, for copying to the Rabbit's app. Domain-wide // (.google.com) cookies win over same-named host ones. export async function exportCookies(): Promise> { const jar = await gvSession().cookies.get({ domain: 'google.com' }) const out: Record = {} for (const c of [...jar].sort((a, b) => Number((a.domain ?? '').startsWith('.')) - Number((b.domain ?? '').startsWith('.')))) out[c.name] = c.value return out } export async function clearGvSession(): Promise { await gvSession().clearStorageData() }