diff --git a/packages/gcp-ai/README.md b/packages/gcp-ai/README.md index b8b0da5..e0460bc 100644 --- a/packages/gcp-ai/README.md +++ b/packages/gcp-ai/README.md @@ -90,6 +90,32 @@ If Console's ID cannot be read and the shown email differs, you can map the save **Credits don't match the billing page?** Promotional credits belong to the billing account and can be shared across projects, and the Console has billing latency. +**"Cannot tell which billing account project … uses"?** The project's billing page showed no billing account, or more than one. Name it per project, so each of your projects keeps its own: + +```json +{ "billingAccounts": { "my-project": "AAAAAA-BBBBBB-CCCCCC" } } +``` + +A project's entry wins over a row's `billingAccount` and `VERTEX_BILLING_ACCOUNT`, which apply to every project. + +**A billing account in yen?** The credits are read in US dollars unless the billing account is named as Japanese yen (USD and JPY are the two currencies read; nothing is converted): + +```json +{ "billingCurrencies": { "AAAAAA-BBBBBB-CCCCCC": "JPY" } } +``` + +A ¥ is never taken for yen on its own, since the Console writes Chinese yuan with the same sign: a ¥ table read as USD names the setting instead. Yen balances show as, for example, `¥8500 JPY`. + +**"The Cloud Console page was translated by Chrome" or "columns are not the English ones"?** The table is read by its English column names. Turn off translation for `console.cloud.google.com` in the plugin's Chrome profile (in the translate icon in the address bar: *Never translate this site*), and retry. + +**Several Chrome profiles in the plugin's profile folder?** Chrome opens the profile used last, so whose session a read uses can change when you switch profiles there. Pin the profile directory (its folder name inside the profile, such as `Default` or `Profile 1`), per Google account or for every account: + +```json +{ "profileDirectories": { "me@example.com": "Profile 1" }, "profileDirectory": "Default" } +``` + +These go in the `gcp-ai` provider's `options` or the plugin's options (the provider's win). A sign-in window opens in the directory `profileDirectory` names, since the account it signs in is not known yet. + ## Configuration | Environment variable | Default | @@ -97,6 +123,7 @@ If Console's ID cannot be read and the shown email differs, you can map the save | `GOOGLE_VERTEX_LOCATION` | `global` | | `VERTEX_BILLING_ACCOUNT` | Looked up from the project | | `VERTEX_CHROME_PROFILE` | `~/.config/gcp-auto-profile` | +| `VERTEX_CHROME_PROFILE_DIRECTORY` | None: Chrome's last-used profile; `profileDirectories` and `profileDirectory` win | | `VERTEX_CHROME_PATH` | Detected | | `VERTEX_GCLOUD_ACCOUNT` | The signed-in account | | `VERTEX_GCLOUD_AUTH_MODE` | `auto`; also `adc` or `gcloud` | diff --git a/packages/gcp-ai/index.mjs b/packages/gcp-ai/index.mjs index 9067635..978cfce 100644 --- a/packages/gcp-ai/index.mjs +++ b/packages/gcp-ai/index.mjs @@ -29,6 +29,15 @@ function settings(provider = {}, auth = {}) { location: auth.location || options.location || env.GOOGLE_VERTEX_LOCATION || "global", billingAccount: auth.billingAccount || options.billingAccount || env.VERTEX_BILLING_ACCOUNT, profile: auth.profile || options.profile || env.VERTEX_CHROME_PROFILE || defaultProfile(), + // A Chrome profile directory inside that profile ("Default", "Profile 1"), + // pinned so Chrome's last-used profile doesn't decide whose session a + // read uses; profileDirectories picks one per credential account. + profileDirectory: auth.profileDirectory || options.profileDirectory || env.VERTEX_CHROME_PROFILE_DIRECTORY, + profileDirectories: options.profileDirectories, + // Per project, the billing account its credits are read from; per billing + // account, the currency it bills in (USD unless named). + billingAccounts: options.billingAccounts, + billingCurrencies: options.billingCurrencies, // The credential selector: gcloud keeps an account's credentials under the // address it was signed in with, so it must not follow an email rename. account: auth.credentialAccount || auth.accountId || auth.account || options.account || env.VERTEX_GCLOUD_ACCOUNT, @@ -140,6 +149,7 @@ export const GoogleVertexAuthPlugin = async (input = {}, pluginOptions = {}) => // the plugin when to close it; the person never closes it themselves. async authorize() { const options = settings(configured) + options.profileDirectory ??= pluginOptions.profileDirectory const login = await startLogin(options) return { url: "", method: "auto", @@ -155,7 +165,7 @@ export const GoogleVertexAuthPlugin = async (input = {}, pluginOptions = {}) => // the hooks that were closed over before the sign-in still // resolve to the project and profile it used. configured = { ...configured, options: { ...(configured.options ?? {}), ...options } } - const record = { type: "success", access: "", refresh: "", expires: 0, source: "gcloud", authMode: identity.authMode, project: identity.project, billingAccount: options.billingAccount, profile: options.profile, creditsSession: identity.creditsSession } + const record = { type: "success", access: "", refresh: "", expires: 0, source: "gcloud", authMode: identity.authMode, project: identity.project, billingAccount: options.billingAccount, profile: options.profile, ...(options.profileDirectory ? { profileDirectory: options.profileDirectory } : {}), creditsSession: identity.creditsSession } // Each account's ADC lives in its own directory: without this // the next sign-in would resolve against another account's. if (identity.cloudsdkConfig) record.cloudsdkConfig = identity.cloudsdkConfig @@ -210,6 +220,10 @@ export const GoogleVertexAuthPlugin = async (input = {}, pluginOptions = {}) => if (!auth) return { error: "GCP AI is not signed in", signIn: "kept" } const options = settings(provider, auth) options.consoleAccountAliases ??= pluginOptions.consoleAccountAliases + options.profileDirectory ??= pluginOptions.profileDirectory + options.profileDirectories ??= pluginOptions.profileDirectories + options.billingAccounts ??= pluginOptions.billingAccounts + options.billingCurrencies ??= pluginOptions.billingCurrencies // Validated even when Google can confirm the email by subject. const mapped = consoleAccountFor(options.account, options.consoleAccountAliases) const aliased = mapped?.toLowerCase() !== options.account?.toLowerCase() diff --git a/packages/gcp-ai/lib/browser.mjs b/packages/gcp-ai/lib/browser.mjs index 8a5680b..52d0464 100644 --- a/packages/gcp-ai/lib/browser.mjs +++ b/packages/gcp-ai/lib/browser.mjs @@ -30,6 +30,24 @@ export const cacheRoot = () => process.env.XDG_CACHE_HOME || (process.platform === "win32" && process.env.LOCALAPPDATA ? process.env.LOCALAPPDATA : join(home(), ".cache")) export const defaultProfile = () => join(configRoot(), "gcp-auto-profile") + +// One Chrome user-data directory can hold several Chrome profiles ("Default", +// "Profile 1", …), each signed in to its own Google accounts. Without +// --profile-directory Chrome opens whichever one was used last, so switching +// profiles by hand changes whose cookies a credit read uses (kidchen94, +// #667). A profile directory named here is pinned for every window the +// plugin opens. It is a name inside the user-data directory, never a path. +export function validateProfileDirectory(value) { + if (value === undefined || value === null || value === "") return undefined + if (typeof value !== "string" || value.length > 255 || value !== value.trim() || /[\\/\0]/.test(value) || value === "." || value === ".." || value.startsWith("-")) { + throw new Error(`Invalid Chrome profile directory: ${JSON.stringify(value)}; use the folder's name inside the profile, such as "Default" or "Profile 1"`) + } + return value +} +const profileDirectoryArgs = (profileDirectory) => { + const name = validateProfileDirectory(profileDirectory) + return name ? [`--profile-directory=${name}`] : [] +} export const expandPath = (value) => resolve(value.startsWith("~/") ? join(home(), value.slice(2)) : value) export async function safeGoto(page, url, options = { waitUntil: "domcontentloaded", timeout: 60000 }) { @@ -223,9 +241,12 @@ async function stepAside(key, entry) { // the read is done and the browser stays, so the next account's read is a tab // rather than another Chrome — and it is closed once nothing has asked for a // while. Reads on one profile take turns; reads on different profiles do not. -export async function withPage({ profile = defaultProfile(), headless = true, javaScriptEnabled = true, launchArgs = [] } = {}, use) { +export async function withPage({ profile = defaultProfile(), profileDirectory, headless = true, javaScriptEnabled = true, launchArgs = [] } = {}, use) { const profilePath = expandPath(profile) - const key = JSON.stringify([profilePath, headless, javaScriptEnabled, launchArgs]) + profileDirectory = validateProfileDirectory(profileDirectory) + // A browser kept for one Chrome profile is never handed to a read that + // pinned another: it holds the other profile's cookies. + const key = JSON.stringify([profilePath, headless, javaScriptEnabled, launchArgs, ...(profileDirectory ? [profileDirectory] : [])]) return serialize(key, async () => { let entry = kept.get(key) if (entry) { @@ -239,7 +260,7 @@ export async function withPage({ profile = defaultProfile(), headless = true, ja } } if (!entry) { - const handle = await openBrowser({ profile: profilePath, headless, javaScriptEnabled, launchArgs }) + const handle = await openBrowser({ profile: profilePath, profileDirectory, headless, javaScriptEnabled, launchArgs }) entry = { handle, browser: handle.context, timer: null, watch: null, lockfile: profileLock(profilePath), takenAt: Date.now() } kept.set(key, entry) // A Chrome that ends on its own must not stay in the table. @@ -260,8 +281,11 @@ export async function withPage({ profile = defaultProfile(), headless = true, ja }) } -export async function openBrowser({ profile = defaultProfile(), headless = true, javaScriptEnabled = true, launchArgs = [] } = {}) { +export async function openBrowser({ profile = defaultProfile(), profileDirectory, headless = true, javaScriptEnabled = true, launchArgs = [] } = {}) { const profilePath = expandPath(profile) + // The lock stays the user-data directory's: Chrome runs one process per + // user-data directory, whichever of its profiles a window shows. + const pinned = profileDirectoryArgs(profileDirectory) await mkdir(profilePath, { recursive: true, mode: 0o700 }) let browser let downloadsPath @@ -279,7 +303,7 @@ export async function openBrowser({ profile = defaultProfile(), headless = true, // app may not be secure"), and a CDP-driven Chrome is exactly that. The // sign-in window is openSignInWindow below, which nothing drives. const args = [ - `--user-data-dir=${profilePath}`, + `--user-data-dir=${profilePath}`, ...pinned, "--no-first-run", "--no-default-browser-check", "--disable-background-networking", "--disable-sync", "--disable-default-apps", "--disable-component-update", "--disable-client-side-phishing-detection", @@ -339,8 +363,9 @@ export async function openBrowser({ profile = defaultProfile(), headless = true, // openTab hook also hands URLs to this window without attaching a client, for // a caller that has a page to put in front of the person in the window they // already have open. -export async function openSignInWindow({ profile = defaultProfile(), url, headless = false } = {}) { +export async function openSignInWindow({ profile = defaultProfile(), profileDirectory, url, headless = false } = {}) { const profilePath = expandPath(profile) + const pinned = profileDirectoryArgs(profileDirectory) await mkdir(profilePath, { recursive: true, mode: 0o700 }) const release = await claimProfile(profilePath) let downloadsPath @@ -351,7 +376,7 @@ export async function openSignInWindow({ profile = defaultProfile(), url, headle try { downloadsPath = await mkdtemp(join(tmpdir(), "vertex-signin-")) const args = [ - `--user-data-dir=${profilePath}`, + `--user-data-dir=${profilePath}`, ...pinned, "--no-first-run", "--no-default-browser-check", "--disable-background-networking", "--disable-sync", "--disable-default-apps", "--disable-component-update", "--disable-client-side-phishing-detection", @@ -398,7 +423,7 @@ export async function openSignInWindow({ profile = defaultProfile(), url, headle if (child.exitCode !== null || child.signalCode !== null) return false if (typeof tabUrl !== "string" || !/^(https?|file):\/\//i.test(tabUrl)) return false const helper = spawn(await chromeExecutable(), [ - `--user-data-dir=${profilePath}`, + `--user-data-dir=${profilePath}`, ...pinned, "--no-first-run", "--no-default-browser-check", ...(process.platform === "darwin" ? ["--use-mock-keychain"] : process.platform === "linux" ? ["--password-store=basic"] : []), tabUrl, diff --git a/packages/gcp-ai/lib/credentials.mjs b/packages/gcp-ai/lib/credentials.mjs index a815426..d314b67 100644 --- a/packages/gcp-ai/lib/credentials.mjs +++ b/packages/gcp-ai/lib/credentials.mjs @@ -708,7 +708,7 @@ export async function startLogin(options = {}, openWindow = openSignInWindow) { // URL. Its window stays open until ADC is saved and read; only then does // this plugin close it. It is closed below, in this block's finally, on // every path out of the sign-in. - window = openWindow({ profile: options.profile, url: signInUrl(consentUrl, registered), headless: false }) + window = openWindow({ profile: options.profile, profileDirectory: options.profileDirectory, url: signInUrl(consentUrl, registered), headless: false }) const signing = await window await new Promise((resolve, reject) => { const expiry = setTimeout(() => reject(stopped(`Google sign-in did not finish within ${Math.round(limit / 60000)} minutes; start the sign-in again and approve the consent page in the window that opens`)), limit) diff --git a/packages/gcp-ai/lib/credits.mjs b/packages/gcp-ai/lib/credits.mjs index 041d352..d0cc098 100644 --- a/packages/gcp-ai/lib/credits.mjs +++ b/packages/gcp-ai/lib/credits.mjs @@ -1,7 +1,7 @@ import { createHash } from "node:crypto" import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises" import { dirname, join } from "node:path" -import { assertConsoleSession, cacheRoot, defaultProfile, expandPath, extractConsoleIdentity, safeGoto, validateBillingAccount, validateProject, withPage } from "./browser.mjs" +import { assertConsoleSession, cacheRoot, defaultProfile, expandPath, extractConsoleIdentity, safeGoto, validateBillingAccount, validateProfileDirectory, validateProject, withPage } from "./browser.mjs" import { take } from "./lock.mjs" import { effectiveAuthMode, resolveProject, validateAccount } from "./credentials.mjs" @@ -10,11 +10,44 @@ const normalize = (value) => String(value ?? "").replace(/\s+/g, " ").trim() // about the account: they are remembered for a minute, not twenty. const NETWORK_FAILURE = /ERR_(?:TIMED_OUT|CONNECTION|NETWORK|INTERNET_DISCONNECTED|NAME_NOT_RESOLVED|NAME_RESOLUTION_FAILED|PROXY|TUNNEL|SSL|EMPTY_RESPONSE)|net::ERR_|timed out after|TimeoutError|ECONNRESET|ETIMEDOUT|ENOTFOUND|socket hang up/i const column = (headers, name) => headers.findIndex((h) => normalize(h).toLowerCase() === name) -const money = (value) => { +// The currencies a credit can be read in. A billing account is read in USD +// unless billingCurrencies names another one for it: the Console writes yen +// and yuan with the same ¥, so a currency is never guessed from a symbol +// (kidchen94, #667). Amounts are kept in the currency's minor unit and +// nothing is ever converted. +export const CURRENCIES = { + USD: { digits: 2, symbol: "$", marks: ["US$", "$"] }, + JPY: { digits: 0, symbol: "¥", marks: ["JP¥", "¥", "¥"] }, +} +const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") +// What an amount looks like in a currency, for telling the person which one +// the page shows when it isn't the one the billing account is read in. +const looksLike = (text) => { + if (/^(?:JP¥|JPY\b)|\bJPY$/.test(text)) return "JPY" + if (/^(?:US\$|USD\b)|\bUSD$/.test(text)) return "USD" + if (/^[¥¥]/.test(text)) return "¥" + if (/^\$/.test(text)) return "USD" +} +const money = (value, currency = "USD", billingAccount) => { const text = normalize(value) - const match = /^(?:US\$|\$|USD\s*)([\d,]+)(?:\.(\d{2}))?(?:\s*USD)?$/.exec(text) - if (!match) throw new Error(`Unsupported credit amount/currency: ${text}. This plugin requires USD billing.`) - return Number(match[1].replaceAll(",", "")) * 100 + Number(match[2] ?? 0) + const { digits, marks } = CURRENCIES[currency] + const mark = `(?:${marks.map(escape).join("|")}|${currency}\\s*)` + const number = `(\\d{1,3}(?:,\\d{3})+|\\d+)${digits ? `(?:\\.(\\d{${digits}}))?` : ""}` + const match = new RegExp(`^${mark}${number}(?:\\s*${currency})?$`).exec(text) ?? new RegExp(`^${number}\\s*${currency}$`).exec(text) + if (!match) { + const seen = looksLike(text) + const which = billingAccount ? `billing account ${billingAccount}` : "this billing account" + const set = (code) => `set billingCurrencies to { "${billingAccount ?? ""}": "${code}" }` + // A ¥ under JPY is yen written wrongly (a fraction, a bad grouping), not + // another currency. + if (seen && seen !== currency && !(seen === "¥" && CURRENCIES[currency].marks.includes("¥"))) { + throw new Error(seen === "¥" + ? `Credits read for ${which} are in ¥ (yen or yuan), not ${currency}. If it bills in Japanese yen, ${set("JPY")} in the gcp-ai options; other currencies are not supported` + : `Credits read for ${which} are in ${seen}, not ${currency}; ${set(seen)} in the gcp-ai options`) + } + throw new Error(`Unsupported credit amount/currency: ${text} (${which} is read in ${currency}; supported: ${Object.keys(CURRENCIES).join(", ")})`) + } + return Number(match[1].replaceAll(",", "")) * 10 ** digits + Number(match[2] ?? 0) } const isoDate = (value) => { const text = normalize(value) @@ -27,9 +60,12 @@ const isoDate = (value) => { // Column names are read from the rendered table, not token offsets or the // unrelated dollar amounts in overview widgets and expired-credit tooltips. -export function parseCreditTables(tables, { now = Date.now() } = {}) { +export function parseCreditTables(tables, { now = Date.now(), currency = "USD", billingAccount } = {}) { + if (!CURRENCIES[currency]) throw new Error(`Unsupported billing currency ${currency}; supported: ${Object.keys(CURRENCIES).join(", ")}`) + const unit = 10 ** CURRENCIES[currency].digits const credits = new Map() let recognized = false + const unread = [] // A credit's status is a small vocabulary that Google grows over time: a // credit that reads "Active" a month before its end date reads "Expiring in // 24 days" in the month of it. That wording is a fact about time rather @@ -43,7 +79,10 @@ export function parseCreditTables(tables, { now = Date.now() } = {}) { for (const table of tables) { const headers = table.headers.map(normalize) const indices = Object.fromEntries(["credit name", "status", "remaining value", "original value", "credit id", "start date", "end date", "usage scope"].map((name) => [name, column(headers, name)])) - if (["credit name", "status", "remaining value", "original value", "credit id"].some((name) => indices[name] < 0)) continue + if (["credit name", "status", "remaining value", "original value", "credit id"].some((name) => indices[name] < 0)) { + if (headers.filter(Boolean).length >= 3 && table.rows?.length) unread.push(headers.filter(Boolean)) + continue + } recognized = true for (const row of table.rows) { const cell = (name) => normalize(row[indices[name]]) @@ -52,26 +91,32 @@ export function parseCreditTables(tables, { now = Date.now() } = {}) { if (!known.includes(status) && !expiring) throw new Error(`Unknown Google Cloud credit status: ${cell("status")}`) const id = cell("credit id") if (!id || credits.has(id)) continue - const reported = money(cell("remaining value")) - const original = money(cell("original value")) + const reported = money(cell("remaining value"), currency, billingAccount) + const original = money(cell("original value"), currency, billingAccount) if (!Number.isSafeInteger(reported) || !Number.isSafeInteger(original) || reported < 0 || reported > original) throw new Error("Invalid Google Cloud credit amounts") const remaining = spent.includes(status) ? 0 : reported const start = isoDate(cell("start date")) const end = isoDate(cell("end date")) const eligible = (usable.includes(status) || expiring) && !(start && Date.parse(start) > now) && !(end && Date.parse(end) <= now) - credits.set(id, { id, name: cell("credit name"), status: cell("status"), remaining: remaining / 100, original: original / 100, start, end, scope: cell("usage scope"), eligible }) + credits.set(id, { id, name: cell("credit name"), status: cell("status"), remaining: remaining / unit, original: original / unit, start, end, scope: cell("usage scope"), eligible }) } } + // A table with rows whose columns aren't the English ones is a page in + // another language (Chrome's translation, or a Console that ignored hl=en), + // not a lapsed session: say what was there. + if (!recognized && unread.length) { + throw new Error(`The Cloud Console credits table's columns are not the English ones this plugin reads (it found: ${unread[0].slice(0, 6).join(", ")}); the page may have been translated or shown in another language. Turn off translation for console.cloud.google.com in the plugin's Chrome profile and retry`) + } if (!recognized || !credits.size) throw new Error("Google Cloud Credits table was not found or is empty; the session may be expired, the page may still be loading, or its layout changed") const active = [...credits.values()].filter((credit) => credit.eligible) - const remaining = active.reduce((sum, credit) => sum + Math.round(credit.remaining * 100), 0) - const original = active.reduce((sum, credit) => sum + Math.round(credit.original * 100), 0) + const remaining = active.reduce((sum, credit) => sum + Math.round(credit.remaining * unit), 0) + const original = active.reduce((sum, credit) => sum + Math.round(credit.original * unit), 0) const ends = active.filter((credit) => credit.remaining > 0 && credit.end).map((credit) => credit.end).sort() const soonest = ends[0] return { - currency: "USD", remaining: remaining / 100, original: original / 100, used: (original - remaining) / 100, + currency, remaining: remaining / unit, original: original / unit, used: (original - remaining) / unit, usedPercent: original > 0 ? ((original - remaining) * 100) / original : 100, - ...(soonest ? { runsOutAt: soonest, runsOut: active.filter((c) => c.end === soonest).reduce((s, c) => s + Math.round(c.remaining * 100), 0) / 100 } : {}), + ...(soonest ? { runsOutAt: soonest, runsOut: active.filter((c) => c.end === soonest).reduce((s, c) => s + Math.round(c.remaining * unit), 0) / unit } : {}), credits: [...credits.values()], fetchedAt: new Date(now).toISOString(), cached: false, } } @@ -92,7 +137,9 @@ export async function discoverBillingAccount(page, project, account) { await page.waitForFunction(() => /billing\/[0-9A-F]{6}-[0-9A-F]{6}-[0-9A-F]{6}/i.test(location.href) || [...document.querySelectorAll("a[href]")].some((a) => /\/billing\/[0-9A-F]{6}-[0-9A-F]{6}-[0-9A-F]{6}/i.test(a.href)), undefined, { timeout: 20000 }).catch((error) => { if (error.name !== "TimeoutError") throw error }) const urls = [await page.url(), ...(await page.evaluate(() => [...document.querySelectorAll("a[href]")].map((link) => link.href)) ?? [])] const accounts = [...new Set(urls.flatMap((url) => [...url.matchAll(/\/billing\/([0-9A-F]{6}-[0-9A-F]{6}-[0-9A-F]{6})(?:[/?#]|$)/gi)].map((m) => m[1])))] - if (accounts.length !== 1) throw new Error("Cannot uniquely identify the project's billing account; set VERTEX_BILLING_ACCOUNT explicitly") + if (accounts.length !== 1) { + throw new Error(`Cannot tell which billing account project ${project} uses (the Console showed ${accounts.length ? accounts.join(", ") : "none"}); set billingAccounts to { "${project}": "" } in the gcp-ai options`) + } return accounts[0] } @@ -155,6 +202,41 @@ export function consoleAccountFor(account, aliases) { return normalized.get(validateAccount(account).toLowerCase()) ?? account } +// The per-account and per-project maps a machine with several Google +// accounts needs, since one machine-wide variable would point every account at +// one value: which billing account a project's credits are read from, which +// currency a billing account bills in, and which Chrome profile directory +// holds an account's Console session. +function readMap(name, value, key, entry) { + const map = new Map() + if (value === undefined || value === null) return map + if (typeof value !== "object" || Array.isArray(value)) throw new Error(`${name} must be an object`) + for (const [k, v] of Object.entries(value)) { + let parsed + try { parsed = [key(k), entry(v)] } catch (error) { throw new Error(`${name}: ${error.message}`) } + if (map.has(parsed[0])) throw new Error(`Duplicate ${name} entry for ${parsed[0]}`) + map.set(...parsed) + } + return map +} +const billingAccountsOf = (value) => readMap("billingAccounts", value, (project) => validateProject(project), (account) => validateBillingAccount(account).toUpperCase()) +export const billingCurrenciesOf = (value) => readMap("billingCurrencies", value, (account) => validateBillingAccount(account).toUpperCase(), (currency) => { + const code = typeof currency === "string" ? currency.trim().toUpperCase() : "" + if (!CURRENCIES[code]) throw new Error(`${JSON.stringify(currency)} is not a currency this plugin reads (${Object.keys(CURRENCIES).join(", ")})`) + return code +}) +const profileDirectoriesOf = (value) => readMap("profileDirectories", value, (account) => validateAccount(account).toLowerCase(), (directory) => { + const name = validateProfileDirectory(directory) + if (!name) throw new Error("a profile directory cannot be empty") + return name +}) +const currencyOf = (currencies, billingAccount) => currencies.get(String(billingAccount ?? "").toUpperCase()) ?? "USD" + +// Chrome marks a page it translated on its root element. Such a page's table +// is words Chrome chose, not the Console's: it is never parsed. +const TRANSLATED = "The Cloud Console page was translated by Chrome, so its credits table can't be read; turn off translation for console.cloud.google.com in the plugin's Chrome profile and retry" +const translated = (page) => page.evaluate(() => location.origin === "https://console.cloud.google.com" && /\btranslated-(?:ltr|rtl)\b/.test(document.documentElement?.className ?? "")) + async function readPage(page, options) { // How long the Console is given to show the credits table. The first wait is // only a hint that the page has started answering: what decides the read is @@ -164,13 +246,19 @@ async function readPage(page, options) { const consoleAccount = options.consoleAccount const account = options.billingAccount ? validateBillingAccount(options.billingAccount) : await discoverBillingAccount(page, options.project, consoleAccount) const source = `https://console.cloud.google.com/billing/${account}/credits/all?hl=en${consoleAccount ? `&authuser=${encodeURIComponent(consoleAccount)}` : ""}` + const currency = currencyOf(options.currencies ?? billingCurrenciesOf(options.billingCurrencies), account) await safeGoto(page, source) - await page.waitForFunction(() => location.hostname === "accounts.google.com" || [...document.querySelectorAll("th, [role='columnheader']")].some((cell) => cell.innerText.trim() === "Remaining value"), undefined, { timeout: wait(45000) }).catch(() => {}) + await page.waitForFunction(() => location.hostname === "accounts.google.com" || /\btranslated-(?:ltr|rtl)\b/.test(document.documentElement?.className ?? "") || [...document.querySelectorAll("th, [role='columnheader']")].some((cell) => cell.innerText.trim() === "Remaining value"), undefined, { timeout: wait(45000) }).catch(() => {}) + if (await translated(page)) throw new Error(TRANSLATED) await assertConsoleSession(page, { timeout: wait(20000) }) // The table is the read: a page that never shows one is not a balance, and - // the error says which of the two waits ran out. - await page.waitForFunction(() => [...document.querySelectorAll("tbody tr, [role='row']")].some((row) => /\$\s*\d/.test(row.innerText)), undefined, { timeout: wait(30000) }) + // the error says which of the two waits ran out. A row is ready when its + // cells hold a number, in whatever currency: waiting for a "$" left a yen + // account waiting out the whole timeout before its currency was named. + await page.waitForFunction(() => /\btranslated-(?:ltr|rtl)\b/.test(document.documentElement?.className ?? "") + || [...document.querySelectorAll("tbody tr, [role='row']")].some((row) => row.querySelector("td, [role='gridcell'], [role='cell']") && /\d/.test(row.innerText)), undefined, { timeout: wait(30000) }) .catch(() => { throw new Error("Google Cloud Credits table was not found or is empty; the session may be expired, the page may still be loading, or its layout changed") }) + if (await translated(page)) throw new Error(TRANSLATED) const confirmed = await confirmAccount(page, consoleAccount, options.googleSubject) const tables = [] const seen = new Set() @@ -181,7 +269,7 @@ async function readPage(page, options) { seen.add(signature) tables.push(...next) if (!(await nextPage(page))) return { - ...parseCreditTables(tables), billingAccount: account, source, + ...parseCreditTables(tables, { currency, billingAccount: account }), billingAccount: account, source, ...(confirmed?.subject ? { googleSubject: confirmed.subject, consoleAccount: confirmed.account } : {}), } await page.waitForFunction((before) => { @@ -201,27 +289,40 @@ async function scrape(options) { // browser this process keeps for the profile, so a second account costs a // tab rather than another Chrome. if (options.browser) return readPage(options.browser.page, options) - return withPage({ profile: options.profile, headless: options.headless ?? true }, (page) => readPage(page, options)) + return withPage({ profile: options.profile, profileDirectory: options.profileDirectory, headless: options.headless ?? true }, (page) => readPage(page, options)) } const pending = new Map() export async function fetchCredits(options = {}) { + const billingAccounts = billingAccountsOf(options.billingAccounts) + const currencies = billingCurrenciesOf(options.billingCurrencies) + const profileDirectories = profileDirectoriesOf(options.profileDirectories) + const project = options.project ?? process.env.GOOGLE_VERTEX_PROJECT ?? process.env.GOOGLE_CLOUD_PROJECT const settings = { ...options, profile: options.profile ?? process.env.VERTEX_CHROME_PROFILE ?? defaultProfile(), - project: options.project ?? process.env.GOOGLE_VERTEX_PROJECT ?? process.env.GOOGLE_CLOUD_PROJECT, - billingAccount: options.billingAccount ?? process.env.VERTEX_BILLING_ACCOUNT, + project, + // The project's own entry beats a row-wide or machine-wide account. + billingAccount: (project && billingAccounts.get(project)) ?? options.billingAccount ?? process.env.VERTEX_BILLING_ACCOUNT, account: options.account ?? process.env.VERTEX_GCLOUD_ACCOUNT, + currencies, } if (settings.billingAccount) validateBillingAccount(settings.billingAccount) - else settings.project = await resolveProject(settings, undefined, await effectiveAuthMode(settings)) + else { + settings.project = await resolveProject(settings, undefined, await effectiveAuthMode(settings)) + if (settings.project && billingAccounts.has(settings.project)) settings.billingAccount = billingAccounts.get(settings.project) + } if (settings.project) validateProject(settings.project) if (settings.account) validateAccount(settings.account) const mapped = consoleAccountFor(settings.account, settings.consoleAccountAliases) settings.consoleAccount = mapped?.toLowerCase() !== settings.account?.toLowerCase() ? mapped : settings.consoleAccount || mapped if (settings.consoleAccount) validateAccount(settings.consoleAccount) + settings.profileDirectory = validateProfileDirectory( + profileDirectories.get(settings.account?.toLowerCase()) ?? profileDirectories.get(settings.consoleAccount?.toLowerCase()) + ?? options.profileDirectory ?? process.env.VERTEX_CHROME_PROFILE_DIRECTORY, + ) // The Chrome profile alone does not tell two Google accounts apart: one // profile can hold both, so each read also names the account whose cookies // it used (and, when it has one, that account's own ADC directory). @@ -232,6 +333,11 @@ export async function fetchCredits(options = {}) { // A subject-verified request must not reuse legacy email-only balances or // mismatch failures. Include the subject and validation version in its key. if (settings.googleSubject) identityParts.push({ googleSubject: settings.googleSubject, identityVersion: 2 }) + // Another Chrome profile is another session, and another currency another + // reading of the same page: neither may reuse what the other cached. Added + // only when set, so the caches of reads that set neither are kept. + if (settings.profileDirectory) identityParts.push({ profileDirectory: settings.profileDirectory }) + if (currencies.size) identityParts.push({ currencies: [...currencies].sort(([a], [b]) => a.localeCompare(b)) }) const identity = JSON.stringify(identityParts) const digest = createHash("sha256").update(identity).digest("hex").slice(0, 24) const file = join(cacheRoot(), "magpie", "gcp-ai", `credits-${digest}.json`) @@ -257,7 +363,7 @@ export async function fetchCredits(options = {}) { if (settings.force || !(age >= 0)) return undefined if (data.failedAt) return age < (transient(data) ? transientTtl : failureTtl) * 1000 ? { ...data, cached: false } : undefined const futureExpiry = !data.runsOutAt || Date.parse(data.runsOutAt) > Date.now() - if (age < ttl * 1000 && futureExpiry && data.currency === "USD" && Number.isFinite(data.remaining) && Number.isFinite(data.original) && Number.isFinite(data.usedPercent)) return { ...data, cached: true } + if (age < ttl * 1000 && futureExpiry && data.currency === currencyOf(currencies, data.billingAccount ?? settings.billingAccount) && Number.isFinite(data.remaining) && Number.isFinite(data.original) && Number.isFinite(data.usedPercent)) return { ...data, cached: true } } const failureTtl = Number(options.failureTtl ?? process.env.VERTEX_CREDITS_FAILURE_TTL ?? 1200) if (!Number.isFinite(failureTtl) || failureTtl < 0) throw new Error("VERTEX_CREDITS_FAILURE_TTL must be a nonnegative number of seconds") @@ -311,12 +417,15 @@ export async function fetchCredits(options = {}) { } export function usageOf(credits) { + const currency = CURRENCIES[credits.currency] ? credits.currency : "USD" + const { digits, symbol } = CURRENCIES[currency] + const amount = (value) => `${symbol}${value.toFixed(digits)}` return { - plan: "Google Cloud promotional credits", balance: `$${credits.remaining.toFixed(2)} USD`, signIn: "kept", + plan: "Google Cloud promotional credits", balance: `${amount(credits.remaining)} ${currency}`, signIn: "kept", windows: [{ name: "Promotional Credits", used: credits.usedPercent, - display: `$${credits.remaining.toFixed(2)} remaining / $${credits.original.toFixed(2)} USD${credits.cached ? " (cached)" : ""}`, - amount: credits.used, limit: credits.original, unit: "USD", + display: `${amount(credits.remaining)} remaining / ${amount(credits.original)} ${currency}${credits.cached ? " (cached)" : ""}`, + amount: credits.used, limit: credits.original, unit: currency, ...(credits.runsOutAt ? { runsOutAt: credits.runsOutAt, runsOut: credits.runsOut } : {}), }], } diff --git a/packages/gcp-ai/lib/fetch_credits.mjs b/packages/gcp-ai/lib/fetch_credits.mjs index 7c21a30..d675137 100644 --- a/packages/gcp-ai/lib/fetch_credits.mjs +++ b/packages/gcp-ai/lib/fetch_credits.mjs @@ -10,11 +10,11 @@ import { availableModels } from "./models.mjs" export async function main(args = process.argv.slice(2)) { const command = args[0] ?? "credits" if (command === "help" || args.includes("--help")) { - console.log("Usage: node lib/fetch_credits.mjs credits|credentials|login|models|endpoint|parse-html [--project ID] [--billing-account ID] [--profile PATH] [--cloudsdk-config DIR] [--force] [--headed] [--account EMAIL] [--auth-mode auto|gcloud|adc] [--location REGION] [--model ID] [--json] [--file HTML]") + console.log("Usage: node lib/fetch_credits.mjs credits|credentials|login|models|endpoint|parse-html [--project ID] [--billing-account ID] [--profile PATH] [--profile-directory NAME] [--currency USD|JPY] [--cloudsdk-config DIR] [--force] [--headed] [--account EMAIL] [--auth-mode auto|gcloud|adc] [--location REGION] [--model ID] [--json] [--file HTML]") return } if (!["credits", "credentials", "login", "models", "endpoint", "parse-html"].includes(command)) throw new Error(`Unknown command: ${command}`) - const valued = new Set(["--project", "--billing-account", "--profile", "--cloudsdk-config", "--account", "--auth-mode", "--file", "--location", "--model"]) + const valued = new Set(["--project", "--billing-account", "--profile", "--profile-directory", "--currency", "--cloudsdk-config", "--account", "--auth-mode", "--file", "--location", "--model"]) for (let i = 1; i < args.length; i++) { const option = args[i] if (valued.has(option)) { @@ -32,6 +32,7 @@ export async function main(args = process.argv.slice(2)) { project: value("--project") ?? process.env.GOOGLE_VERTEX_PROJECT ?? process.env.GOOGLE_CLOUD_PROJECT, billingAccount: value("--billing-account") ?? process.env.VERTEX_BILLING_ACCOUNT, profile: value("--profile") ?? process.env.VERTEX_CHROME_PROFILE ?? defaultProfile(), + profileDirectory: value("--profile-directory") ?? process.env.VERTEX_CHROME_PROFILE_DIRECTORY, account: value("--account") ?? process.env.VERTEX_GCLOUD_ACCOUNT, authMode: value("--auth-mode") ?? process.env.VERTEX_GCLOUD_AUTH_MODE, // Which ADC a command reads: a directory named here, else the plugin's own @@ -42,6 +43,13 @@ export async function main(args = process.argv.slice(2)) { location: value("--location") ?? process.env.GOOGLE_VERTEX_LOCATION ?? "global", force: args.includes("--force"), headless: !args.includes("--headed"), } + // --currency names the currency of the billing account given with + // --billing-account; without one, the account is read in USD. + const currency = value("--currency") + if (currency && command !== "parse-html") { + if (!options.billingAccount) throw new Error("--currency needs --billing-account") + options.billingCurrencies = { [options.billingAccount]: currency } + } if (command === "credits") { try { console.log(JSON.stringify(await fetchCredits(options), null, 2)) @@ -79,7 +87,7 @@ export async function main(args = process.argv.slice(2)) { const encoded = Buffer.from(html).toString("base64") await browser.page.send("Page.navigate", { url: `data:text/html;base64,${encoded}` }) await browser.page.waitForFunction(() => document.readyState !== "loading") - console.log(JSON.stringify(parseCreditTables(await readTables(browser.page)), null, 2)) + console.log(JSON.stringify(parseCreditTables(await readTables(browser.page), { currency: currency?.toUpperCase() ?? "USD", billingAccount: options.billingAccount }), null, 2)) } finally { await browser.close() } } } diff --git a/packages/gcp-ai/package.json b/packages/gcp-ai/package.json index 0446d8b..955d473 100644 --- a/packages/gcp-ai/package.json +++ b/packages/gcp-ai/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-gcp-ai-auth", - "version": "0.1.4", + "version": "0.1.5", "description": "Vertex AI models and Google Cloud promotional credits, signed with your own gcloud / ADC login", "type": "module", "main": "./opencode.mjs", diff --git a/packages/gcp-ai/test/browser.test.mjs b/packages/gcp-ai/test/browser.test.mjs index 6e10e08..117568d 100644 --- a/packages/gcp-ai/test/browser.test.mjs +++ b/packages/gcp-ai/test/browser.test.mjs @@ -378,3 +378,112 @@ test("a failed credit read is cached instead of opening a browser each poll", { await rm(directory, { recursive: true, force: true }) } }) + +// kidchen94's cases (#667), on a Console served from inside the test. Each +// read would have waited out its whole timeout on the old code and said the +// session may have expired; now it reads, or says what is wrong, at once. +async function consoleFixture(name, serve, use) { + const directory = await mkdtemp(join(tmpdir(), `vertex-browser-${name}-`)) + const previousCache = process.env.XDG_CACHE_HOME + let browser + try { + process.env.XDG_CACHE_HOME = directory + const profile = join(directory, "profile") + browser = await openBrowser({ profile, launchArgs }) + const paths = [] + await routeAll(browser.page, async (request) => { + const url = new URL(request.url()) + if (url.origin !== "https://console.cloud.google.com") return request.abort() + paths.push(url.pathname) + // The Console names the account it rendered for under its own key. + const shown = url.searchParams.get("authuser") + return request.fulfill({ body: `${shown ? `` : ""}${serve(url)}` }) + }) + return await use({ profile, browser, paths }) + } finally { + if (browser) await browser.close() + if (previousCache === undefined) delete process.env.XDG_CACHE_HOME + else process.env.XDG_CACHE_HOME = previousCache + await rm(directory, { recursive: true, force: true }) + } +} + +const creditsTable = (rows, { html = "", head = ["Credit name", "Status", "Remaining value", "Original value", "Credit ID"] } = {}) => ` + ${head.map((h) => ``).join("")} + ${rows.map((r) => `${r.map((c) => ``).join("")}`).join("")}
${h}
${c}
` + +test("a JPY billing account is read in yen, and read as USD it names its currency at once", { timeout: 60000, ...needsBrowser }, async () => { + await consoleFixture("jpy", () => creditsTable([["Trial", "Available", "¥8,500", "¥10,000", "one"]]), async ({ profile, browser }) => { + const options = { profile, browser, billingAccount: "AAAAAA-BBBBBB-CCCCCC", account: "reader@example.com", scrapeTimeout: 20000 } + const started = Date.now() + await assert.rejects(fetchCredits(options), /in ¥ \(yen or yuan\), not USD\. If it bills in Japanese yen, set billingCurrencies to \{ "AAAAAA-BBBBBB-CCCCCC": "JPY" \}/) + assert.ok(Date.now() - started < 15000, `the currency was named after ${Date.now() - started}ms, not at once`) + // Naming the currency is a different read: the remembered USD failure is + // not handed back for it. + const yen = await fetchCredits({ ...options, billingCurrencies: { "AAAAAA-BBBBBB-CCCCCC": "JPY" } }) + assert.equal(yen.currency, "JPY") + assert.equal(yen.remaining, 8500) + assert.equal(usageOf(yen).balance, "¥8500 JPY") + const cached = await fetchCredits({ ...options, billingCurrencies: { "AAAAAA-BBBBBB-CCCCCC": "JPY" } }) + assert.equal(cached.cached, true) + }) +}) + +test("a Console page Chrome translated is named as translated, not as an expired session", { timeout: 60000, ...needsBrowser }, async () => { + // Chrome marks the root of a page it translated and wraps the words it + // replaced in ; the amounts become words. + const font = (text) => `${text}` + const page = creditsTable([[font("試用"), font("利用可能"), font("8.50 米ドル"), font("10.00 米ドル"), "one"]], { + html: ' class="translated-ltr" lang="ja"', head: ["クレジット名", "ステータス", "残額", "元の値", "クレジット ID"].map(font), + }) + await consoleFixture("translated", () => page, async ({ profile, browser }) => { + const started = Date.now() + await assert.rejects(fetchCredits({ profile, browser, billingAccount: "AAAAAA-BBBBBB-CCCCCC", account: "reader@example.com", scrapeTimeout: 20000 }), /translated by Chrome/) + assert.ok(Date.now() - started < 15000, `the translation was named after ${Date.now() - started}ms, not at once`) + }) + // The same columns without Chrome's mark (a Console in another language) + // are named by what they say. + await consoleFixture("foreign", () => page.replace(' class="translated-ltr"', ""), async ({ profile, browser }) => { + await assert.rejects(fetchCredits({ profile, browser, billingAccount: "AAAAAA-BBBBBB-CCCCCC", account: "reader@example.com", scrapeTimeout: 3000 }), /columns are not the English ones this plugin reads \(it found: .*クレジット名/) + }) +}) + +test("billingAccounts picks a project's billing account, and an ambiguous project says which to set", { timeout: 60000, ...needsBrowser }, async () => { + const serve = (url) => url.pathname === "/billing/linkedaccount" + ? 'OneTwo' + : creditsTable([["Trial", "Available", "$4.00", "$10.00", url.pathname.split("/")[2]]]) + await consoleFixture("billing", serve, async ({ profile, browser, paths }) => { + await browser.page.goto("https://console.cloud.google.com/") + await assert.rejects(discoverBillingAccount(browser.page, "example-project"), /Cannot tell which billing account project example-project uses \(the Console showed AAAAAA-BBBBBB-CCCCCC, DDDDDD-EEEEEE-FFFFFF\); set billingAccounts to \{ "example-project": "" \}/) + // Mapped, the project's credits are read without asking the Console. + paths.length = 0 + const options = { profile, browser, project: "example-project", account: "reader@example.com", scrapeTimeout: 5000 } + const mapped = await fetchCredits({ ...options, billingAccounts: { "example-project": "dddddd-eeeeee-ffffff" } }) + assert.equal(mapped.billingAccount, "DDDDDD-EEEEEE-FFFFFF") + assert.equal(mapped.remaining, 4) + const read = paths.filter((path) => path !== "/favicon.ico") + assert.ok(read.length && read.every((path) => path === "/billing/DDDDDD-EEEEEE-FFFFFF/credits/all"), read.join(", ")) + }) +}) + +// One user-data directory holding several Chrome profiles: without +// --profile-directory, Chrome opens the one used last. +test("a pinned profile directory is the Chrome profile every read opens", { timeout: 60000, ...needsBrowser }, async () => { + const directory = await mkdtemp(join(tmpdir(), "vertex-browser-profile-dir-")) + try { + const profile = join(directory, "profile") + const seen = await withPage({ profile, profileDirectory: "Profile 1", launchArgs }, (page) => page.evaluate(() => "ok")) + assert.equal(seen, "ok") + await endKeptBrowsers() + const { readdir } = await import("node:fs/promises") + const entries = await readdir(profile) + assert.ok(entries.includes("Profile 1"), `Chrome used ${entries.filter((e) => /^(Default|Profile \d+)$/.test(e)).join(", ") || "no profile"}, not Profile 1`) + assert.ok(!entries.includes("Default"), "the unpinned Default profile was opened too") + for (const bad of ["../escape", "a/b", "-flag", ".."]) { + await assert.rejects(withPage({ profile, profileDirectory: bad, launchArgs }, async () => {}), /Invalid Chrome profile directory/) + } + } finally { + await endKeptBrowsers() + await rm(directory, { recursive: true, force: true }) + } +}) diff --git a/packages/gcp-ai/test/plugin.test.mjs b/packages/gcp-ai/test/plugin.test.mjs index 59c3bce..67f6ee2 100644 --- a/packages/gcp-ai/test/plugin.test.mjs +++ b/packages/gcp-ai/test/plugin.test.mjs @@ -11,7 +11,7 @@ import { EventEmitter } from "node:events" import { promisify } from "node:util" import { accountOf, adcDirectoryFor, adcDirectoryOwnedBy, adcDirectoryToCreate, adcFile, adcSlug, beginAdcLogin, command, effectiveAuthMode, gcloudProgram, hasAdc, resolveAccount, resolveIdentity, resolveProject, runGcloud, startLogin, tokenProvider, windowsCommand } from "../lib/credentials.mjs" import { fakeGcloud } from "./gcloud.mjs" -import { consoleAccountFor, parseCreditTables, usageOf } from "../lib/credits.mjs" +import { billingCurrenciesOf, consoleAccountFor, parseCreditTables, usageOf } from "../lib/credits.mjs" import { availableModels, toProviderModels } from "../lib/models.mjs" import { assertConsoleSession } from "../lib/browser.mjs" import { main } from "../lib/fetch_credits.mjs" @@ -80,6 +80,51 @@ test("credits fail closed on missing layout, unknown statuses, unsupported curre assert.equal(parseCreditTables([{ headers, rows: [row("a", "$10.00", "$10.00", "Expired")] }], { now }).remaining, 0) }) +// kidchen94's JPY billing account (#667): yen amounts have no minor unit, and +// a bare ¥ is never taken for yen unless the billing account is said to bill +// in JPY, since the Console writes yuan with the same sign. +test("a billing account named as JPY reads yen, and a ¥ is never guessed", () => { + const yen = (id, remaining, original = "¥10,000", status = "Available") => row(id, remaining, original, status) + const result = parseCreditTables([{ headers, rows: [yen("a", "¥8,500"), yen("b", "¥1,000"), yen("c", "JP¥0", "¥5,000", "Exhausted")] }], { now, currency: "JPY", billingAccount: "AAAAAA-BBBBBB-CCCCCC" }) + assert.equal(result.currency, "JPY") + assert.equal(result.remaining, 9500) + assert.equal(result.original, 25000) + const usage = usageOf(result) + assert.equal(usage.balance, "¥9500 JPY") + assert.equal(usage.windows[0].display, "¥9500 remaining / ¥25000 JPY") + assert.equal(usage.windows[0].unit, "JPY") + // The same page read as the default USD names the currency and the switch. + assert.throws(() => parseCreditTables([{ headers, rows: [yen("a", "¥8,500")] }], { now, billingAccount: "AAAAAA-BBBBBB-CCCCCC" }), + /in ¥ \(yen or yuan\), not USD\. If it bills in Japanese yen, set billingCurrencies to \{ "AAAAAA-BBBBBB-CCCCCC": "JPY" \}/) + // A USD page read as JPY is not taken as yen either. + assert.throws(() => parseCreditTables([{ headers, rows: [row("a", "$10.00")] }], { now, currency: "JPY", billingAccount: "AAAAAA-BBBBBB-CCCCCC" }), /are in USD, not JPY/) + // Yen has no fraction, and a misplaced group separator is not a number. + assert.throws(() => parseCreditTables([{ headers, rows: [yen("a", "¥8,500.50")] }], { now, currency: "JPY" }), /Unsupported credit amount/) + assert.throws(() => parseCreditTables([{ headers, rows: [row("a", "$1,00.00")] }], { now }), /Unsupported credit amount/) + assert.throws(() => parseCreditTables([{ headers, rows: [row("a", "$1.00")] }], { now, currency: "CNY" }), /Unsupported billing currency CNY/) + // USD reads as it did. + assert.equal(parseCreditTables([{ headers, rows: [row("a", "$1,234.56", "$2,000.00"), row("b", "USD 1.00"), row("c", "2.00 USD")] }], { now }).remaining, 1237.56) +}) + +test("billingCurrencies names a supported currency for a valid billing account", () => { + assert.deepEqual([...billingCurrenciesOf({ "aaaaaa-bbbbbb-cccccc": "jpy" })], [["AAAAAA-BBBBBB-CCCCCC", "JPY"]]) + assert.throws(() => billingCurrenciesOf({ "AAAAAA-BBBBBB-CCCCCC": "CNY" }), /not a currency this plugin reads/) + assert.throws(() => billingCurrenciesOf({ "not-an-account": "JPY" }), /billingCurrencies/) + assert.throws(() => billingCurrenciesOf("JPY"), /billingCurrencies must be an object/) +}) + +// What Chrome's translation left of the Console's table (#667): the column +// names and the amounts rewritten. That is a page in another language, said as +// such, not an expired session or an empty table. +test("a credits table whose columns were translated says so", () => { + const translatedHeaders = ["クレジット名", "ステータス", "残りの割合", "残額", "元の値", "タイプ", "クレジット ID", "使用範囲", "開始日", "終了日"] + const translatedRow = ["特典の例", "利用可能", "100%", "10.00 米ドル", "10.00 米ドル", "1回限り", "a", "すべての Google Cloud サービス", "2026年7月15日", "2027年7月1日"] + assert.throws(() => parseCreditTables([{ headers: [], rows: [] }, { headers: translatedHeaders, rows: [translatedRow] }], { now }), + /columns are not the English ones this plugin reads \(it found: クレジット名, ステータス, 残りの割合, 残額, 元の値, タイプ\); the page may have been translated/) + // A page with no table at all is still the old answer. + assert.throws(() => parseCreditTables([]), /Credits table was not found/) +}) + test("a credit near its end date reads as expiring, and is still spendable", () => { const result = parseCreditTables([{ headers, rows: [row("expiring", "$229.42", "$300.00", "Expiring in 24 days", "August 20, 2026", "November 20, 2026")] }], { now }) assert.equal(result.remaining, 229.42) @@ -1107,6 +1152,25 @@ test("account settings beat the row, and row settings beat environment defaults" } }) +test("the usage hook takes the billing, currency and profile maps from the provider's or the plugin's options", async () => { + const auth = { accountId: "reader@example.com" } + for (const [name, bad, wanted] of [ + ["billingAccounts", { "example-project": "nope" }, /billingAccounts: /], + ["billingCurrencies", { "AAAAAA-BBBBBB-CCCCCC": "EUR" }, /billingCurrencies: "EUR" is not a currency/], + ["profileDirectories", { "reader@example.com": "../elsewhere" }, /profileDirectories: Invalid Chrome profile directory/], + ]) { + const fromRow = await (await plugin()).auth.usage(async () => auth, { options: { billingAccount: "AAAAAA-BBBBBB-CCCCCC", [name]: bad } }) + assert.match(fromRow.error, wanted) + assert.equal(fromRow.signIn, "kept") + const fromPlugin = await (await plugin({}, { [name]: bad })).auth.usage(async () => auth, { options: { billingAccount: "AAAAAA-BBBBBB-CCCCCC" } }) + assert.match(fromPlugin.error, wanted) + } + const pinned = await (await plugin()).auth.usage(async () => auth, { options: { billingAccount: "AAAAAA-BBBBBB-CCCCCC", profileDirectory: "-flag" } }) + assert.match(pinned.error, /Invalid Chrome profile directory/) + const pinnedByPlugin = await (await plugin({}, { profileDirectory: "a/b" })).auth.usage(async () => auth, { options: { billingAccount: "AAAAAA-BBBBBB-CCCCCC" } }) + assert.match(pinnedByPlugin.error, /Invalid Chrome profile directory/) +}) + test("usage accepts plugin-level aliases while provider options take precedence", async () => { const hooks = await plugin({}, { consoleAccountAliases: "invalid-plugin-aliases" }) const auth = { accountId: "old@example.com" }