Files
bubble/src/main/gvoice/session.ts
T
trav cde8cc6c55 v0.2.0: bubble for Android 0.2.0 — chat search, swipe for unread, faster chat opening
Desktop:
- Search lists chats whose own name matches first, so a named group
  isn't pushed out of the top 8 by chats that merely include a member.

Android (Rabbit R1) app, 0.2.0:
- Pull the chat list past its top for a search box (name, person,
  number, then group members; archived chats too; Back clears it).
- Swipe right to left marks a chat unread / read over a magenta band;
  left to right still archives (SwipeActions replaces SwipeArchive).
- Google Voice chats don't offer voice notes in the paperclip bubble.
- Chats open with their newest 60 messages, then the full history;
  marking read (and the Google Voice network call) waits until they're
  on screen. Cached pictures show at once, and one slow download no
  longer blocks the other images. Fixed a contacts reload race.
- Sandbox data gains filler chats, a named group and a 4,000-message chat.

Also: the Android app, Google Voice support, media, export, emoji and
the other work since the first commit, and a CLAUDE.md carrying the
privacy rule.
2026-11-06 02:19:56 -08:00

139 lines
5.6 KiB
TypeScript

// 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<boolean> {
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<void> {
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<void> => {
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<string, string> {
const text = input.trim()
if (text.startsWith('{')) {
const obj = JSON.parse(text) as Record<string, unknown>
return Object.fromEntries(Object.entries(obj).filter(([, v]) => typeof v === 'string')) as Record<string, string>
}
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<string, string> = {}
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<string, string>): Promise<void> {
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<Record<string, string>> {
const jar = await gvSession().cookies.get({ domain: 'google.com' })
const out: Record<string, string> = {}
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<void> {
await gvSession().clearStorageData()
}