gcp-ai: Vertex models and Google Cloud credits with your own gcloud ADC (#307)
New package gcp-ai (Yaka88): Vertex models and Google Cloud credits through the user's own gcloud ADC, with multiple accounts, a signed-in model list, and a pipe-only Chrome for the credits read.
Reviewed at 8989b58 against the 10-24 review at 4586c99. I read the whole incremental diff (index.mjs, lib/browser, lib/credentials, lib/lock, test/*). Earlier rounds had already reviewed the rest.
- Tests reaching the network: fixed. test/network.mjs replaces fetch and blocks non-local net/tls/http/dns. `bun test` (40 pass, 1 skip [Linux-only lock test], 0 fail, 106s) ran in a sandbox HOME/TMPDIR behind a dead HTTPS_PROXY, with a preload that logged non-local fetch and connect calls: 0 lines logged. Broken by hand: with the fetch stub removed from "already filed", the guard prints "Unexpected network fetch … userinfo" and bun exits 1. Restored, it exits 0.
- Chrome background traffic: lsof on the test Chrome processes (56 samples during browser.test.mjs, 5 pass) found no inet sockets at all.
- Leftover work after a test: close() now awaits settled, and every sign-in test closes in finally before restoring fetch.
- Smaller points: the lock's age ceiling now comes after the Linux /proc check; settings() is auth > options > env for every field; resolveAdcDirectory and authorizeAdc are removed.
- `bun scripts/check.mjs gcp-ai`: ok. The merge onto main 98985a2 is clean. Loaded into magpie's plugin host (origin/main 4dfd88206) with scripts/try.sh in a sandbox HOME: gcp-ai, 12 models, not signed in.
Not tried: a real Google account or gcloud sign-in, Windows, Linux (the lock test is skipped on macOS). The headless Console credits scrape still runs for every signed-in account, cached on failure, as noted in the earlier review.
This commit is contained in:
@@ -17,6 +17,7 @@ subscription and makes its requests. The packages work in OpenCode and in
|
||||
| [cursor](packages/cursor) | Cursor subscriptions (Pro, Pro+, Ultra, Teams), on the API cursor-agent talks to | `cursor` |
|
||||
| [devin](packages/devin) | Devin subscription (the devin CLI's account) | `devin` |
|
||||
| [factory](packages/factory) | Factory (Droid) subscription | `factory` |
|
||||
| [gcp-ai](packages/gcp-ai) | Google Cloud Vertex AI with your own gcloud / ADC login (needs `gcloud` and Chrome), plus the project's promotional credits | `gcp-ai` |
|
||||
| [grok](packages/grok) | Grok (SuperGrok / X Premium+), through the Grok Build CLI's sign-in | `grok` |
|
||||
| [joycode](packages/joycode) | JoyCode IDE credits with JD account browser sign-in, live models and credit multipliers (unofficial) | `joycode` |
|
||||
| [kimi-work](packages/kimi-work) | Ordinary Kimi desktop Work subscription, through the desktop app's local sign-in; separate from Kimi Code | `kimi-work` |
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Yaka88
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,98 @@
|
||||
# GCP AI — Google Cloud credits and Vertex models (Magpie / OpenCode plugin)
|
||||
|
||||
- **Models**: the Vertex chat models your project can call, newest first.
|
||||
- **Inference**: requests speak Gemini's own protocol (`@ai-sdk/google`) to the project's Vertex endpoint, signed with your local gcloud / ADC credentials and billed to your own project.
|
||||
- **Credits**: the quota panel can show your Google Cloud promotional credit balance and its expiry date.
|
||||
|
||||
You sign in once with your own Google account. No service accounts, no JSON keys, no extra packages: the plugin uses the Chrome you already have.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Google Chrome or Chromium (set `VERTEX_CHROME_PATH` if it is somewhere unusual)
|
||||
- Google Cloud CLI (`gcloud`), already working — on Windows the `gcloud.cmd` the installer puts on `PATH` is used
|
||||
- A Google Cloud project with Vertex AI enabled
|
||||
- To read credits: permission to view the project's billing account (usually `billing.viewer`)
|
||||
|
||||
Linux has been tried with real accounts. Support for macOS and Windows is
|
||||
implemented, but has not been tried with a real account on either platform.
|
||||
On Windows the plugin's own files live under `%APPDATA%` and `%LOCALAPPDATA%`
|
||||
instead of `~/.config` and `~/.cache`, and gcloud is
|
||||
started through `cmd.exe`, which is the only way Windows runs a `.cmd`.
|
||||
|
||||
## What this was run on
|
||||
|
||||
Sign-in, model listing and a real inference request were run on **Linux** against
|
||||
**two real Google accounts**, with gcloud's own ADC and with an ADC the plugin wrote.
|
||||
|
||||
The Windows path — `cmd.exe` for `gcloud.cmd`, `%APPDATA%`/`%LOCALAPPDATA%` for the
|
||||
plugin's own files — is implemented and covered by the unit tests' path handling, but
|
||||
**has not been run on a Windows machine with a real account**. If it misbehaves there,
|
||||
that is why; macOS has likewise not been tried with a real account.
|
||||
|
||||
## Install and sign in
|
||||
|
||||
```bash
|
||||
magpie plugin add @magpie-community/gcp-ai
|
||||
```
|
||||
|
||||
Then click sign in on the **GCP AI** row, or run:
|
||||
|
||||
```bash
|
||||
magpie plugin login gcp-ai
|
||||
```
|
||||
|
||||
One Chrome window opens. Approve the consent page there and the plugin closes the window itself — never close it yourself.
|
||||
|
||||
- The first account goes straight to Google's consent page. Adding a second one starts on Google's account picker instead, in the same window.
|
||||
- Add another account by clicking sign in again with a different Google account.
|
||||
- The project is picked for you: the first of the account's projects with the Vertex AI API enabled.
|
||||
- If the account already has an ADC here, nothing is added and your existing sign-in is left alone.
|
||||
|
||||
## Credits
|
||||
|
||||
Google has no API for promotional credits, so the balance is read from the Cloud Console page. The row opens a browser when it needs a balance, and only then. Balances are cached for five minutes.
|
||||
|
||||
## What it keeps where
|
||||
|
||||
- **Credentials**: never held by the plugin. gcloud writes them and prints tokens on demand.
|
||||
- **ADC directories**: `<config>/gcp-ai/adc-<account>`, one per Google account. The plugin never writes gcloud's own directory. Two addresses that differ only in punctuation would share a directory name, so the second one gets a short hash of its address appended.
|
||||
- **Chrome profile**: `<config>/gcp-auto-profile`.
|
||||
- **Cache**: `<cache>/magpie/gcp-ai`.
|
||||
|
||||
`<config>` is `$XDG_CONFIG_HOME`, else `%APPDATA%` on Windows, else `~/.config`. `<cache>` is
|
||||
`$XDG_CACHE_HOME`, else `%LOCALAPPDATA%` on Windows, else `~/.cache`.
|
||||
|
||||
## FAQ
|
||||
|
||||
**No credits shown?** The Chrome sign-in has probably expired. Sign in again.
|
||||
|
||||
**"This browser or app may not be secure"?** Start the sign-in again from the row and use the window that opens. Nothing in it is automated.
|
||||
|
||||
**"That account was already signed in"?** Signing in adds an account; it does not refresh one. Use a different Google account.
|
||||
|
||||
**Wrong account on the consent page?** Sign in again and pick the right one. Nothing that was already here is removed.
|
||||
|
||||
**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.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Environment variable | Default |
|
||||
| --- | --- |
|
||||
| `GOOGLE_VERTEX_LOCATION` | `global` |
|
||||
| `VERTEX_BILLING_ACCOUNT` | Looked up from the project |
|
||||
| `VERTEX_CHROME_PROFILE` | `~/.config/gcp-auto-profile` |
|
||||
| `VERTEX_CHROME_PATH` | Detected |
|
||||
| `VERTEX_GCLOUD_ACCOUNT` | The signed-in account |
|
||||
| `VERTEX_GCLOUD_AUTH_MODE` | `auto`; also `adc` or `gcloud` |
|
||||
| `VERTEX_CHROME_IDLE` | `30` seconds a kept browser waits before closing; `0` closes it right away |
|
||||
| `VERTEX_CHROME_GAP` | `0` seconds between one process closing Chrome and the next opening the profile |
|
||||
| `VERTEX_CREDITS_CACHE_TTL` | `300` seconds |
|
||||
| `VERTEX_CREDITS_FAILURE_TTL` | `1200` seconds |
|
||||
| `VERTEX_CREDITS_TRANSIENT_TTL` | `60` seconds, for network failures |
|
||||
| `VERTEX_MODELS_CACHE_TTL` | `21600` seconds (6 hours) |
|
||||
|
||||
A machine-wide `CLOUDSDK_CONFIG` is never read. It would point every account at one ADC, and a sign-in there would overwrite credentials the plugin didn't write; the plugin only uses its own `<config>/gcp-ai/adc-<account>` directories.
|
||||
|
||||
## Privacy
|
||||
|
||||
The plugin asks Google for your model list with your credentials, sends inference requests to the Vertex endpoint, and opens Cloud Console in a Chrome it started to read your credits. No third-party server, no credential upload, no debugging port.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.5 KiB |
@@ -0,0 +1,227 @@
|
||||
import { readFile } from "node:fs/promises"
|
||||
import { defaultProfile, validateProject } from "./lib/browser.mjs"
|
||||
import { resolveIdentity, startLogin, tokenProvider, accountOf } from "./lib/credentials.mjs"
|
||||
import { fetchCredits, usageOf } from "./lib/credits.mjs"
|
||||
import { testEndpoint } from "./lib/endpoint.mjs"
|
||||
import { providerModels, seedModels } from "./lib/models.mjs"
|
||||
|
||||
// This plugin is its own provider: Magpie's built-in Vertex row keeps its own
|
||||
// project, location and ADC path, and nothing here touches it. What the plugin
|
||||
// adds is the model list Google says the account can call, requests signed
|
||||
// with the gcloud user's own token, and the promotional-credit balance.
|
||||
const ID = "gcp-ai"
|
||||
|
||||
// Two Google accounts can share one Magpie row: the host keeps each sign-in as
|
||||
// its own account and calls these hooks once per account, handing that
|
||||
// account's record in. So what an account recorded beats what the row says —
|
||||
// otherwise the second account would read the first one's project, Chrome
|
||||
// profile and ADC. So what an account recorded beats what the row says, and
|
||||
// both beat the environment: one machine can hold several Google accounts, and
|
||||
// a machine-wide variable would point all of them at one account's project.
|
||||
// An environment variable is the last resort, for a machine with no account
|
||||
// record yet (a first sign-in).
|
||||
function settings(provider = {}, auth = {}) {
|
||||
auth ??= {}
|
||||
const options = provider.options ?? {}
|
||||
const env = process.env
|
||||
return {
|
||||
project: auth.project || options.project || env.GOOGLE_VERTEX_PROJECT || env.GOOGLE_CLOUD_PROJECT,
|
||||
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(),
|
||||
account: auth.accountId || auth.account || options.account || env.VERTEX_GCLOUD_ACCOUNT,
|
||||
authMode: auth.authMode || options.authMode || env.VERTEX_GCLOUD_AUTH_MODE,
|
||||
// Only the directory this plugin filed for an account, never a machine-wide
|
||||
// CLOUDSDK_CONFIG: one variable would point every account at one ADC, and a
|
||||
// sign-in there would overwrite credentials the plugin didn't write.
|
||||
cloudsdkConfig: auth.cloudsdkConfig || options.cloudsdkConfig,
|
||||
}
|
||||
}
|
||||
|
||||
// The host takes a provider icon as an https URL or a data:image URI from the
|
||||
// auth hook. The picture is local, so it is read once and inlined; a missing
|
||||
// file only costs the icon, never the sign-in.
|
||||
const icon = await readFile(new URL("./assets/icon.png", import.meta.url))
|
||||
.then((png) => `data:image/png;base64,${png.toString("base64")}`)
|
||||
.catch(() => undefined)
|
||||
|
||||
// Where Vertex AI serves Gemini itself: the model is in the path and the body
|
||||
// is Gemini's own request, which is what the native protocol speaks. Magpie
|
||||
// appends "/models/<id>:streamGenerateContent?alt=sse" to this base, and
|
||||
// OpenCode's @ai-sdk/google does the same, so the base ends at the publisher.
|
||||
function endpoint(project, location) {
|
||||
validateProject(project)
|
||||
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(location)) throw new Error("Invalid GOOGLE_VERTEX_LOCATION")
|
||||
const host = location === "global" ? "aiplatform.googleapis.com" : `${location}-aiplatform.googleapis.com`
|
||||
return `https://${host}/v1beta1/projects/${project}/locations/${location}/publishers/google`
|
||||
}
|
||||
|
||||
// The routes Gemini's own API serves under a publisher, and nothing else: a
|
||||
// model call, its count, and the catalog. The token goes no further than these.
|
||||
const GEMINI_ROUTE = /^\/models(?:\/[^/]+(?::(?:generateContent|streamGenerateContent|countTokens))?)?$/
|
||||
|
||||
function geminiRoute(pathname, base) {
|
||||
return GEMINI_ROUTE.test(pathname.slice(base.length))
|
||||
}
|
||||
|
||||
// ADC records a project and a quota project, not who signed in, so a sign-in
|
||||
// made in ADC mode is saved without an account id and the row reads "Signed
|
||||
// in". The token can tell the host that account once; it is written back so
|
||||
// later reads of the sign-in are labelled without asking Google again.
|
||||
const named = new Set()
|
||||
// One probe per project and location per process: the answer cannot change
|
||||
// between two model calls in the same run, and the same run's later loads
|
||||
// should not ask Google again.
|
||||
const tested = new Set()
|
||||
|
||||
async function endorse(identity, location, owner) {
|
||||
// Two accounts can serve the same project and location; the probe is about
|
||||
// the credential, so it is remembered per account, not per address.
|
||||
const key = `${owner ?? identity.project}/${identity.project}/${location}`
|
||||
if (tested.has(key)) return
|
||||
const report = await testEndpoint({ ...identity, location }, { models: [], timeout: 15000 })
|
||||
if (!report.reachable) throw new Error(`The Google model endpoint is not usable for ${identity.project} (${location}); check that the project exists, the Vertex AI API is enabled and the account may use it`)
|
||||
tested.add(key)
|
||||
}
|
||||
|
||||
async function label(client, auth, account) {
|
||||
if (!account || auth.accountId === account) return
|
||||
const key = `${auth.authMode ?? ""}/${account}`
|
||||
if (named.has(key)) return
|
||||
named.add(key)
|
||||
try { await client?.auth?.set?.({ path: { id: ID }, body: { ...auth, accountId: account } }) } catch { named.delete(key) }
|
||||
}
|
||||
|
||||
export const GoogleVertexAuthPlugin = async (input = {}) => {
|
||||
const client = input.client
|
||||
let configured = {}
|
||||
return {
|
||||
// The row's name, protocol and the list it starts with. Magpie lists a
|
||||
// plugin provider from what this hook gives it, so a row configured with no
|
||||
// models stays empty until someone presses Fetch models; the seed is
|
||||
// Google's current catalog so the row is usable before it is signed in.
|
||||
// The provider hook below replaces it with what the signed-in project can
|
||||
// actually call, which is also where retired models are left out.
|
||||
config: async (config) => {
|
||||
config.provider ??= {}
|
||||
const provider = config.provider[ID] ??= {}
|
||||
provider.name ??= "GCP AI"
|
||||
// Gemini's own protocol, not the OpenAI-compatible shim: a tool call's
|
||||
// thought signature is part of the conversation there, so a second turn
|
||||
// with a tool result is accepted as it is, and the reply streams with
|
||||
// Vertex's own usage and caching numbers.
|
||||
provider.npm ??= "@ai-sdk/google"
|
||||
provider.models = { ...seedModels(), ...(provider.models ?? {}) }
|
||||
configured = provider
|
||||
},
|
||||
provider: {
|
||||
id: ID,
|
||||
// The host asks once per account and hands that account's sign-in in;
|
||||
// asking without it would list the first account's models for all of
|
||||
// them. This is where the list is read, from Google, with that account's
|
||||
// credentials — nobody has to press Fetch models first. A list Google
|
||||
// can't be asked for is not replaced with a guess: the row keeps the
|
||||
// models it had rather than offer ones the project can't call.
|
||||
//
|
||||
// The first argument is the whole provider info, not its models — it
|
||||
// carries id, name, source and the rest beside `models`. Handing that
|
||||
// object back on failure made the host read its keys as model ids and
|
||||
// list "id", "name" and "source" as models, so only provider.models is
|
||||
// ever given back.
|
||||
async models(provider, context) {
|
||||
try { return await providerModels(settings(configured, context?.auth), ID) }
|
||||
catch { return provider?.models ?? {} }
|
||||
},
|
||||
},
|
||||
auth: {
|
||||
provider: ID,
|
||||
...(icon ? { icon } : {}),
|
||||
methods: [{
|
||||
type: "oauth", label: "Google Cloud ADC / gcloud account (Chrome for credits)",
|
||||
// The first account on a machine opens gcloud's consent page directly;
|
||||
// a later one opens Google's add-account page first so the account can
|
||||
// be picked. Both continue in the same window, and gcloud's exit tells
|
||||
// the plugin when to close it; the person never closes it themselves.
|
||||
async authorize() {
|
||||
const options = settings(configured)
|
||||
const login = await startLogin(options)
|
||||
return {
|
||||
url: "", method: "auto",
|
||||
instructions: `A Chrome window opens on Google's consent page and you approve it there; when the plugin already has an account, it opens Google's add-account page first so you can pick which account this is. The plugin closes the window itself when gcloud finishes, so leave it open. An addition counts only when the account approved in the window and the account the new ADC belongs to are the same, and neither was here before; anything else is an overwrite and is removed again. The project is the first of the account's projects that already has the Vertex AI API enabled, chosen automatically; with no such project the sign-in fails instead, so create one and enable the API before trying again. The sign-in expires after ten minutes.`,
|
||||
async callback() {
|
||||
try {
|
||||
const identity = await login.result
|
||||
// Consent may already have saved ADC and identified its owner.
|
||||
// A project is still required for a usable host record; surface
|
||||
// the recovery instructions without saving an incomplete row.
|
||||
if (!identity.project) return { type: "failed", error: identity.warning ?? "The sign-in did not finish; nothing was saved" }
|
||||
// This run's settings are the row's until it is restarted, so
|
||||
// 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 }
|
||||
// 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
|
||||
// startLogin names an ADC sign-in from its token; when even
|
||||
// that fails the record still succeeds, just unnamed.
|
||||
if (identity.account) record.accountId = identity.account
|
||||
return { ...record, ...(identity.warning ? { warning: identity.warning } : {}) }
|
||||
} catch (error) {
|
||||
return { type: "failed", error: error.message }
|
||||
} finally { await login.close() } // ends the sign-in's Chrome window
|
||||
},
|
||||
}
|
||||
},
|
||||
}],
|
||||
// The gcloud user's token signs requests to this project's publisher
|
||||
// endpoint only, and only on the Gemini routes it serves.
|
||||
async loader(getAuth, provider = configured) {
|
||||
const auth = await getAuth()
|
||||
const options = settings(provider, auth)
|
||||
const identity = await resolveIdentity(options)
|
||||
const baseURL = endpoint(identity.project, options.location)
|
||||
const getToken = tokenProvider(identity)
|
||||
// The host has no test button of its own, so the first request after a
|
||||
// sign-in is where an unusable endpoint is named. Reading the location
|
||||
// resource is free, runs once per project, and turns a bad project or a
|
||||
// disabled API into a clear error instead of a failed model call. No
|
||||
// model is asked anything: that is the person's test to make.
|
||||
await endorse(identity, options.location, auth?.accountId ?? auth?.project ?? identity.project)
|
||||
const allowed = new URL(baseURL)
|
||||
return {
|
||||
baseURL, apiKey: "vertex-managed",
|
||||
async fetch(input, init) {
|
||||
const request = new Request(input, init)
|
||||
const url = new URL(request.url)
|
||||
if (url.origin !== allowed.origin || !url.pathname.startsWith(allowed.pathname + "/")) throw new Error("Refusing to send a Vertex credential outside the configured Google model endpoint")
|
||||
if (!geminiRoute(url.pathname, allowed.pathname)) throw new Error("Refusing to send a Vertex credential to a route the Gemini endpoint does not serve")
|
||||
const headers = new Headers(request.headers)
|
||||
headers.delete("x-goog-api-key")
|
||||
headers.delete("x-api-key")
|
||||
headers.set("authorization", `Bearer ${await getToken()}`)
|
||||
headers.set("x-goog-user-project", identity.project)
|
||||
return fetch(new Request(request, { headers, redirect: "error" }))
|
||||
},
|
||||
}
|
||||
},
|
||||
async usage(getAuth, provider = configured) {
|
||||
try {
|
||||
const auth = await getAuth()
|
||||
if (!auth) return { error: "GCP AI is not signed in", signIn: "kept" }
|
||||
const options = settings(provider, auth)
|
||||
// The row is named after this read as well, so a sign-in made before
|
||||
// this naming existed is fixed on its next usage refresh.
|
||||
if (!auth.accountId && auth.authMode === "adc" && auth.project) {
|
||||
void tokenProvider(options)()
|
||||
.then((token) => accountOf(token))
|
||||
.then((account) => label(client, auth, account)).catch(() => {})
|
||||
}
|
||||
return usageOf(await fetchCredits(options))
|
||||
} catch (error) { return { error: error.message, signIn: "kept" } }
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export default GoogleVertexAuthPlugin
|
||||
@@ -0,0 +1,548 @@
|
||||
import { spawn } from "node:child_process"
|
||||
import { createHash } from "node:crypto"
|
||||
import { access, mkdir, mkdtemp, rm } from "node:fs/promises"
|
||||
import { homedir, tmpdir } from "node:os"
|
||||
import { join, resolve } from "node:path"
|
||||
import { launch } from "./cdp.mjs"
|
||||
import { apart, take, wanted } from "./lock.mjs"
|
||||
|
||||
// The browser here is the user's own Chrome, started for this plugin alone on a
|
||||
// profile of its own. It is spoken to over Chrome's pipe transport (see
|
||||
// cdp.mjs): no debugging port is opened and no Chrome the plugin did not start
|
||||
// is ever attached to, so the Google session in that profile is reachable only
|
||||
// from this process.
|
||||
|
||||
// The user's home as the environment states it. os.homedir() is the fallback,
|
||||
// not the answer: a runner or a shell may set HOME for a process, and that is
|
||||
// the home every path here is meant to be relative to.
|
||||
export const home = () => process.env.HOME || process.env.USERPROFILE || homedir()
|
||||
|
||||
// The user's configuration root: what XDG_CONFIG_HOME names, else the platform's
|
||||
// own place — %APPDATA% on Windows, ~/.config everywhere else. The variable is
|
||||
// read first on every platform so a test or a sandbox can move the whole
|
||||
// directory, and so a Windows user who sets it gets what they asked for.
|
||||
export const configRoot = () => process.env.XDG_CONFIG_HOME
|
||||
|| (process.platform === "win32" && process.env.APPDATA ? process.env.APPDATA : join(home(), ".config"))
|
||||
|
||||
// The user's cache root, by the same rule: XDG_CACHE_HOME, else %LOCALAPPDATA%
|
||||
// on Windows (a cache is machine-local, not roaming), else ~/.cache.
|
||||
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")
|
||||
export const expandPath = (value) => resolve(value.startsWith("~/") ? join(home(), value.slice(2)) : value)
|
||||
|
||||
export async function safeGoto(page, url, options = { waitUntil: "domcontentloaded", timeout: 60000 }) {
|
||||
try {
|
||||
await page.goto(url, options)
|
||||
} catch (error) {
|
||||
if (!/ERR_ABORTED|frame was detached/i.test(error.message)) throw error
|
||||
}
|
||||
}
|
||||
|
||||
// Where Chrome keeps its binary on each platform. The macOS entry is a path
|
||||
// inside the app bundle, which is where Chrome installs itself for everyone.
|
||||
export async function chromeExecutable() {
|
||||
if (process.env.VERTEX_CHROME_PATH) return expandPath(process.env.VERTEX_CHROME_PATH)
|
||||
const candidates = process.platform === "win32"
|
||||
? [
|
||||
process.env.PROGRAMFILES && join(process.env.PROGRAMFILES, "Google", "Chrome", "Application", "chrome.exe"),
|
||||
process.env["PROGRAMFILES(X86)"] && join(process.env["PROGRAMFILES(X86)"], "Google", "Chrome", "Application", "chrome.exe"),
|
||||
process.env.LOCALAPPDATA && join(process.env.LOCALAPPDATA, "Google", "Chrome", "Application", "chrome.exe"),
|
||||
process.env.LOCALAPPDATA && join(process.env.LOCALAPPDATA, "Chromium", "Application", "chrome.exe"),
|
||||
].filter(Boolean)
|
||||
: process.platform === "darwin"
|
||||
? ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", join(home(), "Applications", "Google Chrome.app", "Contents", "MacOS", "Google Chrome")]
|
||||
: ["/usr/bin/google-chrome", "/usr/bin/google-chrome-stable", "/usr/bin/chromium", "/usr/bin/chromium-browser", "/snap/bin/chromium"]
|
||||
for (const path of candidates) {
|
||||
try { await access(path); return path } catch {}
|
||||
}
|
||||
throw new Error("Chrome not found; set VERTEX_CHROME_PATH to its executable")
|
||||
}
|
||||
|
||||
// One browser at a time per profile, across processes: magpie asks each
|
||||
// account's row separately and each may be a process of its own, so the wait
|
||||
// for the profile lives on disk. A second process waits its turn instead of
|
||||
// failing with "profile in use".
|
||||
//
|
||||
// Within one process there is no wait at all: the reads share one Chrome and
|
||||
// take turns opening a tab (withPage below), which is what two accounts are —
|
||||
// one browser, two tabs, one after the other.
|
||||
const PROFILE_GAP = 0
|
||||
|
||||
// The gap after a process closed its Chrome and the next one starts another.
|
||||
// Back to back by default: the profile is a session, not a file, and closing
|
||||
// Chrome properly is enough. A machine that wants breathing room between
|
||||
// browsers sets this in seconds.
|
||||
function profileGap() {
|
||||
const raw = process.env.VERTEX_CHROME_GAP
|
||||
if (raw === undefined || raw === "") return PROFILE_GAP
|
||||
const seconds = Number(raw)
|
||||
if (!Number.isFinite(seconds) || seconds < 0) throw new Error("VERTEX_CHROME_GAP must be a nonnegative number of seconds")
|
||||
return seconds * 1000
|
||||
}
|
||||
|
||||
// How long a Chrome kept for reuse stays open with nothing to do. The accounts
|
||||
// magpie asks are asked in one go and read one after the other, so a short
|
||||
// window is enough to cover the whole batch: when the reads stop, the browser
|
||||
// closes instead of sitting there. A read that comes later simply starts one
|
||||
// again, which is no worse than opening a browser per read.
|
||||
function idleAfter() {
|
||||
const raw = process.env.VERTEX_CHROME_IDLE
|
||||
if (raw === undefined || raw === "") return 30_000
|
||||
const seconds = Number(raw)
|
||||
if (!Number.isFinite(seconds) || seconds < 0) throw new Error("VERTEX_CHROME_IDLE must be a nonnegative number of seconds")
|
||||
return seconds * 1000
|
||||
}
|
||||
|
||||
// The lock is kept beside the cache rather than inside the Chrome profile: the
|
||||
// profile is Chrome's own directory and nothing of this plugin's belongs in it.
|
||||
export function profileLock(profilePath) {
|
||||
return join(cacheRoot(), "magpie", "gcp-ai", "profiles", createHash("sha256").update(profilePath).digest("hex").slice(0, 16))
|
||||
}
|
||||
|
||||
async function claimProfile(profilePath, { timeout = 180000, gap = profileGap() } = {}) {
|
||||
const lockfile = profileLock(profilePath)
|
||||
const release = await take(lockfile, { timeout, busy: `The Chrome profile ${profilePath} is still busy with another Vertex operation; retry shortly` })
|
||||
try { await apart(lockfile, gap) } catch { /* a gap is a courtesy, not a requirement */ }
|
||||
return release
|
||||
}
|
||||
|
||||
// A request handler that answers every request a page makes, for tests and for
|
||||
// the offline HTML parser. It rides on the same pipe: the page's own network is
|
||||
// paused at the request stage and continued or failed here, so a test never
|
||||
// reaches Google and a document opened from a file never loads anything.
|
||||
export async function routeAll(page, handler) {
|
||||
// The newest handler answers: a test that changes what its pages say only
|
||||
// calls this again, and the earlier one is dropped before the new one is
|
||||
// armed, instead of racing it.
|
||||
if (page.unroute) await page.unroute()
|
||||
await page.send("Fetch.enable", { patterns: [{ urlPattern: "*" }] })
|
||||
const listener = (params) => {
|
||||
const request = params.request
|
||||
const respond = (response) => page.send("Fetch.fulfillRequest", {
|
||||
requestId: params.requestId, responseCode: 200,
|
||||
responseHeaders: [{ name: "content-type", value: response.contentType ?? "text/html; charset=utf-8" }],
|
||||
body: Buffer.from(response.body ?? "").toString("base64"),
|
||||
})
|
||||
Promise.resolve(handler({
|
||||
url: () => request.url,
|
||||
method: () => request.method,
|
||||
fulfill: respond,
|
||||
abort: () => page.send("Fetch.failRequest", { requestId: params.requestId, errorReason: "Aborted" }),
|
||||
continue: () => page.send("Fetch.continueRequest", { requestId: params.requestId }),
|
||||
}))
|
||||
.then((response) => (response ? respond(response) : page.send("Fetch.failRequest", { requestId: params.requestId, errorReason: "Aborted" })))
|
||||
.catch(() => {})
|
||||
}
|
||||
const previous = page.unroute
|
||||
const off = page.connection.subscribe("Fetch.requestPaused", listener, page.sessionId)
|
||||
page.unroute = async () => {
|
||||
off()
|
||||
await page.send("Fetch.disable").catch(() => {})
|
||||
await previous?.()
|
||||
}
|
||||
return page.unroute
|
||||
}
|
||||
|
||||
// One read at a time per profile inside this process. Two accounts are read
|
||||
// one after the other in the same browser; they must not drive it at once.
|
||||
const chains = new Map()
|
||||
// Browsers kept for the next read, by profile, with the timer that ends them.
|
||||
const kept = new Map()
|
||||
|
||||
function serialize(key, task) {
|
||||
const previous = chains.get(key) ?? Promise.resolve()
|
||||
const run = previous.then(task, task)
|
||||
const tail = run.catch(() => {})
|
||||
chains.set(key, tail)
|
||||
tail.then(() => { if (chains.get(key) === tail) chains.delete(key) })
|
||||
return run
|
||||
}
|
||||
|
||||
// Ending the browsers this process kept. Without this a Chrome would be left
|
||||
// running when the process ends for a reason other than the idle timer.
|
||||
let ending = false
|
||||
// This module is loaded inside magpie's plugin host, which other plugins share
|
||||
// and which ends the process itself. A SIGINT handler that exits here would cut
|
||||
// short that shutdown for every one of them, and an exit handler cannot await.
|
||||
// So the exit path only does what can be done at once — kill the Chromes this
|
||||
// process started — and leaves the process's own ending to its owner.
|
||||
function endKept() {
|
||||
ending = true
|
||||
for (const [key, entry] of kept) {
|
||||
clearTimeout(entry.timer)
|
||||
clearInterval(entry.watch)
|
||||
kept.delete(key)
|
||||
try { entry.browser.child?.kill("SIGTERM") } catch {}
|
||||
}
|
||||
}
|
||||
process.once("exit", endKept)
|
||||
|
||||
// For a caller that means to leave nothing running, as a test does.
|
||||
export async function closeKeptBrowsers() {
|
||||
const closing = [...kept.entries()].map(([key, entry]) => giveBack(key, entry))
|
||||
ending = false
|
||||
await Promise.all(closing)
|
||||
}
|
||||
|
||||
// With nothing to do, the browser is kept for the next read and ends when it
|
||||
// has gone unused. While it is kept it still holds the profile's lock, so it
|
||||
// also watches for another process that wants the profile — a `magpie quota`
|
||||
// on its own process, or a sign-in window — and steps aside at once rather
|
||||
// than making that process sit out its whole patience.
|
||||
function keepIdle(key, entry) {
|
||||
if (kept.get(key) !== entry) return
|
||||
clearTimeout(entry.timer)
|
||||
clearInterval(entry.watch)
|
||||
entry.timer = setTimeout(() => { void giveBack(key, entry).catch(() => {}) }, idleAfter())
|
||||
entry.timer.unref?.()
|
||||
entry.watch = setInterval(() => { void stepAside(key, entry).catch(() => {}) }, 2000)
|
||||
entry.watch.unref?.()
|
||||
}
|
||||
|
||||
async function giveBack(key, entry) {
|
||||
clearTimeout(entry.timer)
|
||||
clearInterval(entry.watch)
|
||||
entry.timer = null
|
||||
entry.watch = null
|
||||
if (kept.get(key) === entry) kept.delete(key)
|
||||
await entry.handle.close().catch(() => {})
|
||||
}
|
||||
|
||||
// Another process waiting on this profile outranks keeping the browser for
|
||||
// the next read: it cannot make progress until this one lets go.
|
||||
async function stepAside(key, entry) {
|
||||
if (ending || kept.get(key) !== entry) return
|
||||
if ((await wanted(entry.lockfile)) <= entry.takenAt) return
|
||||
await giveBack(key, entry)
|
||||
}
|
||||
|
||||
// withPage is how a read uses the profile: a tab of the browser this process
|
||||
// has open on it, or a browser opened for the occasion. The tab is closed when
|
||||
// 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) {
|
||||
const profilePath = expandPath(profile)
|
||||
const key = JSON.stringify([profilePath, headless, javaScriptEnabled, launchArgs])
|
||||
return serialize(key, async () => {
|
||||
let entry = kept.get(key)
|
||||
if (entry) {
|
||||
clearTimeout(entry.timer)
|
||||
clearInterval(entry.watch)
|
||||
entry.timer = null
|
||||
entry.watch = null
|
||||
if (entry.browser.connection.closed || entry.browser.child.exitCode !== null) {
|
||||
kept.delete(key)
|
||||
entry = undefined
|
||||
}
|
||||
}
|
||||
if (!entry) {
|
||||
const handle = await openBrowser({ profile: profilePath, 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.
|
||||
handle.context.connection.onClosed(() => {
|
||||
if (kept.get(key) === entry) kept.delete(key)
|
||||
})
|
||||
}
|
||||
const page = await entry.browser.newPage()
|
||||
try {
|
||||
return await use(page)
|
||||
} finally {
|
||||
await page.close().catch(() => {})
|
||||
if (!ending) {
|
||||
await stepAside(key, entry).catch(() => {})
|
||||
if (kept.get(key) === entry) keepIdle(key, entry)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export async function openBrowser({ profile = defaultProfile(), headless = true, javaScriptEnabled = true, launchArgs = [] } = {}) {
|
||||
const profilePath = expandPath(profile)
|
||||
await mkdir(profilePath, { recursive: true, mode: 0o700 })
|
||||
let browser
|
||||
let downloadsPath
|
||||
let release = await claimProfile(profilePath)
|
||||
const cleanDownloads = async () => { if (downloadsPath) await rm(downloadsPath, { recursive: true, force: true }) }
|
||||
try {
|
||||
await mkdir(profilePath, { recursive: true, mode: 0o700 })
|
||||
downloadsPath = await mkdtemp(join(tmpdir(), "vertex-download-"))
|
||||
// Chrome is started plainly, with no automation flag. Its cookie store is
|
||||
// mocked as Playwright's own launch mocks it, so the profile neither
|
||||
// prompts for nor writes to the macOS Keychain or the Linux keyring.
|
||||
//
|
||||
// This browser is for reading, never for signing in: Google turns a sign-in
|
||||
// away from a browser that has a DevTools client attached ("This browser or
|
||||
// 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}`,
|
||||
"--no-first-run", "--no-default-browser-check",
|
||||
"--disable-background-networking", "--disable-sync", "--disable-default-apps",
|
||||
"--disable-component-update", "--disable-client-side-phishing-detection",
|
||||
"--disable-domain-reliability", "--disable-features=Translate,OptimizationHints,MediaRouter,DialMediaRouteProvider",
|
||||
"--metrics-recording-only", "--no-service-autorun",
|
||||
// The same cookie store Playwright's launch uses: the profile's cookies
|
||||
// are encrypted with a key kept beside the profile, so neither the macOS
|
||||
// Keychain nor the Linux keyring is asked for anything.
|
||||
...(process.platform === "darwin" ? ["--use-mock-keychain"] : process.platform === "linux" ? ["--password-store=basic"] : []),
|
||||
"--window-size=1440,1000",
|
||||
...(headless ? ["--headless=new", "--disable-gpu"] : []),
|
||||
...(javaScriptEnabled ? [] : ["--blink-settings=scriptEnabled=false"]),
|
||||
`--crash-dumps-dir=${downloadsPath}`,
|
||||
// Tests can refuse DNS for Chrome's background services too; page
|
||||
// interception alone cannot see those requests.
|
||||
...launchArgs,
|
||||
"about:blank",
|
||||
]
|
||||
const started = await launch(await chromeExecutable(), args)
|
||||
browser = started.browser
|
||||
const page = started.page
|
||||
// A Chrome that ends on its own (a crash, or a window the user closed)
|
||||
// releases the profile as surely as one this plugin closed.
|
||||
browser.connection.onClosed(() => { release(); void cleanDownloads().catch(() => {}) })
|
||||
const close = async () => {
|
||||
try { await browser.close() } finally { release(); await cleanDownloads() }
|
||||
}
|
||||
return { context: browser, page: Object.assign(page, { browser: () => browser }), close }
|
||||
} catch (error) {
|
||||
try { await browser?.close() } finally { release(); await cleanDownloads() }
|
||||
if (/Singleton|ProcessSingleton|profile.*in use|already in use/i.test(error.message)) {
|
||||
throw new Error(`Chrome profile is already open: ${profilePath}. Close Chrome using that profile and retry.`)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// The window a person signs in to Google in.
|
||||
//
|
||||
// It is Chrome with no debugging transport of any kind: nothing of this plugin
|
||||
// is attached to it, so there is no DevTools client for Google to find and the
|
||||
// sign-in is an ordinary one. That is the whole point — a browser driven over
|
||||
// CDP is turned away with "This browser or app may not be secure", and hiding
|
||||
// the marks it is detected by is a race the plugin would lose on Google's next
|
||||
// change. So this window is never driven: the person uses it, and the caller
|
||||
// closes it once gcloud has finished the consent flow.
|
||||
//
|
||||
// The profile is the same one the credit reads use, which is what makes the
|
||||
// cookies set here the cookies those reads are made with. Waiting is by
|
||||
// process exit rather than by polling the profile, so the lock is held for as
|
||||
// long as the window is open and no read can start on a profile Chrome is
|
||||
// still writing.
|
||||
//
|
||||
// The address it opens is chosen by the caller. ADC sign-in opens directly on
|
||||
// Google's add-account page with the consent URL as its continuation; `close`
|
||||
// ends the window when gcloud finishes or the sign-in times out. The optional
|
||||
// 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 } = {}) {
|
||||
const profilePath = expandPath(profile)
|
||||
await mkdir(profilePath, { recursive: true, mode: 0o700 })
|
||||
const release = await claimProfile(profilePath)
|
||||
let downloadsPath
|
||||
const clean = async () => {
|
||||
if (downloadsPath) await rm(downloadsPath, { recursive: true, force: true }).catch(() => {})
|
||||
downloadsPath = undefined
|
||||
}
|
||||
try {
|
||||
downloadsPath = await mkdtemp(join(tmpdir(), "vertex-signin-"))
|
||||
const args = [
|
||||
`--user-data-dir=${profilePath}`,
|
||||
"--no-first-run", "--no-default-browser-check",
|
||||
"--disable-background-networking", "--disable-sync", "--disable-default-apps",
|
||||
"--disable-component-update", "--disable-client-side-phishing-detection",
|
||||
"--disable-domain-reliability", "--disable-features=Translate,OptimizationHints,MediaRouter,DialMediaRouteProvider",
|
||||
"--metrics-recording-only", "--no-service-autorun",
|
||||
...(process.platform === "darwin" ? ["--use-mock-keychain"] : process.platform === "linux" ? ["--password-store=basic"] : []),
|
||||
"--window-size=1440,1000",
|
||||
...(headless ? ["--headless=new", "--disable-gpu"] : []),
|
||||
`--crash-dumps-dir=${downloadsPath}`,
|
||||
...(url ? [url] : []),
|
||||
]
|
||||
// No pipes on 3 and 4: those are what --remote-debugging-pipe would use, and
|
||||
// the point of this window is that no such client exists.
|
||||
const child = spawn(await chromeExecutable(), args, { stdio: "ignore", detached: false })
|
||||
let ended = false
|
||||
const exited = new Promise((resolve) => {
|
||||
const finish = (error) => {
|
||||
if (ended) return
|
||||
ended = true
|
||||
void clean().then(() => release())
|
||||
resolve(error)
|
||||
}
|
||||
child.once("exit", (code, signal) => finish(code === 0 || signal ? undefined : new Error(`Chrome exited with code ${code}`)))
|
||||
child.once("error", (error) => finish(new Error(error.code === "ENOENT"
|
||||
? "Chrome not found; set VERTEX_CHROME_PATH to its executable"
|
||||
: `Chrome could not be started: ${error.message}`)))
|
||||
})
|
||||
// Waiting for the person, with no timeout of its own: the caller decides
|
||||
// how long a sign-in may take, and a window that closed for any reason is
|
||||
// reported by `ended` rather than guessed at from the profile.
|
||||
return {
|
||||
child,
|
||||
profile: profilePath,
|
||||
ended: exited,
|
||||
// A tab in the window that is already open. Chrome hands a URL given to
|
||||
// its binary to the running instance for that profile and exits at once,
|
||||
// so this opens a tab without attaching anything to the browser: there is
|
||||
// still no DevTools client, and no second Chrome is started.
|
||||
//
|
||||
// The URL is the last argument, and it is only ever one the caller built
|
||||
// (a local page or an https one): a string starting with "-" would be
|
||||
// read by Chrome as a switch, so it is refused rather than handed over.
|
||||
openTab: async (tabUrl) => {
|
||||
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}`,
|
||||
"--no-first-run", "--no-default-browser-check",
|
||||
...(process.platform === "darwin" ? ["--use-mock-keychain"] : process.platform === "linux" ? ["--password-store=basic"] : []),
|
||||
tabUrl,
|
||||
], { stdio: "ignore", detached: false })
|
||||
const handedOver = await new Promise((resolve) => {
|
||||
helper.once("exit", (code) => resolve(code === 0))
|
||||
helper.once("error", () => resolve(false))
|
||||
})
|
||||
return handedOver
|
||||
},
|
||||
// Ends the window the way the person would, and only if it is still open.
|
||||
close: async () => {
|
||||
if (child.exitCode !== null || child.signalCode !== null) { await exited; return }
|
||||
child.kill("SIGTERM")
|
||||
const stopped = await Promise.race([exited.then(() => true), new Promise((resolve) => setTimeout(() => resolve(false), 5000))])
|
||||
if (!stopped) { child.kill("SIGKILL"); await exited }
|
||||
},
|
||||
}
|
||||
} catch (error) {
|
||||
await clean()
|
||||
release()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function assertConsoleSession(page, { timeout = 20000 } = {}) {
|
||||
if (!Number.isFinite(timeout) || timeout <= 0) throw new Error("Console session timeout must be a positive number of milliseconds")
|
||||
const deadline = Date.now() + timeout
|
||||
while (Date.now() < deadline) {
|
||||
if (page.isClosed()) throw new Error("Google Cloud page closed while checking the session")
|
||||
let ready
|
||||
try {
|
||||
// A passive sign-in can display the identifier form before returning to
|
||||
// Console. Only a return to Console establishes success; give both forms
|
||||
// and redirects the same bounded grace period without entering anything.
|
||||
ready = await page.waitForFunction(() => {
|
||||
if (location.origin !== "https://console.cloud.google.com" || !document.body) return false
|
||||
const text = document.body.innerText
|
||||
const login = /Sign in with your Google Account|Sign in to (?:your )?Google Account/i.test(text)
|
||||
|| (document.querySelector('input[type="password"], input[name="identifier"]') && /sign in/i.test(text))
|
||||
return text.trim() && !login ? { text } : false
|
||||
}, undefined, { timeout: Math.max(1, deadline - Date.now()) })
|
||||
const { text } = await ready.jsonValue()
|
||||
if (/You do not have permission|Permission denied|You need additional access/i.test(text)) throw new Error("Google Cloud Console permission denied for the signed-in Google account")
|
||||
return
|
||||
} catch (error) {
|
||||
if (page.isClosed()) throw new Error("Google Cloud page closed while checking the session", { cause: error })
|
||||
if (error.name === "TimeoutError") break
|
||||
if (!/Execution context was destroyed|Cannot find context with specified id|frame was detached/i.test(error.message)) throw error
|
||||
} finally { await ready?.dispose().catch(() => {}) }
|
||||
}
|
||||
throw new Error("Google session expired; automatic sign-in did not return to a signed-in Cloud Console before the timeout. Sign in with the Chrome profile again.")
|
||||
}
|
||||
|
||||
// Runs in the page so SPA redirects and asynchronously populated context are
|
||||
// observed together. Never choose an arbitrary project from a billing list.
|
||||
function projectInConsole(waitForConsole = false) {
|
||||
if (location.hostname === "accounts.google.com") return waitForConsole ? null : "sign-in-required"
|
||||
if (location.origin !== "https://console.cloud.google.com") return null
|
||||
const valid = (value) => typeof value === "string" && /^[a-z][a-z0-9-]{4,61}[a-z0-9]$/.test(value)
|
||||
let stored
|
||||
try { stored = window.sessionStorage.getItem("last_project_id") } catch {}
|
||||
for (const value of [new URL(location.href).searchParams.get("project"), window.cloudConsoleContext?.project?.id, stored]) {
|
||||
if (valid(value)) return value
|
||||
}
|
||||
const ids = [...new Set([...document.querySelectorAll("[data-project-id]")].map((element) => element.getAttribute("data-project-id")).filter(valid))]
|
||||
if (ids.length === 1) return ids[0]
|
||||
const linked = [...new Set([...document.querySelectorAll("a[href]")].flatMap((link) => {
|
||||
try {
|
||||
const url = new URL(link.href, location.href)
|
||||
const value = url.searchParams.get("project")
|
||||
return url.origin === location.origin && valid(value) ? [value] : []
|
||||
} catch { return [] }
|
||||
}))]
|
||||
if (!ids.length && linked.length === 1) return linked[0]
|
||||
return null
|
||||
}
|
||||
|
||||
// The Console page carries the signed-in account in the same payload that
|
||||
// names the project, under an obfuscated key. Reading that key is what makes
|
||||
// the answer "who is signed in" rather than "which address appears first":
|
||||
// a page can mention other accounts in its scripts and chooser markup, so a
|
||||
// page without the key has no answer at all and none is invented.
|
||||
function accountInPage() {
|
||||
const text = document.documentElement?.innerHTML ?? ""
|
||||
const keyed = text.match(/"oPEP7c":"([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})"/)?.[1]
|
||||
if (keyed && !/(\.gserviceaccount\.com|@system\.|noreply|no-reply)/i.test(keyed)) return keyed
|
||||
return null
|
||||
}
|
||||
|
||||
export async function extractAccount(page, { timeout = 20000 } = {}) {
|
||||
const found = await page.waitForFunction(accountInPage, undefined, { timeout }).catch(() => undefined)
|
||||
try { return found ? await found.jsonValue() : undefined } finally { await found?.dispose().catch(() => {}) }
|
||||
}
|
||||
|
||||
// One page visit answers both questions, so this waits for either signal and
|
||||
// reads both from the same DOM rather than loading the Console a second time.
|
||||
export async function readConsole(page, { timeout = 30000 } = {}) {
|
||||
const found = await page.waitForFunction(projectInConsole, undefined, { timeout }).catch(() => undefined)
|
||||
let project
|
||||
try { project = found ? await found.jsonValue() : undefined } finally { await found?.dispose().catch(() => {}) }
|
||||
const account = await extractAccount(page, { timeout: 5000 })
|
||||
return { project: project === "sign-in-required" ? undefined : project ?? undefined, account }
|
||||
}
|
||||
|
||||
export async function extractProjectId(page) {
|
||||
const requireProject = async (project) => {
|
||||
if (project === "sign-in-required") {
|
||||
await assertConsoleSession(page)
|
||||
const resolved = await page.waitForFunction(projectInConsole, true, { timeout: 20000 })
|
||||
try { project = await resolved.jsonValue() } finally { await resolved.dispose() }
|
||||
}
|
||||
return project ? validateProject(project) : undefined
|
||||
}
|
||||
// Prefer the active page before navigating away from a user-selected project.
|
||||
let current
|
||||
try { current = await page.evaluate(projectInConsole) } catch (error) {
|
||||
if (!/Execution context was destroyed|Cannot find context with specified id/i.test(error.message)) throw error
|
||||
}
|
||||
const project = await requireProject(current)
|
||||
if (project) return project
|
||||
// Billing pages need not carry a project. The console landing page resolves
|
||||
// the profile's default/active project without asking for a typed ID.
|
||||
await safeGoto(page, "https://console.cloud.google.com/?hl=en")
|
||||
let result
|
||||
try {
|
||||
result = await page.waitForFunction(projectInConsole, undefined, { timeout: 45000 })
|
||||
return await requireProject(await result.jsonValue())
|
||||
} catch (error) {
|
||||
if (error.name === "TimeoutError") throw new Error("Cannot automatically identify the active Google Cloud project. Select the intended project in Cloud Console and retry.")
|
||||
throw error
|
||||
} finally { await result?.dispose() }
|
||||
}
|
||||
|
||||
export function validateProject(project) {
|
||||
if (typeof project !== "string" || !/^[a-z][a-z0-9-]{4,61}[a-z0-9]$/.test(project)) {
|
||||
throw new Error("Set GOOGLE_VERTEX_PROJECT to a Google Cloud project ID (not its display name)")
|
||||
}
|
||||
return project
|
||||
}
|
||||
|
||||
export function validateBillingAccount(value) {
|
||||
if (typeof value !== "string" || !/^[A-Fa-f0-9]{6}-[A-Fa-f0-9]{6}-[A-Fa-f0-9]{6}$/.test(value)) {
|
||||
throw new Error("Invalid billing account ID; expected XXXXXX-XXXXXX-XXXXXX")
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
import { spawn } from "node:child_process"
|
||||
|
||||
// A small Chrome DevTools Protocol client over the pipe transport.
|
||||
//
|
||||
// Chrome is started with --remote-debugging-pipe, which speaks CDP on file
|
||||
// descriptors 3 (commands in) and 4 (responses out) of the process this module
|
||||
// starts. Nothing listens on a TCP port, so no other process on the machine can
|
||||
// reach the Google session the browser holds, and the plugin never drives a
|
||||
// Chrome it did not start itself. That is why this is not Playwright: the only
|
||||
// page operations used are navigation and evaluating a function in the page.
|
||||
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
||||
|
||||
const timeoutError = (message) => Object.assign(new Error(message), { name: "TimeoutError" })
|
||||
|
||||
// Delimited messages: Chrome writes one JSON object per NUL.
|
||||
class Pipe {
|
||||
constructor(child) {
|
||||
this.child = child
|
||||
this.toChrome = child.stdio[3]
|
||||
this.fromChrome = child.stdio[4]
|
||||
this.buffer = ""
|
||||
this.nextId = 1
|
||||
this.pending = new Map()
|
||||
this.listeners = new Set()
|
||||
this.events = new Map()
|
||||
this.closed = false
|
||||
this.closedReason = "Chrome was closed"
|
||||
this.fromChrome.setEncoding("utf8")
|
||||
this.fromChrome.on("data", (chunk) => this.read(chunk))
|
||||
this.fromChrome.on("end", () => this.shut("Chrome closed the debugging connection"))
|
||||
this.fromChrome.on("error", () => this.shut("Chrome closed the debugging connection"))
|
||||
this.toChrome.on("error", () => this.shut("Chrome closed the debugging connection"))
|
||||
child.once("exit", (code) => this.shut(`Chrome exited (${code ?? "signal"})`))
|
||||
}
|
||||
|
||||
read(chunk) {
|
||||
this.buffer += chunk
|
||||
for (let end = this.buffer.indexOf("\0"); end >= 0; end = this.buffer.indexOf("\0")) {
|
||||
const raw = this.buffer.slice(0, end)
|
||||
this.buffer = this.buffer.slice(end + 1)
|
||||
let message
|
||||
try { message = JSON.parse(raw) } catch { continue }
|
||||
if (message.id === undefined) {
|
||||
// An event: a message Chrome sends on its own. Each is delivered to the
|
||||
// listeners of the session it belongs to.
|
||||
for (const listener of this.events.get(`${message.sessionId ?? ""}:${message.method}`) ?? []) listener(message.params ?? {})
|
||||
for (const listener of this.events.get(`*:${message.method}`) ?? []) listener(message.params ?? {}, message.sessionId)
|
||||
continue
|
||||
}
|
||||
const pending = this.pending.get(message.id)
|
||||
if (!pending) continue
|
||||
this.pending.delete(message.id)
|
||||
if (message.error) pending.reject(new Error(message.error.message ?? "Chrome refused the command"))
|
||||
else pending.resolve(message.result ?? {})
|
||||
}
|
||||
}
|
||||
|
||||
shut(reason) {
|
||||
if (this.closed) return
|
||||
this.closed = true
|
||||
this.closedReason = reason
|
||||
for (const { reject } of this.pending.values()) reject(new Error(reason))
|
||||
this.pending.clear()
|
||||
for (const listener of this.listeners) listener()
|
||||
this.listeners.clear()
|
||||
}
|
||||
|
||||
// Called once when the connection ends, however it ends.
|
||||
onClosed(listener) {
|
||||
if (this.closed) { listener(); return }
|
||||
this.listeners.add(listener)
|
||||
}
|
||||
|
||||
subscribe(method, listener, sessionId) {
|
||||
const key = `${sessionId ?? ""}:${method}`
|
||||
if (!this.events.has(key)) this.events.set(key, new Set())
|
||||
this.events.get(key).add(listener)
|
||||
return () => this.events.get(key)?.delete(listener)
|
||||
}
|
||||
|
||||
send(method, params = {}, sessionId) {
|
||||
if (this.closed) return Promise.reject(new Error(this.closedReason))
|
||||
const id = this.nextId++
|
||||
const message = { id, method, params, ...(sessionId ? { sessionId } : {}) }
|
||||
return new Promise((resolve, reject) => {
|
||||
this.pending.set(id, { resolve, reject })
|
||||
this.toChrome.write(JSON.stringify(message) + "\0")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// One tab. The methods mirror the three things the rest of the plugin asks a
|
||||
// page for: navigate, wait for an expression to become truthy, and evaluate an
|
||||
// expression for its value.
|
||||
class Page {
|
||||
constructor(connection, sessionId, targetId) {
|
||||
this.connection = connection
|
||||
this.sessionId = sessionId
|
||||
this.targetId = targetId
|
||||
this.closed = false
|
||||
}
|
||||
|
||||
send(method, params) {
|
||||
return this.connection.send(method, params, this.sessionId)
|
||||
}
|
||||
|
||||
isClosed() {
|
||||
return this.closed || this.connection.closed
|
||||
}
|
||||
|
||||
async url() {
|
||||
try {
|
||||
const { result } = await this.send("Runtime.evaluate", { expression: "location.href", returnByValue: true })
|
||||
return String(result?.value ?? "")
|
||||
} catch { return "" }
|
||||
}
|
||||
|
||||
async evaluate(fn, arg) {
|
||||
const expression = typeof fn === "string" ? fn : `(${fn.toString()})(${arg === undefined ? "undefined" : JSON.stringify(arg)})`
|
||||
const { result, exceptionDetails } = await this.send("Runtime.evaluate", {
|
||||
expression, returnByValue: true, awaitPromise: true,
|
||||
})
|
||||
if (exceptionDetails) {
|
||||
throw new Error(exceptionDetails.exception?.description?.split("\n")[0] ?? exceptionDetails.text ?? "The page threw while it was read")
|
||||
}
|
||||
return result?.value
|
||||
}
|
||||
|
||||
// Playwright's waitForFunction returns a handle whose value is read with
|
||||
// jsonValue(); the same shape is kept so callers do not care which client
|
||||
// opened the page.
|
||||
async waitForFunction(fn, arg, { timeout = 30000 } = {}) {
|
||||
if (!Number.isFinite(timeout) || timeout <= 0) throw new Error("Page wait timeout must be a positive number of milliseconds")
|
||||
const deadline = Date.now() + timeout
|
||||
for (;;) {
|
||||
if (this.isClosed()) throw new Error("Google Cloud page closed while checking the session")
|
||||
try {
|
||||
const value = await this.evaluate(fn, arg)
|
||||
if (value) return { jsonValue: async () => value, dispose: async () => {} }
|
||||
} catch (error) {
|
||||
// A navigation destroys the execution context the expression was
|
||||
// running in; the next attempt runs in the new document.
|
||||
if (this.isClosed()) throw new Error("Google Cloud page closed while checking the session", { cause: error })
|
||||
// A page whose document is not up yet has nothing to answer with: that
|
||||
// is a reason to ask again, not a failure of the expression.
|
||||
if (/Cannot find context|Execution context was destroyed|Inspected target navigated|Target closed|not available|frame was detached|no execution context/i.test(error.message)) {
|
||||
if (Date.now() >= deadline) throw timeoutError(`Timed out after ${timeout}ms waiting for the page`)
|
||||
await sleep(100)
|
||||
continue
|
||||
}
|
||||
if (!/context was destroyed|Cannot find context|Execution context|Inspected target navigated|Target closed|not available|frame was detached/i.test(error.message)) throw error
|
||||
}
|
||||
if (Date.now() >= deadline) throw timeoutError(`Timed out after ${timeout}ms waiting for the page`)
|
||||
await sleep(100)
|
||||
}
|
||||
}
|
||||
|
||||
// Navigation reports its own failure; the wait for the document to leave the
|
||||
// loading state is bounded separately, because callers poll the page for what
|
||||
// they actually want and a slow Console never means the address was wrong.
|
||||
async goto(url, { timeout = 60000 } = {}) {
|
||||
if (this.closed) throw new Error("Google Cloud page closed before it could be opened")
|
||||
const { errorText } = await this.send("Page.navigate", { url })
|
||||
if (errorText) throw new Error(`Could not open ${url}: ${errorText === "net::ERR_ABORTED" ? "the navigation was replaced by a redirect" : errorText}`)
|
||||
const deadline = Date.now() + Math.min(timeout, 30000)
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
const state = await this.evaluate("document.readyState")
|
||||
if (state && state !== "loading") return
|
||||
} catch (error) {
|
||||
if (this.isClosed()) return
|
||||
if (!/context|navigated|not available|Target closed/i.test(error.message)) throw error
|
||||
}
|
||||
await sleep(50)
|
||||
}
|
||||
}
|
||||
|
||||
async close() {
|
||||
if (this.closed) return
|
||||
this.closed = true
|
||||
if (this.connection.closed) return
|
||||
await this.connection.send("Target.closeTarget", { targetId: this.targetId }).catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
export class Browser {
|
||||
constructor(child, connection) {
|
||||
this.child = child
|
||||
this.connection = connection
|
||||
this.pages = new Set()
|
||||
}
|
||||
|
||||
// A new tab, for the consent page gcloud asks to have opened: it is closed on
|
||||
// its own and leaves the Console page underneath where it was.
|
||||
async newPage() {
|
||||
const { targetId } = await this.connection.send("Target.createTarget", { url: "about:blank" })
|
||||
return this.attach(targetId)
|
||||
}
|
||||
|
||||
async attach(targetId) {
|
||||
const { sessionId } = await this.connection.send("Target.attachToTarget", { targetId, flatten: true })
|
||||
const page = new Page(this.connection, sessionId, targetId)
|
||||
this.pages.add(page)
|
||||
page.send("Page.enable").catch(() => {})
|
||||
return page
|
||||
}
|
||||
|
||||
async firstPage(timeout = 15000) {
|
||||
const deadline = Date.now() + timeout
|
||||
while (Date.now() < deadline) {
|
||||
const { targetInfos = [] } = await this.connection.send("Target.getTargets").catch(() => ({}))
|
||||
const found = targetInfos.find((target) => target.type === "page")
|
||||
if (found) return this.attach(found.targetId)
|
||||
if (this.connection.closed) throw new Error(this.connection.closedReason)
|
||||
await sleep(100)
|
||||
}
|
||||
throw new Error("Chrome did not open a page")
|
||||
}
|
||||
|
||||
// Ending the process ends the profile's session: the cookies stay on disk,
|
||||
// and no Chrome is left running behind the user. The promise settles only
|
||||
// when the process is gone, so whoever holds the profile's lock can be sure
|
||||
// the next Chrome is not starting on top of this one.
|
||||
async close() {
|
||||
for (const page of this.pages) page.closed = true
|
||||
const exited = new Promise((resolve) => {
|
||||
if (this.child.exitCode !== null || this.child.signalCode !== null) resolve()
|
||||
else this.child.once("exit", resolve)
|
||||
})
|
||||
await this.connection.send("Browser.close").catch(() => {})
|
||||
this.connection.shut("Chrome was closed")
|
||||
let timer
|
||||
const gone = await Promise.race([
|
||||
exited.then(() => true),
|
||||
new Promise((resolve) => { timer = setTimeout(() => resolve(false), 5000) }),
|
||||
]).finally(() => clearTimeout(timer))
|
||||
if (!gone) {
|
||||
this.child.kill("SIGTERM")
|
||||
const stopped = await Promise.race([
|
||||
exited.then(() => true),
|
||||
sleep(3000).then(() => false),
|
||||
])
|
||||
if (!stopped) {
|
||||
this.child.kill("SIGKILL")
|
||||
await Promise.race([exited, sleep(2000)])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Chrome answers CDP on descriptors 3 and 4 of the process started here. That
|
||||
// is a private pipe, not a port: nothing else on the machine can connect to it.
|
||||
export function launch(executable, args, { timeout = 30000 } = {}) {
|
||||
const child = spawn(executable, [...args, "--remote-debugging-pipe"], {
|
||||
stdio: ["ignore", "ignore", "ignore", "pipe", "pipe"],
|
||||
detached: false,
|
||||
})
|
||||
const connection = new Pipe(child)
|
||||
const failed = new Promise((_, reject) => {
|
||||
child.once("error", (error) => {
|
||||
connection.shut("Chrome could not be started")
|
||||
reject(error.code === "ENOENT"
|
||||
? new Error("Chrome not found; set VERTEX_CHROME_PATH to its executable")
|
||||
: new Error(`Chrome could not be started: ${error.message}`))
|
||||
})
|
||||
child.once("exit", (code) => {
|
||||
connection.shut(`Chrome exited (${code ?? "signal"})`)
|
||||
})
|
||||
})
|
||||
failed.catch(() => {})
|
||||
const browser = new Browser(child, connection)
|
||||
// A profile that is already open refuses the second launch: Chrome prints
|
||||
// that and exits, which the first command below reports as a closed pipe.
|
||||
return Promise.race([browser.firstPage(timeout).then((page) => ({ browser, page })), failed])
|
||||
}
|
||||
@@ -0,0 +1,785 @@
|
||||
import { execFile, spawn } from "node:child_process"
|
||||
import { createHash } from "node:crypto"
|
||||
import { mkdir, mkdtemp, readFile, readdir, rename, rm, stat } from "node:fs/promises"
|
||||
import { homedir } from "node:os"
|
||||
import { dirname, join } from "node:path"
|
||||
import { promisify } from "node:util"
|
||||
import { configRoot, expandPath, home, openSignInWindow, validateProject } from "./browser.mjs"
|
||||
|
||||
const execute = promisify(execFile)
|
||||
const loginTimeout = 10 * 60 * 1000
|
||||
|
||||
// gcloud owns refresh tokens and its on-disk token cache. This module reads
|
||||
// them and, only when no ADC exists at all, has gcloud make one from the Chrome
|
||||
// sign-in already in progress; it never handles token material itself.
|
||||
// Never include command output in failures: it can contain credential material.
|
||||
//
|
||||
// A Google account's ADC is one file in one config directory, so a second
|
||||
// account on the same machine gets a directory of its own. Cloud SDK reads
|
||||
// CLOUDSDK_CONFIG before its default and does not expand "~" in it, so the
|
||||
// path is made absolute here.
|
||||
//
|
||||
// Only a directory this plugin resolved for an account is ever used: the
|
||||
// machine-wide CLOUDSDK_CONFIG variable is not read at all. One variable would
|
||||
// point every account at one ADC, and a sign-in there would write over
|
||||
// credentials the plugin never made.
|
||||
export function cloudsdkConfig(options = {}) {
|
||||
const configured = options.cloudsdkConfig
|
||||
return configured ? expandPath(configured) : undefined
|
||||
}
|
||||
|
||||
// gcloud reads CLOUDSDK_CONFIG before its default. With no directory of this
|
||||
// plugin's own, the variable is taken away rather than passed through: the ADC
|
||||
// read here is gcloud's default, and a machine-wide variable pointing somewhere
|
||||
// else would make gcloud print a token from a directory this plugin never read.
|
||||
function gcloudEnvironment(options = {}) {
|
||||
const directory = cloudsdkConfig(options)
|
||||
if (directory) return { ...process.env, CLOUDSDK_CONFIG: directory }
|
||||
if (!("CLOUDSDK_CONFIG" in process.env)) return process.env
|
||||
const env = { ...process.env }
|
||||
delete env.CLOUDSDK_CONFIG
|
||||
return env
|
||||
}
|
||||
|
||||
// gcloud on Windows is gcloud.cmd, a batch file. execFile and spawn without a
|
||||
// shell run it as a binary, which the OS refuses with EINVAL, so every call
|
||||
// there goes through cmd.exe. The arguments are fixed strings this module built
|
||||
// (never anything a person typed), and cmd is only asked to start one program
|
||||
// by name, so there is nothing for a shell to interpolate: the command name and
|
||||
// each argument are quoted, and a quote inside one would end the quoting, so an
|
||||
// argument that could not be carried is refused rather than handed over.
|
||||
const WINDOWS = process.platform === "win32"
|
||||
|
||||
function command(name, args) {
|
||||
if (!WINDOWS) return { file: name, args, options: {} }
|
||||
for (const value of [name, ...args]) {
|
||||
if (/["\r\n]/.test(value)) throw new Error(`Cannot run ${name} on Windows: an argument contains a quote or a line break`)
|
||||
}
|
||||
return { file: process.env.ComSpec || "cmd.exe", args: ["/d", "/s", "/c", `"${[name, ...args].map((value) => `"${value}"`).join(" ")}"`], options: { windowsVerbatimArguments: true } }
|
||||
}
|
||||
|
||||
export async function runGcloud(args, options = {}) {
|
||||
try {
|
||||
const started = command("gcloud", [...args, "--quiet"])
|
||||
const { stdout } = await execute(started.file, started.args, {
|
||||
timeout: 30000, maxBuffer: 1024 * 1024, encoding: "utf8", windowsHide: true, env: gcloudEnvironment(options), ...started.options,
|
||||
})
|
||||
return stdout.trim()
|
||||
} catch (error) {
|
||||
if (error.code === "ENOENT") throw new Error("gcloud CLI was not found; install Google Cloud CLI and make it available on PATH")
|
||||
if (error.killed) throw new Error("gcloud timed out while reading Google Cloud credentials; retry after checking connectivity")
|
||||
const adc = args.includes("application-default")
|
||||
throw new Error(`gcloud could not read Google Cloud credentials or configuration. Run ${adc ? "gcloud auth application-default login" : "gcloud auth login"} yourself in a terminal, and check the active gcloud configuration.`)
|
||||
}
|
||||
}
|
||||
|
||||
function configured(value) {
|
||||
return value && value !== "(unset)" ? value : undefined
|
||||
}
|
||||
|
||||
export function authMode(options = {}) {
|
||||
const mode = options.authMode || process.env.VERTEX_GCLOUD_AUTH_MODE || "auto"
|
||||
if (!["auto", "gcloud", "adc"].includes(mode)) throw new Error("VERTEX_GCLOUD_AUTH_MODE must be auto, gcloud or adc")
|
||||
return mode
|
||||
}
|
||||
|
||||
// Application Default Credentials are what the official Vertex clients use.
|
||||
// Mirror their lookup: an explicit credentials file first, then gcloud's
|
||||
// well-known ADC file. Existence alone decides the default mode; a broken file
|
||||
// still surfaces as a clear ADC error rather than silently switching identity.
|
||||
//
|
||||
// An account that named its own config directory is read from there and
|
||||
// nowhere else: GOOGLE_APPLICATION_CREDENTIALS is a machine-wide setting, and
|
||||
// letting it win would give every account the same ADC again.
|
||||
export async function adcFile(options = {}) {
|
||||
if (options.cloudsdkConfig) return join(expandPath(options.cloudsdkConfig), "application_default_credentials.json")
|
||||
const explicit = process.env.GOOGLE_APPLICATION_CREDENTIALS
|
||||
if (explicit) return expandPath(explicit)
|
||||
// gcloud's default directory, as gcloudEnvironment tells gcloud: a
|
||||
// machine-wide CLOUDSDK_CONFIG is not read here either.
|
||||
return join(gcloudDefaultDirectory(), "application_default_credentials.json")
|
||||
}
|
||||
|
||||
export async function hasAdc(options = {}, exists = async (path) => { try { await readFile(path); return true } catch { return false } }) {
|
||||
return exists(await adcFile(options))
|
||||
}
|
||||
|
||||
// The quota project recorded in ADC is the same hint official clients send as
|
||||
// x-goog-user-project, so it is a better default than gcloud's active project.
|
||||
export async function adcQuotaProject(options = {}) {
|
||||
try {
|
||||
const data = JSON.parse(await readFile(await adcFile(options), "utf8"))
|
||||
return typeof data.quota_project_id === "string" ? data.quota_project_id : undefined
|
||||
} catch { return undefined }
|
||||
}
|
||||
|
||||
export async function effectiveAuthMode(options = {}) {
|
||||
const mode = authMode(options)
|
||||
if (mode !== "auto") return mode
|
||||
return (await hasAdc(options)) ? "adc" : "gcloud"
|
||||
}
|
||||
|
||||
export function validateAccount(account) {
|
||||
if (typeof account !== "string" || !/^[^\s@]+@[^\s@]+$/.test(account) || account.startsWith("-")) throw new Error("Set VERTEX_GCLOUD_ACCOUNT to the intended Google account email")
|
||||
return account
|
||||
}
|
||||
|
||||
// An explicit project wins. Otherwise the one the signed-in Chrome is actually
|
||||
// on comes before anything gcloud remembers: the Console page is the only
|
||||
// source that names a project the same Google account the cookies belong to
|
||||
// can open, so the models and the credits cannot drift onto different projects.
|
||||
export async function resolveProject(options = {}, run = runGcloud, mode) {
|
||||
// An account's own project is the one that account reads credits from and
|
||||
// bills to; it outranks the machine-wide variables, which every account
|
||||
// would otherwise share.
|
||||
const project = options.project
|
||||
|| options.chromeProject
|
||||
|| process.env.GOOGLE_VERTEX_PROJECT || process.env.GOOGLE_CLOUD_PROJECT
|
||||
// ADC's quota_project_id selects quota billing, not the project whose
|
||||
// Vertex resources this account should use. It cannot fill this gap.
|
||||
|| configured(await run(["config", "get-value", "project"], options))
|
||||
if (!project) throw Object.assign(new Error("No Google Cloud project is configured. Set the project selected in Cloud Console using GOOGLE_VERTEX_PROJECT, GOOGLE_CLOUD_PROJECT or --project."), { code: "VERTEX_PROJECT_REQUIRED" })
|
||||
return validateProject(project)
|
||||
}
|
||||
|
||||
export async function resolveAccount(options = {}, run = runGcloud) {
|
||||
const account = options.account || process.env.VERTEX_GCLOUD_ACCOUNT || configured(await run(["config", "get-value", "account"], options))
|
||||
if (!account) throw new Error("No Google Cloud account is signed in. Run gcloud auth login yourself in a terminal.")
|
||||
return validateAccount(account)
|
||||
}
|
||||
|
||||
export async function resolveIdentity(options = {}, run = runGcloud) {
|
||||
const mode = await effectiveAuthMode(options)
|
||||
// ADC is independent of the active gcloud user. An explicit account in ADC
|
||||
// mode is only a Console hint; never mislabel ADC with gcloud's active email.
|
||||
const hint = options.account || process.env.VERTEX_GCLOUD_ACCOUNT
|
||||
const [project, account] = await Promise.all([
|
||||
resolveProject(options, run, mode),
|
||||
mode === "gcloud" ? resolveAccount(options, run) : hint ? validateAccount(hint) : undefined,
|
||||
])
|
||||
// The config directory travels with the identity: every later gcloud call
|
||||
// for this account must read the same ADC it was resolved from.
|
||||
const cloudsdkConfig = options.cloudsdkConfig
|
||||
return { project, ...(account ? { account } : {}), source: "gcloud", authMode: mode, ...(cloudsdkConfig ? { cloudsdkConfig } : {}) }
|
||||
}
|
||||
|
||||
// ADC records a client id and a quota project, not who signed in, so an ADC
|
||||
// identity has no email. The token it prints can ask Google that question
|
||||
// directly; the answer is the same account the token bills to. A failure here
|
||||
// is not a credential failure: it only leaves the account unnamed.
|
||||
export async function accountOf(token, request = fetch) {
|
||||
try {
|
||||
const response = await request("https://openidconnect.googleapis.com/v1/userinfo", {
|
||||
headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(10000),
|
||||
})
|
||||
if (!response.ok) return undefined
|
||||
const body = await response.json()
|
||||
return typeof body.email === "string" ? validateAccount(body.email) : undefined
|
||||
} catch { return undefined }
|
||||
}
|
||||
|
||||
// Which projects the signed-in account could actually serve. Cloud Resource
|
||||
// Manager lists the projects that are alive; Service Usage says whether Vertex
|
||||
// AI is turned on in each. Billing is deliberately not consulted: whether a
|
||||
// project can pay is the account owner's decision, not a reason to hide it.
|
||||
//
|
||||
// This runs inside a sign-in, so it never throws: no list, no permission or no
|
||||
// network only means there is nothing to offer, and the sign-in can then say
|
||||
// so instead of failing as a credential error. Neither the token nor a
|
||||
// response body is ever put in an error or logged.
|
||||
const PROJECT_CONCURRENCY = 6
|
||||
const PROJECT_TIMEOUT = 15000
|
||||
|
||||
async function usableProjects(token, request = fetch) {
|
||||
const response = await request("https://cloudresourcemanager.googleapis.com/v1/projects", {
|
||||
headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(PROJECT_TIMEOUT),
|
||||
})
|
||||
if (!response.ok) throw new Error(`Cloud Resource Manager returned ${response.status}`)
|
||||
const body = await response.json()
|
||||
const active = Array.isArray(body?.projects)
|
||||
? body.projects.filter((project) => project && project.lifecycleState === "ACTIVE" && typeof project.projectId === "string" && project.projectId)
|
||||
: []
|
||||
const usable = new Array(active.length)
|
||||
let next = 0
|
||||
// A small pool: a person may have dozens of projects, and asking for all of
|
||||
// them at once is how a sign-in gets rate limited by its own probe.
|
||||
const worker = async () => {
|
||||
while (next < active.length) {
|
||||
const index = next++
|
||||
const project = active[index]
|
||||
const enabled = await request(
|
||||
`https://serviceusage.googleapis.com/v1/projects/${encodeURIComponent(project.projectId)}/services/aiplatform.googleapis.com`,
|
||||
{ headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(PROJECT_TIMEOUT) },
|
||||
)
|
||||
.then((probe) => (probe.ok ? probe.json() : undefined))
|
||||
.then((service) => service?.state === "ENABLED")
|
||||
.catch(() => false)
|
||||
usable[index] = {
|
||||
projectId: project.projectId,
|
||||
name: typeof project.name === "string" && project.name ? project.name : project.projectId,
|
||||
vertexEnabled: enabled === true,
|
||||
}
|
||||
}
|
||||
}
|
||||
await Promise.all(Array.from({ length: Math.min(PROJECT_CONCURRENCY, active.length) }, worker))
|
||||
return usable
|
||||
}
|
||||
|
||||
export async function listUsableProjects(token, request = fetch) {
|
||||
if (typeof token !== "string" || !token) return { projects: [], error: "No access token was available" }
|
||||
try {
|
||||
return { projects: await usableProjects(token, request), error: undefined }
|
||||
} catch (error) {
|
||||
return { projects: [], error: error?.message ?? "The project list could not be read" }
|
||||
}
|
||||
}
|
||||
|
||||
export function tokenProvider(options = {}, run = runGcloud) {
|
||||
let pending
|
||||
// print-access-token can return a token near expiry. Do not assume it has a
|
||||
// fresh one-hour lifetime; gcloud checks expiry and refreshes on each call.
|
||||
// Simultaneous requests still share a single subprocess. The mode is resolved
|
||||
// once per call chain so an identity resolved earlier pins it.
|
||||
return () => {
|
||||
pending ??= (async () => {
|
||||
const mode = await effectiveAuthMode(options)
|
||||
const args = mode === "adc"
|
||||
? ["auth", "application-default", "print-access-token"]
|
||||
: ["auth", "print-access-token", `--account=${await resolveAccount(options, run)}`]
|
||||
const token = await run(args, options)
|
||||
if (!token || /\s/.test(token)) throw new Error(`gcloud returned an empty or invalid access token; run ${mode === "adc" ? "gcloud auth application-default login" : "gcloud auth login"} yourself in a terminal`)
|
||||
return token
|
||||
})().finally(() => { pending = undefined })
|
||||
return pending
|
||||
}
|
||||
}
|
||||
|
||||
// This is only a Chrome Console login. gcloud authentication must already be
|
||||
// usable, and is verified before opening the browser. No CLI login is invoked.
|
||||
// gcloud's own browser flow keeps the localhost callback server and the token
|
||||
// exchange; only the window it would open is taken away, by pointing BROWSER
|
||||
// at a command that does nothing. The consent page is then opened in the
|
||||
// Chrome profile that is already signed in for credits, so one approval sets
|
||||
// up ADC and the Console cookies for the same account. gcloud still writes
|
||||
// ADC itself: this never handles a refresh token or a client secret.
|
||||
//
|
||||
// What it returns is what the caller may undo: `file` exists only when this
|
||||
// run is the one that made it, and only that file is ever removed again.
|
||||
// gcloud's consent flow, started but not yet shown.
|
||||
//
|
||||
// What comes back is the address gcloud wants approved and a promise that
|
||||
// settles when gcloud is done with it. That order matters: the address has to
|
||||
// exist before a window opens, because the window is opened *on it* — one
|
||||
// window, one tab, and the person signs in and approves in the same place.
|
||||
// Waiting for gcloud's exit is also how the sign-in knows it is over; there is
|
||||
// nothing to poll and nothing to guess at.
|
||||
export async function beginAdcLogin(options = {}, run = spawn) {
|
||||
// The project is handed over as gcloud's own --project, which it writes to
|
||||
// ADC as the quota project, so later calls bill the project this plugin
|
||||
// serves rather than whatever gcloud last had active. --quiet is left off:
|
||||
// it is what suppresses the consent URL that is read here.
|
||||
const project = options.project || process.env.GOOGLE_VERTEX_PROJECT || process.env.GOOGLE_CLOUD_PROJECT
|
||||
const args = ["auth", "application-default", "login"]
|
||||
if (project) args.push(`--project=${project}`, `--billing-project=${project}`)
|
||||
// gcloud writes ADC before it looks for a quota project, and that lookup
|
||||
// needs Cloud Resource Manager. When the API is off it throws after the file
|
||||
// is already saved, so the exit code alone would report a failed sign-in
|
||||
// that in fact produced usable credentials. What tells the two apart is the
|
||||
// file itself: one written after this run began is success either way.
|
||||
const file = await adcFile(options)
|
||||
const before = await stat(file).then((s) => s.mtimeMs, () => 0)
|
||||
// BROWSER is neutralised so gcloud does not open a window of its own: the
|
||||
// person approves in the one window this plugin opened, and a second browser
|
||||
// would be both confusing and, being unapproved by them, unwanted.
|
||||
//
|
||||
// gcloud hands BROWSER to Python's webbrowser, which reads the value as a
|
||||
// command line with %s standing for the address. `true` is that command on
|
||||
// macOS and Linux and does not exist on Windows, where cmd.exe's own `rem`
|
||||
// is the no-op — spelled out with /c so it is one command, not a shell.
|
||||
const started = command("gcloud", args)
|
||||
const child = run(started.file, started.args, {
|
||||
stdio: ["ignore", "pipe", "pipe"], env: { ...gcloudEnvironment(options), BROWSER: WINDOWS ? "cmd /c rem %s" : "true" }, windowsHide: true, ...started.options,
|
||||
})
|
||||
let seen = ""
|
||||
let announce
|
||||
const url = new Promise((resolve) => { announce = resolve })
|
||||
// A gcloud that never prints an address (no network, no CLI) must not leave
|
||||
// the caller waiting on a window that can never open.
|
||||
const timer = setTimeout(() => announce(undefined), 60000)
|
||||
timer.unref?.()
|
||||
const scan = (chunk) => {
|
||||
if (seen.includes("\u0000")) return
|
||||
seen += String(chunk)
|
||||
// gcloud ends the URL with a newline: a match followed by whitespace is the
|
||||
// whole address, while a chunk boundary is not.
|
||||
const found = /https:\/\/accounts\.google\.com\/o\/oauth2\/auth\?\S+(?=\s)/.exec(seen)
|
||||
if (!found) return
|
||||
seen += "\u0000" // one address, announced once
|
||||
clearTimeout(timer)
|
||||
announce(found[0].trim())
|
||||
}
|
||||
child.stderr?.on("data", scan)
|
||||
child.stdout?.on("data", scan)
|
||||
const done = new Promise((resolve, reject) => {
|
||||
const expiry = setTimeout(() => {
|
||||
child.kill("SIGKILL")
|
||||
reject(new Error("Google sign-in did not finish within ten minutes; run gcloud auth application-default login yourself in a terminal"))
|
||||
}, loginTimeout)
|
||||
expiry.unref?.()
|
||||
const finish = (error) => { clearTimeout(expiry); clearTimeout(timer); announce(undefined); error ? reject(error) : resolve() }
|
||||
child.once("error", (error) => finish(new Error(error.code === "ENOENT"
|
||||
? "gcloud CLI was not found; installing it lets this plugin set up ADC from the Chrome sign-in"
|
||||
: "gcloud could not be started to set up ADC")))
|
||||
child.once("exit", async (code) => {
|
||||
if (code !== 0) {
|
||||
const written = await stat(file).then((s) => s.mtimeMs > before).catch(() => false)
|
||||
// A new ADC file means the sign-in worked; only the quota-project probe
|
||||
// after it failed, which this plugin does not depend on.
|
||||
if (!written) return finish(new Error("gcloud could not set up ADC from the Chrome sign-in; run gcloud auth application-default login yourself in a terminal"))
|
||||
}
|
||||
finish()
|
||||
})
|
||||
})
|
||||
// The caller owns the rejection; this keeps a process that never awaits it
|
||||
// from crashing on an unhandled one.
|
||||
done.catch(() => {})
|
||||
return { url, done, child, file: before ? undefined : file }
|
||||
}
|
||||
|
||||
// One Google account's ADC is one file, and the plugin keeps its own for every
|
||||
// account it serves. gcloud's default directory (~/.config/gcloud) is the
|
||||
// machine's: it is what every other Google client library on the machine reads,
|
||||
// so a sign-in here writes nothing there. Each account's ADC goes to a
|
||||
// directory of its own under the plugin's own root instead, which is also what
|
||||
// lets two Google accounts coexist and keeps the plugin's quota project from
|
||||
// leaking into anyone else's tooling.
|
||||
export function adcSlug(account) {
|
||||
return account.replace(/[^a-z0-9]+/gi, "-").toLowerCase()
|
||||
}
|
||||
|
||||
// Where the plugin keeps per-account state: ADC directories named by account,
|
||||
// and the profile lock that says which account a Chrome profile last served.
|
||||
export function adcRoot() {
|
||||
return join(configRoot(), "gcp-ai")
|
||||
}
|
||||
|
||||
export function adcDirectoryFor(account, root = adcRoot()) {
|
||||
return join(root, `adc-${adcSlug(account)}`)
|
||||
}
|
||||
|
||||
// A slug is readable, not unique: a.b@x.com and a-b@x.com both become
|
||||
// a-b-x-com, and one directory holding the other account's ADC is a sign-in
|
||||
// refused for an account that was never here. So a slug another account
|
||||
// already owns gets a short hash of the full address appended; the first
|
||||
// account keeps the readable name.
|
||||
const disambiguated = (account, root) => join(root, `adc-${adcSlug(account)}-${createHash("sha256").update(account.toLowerCase()).digest("hex").slice(0, 6)}`)
|
||||
|
||||
// Where this account's own ADC lives, whether or not it exists yet. The
|
||||
// readable directory is read first, so the check costs nothing for the usual
|
||||
// case; a hash-suffixed one is only ever consulted after it.
|
||||
export async function adcDirectoryOwnedBy(account, root = adcRoot()) {
|
||||
const plain = adcDirectoryFor(account, root)
|
||||
if (await hasAdc({ cloudsdkConfig: plain })) {
|
||||
// Offline is not evidence of another owner: only a definite answer moves
|
||||
// the account to a directory of its own.
|
||||
const owner = await adcOwner({ cloudsdkConfig: plain }).catch(() => undefined)
|
||||
if (!owner || owner.toLowerCase() === account.toLowerCase()) return plain
|
||||
return disambiguated(account, root)
|
||||
}
|
||||
const hashed = disambiguated(account, root)
|
||||
return (await hasAdc({ cloudsdkConfig: hashed })) ? hashed : plain
|
||||
}
|
||||
|
||||
// The directory a sign-in may write this account's ADC into: the readable one
|
||||
// unless another account already owns it, in which case the hash-suffixed one.
|
||||
export async function adcDirectoryToCreate(account, root = adcRoot()) {
|
||||
const plain = adcDirectoryFor(account, root)
|
||||
const exists = await stat(plain).then(() => true, (error) => { if (error.code === "ENOENT") return false; throw error })
|
||||
if (!exists) return plain
|
||||
const owner = await adcOwner({ cloudsdkConfig: plain }).catch(() => undefined)
|
||||
if (!owner || owner.toLowerCase() === account.toLowerCase()) return plain
|
||||
return disambiguated(account, root)
|
||||
}
|
||||
|
||||
// gcloud's own default directory. ADC written here is read by every Google
|
||||
// client library on the machine, so this plugin never writes to it: it is only
|
||||
// ever read, when a machine already signed in that way before the plugin
|
||||
// existed. A configured CLOUDSDK_CONFIG that points here is the same directory
|
||||
// under another name.
|
||||
export function gcloudDefaultDirectory() {
|
||||
if (process.platform === "win32" && process.env.APPDATA) return join(process.env.APPDATA, "gcloud")
|
||||
return join(home(), ".config", "gcloud")
|
||||
}
|
||||
|
||||
export const isGcloudDefault = (directory) => expandPath(directory) === expandPath(gcloudDefaultDirectory())
|
||||
|
||||
const ADC_DIRS = "adc-"
|
||||
|
||||
// The Google accounts this plugin has already filed an ADC for, as the
|
||||
// directories under its own root name them. A sign-in compares the account its
|
||||
// new ADC belongs to against this: an account already here is an overwrite and
|
||||
// is not recorded again. A directory that exists without an ADC file is not one
|
||||
// of them — an interrupted run must not make its account look signed in.
|
||||
//
|
||||
// The machine's own gcloud ADC is deliberately not part of this set. It is a
|
||||
// different credential in a different place, read by every other Google client
|
||||
// on the machine; signing in here adds the plugin's own ADC even for an account
|
||||
// that file already belongs to. Only what this plugin filed counts.
|
||||
export async function knownAccounts(options = {}) {
|
||||
const root = options.adcRoot ? expandPath(options.adcRoot) : adcRoot()
|
||||
const known = new Set()
|
||||
for (const name of await readdir(root).catch(() => [])) {
|
||||
if (!name.startsWith(ADC_DIRS)) continue
|
||||
// A staging directory is one a sign-in made before it knew whose ADC it
|
||||
// was writing. Its suffix is random, not an account, so counting it would
|
||||
// add a name nobody can sign in as and let a later sign-in match it.
|
||||
if (name.startsWith(`${ADC_DIRS}pending-`)) continue
|
||||
if (await hasAdc({ cloudsdkConfig: join(root, name) })) known.add(name.slice(ADC_DIRS.length))
|
||||
}
|
||||
return known
|
||||
}
|
||||
|
||||
// Who an ADC belongs to. ADC records a client id and a quota project, not an
|
||||
// email, so the only answer comes from the token gcloud prints for it.
|
||||
async function adcOwner(options = {}) {
|
||||
try {
|
||||
return await accountOf(await tokenProvider({ authMode: "adc", ...options })())
|
||||
} catch { return undefined }
|
||||
}
|
||||
|
||||
// Google's own "add another account" page. Console is the fallback destination
|
||||
// for a session without ADC consent; signInUrl replaces that destination with
|
||||
// gcloud's consent URL whenever this run is creating credentials.
|
||||
export const ADD_ACCOUNT_URL = "https://accounts.google.com/AddSession?hl=en&continue=https%3A%2F%2Fconsole.cloud.google.com%2F"
|
||||
|
||||
const consoleUrl = (account, project) => "https://console.cloud.google.com/?hl=en"
|
||||
+ (project ? `&project=${encodeURIComponent(project)}` : "")
|
||||
+ (account ? `&authuser=${encodeURIComponent(account)}` : "")
|
||||
|
||||
// An error that ends the sign-in instead of merely leaving it without a
|
||||
// Console: the person added no account, or added one that is already here.
|
||||
// There is nothing to save, and the message is what they are shown.
|
||||
const stopped = (message) => Object.assign(new Error(message), { stopped: true })
|
||||
|
||||
// The project a new ADC will serve. Magpie cannot ask the person anything once
|
||||
// authorize() has started, and the project list only exists after consent, so
|
||||
// there is nowhere to ask and nothing to ask with: the first project the
|
||||
// account already has Vertex AI turned on in is taken as it is. The order is
|
||||
// Cloud Resource Manager's, which keeps the answer stable between two sign-ins
|
||||
// of the same account.
|
||||
//
|
||||
// An explicit project wins and needs no list. `picked` tells the caller the
|
||||
// sign-in chose this one itself, which is what the editor's field then shows.
|
||||
function chooseProject({ projects, who, options = {} }) {
|
||||
const explicit = options.project || process.env.GOOGLE_VERTEX_PROJECT || process.env.GOOGLE_CLOUD_PROJECT
|
||||
if (explicit) {
|
||||
const project = validateProject(explicit)
|
||||
// A configured project needs no list, but a list that was read may say the
|
||||
// API is off. Refusing then is the same clear verdict as the empty case;
|
||||
// a project the list does not mention is not second-guessed.
|
||||
const listed = (projects ?? []).find((candidate) => candidate.projectId === project)
|
||||
if (listed && listed.vertexEnabled !== true) {
|
||||
throw stopped(`${project} does not have Vertex AI enabled, so nothing was registered. Enable the Vertex AI API (aiplatform.googleapis.com) in ${project} in Cloud Console, then sign in again`)
|
||||
}
|
||||
return project
|
||||
}
|
||||
const account = who ? ` for ${who}` : ""
|
||||
const usable = (projects ?? []).filter((project) => project.vertexEnabled === true)
|
||||
if (!usable.length) {
|
||||
throw stopped(`No Google Cloud project${account} has Vertex AI enabled, so nothing was registered. Create a Google Cloud project and enable the Vertex AI API (aiplatform.googleapis.com) in it in Cloud Console, then sign in again.`)
|
||||
}
|
||||
return validateProject(usable[0].projectId)
|
||||
}
|
||||
|
||||
// Which Google account this sign-in serves.
|
||||
//
|
||||
// Signing in is the one thing a browser this plugin drives cannot do: Google
|
||||
// refuses a sign-in from a browser that has a DevTools client attached ("This
|
||||
// browser or app may not be secure"), and every way of driving Chrome — a
|
||||
// debugging port, a debugging pipe — is such a client. Hiding the marks it is
|
||||
// detected by is a race against Google's next change, so this does not try:
|
||||
// the sign-in happens in a window with no debugging transport at all, opened
|
||||
// by openSignInWindow, and the plugin closes that window when gcloud finishes.
|
||||
// Later credits reads use the same Chrome profile, so the cookies set by hand
|
||||
// are the cookies the Console is read with.
|
||||
//
|
||||
// The first account on a machine goes straight to gcloud's consent page. The
|
||||
// add-account page exists to put a second identity into a profile that already
|
||||
// has one; with nothing to add it is a page stood in front of the sign-in that
|
||||
// asks the person to choose between nothing. Every later sign-in does open it,
|
||||
// because there the choice is real: the account picked there is the account the
|
||||
// consent page is approved as, so the cookies the credits are read with and the
|
||||
// token gcloud writes belong to the same person. gcloud's own address is passed
|
||||
// through untouched either way, which is what Google accepts.
|
||||
function signInUrl(consentUrl, known) {
|
||||
if (!consentUrl) return known.size ? ADD_ACCOUNT_URL : consoleUrl(undefined)
|
||||
if (!known.size) return consentUrl
|
||||
const url = new URL(ADD_ACCOUNT_URL)
|
||||
// Replace the Console destination rather than append a second continue:
|
||||
// Google could otherwise choose the first one and never reach consent.
|
||||
// Treat gcloud's URL as one opaque value so decoding this outer parameter
|
||||
// returns the original state, redirect_uri and scope byte for byte.
|
||||
url.searchParams.set("continue", consentUrl)
|
||||
return url.href
|
||||
}
|
||||
|
||||
export async function startLogin(options = {}, openWindow = openSignInWindow) {
|
||||
const wanted = authMode(options)
|
||||
const limit = Number(options.loginTimeout) > 0 ? Number(options.loginTimeout) : loginTimeout
|
||||
// Snapshot existing ADC accounts before this run writes credentials, so its
|
||||
// own ADC cannot make a newly approved account look like an existing one.
|
||||
const registered = await knownAccounts(options)
|
||||
let window
|
||||
let login
|
||||
let finished = false
|
||||
let cancelled = false
|
||||
let closing
|
||||
// Closing is shared by the timeout, the host and the normal end of sign-in.
|
||||
// Stop an unfinished writer before any cleanup, so it cannot recreate an ADC
|
||||
// after this run removed it.
|
||||
const close = () => {
|
||||
cancelled = true
|
||||
closing ??= (async () => {
|
||||
clearTimeout(timer)
|
||||
if (login && !finished) {
|
||||
login.child.kill("SIGKILL")
|
||||
await login.done.catch(() => {})
|
||||
}
|
||||
const opened = await Promise.resolve(window).catch(() => undefined)
|
||||
if (opened) await opened.close().catch(() => {})
|
||||
})()
|
||||
return closing
|
||||
}
|
||||
const timer = setTimeout(() => { void close().catch(() => {}) }, limit)
|
||||
timer.unref?.()
|
||||
const result = (async () => {
|
||||
const account = options.account
|
||||
const pinned = Boolean(options.cloudsdkConfig && !account)
|
||||
const creating = wanted !== "gcloud" && !pinned
|
||||
const root = options.adcRoot ? expandPath(options.adcRoot) : adcRoot()
|
||||
let directory = options.cloudsdkConfig
|
||||
let createdDirectory = false
|
||||
let chromeError
|
||||
let adcEmail
|
||||
// An existing directory is never removed, even if this run made its ADC.
|
||||
// Conversely, an unnamed sign-in gets a unique directory that this run can
|
||||
// safely remove or rename without touching another sign-in's files.
|
||||
const discard = async () => {
|
||||
if (!directory || isGcloudDefault(directory)) return
|
||||
if (login?.file) await rm(login.file, { force: true })
|
||||
if (createdDirectory) await rm(directory, { recursive: true, force: true })
|
||||
}
|
||||
// Naming an existing ADC directory without an account is an explicit
|
||||
// read-only import, including recovery after consent succeeded but project
|
||||
// selection failed. It neither adds another ADC nor needs another consent
|
||||
// window; the host can save its project once the caller supplies it.
|
||||
if (pinned && wanted !== "gcloud") {
|
||||
const found = await resolveIdentity({ ...options, authMode: "adc" })
|
||||
const owner = await accountOf(await tokenProvider(found)())
|
||||
if (!owner) throw stopped("The existing ADC was kept, but its Google account could not be confirmed; no account was recorded")
|
||||
return { ...found, account: owner, creditsSession: "unavailable", warning: "Existing ADC imported; the Chrome Console session was not checked" }
|
||||
}
|
||||
// Saving and reading ADC happens while the window is still open. A failure
|
||||
// here leaves through the block below, whose finally closes it.
|
||||
try {
|
||||
if (creating) {
|
||||
if (account) {
|
||||
// Login writes one directory and it is always this plugin's own, named
|
||||
// for the account. A directory the plugin didn't create — a
|
||||
// CLOUDSDK_CONFIG the user set, gcloud's default — is read at most:
|
||||
// pointing gcloud's consent flow at it overwrote another account's ADC
|
||||
// while the sign-in said nothing had been added.
|
||||
directory = await adcDirectoryToCreate(account, root)
|
||||
if (isGcloudDefault(directory)) throw stopped("Cannot create sign-in credentials in the machine's default gcloud directory")
|
||||
// An ADC this plugin already filed for the account is an overwrite
|
||||
// rather than a new account: refusing here means no window opens and
|
||||
// the file is never written a second time. The machine's own ADC does
|
||||
// not count — it belongs to gcloud, is only ever read, and signing in
|
||||
// adds this plugin's own credential beside it.
|
||||
if (await hasAdc({ cloudsdkConfig: directory })) {
|
||||
throw stopped("That account was already signed in and its ADC already existed, so no new account or ADC was added. Sign in again with a different Google account")
|
||||
}
|
||||
await mkdir(dirname(directory), { recursive: true, mode: 0o700 })
|
||||
try {
|
||||
await mkdir(directory, { mode: 0o700 })
|
||||
createdDirectory = true
|
||||
} catch (error) { if (error.code !== "EEXIST") throw error }
|
||||
} else {
|
||||
await mkdir(root, { recursive: true, mode: 0o700 })
|
||||
directory = await mkdtemp(join(root, "adc-pending-"))
|
||||
createdDirectory = true
|
||||
}
|
||||
login = await beginAdcLogin({ ...options, cloudsdkConfig: directory })
|
||||
}
|
||||
const consentUrl = login ? await login.url : undefined
|
||||
if (cancelled) throw stopped("Google sign-in was stopped; no new account was saved")
|
||||
if (login && !consentUrl) {
|
||||
await login.done
|
||||
throw stopped("gcloud did not provide a consent page; no new account was added. Start the sign-in again")
|
||||
}
|
||||
// One undriven Chrome opens directly on AddSession with gcloud's consent
|
||||
// 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 })
|
||||
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)
|
||||
expiry.unref?.()
|
||||
const completion = login ? login.done : signing.ended.then((error) => { if (error) throw error })
|
||||
completion.then(() => { finished = true; clearTimeout(expiry); resolve() }, (error) => { clearTimeout(expiry); reject(error) })
|
||||
})
|
||||
} catch (error) {
|
||||
chromeError = error
|
||||
}
|
||||
// The window is closed only when this section is done — by its own finally,
|
||||
// which every return and failure below goes through. The other closer is
|
||||
// the caller (close), on a cancellation or its timeout.
|
||||
try {
|
||||
if (creating && chromeError) {
|
||||
await discard()
|
||||
throw chromeError
|
||||
}
|
||||
if (creating) {
|
||||
// A successful gcloud exit is not proof of a new ADC: login.file is set
|
||||
// only when there was no file before this run. Reapproving an existing
|
||||
// ADC must not turn an overwrite into a new account record.
|
||||
if (!login.file) {
|
||||
await discard()
|
||||
throw stopped("That account was already signed in and its ADC already existed, so no new account or ADC was added. Sign in again with a different Google account")
|
||||
}
|
||||
if (!(await hasAdc({ cloudsdkConfig: directory }))) {
|
||||
await discard()
|
||||
throw stopped("Google sign-in created no readable ADC, so no new account was added. Start the sign-in again")
|
||||
}
|
||||
adcEmail = await tokenProvider({ authMode: "adc", cloudsdkConfig: directory })()
|
||||
.then((token) => accountOf(token)).then((email) => email?.toLowerCase()).catch(() => undefined)
|
||||
if (!adcEmail) {
|
||||
// An unnamed sign-in staged its ADC in a directory with a random
|
||||
// suffix; keeping it would leave a refresh token on disk that nothing
|
||||
// ever names again. A named sign-in's directory is the account's own,
|
||||
// so its ADC is kept and only the row is left unwritten.
|
||||
if (createdDirectory && !account) {
|
||||
await discard()
|
||||
throw stopped("The Google account identity could not be confirmed after consent, so the credentials this run wrote were removed; no new account was recorded. Start the sign-in again")
|
||||
}
|
||||
throw stopped("The ADC was kept, but the Google account identity could not be confirmed; no new account was recorded. Check the credentials before signing in again")
|
||||
}
|
||||
// Only accounts already filed under the plugin's own root count here.
|
||||
// The machine's default ADC is independent: this sign-in may create the
|
||||
// plugin's first ADC for that same email without touching the default.
|
||||
// The account's own directory is asked rather than the snapshot's slug,
|
||||
// which two different addresses can share. A named sign-in just wrote
|
||||
// that directory itself, so only another directory can be a duplicate.
|
||||
const existing = await adcDirectoryOwnedBy(adcEmail, root)
|
||||
if (existing !== directory && await hasAdc({ cloudsdkConfig: existing })) {
|
||||
await discard()
|
||||
throw stopped(`${adcEmail} was already signed in, so no new ADC was added. Sign in again with a different Google account`)
|
||||
}
|
||||
if (account && adcEmail !== account.toLowerCase()) {
|
||||
await discard()
|
||||
throw stopped(`The consent page approved ${adcEmail}, not ${account}; no new account or ADC was saved. Sign in again and choose ${account} on Google's consent page.`)
|
||||
}
|
||||
if (!account && createdDirectory) {
|
||||
// The readable directory unless another account already owns it, in
|
||||
// which case this one gets its own hashed name beside it.
|
||||
const own = await adcDirectoryToCreate(adcEmail, root)
|
||||
if (isGcloudDefault(own)) {
|
||||
await discard()
|
||||
throw stopped("Cannot move sign-in credentials into the machine's default gcloud directory")
|
||||
}
|
||||
// A concurrent sign-in may have registered the account since the
|
||||
// snapshot. Even an empty existing folder belongs to an earlier run
|
||||
// and is never replaced by this run's staging directory.
|
||||
const exists = await stat(own).then(() => true, (error) => { if (error.code === "ENOENT") return false; throw error })
|
||||
if (exists) {
|
||||
await discard()
|
||||
throw stopped(`${adcEmail} was already signed in or its ADC directory already exists, so no new account or ADC was added. Sign in again with a different Google account`)
|
||||
}
|
||||
await rename(directory, own)
|
||||
directory = own
|
||||
}
|
||||
}
|
||||
// A new ADC arrives with no project to serve yet. The one it is filed
|
||||
// with is the first of the account's projects with Vertex AI already
|
||||
// turned on; an account with none is not registered at all, and the
|
||||
// window closes on the way out as it does on every other failure.
|
||||
let project
|
||||
if (creating) {
|
||||
const named = options.project || process.env.GOOGLE_VERTEX_PROJECT || process.env.GOOGLE_CLOUD_PROJECT
|
||||
try {
|
||||
if (named) {
|
||||
// Nothing to ask and no list worth reading: an explicit project is
|
||||
// the answer, whether or not its API probe would have agreed.
|
||||
project = validateProject(named)
|
||||
} else {
|
||||
const token = await tokenProvider({ authMode: "adc", cloudsdkConfig: directory })()
|
||||
if (cancelled) throw stopped("Google sign-in was stopped; no new account was saved")
|
||||
const { projects, error } = await listUsableProjects(token)
|
||||
if (cancelled) throw stopped("Google sign-in was stopped; no new account was saved")
|
||||
if (!projects.some((project) => project.vertexEnabled) && error) {
|
||||
// An unreadable list is not an empty one: saying "create a
|
||||
// project" would be advice about a list this run never saw.
|
||||
throw stopped(`The Google Cloud projects for ${adcEmail} could not be listed (${error}), so nothing was registered. Sign in again, or set the project explicitly with GOOGLE_VERTEX_PROJECT`)
|
||||
}
|
||||
project = chooseProject({ projects, who: adcEmail, options })
|
||||
}
|
||||
} catch (failure) {
|
||||
// Nothing was registered: undo exactly what this run wrote.
|
||||
await discard()
|
||||
throw failure
|
||||
}
|
||||
}
|
||||
let found
|
||||
try {
|
||||
found = await resolveIdentity({
|
||||
...options,
|
||||
// The chosen project is this sign-in's answer, so it is handed to the
|
||||
// resolver rather than guessed at from Console or gcloud.
|
||||
...(project ? { project } : {}),
|
||||
...(creating ? { authMode: "adc", account: adcEmail } : {}),
|
||||
...(directory ? { cloudsdkConfig: directory } : {}),
|
||||
})
|
||||
} catch (error) {
|
||||
if (!creating || error.code !== "VERTEX_PROJECT_REQUIRED") throw error
|
||||
// Consent already succeeded. Keep the account and ADC location available
|
||||
// even though the host cannot save a complete record without a project;
|
||||
// repeating OAuth would only hit the duplicate-account guard next time.
|
||||
return {
|
||||
account: adcEmail, authMode: "adc", cloudsdkConfig: directory, creditsSession: "ready",
|
||||
warning: `ADC for ${adcEmail} was saved in ${directory}, but no Google Cloud project was selected. To finish registration without signing in again, set project to the project ID selected in Console, set cloudsdkConfig to this directory, and leave account unset.`,
|
||||
}
|
||||
}
|
||||
// Existing pinned ADC and explicit gcloud mode are read as they stand.
|
||||
// Their tokens are unrelated to a new consent flow and are not subjected
|
||||
// to the new-account checks above.
|
||||
let owner = found.account
|
||||
if (!creating) {
|
||||
const token = await tokenProvider(found)()
|
||||
owner ??= found.authMode === "adc" ? await accountOf(token) : undefined
|
||||
}
|
||||
const identity = owner ? { ...found, account: owner } : found
|
||||
if (chromeError) return { ...identity, creditsSession: "unavailable", warning: chromeError.message }
|
||||
return { ...identity, creditsSession: "ready" }
|
||||
} finally {
|
||||
// The sign-in's window, whatever the outcome, is closed here: one window,
|
||||
// opened once, and the person never has to close it. A gcloud still
|
||||
// writing here (the failure paths above) is stopped first, as it always
|
||||
// was, so it cannot recreate an ADC after discard() removed it.
|
||||
if (login && !finished) {
|
||||
login.child.kill("SIGKILL")
|
||||
await login.done.catch(() => {})
|
||||
}
|
||||
await close()
|
||||
}
|
||||
})()
|
||||
// The host may await the callback later. Retain failures as a result without
|
||||
// a project, which the callback reports as failed instead of saving a row.
|
||||
const settled = result.catch((error) => ({ creditsSession: "unavailable", warning: error.message }))
|
||||
settled.finally(() => { void close().catch(() => {}) })
|
||||
// Internal cleanup must not await its own result. The caller's close also
|
||||
// joins identity/project work, so restoring a request stub or environment
|
||||
// after cancellation cannot leave a sign-in running against the next one.
|
||||
const drain = async () => { await close(); await settled }
|
||||
return { result: settled, close: drain, terminate: drain }
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
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, extractAccount, safeGoto, validateBillingAccount, validateProject, withPage } from "./browser.mjs"
|
||||
import { take } from "./lock.mjs"
|
||||
import { effectiveAuthMode, resolveProject, validateAccount } from "./credentials.mjs"
|
||||
|
||||
const normalize = (value) => String(value ?? "").replace(/\s+/g, " ").trim()
|
||||
// Failures that say something about the network at this moment rather than
|
||||
// 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) => {
|
||||
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 isoDate = (value) => {
|
||||
const text = normalize(value)
|
||||
if (!text) return undefined
|
||||
const dateOnly = /^(?:January|February|March|April|May|June|July|August|September|October|November|December) \d{1,2}, \d{4}$/.test(text)
|
||||
const ms = Date.parse(dateOnly ? text + " 00:00:00 UTC" : text)
|
||||
if (!Number.isFinite(ms)) throw new Error(`Unsupported Google Cloud credit date: ${text}`)
|
||||
return new Date(ms).toISOString()
|
||||
}
|
||||
|
||||
// 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() } = {}) {
|
||||
const credits = new Map()
|
||||
let recognized = false
|
||||
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
|
||||
recognized = true
|
||||
for (const row of table.rows) {
|
||||
const cell = (name) => normalize(row[indices[name]])
|
||||
const status = cell("status").toLowerCase()
|
||||
if (!["available", "active", "exhausted", "used up", "used", "expired", "pending"].includes(status)) 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"))
|
||||
if (!Number.isSafeInteger(reported) || !Number.isSafeInteger(original) || reported < 0 || reported > original) throw new Error("Invalid Google Cloud credit amounts")
|
||||
const remaining = ["exhausted", "used up", "used"].includes(status) ? 0 : reported
|
||||
const start = isoDate(cell("start date"))
|
||||
const end = isoDate(cell("end date"))
|
||||
const eligible = ["available", "active", "exhausted", "used up", "used"].includes(status) && !(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 })
|
||||
}
|
||||
}
|
||||
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 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,
|
||||
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 } : {}),
|
||||
credits: [...credits.values()], fetchedAt: new Date(now).toISOString(), cached: false,
|
||||
}
|
||||
}
|
||||
|
||||
export async function readTables(page) {
|
||||
return page.evaluate(() => [...document.querySelectorAll("table, [role='grid'], [role='table']")].map((table) => ({
|
||||
headers: [...table.querySelectorAll("thead th, [role='columnheader']")].map((cell) => cell.innerText),
|
||||
rows: [...table.querySelectorAll("tbody tr, [role='row']")].map((row) => [...row.querySelectorAll("td, [role='gridcell'], [role='cell']")].map((cell) => cell.innerText)).filter((row) => row.length),
|
||||
})))
|
||||
}
|
||||
|
||||
export async function discoverBillingAccount(page, project, account) {
|
||||
validateProject(project)
|
||||
if (account) validateAccount(account)
|
||||
await safeGoto(page, `https://console.cloud.google.com/billing/linkedaccount?project=${encodeURIComponent(project)}&hl=en${account ? `&authuser=${encodeURIComponent(account)}` : ""}`)
|
||||
await page.waitForFunction(() => location.hostname === "accounts.google.com" || /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: 45000 }).catch(() => {})
|
||||
await assertConsoleSession(page)
|
||||
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")
|
||||
return accounts[0]
|
||||
}
|
||||
|
||||
// The Console pages the table in place. The button is found by the words it
|
||||
// shows — Google's own label is "Next page" — and clicked in the page, which
|
||||
// needs nothing of the browser beyond evaluating an expression.
|
||||
async function nextPage(page) {
|
||||
return page.evaluate(() => {
|
||||
const label = (element) => (element.getAttribute("aria-label") ?? element.innerText ?? "").trim()
|
||||
const button = [...document.querySelectorAll("button, [role='button']")].find((element) => /^(?:Go to )?Next page$/i.test(label(element)))
|
||||
if (!button || button.disabled || button.getAttribute("aria-disabled") === "true") return false
|
||||
button.click()
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
// The account the page was rendered for. authuser picks it, but Google may
|
||||
// silently fall back to the profile's default account, and a balance read as
|
||||
// the wrong person is worse than no balance: it is a plausible wrong number on
|
||||
// someone else's row. So every read that names an account checks that the page
|
||||
// agrees, and refuses rather than report another account's credits.
|
||||
async function confirmAccount(page, account) {
|
||||
if (!account) return
|
||||
const shown = await extractAccount(page, { timeout: 8000 })
|
||||
// A page that never named an account is not evidence that it named this one.
|
||||
// A fallback to another authuser is exactly what the check is for, and it is
|
||||
// silent: the URL still says this account while the page is another person's.
|
||||
if (!shown) throw new Error(`Cloud Console did not show which account the credits belong to; refusing to report a balance that may be another account's. Sign in as ${account} in the Chrome profile and retry`)
|
||||
if (shown.toLowerCase() !== account.toLowerCase()) {
|
||||
throw new Error(`Cloud Console is signed in as ${shown}, not ${account}; sign in as ${account} in the Chrome profile and retry`)
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
// assertConsoleSession below (which says a lapsed session is a lapsed
|
||||
// session) and the table's own wait, whose timeout is the failure to report.
|
||||
const wait = (fallback) => (Number(options.scrapeTimeout) > 0 ? Math.min(Number(options.scrapeTimeout), fallback) : fallback)
|
||||
const account = options.billingAccount ? validateBillingAccount(options.billingAccount) : await discoverBillingAccount(page, options.project, options.account)
|
||||
const source = `https://console.cloud.google.com/billing/${account}/credits/all?hl=en${options.account ? `&authuser=${encodeURIComponent(options.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 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) })
|
||||
.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") })
|
||||
await confirmAccount(page, options.account)
|
||||
const tables = []
|
||||
const seen = new Set()
|
||||
for (let index = 0; index < 100; index++) {
|
||||
const next = await readTables(page)
|
||||
const signature = JSON.stringify(next)
|
||||
if (seen.has(signature)) throw new Error("Credits pagination did not advance; refusing an incomplete balance")
|
||||
seen.add(signature)
|
||||
tables.push(...next)
|
||||
if (!(await nextPage(page))) return { ...parseCreditTables(tables), billingAccount: account, source }
|
||||
await page.waitForFunction((before) => {
|
||||
const tables = [...document.querySelectorAll("table, [role='grid'], [role='table']")].map((table) => ({
|
||||
headers: [...table.querySelectorAll("thead th, [role='columnheader']")].map((cell) => cell.innerText),
|
||||
rows: [...table.querySelectorAll("tbody tr, [role='row']")].map((row) => [...row.querySelectorAll("td, [role='gridcell'], [role='cell']")].map((cell) => cell.innerText)).filter((row) => row.length),
|
||||
}))
|
||||
return JSON.stringify(tables) !== before
|
||||
}, signature, { timeout: 20000 })
|
||||
}
|
||||
throw new Error("Credits table exceeded 100 pages; refusing an incomplete balance")
|
||||
}
|
||||
|
||||
async function scrape(options) {
|
||||
// A caller that brought its own browser (a test, or a sign-in that already
|
||||
// has a window) reads on its page; otherwise the read takes a tab of the
|
||||
// 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))
|
||||
}
|
||||
|
||||
const pending = new Map()
|
||||
|
||||
export async function fetchCredits(options = {}) {
|
||||
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,
|
||||
account: options.account ?? process.env.VERTEX_GCLOUD_ACCOUNT,
|
||||
}
|
||||
if (settings.billingAccount) validateBillingAccount(settings.billingAccount)
|
||||
else settings.project = await resolveProject(settings, undefined, await effectiveAuthMode(settings))
|
||||
if (settings.project) validateProject(settings.project)
|
||||
if (settings.account) validateAccount(settings.account)
|
||||
// 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).
|
||||
const identity = JSON.stringify([expandPath(settings.profile), settings.project ?? "", settings.billingAccount ?? "", settings.account ?? "", settings.cloudsdkConfig ?? ""])
|
||||
const digest = createHash("sha256").update(identity).digest("hex").slice(0, 24)
|
||||
const file = join(cacheRoot(), "magpie", "gcp-ai", `credits-${digest}.json`)
|
||||
// The cache is what keeps this from opening a browser on every poll, so both
|
||||
// outcomes are kept: a balance for a few minutes, a failure for much longer.
|
||||
// The usual failures — no billing.viewer on the project, a billing account in
|
||||
// another currency, a Console layout change, nobody signed in to the profile
|
||||
// — do not fix themselves between two usage polls, and asking again would
|
||||
// open a browser for an answer that cannot change.
|
||||
const ttl = Number(options.ttl ?? process.env.VERTEX_CREDITS_CACHE_TTL ?? 300)
|
||||
if (!Number.isFinite(ttl) || ttl < 0) throw new Error("VERTEX_CREDITS_CACHE_TTL must be a nonnegative number of seconds")
|
||||
const cached = async () => {
|
||||
try {
|
||||
const data = JSON.parse(await readFile(file, "utf8"))
|
||||
const age = Date.now() - Date.parse(data.failedAt ?? data.fetchedAt)
|
||||
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 }
|
||||
} catch {}
|
||||
}
|
||||
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")
|
||||
// A failure that is about this moment — a network that dropped, a Console
|
||||
// that took too long, a Chrome still starting — is not a property of the
|
||||
// account, so remembering it for twenty minutes is how a single bad minute
|
||||
// becomes twenty minutes of "timed out" on the row. Only the stable answers
|
||||
// (no billing.viewer, an expired session, a layout change) are kept that long.
|
||||
const transientTtl = Number(options.transientTtl ?? process.env.VERTEX_CREDITS_TRANSIENT_TTL ?? 60)
|
||||
if (!Number.isFinite(transientTtl) || transientTtl < 0) throw new Error("VERTEX_CREDITS_TRANSIENT_TTL must be a nonnegative number of seconds")
|
||||
const transient = (data) => NETWORK_FAILURE.test(String(data?.error ?? ""))
|
||||
const save = async (data) => {
|
||||
const temp = `${file}.${process.pid}.tmp`
|
||||
try {
|
||||
await writeFile(temp, JSON.stringify(data) + "\n", { mode: 0o600, flag: "wx" })
|
||||
await rename(temp, file)
|
||||
} finally { await rm(temp, { force: true }) }
|
||||
}
|
||||
// A cached read that is not `cached: true` is a remembered failure: it is
|
||||
// raised again as the error it was, not returned as a balance of zero.
|
||||
const remembered = (hit) => {
|
||||
if (!hit.failedAt) return hit
|
||||
throw Object.assign(new Error(hit.error), { remembered: true })
|
||||
}
|
||||
const hit = await cached()
|
||||
if (hit) return remembered(hit)
|
||||
if (pending.has(file)) return pending.get(file)
|
||||
const task = (async () => {
|
||||
await mkdir(dirname(file), { recursive: true, mode: 0o700 })
|
||||
// One read at a time, across processes: magpie asks each account's row
|
||||
// separately, so a process of its own may already be reading. The wait is
|
||||
// the answer — a second read that overlapped would open a second browser
|
||||
// on the same Chrome profile and the two would fight over it.
|
||||
const release = await take(file, { busy: "Another process is still refreshing Vertex credits; retry shortly" })
|
||||
try {
|
||||
const again = await cached()
|
||||
if (again) return remembered(again)
|
||||
let result
|
||||
try {
|
||||
result = await scrape(settings)
|
||||
} catch (error) {
|
||||
await save({ error: error.message, failedAt: new Date().toISOString() })
|
||||
throw error
|
||||
}
|
||||
await save(result)
|
||||
return result
|
||||
} finally { await release() }
|
||||
})().finally(() => pending.delete(file))
|
||||
pending.set(file, task)
|
||||
return task
|
||||
}
|
||||
|
||||
export function usageOf(credits) {
|
||||
return {
|
||||
plan: "Google Cloud promotional credits", balance: `$${credits.remaining.toFixed(2)} USD`, 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",
|
||||
...(credits.runsOutAt ? { runsOutAt: credits.runsOutAt, runsOut: credits.runsOut } : {}),
|
||||
}],
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { resolveIdentity, tokenProvider } from "./credentials.mjs"
|
||||
|
||||
// This is the check the official Vertex provider runs: the project's location
|
||||
// resource. It answers whether the endpoint, the project, the location and the
|
||||
// caller's permission are all right, without spending a model request.
|
||||
const API = "https://aiplatform.googleapis.com/v1"
|
||||
|
||||
export function locationUrl(project, location) {
|
||||
return `${API}/projects/${project}/locations/${location}`
|
||||
}
|
||||
|
||||
export async function checkLocation(token, project, location, timeout = 15000) {
|
||||
const started = Date.now()
|
||||
const response = await fetch(locationUrl(project, location), {
|
||||
headers: { authorization: `Bearer ${token}`, "x-goog-user-project": project },
|
||||
signal: AbortSignal.timeout(timeout),
|
||||
})
|
||||
const body = await response.json().catch(() => undefined)
|
||||
return {
|
||||
ok: response.ok, status: response.status, ms: Date.now() - started,
|
||||
...(body?.locationId ? { locationId: body.locationId } : {}),
|
||||
...(body?.error?.message ? { error: String(body.error.message).split("\n")[0] } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
// A model probe answers what the location test cannot: which models this
|
||||
// project may actually call. countTokens is free and is the cheapest call
|
||||
// Vertex offers.
|
||||
export async function checkModel(token, project, location, model, timeout = 20000) {
|
||||
const started = Date.now()
|
||||
const response = await fetch(
|
||||
`${API}/projects/${project}/locations/${location}/publishers/google/models/${encodeURIComponent(model)}:countTokens`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}`, "x-goog-user-project": project, "content-type": "application/json" },
|
||||
body: JSON.stringify({ contents: [{ role: "user", parts: [{ text: "hi" }] }] }),
|
||||
signal: AbortSignal.timeout(timeout),
|
||||
},
|
||||
)
|
||||
const body = await response.json().catch(() => undefined)
|
||||
return {
|
||||
model, ok: response.ok, status: response.status, ms: Date.now() - started,
|
||||
...(body?.totalTokens !== undefined ? { tokens: body.totalTokens } : {}),
|
||||
...(body?.error?.message ? { error: String(body.error.message).split("\n")[0] } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
// A location that answers, or refuses for a reason about the project or the
|
||||
// model, proves the endpoint is reachable. Only a rejected credential, a quota
|
||||
// block or a server failure means it cannot be used at all.
|
||||
const UNUSABLE = new Set([401, 429, 500, 502, 503, 504])
|
||||
|
||||
export async function testEndpoint(settings = {}, { models = [], timeout = 20000 } = {}) {
|
||||
const identity = await resolveIdentity(settings)
|
||||
const location = settings.location || "global"
|
||||
const token = await tokenProvider(identity)()
|
||||
const where = { project: identity.project, location, ...(identity.account ? { account: identity.account } : {}) }
|
||||
let locationTest
|
||||
try { locationTest = await checkLocation(token, identity.project, location) }
|
||||
catch (error) { locationTest = { ok: false, ms: 0, error: error.name === "TimeoutError" ? "no answer in time" : error.message } }
|
||||
if (!locationTest.ok) {
|
||||
return { ...where, authMode: identity.authMode, reachable: !UNUSABLE.has(locationTest.status), locationTest, models: [] }
|
||||
}
|
||||
const candidates = models.length ? models : ["gemini-2.5-flash"]
|
||||
const probes = []
|
||||
for (const model of candidates) {
|
||||
try { probes.push(await checkModel(token, identity.project, location, model.replace(/^google\//, ""), timeout)) }
|
||||
catch (error) { probes.push({ model, ok: false, ms: 0, error: error.name === "TimeoutError" ? "no answer in time" : error.message }) }
|
||||
}
|
||||
return {
|
||||
...where, authMode: identity.authMode, reachable: true, locationTest, models: probes,
|
||||
served: probes.filter((p) => p.ok).map((p) => p.model),
|
||||
}
|
||||
}
|
||||
|
||||
export function summarize(report) {
|
||||
const line = report.locationTest
|
||||
? `Location ${report.locationTest.ok ? "ok" : `failed (${report.locationTest.status ?? "no answer"})`} · ${report.locationTest.ms}ms${report.locationTest.error ? `\n ${report.locationTest.error}` : ""}`
|
||||
: "Location not tested"
|
||||
const lines = [
|
||||
`Endpoint ${report.reachable ? "reachable" : "UNREACHABLE"}: ${locationUrl(report.project, report.location)}`,
|
||||
`Project ${report.project} · ${report.location}${report.account ? ` · ${report.account}` : ""}`,
|
||||
line,
|
||||
]
|
||||
for (const probe of report.models) {
|
||||
const verdict = probe.ok ? "ok" : probe.status ? `failed (${probe.status})` : "failed"
|
||||
lines.push(` ${probe.model}: ${verdict} · ${probe.ms}ms${probe.tokens !== undefined ? ` · ${probe.tokens} tokens` : ""}${probe.error ? `\n ${probe.error}` : ""}`)
|
||||
}
|
||||
if (report.models.length) lines.push(report.served.length ? `${report.served.length} of ${report.models.length} models answered` : "No model answered")
|
||||
return lines.join("\n")
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env node
|
||||
import { readFile } from "node:fs/promises"
|
||||
import { pathToFileURL } from "node:url"
|
||||
import { closeKeptBrowsers, defaultProfile, openBrowser, routeAll } from "./browser.mjs"
|
||||
import { accountOf, resolveIdentity, startLogin, tokenProvider } from "./credentials.mjs"
|
||||
import { fetchCredits, parseCreditTables, readTables } from "./credits.mjs"
|
||||
import { testEndpoint, summarize } from "./endpoint.mjs"
|
||||
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]")
|
||||
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"])
|
||||
for (let i = 1; i < args.length; i++) {
|
||||
const option = args[i]
|
||||
if (valued.has(option)) {
|
||||
if (!args[i + 1] || args[i + 1].startsWith("--")) throw new Error(`${option} requires a value`)
|
||||
i++
|
||||
} else if (!["--force", "--headed", "--json"].includes(option)) throw new Error(`Unknown option: ${option}`)
|
||||
}
|
||||
const value = (name) => {
|
||||
const i = args.indexOf(name)
|
||||
if (i < 0) return undefined
|
||||
if (!args[i + 1] || args[i + 1].startsWith("--")) throw new Error(`${name} requires a value`)
|
||||
return args[i + 1]
|
||||
}
|
||||
const options = {
|
||||
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(),
|
||||
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
|
||||
// for the account, else gcloud's default. The machine-wide CLOUDSDK_CONFIG
|
||||
// is deliberately not read: one variable would point every account at one
|
||||
// credential, and this plugin writes only its own directories.
|
||||
cloudsdkConfig: value("--cloudsdk-config"),
|
||||
location: value("--location") ?? process.env.GOOGLE_VERTEX_LOCATION ?? "global",
|
||||
force: args.includes("--force"), headless: !args.includes("--headed"),
|
||||
}
|
||||
if (command === "credits") {
|
||||
try {
|
||||
console.log(JSON.stringify(await fetchCredits(options), null, 2))
|
||||
} finally { await closeKeptBrowsers() }
|
||||
} else if (command === "credentials") {
|
||||
const identity = await resolveIdentity(options)
|
||||
const token = await tokenProvider(identity)()
|
||||
const account = identity.account ?? (identity.authMode === "adc" ? await accountOf(token) : undefined)
|
||||
console.log(JSON.stringify({ ...identity, ...(account ? { account } : {}), inferenceAuth: "token-verified" }, null, 2))
|
||||
} else if (command === "login") {
|
||||
console.error("Opening Chrome. If no Application Default Credentials exist yet, approving Google there also has gcloud write them.")
|
||||
const login = await startLogin(options)
|
||||
try {
|
||||
console.log(JSON.stringify({ ...await login.result, inferenceAuth: "token-verified" }, null, 2))
|
||||
} finally { await login.close() }
|
||||
} else if (command === "models") {
|
||||
console.log(JSON.stringify(await availableModels({ ...options, force: options.force }), null, 2))
|
||||
} else if (command === "endpoint") {
|
||||
// The models the row offers are what a real endpoint test should ask
|
||||
// about; --model narrows it to one when a single answer is wanted.
|
||||
const chosen = value("--model")
|
||||
const models = chosen ? [chosen] : (await availableModels(options).catch(() => ({ ids: [] }))).ids
|
||||
const report = await testEndpoint(options, { models })
|
||||
console.log(args.includes("--json") ? JSON.stringify(report, null, 2) : summarize(report))
|
||||
if (!report.reachable) process.exitCode = 1
|
||||
} else if (command === "parse-html") {
|
||||
const file = value("--file")
|
||||
if (!file) throw new Error("parse-html requires --file PATH")
|
||||
const browser = await openBrowser({ profile: options.profile, headless: true, javaScriptEnabled: false })
|
||||
try {
|
||||
// The file is data, never code: scripts are stripped before it is parsed,
|
||||
// and every request it would make is refused.
|
||||
await routeAll(browser.page, () => undefined)
|
||||
const html = (await readFile(file, "utf8")).replace(/<script\b[^>]*>[\s\S]*?<\/script\s*>/gi, "")
|
||||
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))
|
||||
} finally { await browser.close() }
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
main().catch((error) => { console.error(JSON.stringify({ error: error.message })); process.exitCode = 1 })
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { mkdir, open, readFile, rm, stat, writeFile } from "node:fs/promises"
|
||||
import { dirname } from "node:path"
|
||||
|
||||
// A lock that holds across processes, not just within one. magpie asks each
|
||||
// account's row separately and may do it in a process of its own, so an
|
||||
// in-process guard would let two of them reach the same Chrome profile at once.
|
||||
//
|
||||
// The lock file holds the holder's pid. A lock left behind by a process that
|
||||
// has ended (a crash, a kill, a reboot) is removed rather than waited on: the
|
||||
// pid is checked against the running processes, and a PID the machine handed
|
||||
// out again after a reboot is not taken for the holder.
|
||||
|
||||
// alive asks the operating system whether pid is still running, on every
|
||||
// platform: signal 0 checks for the process without sending anything. ESRCH
|
||||
// means it is gone; EPERM means it exists but belongs to someone else, which
|
||||
// is still alive. Any other error is not proof either way, and the caller
|
||||
// falls back to the lock's age.
|
||||
function alive(pid) {
|
||||
try {
|
||||
process.kill(pid, 0)
|
||||
return true
|
||||
} catch (error) {
|
||||
if (error?.code === "ESRCH") return false
|
||||
if (error?.code === "EPERM") return true
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
async function abandoned(path) {
|
||||
const locked = (await stat(path)).mtimeMs
|
||||
let pid
|
||||
try { pid = Number((await readFile(path, "utf8")).trim()) } catch { return Date.now() - locked > 10000 }
|
||||
// An empty lock is one just created by another process, not one abandoned:
|
||||
// only a lock that stayed empty is stale.
|
||||
if (!pid) return Date.now() - locked > 10000
|
||||
if (!Number.isSafeInteger(pid) || pid <= 0) return true
|
||||
const running = alive(pid)
|
||||
if (running === false) return true
|
||||
if (running === undefined) return Date.now() - locked > 10 * 60 * 1000
|
||||
if (process.platform === "linux") {
|
||||
try {
|
||||
// A known live holder outranks age; a reused pid started after the lock.
|
||||
const started = (await stat(`/proc/${pid}`)).mtimeMs
|
||||
return started > locked + 1000
|
||||
} catch {}
|
||||
}
|
||||
// A reused pid cannot hold the lock forever where its start time cannot be
|
||||
// checked. Fifteen minutes leaves room for the ten-minute sign-in limit.
|
||||
return Date.now() - locked > 15 * 60 * 1000
|
||||
}
|
||||
|
||||
// take waits for the lock and returns the function that gives it back. Waiting
|
||||
// is the point: the caller has nothing better to do than let the other read
|
||||
// finish, and failing here would only show the user a lock error.
|
||||
export async function take(file, { timeout = 180000, poll = 250, busy = "Another process is still using this; retry shortly" } = {}) {
|
||||
const path = `${file}.lock`
|
||||
const deadline = Date.now() + timeout
|
||||
await mkdir(dirname(path), { recursive: true, mode: 0o700 })
|
||||
for (;;) {
|
||||
try {
|
||||
const handle = await open(path, "wx", 0o600)
|
||||
await handle.writeFile(String(process.pid))
|
||||
// Nobody is waiting any more: the flag is about a waiter that has not
|
||||
// got the lock yet, not a record of who once wanted it.
|
||||
await rm(`${file}.want`, { force: true }).catch(() => {})
|
||||
let released = false
|
||||
return async () => {
|
||||
if (released) return
|
||||
released = true
|
||||
await handle.close().catch(() => {})
|
||||
// The moment of release, for callers that want a gap before the next
|
||||
// hold. Written before the lock goes, so a waiter that takes it at
|
||||
// once still sees the time.
|
||||
await writeFile(`${file}.since`, new Date().toISOString(), { mode: 0o600 }).catch(() => {})
|
||||
await rm(path, { force: true })
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.code !== "EEXIST") throw error
|
||||
if (await abandoned(path)) { await rm(path, { force: true }); continue }
|
||||
// Say that someone is waiting, so a holder that is only keeping the lock
|
||||
// warm lets go now instead of making this process sit out its leisure.
|
||||
await writeFile(`${file}.want`, String(process.pid), { mode: 0o600 }).catch(() => {})
|
||||
if (Date.now() >= deadline) throw new Error(busy)
|
||||
await new Promise((resolve) => setTimeout(resolve, poll))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// wanted is when someone last said it was waiting for this lock: a time later
|
||||
// than the moment the caller took it means a process is waiting right now.
|
||||
export async function wanted(file) {
|
||||
try { return (await stat(`${file}.want`)).mtimeMs } catch { return 0 }
|
||||
}
|
||||
|
||||
// apart waits until at least `gap` milliseconds have passed since the last
|
||||
// release. Two Google accounts sharing a Chrome profile are read one after
|
||||
// another with breathing room between them, rather than back to back: the
|
||||
// profile is a real browser session with Google, not a file to be reopened.
|
||||
export async function apart(file, gap) {
|
||||
if (!(gap > 0)) return
|
||||
let last
|
||||
try { last = Date.parse(await readFile(`${file}.since`, "utf8")) } catch { return }
|
||||
if (!Number.isFinite(last)) return
|
||||
const wait = last + gap - Date.now()
|
||||
if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
import { createHash } from "node:crypto"
|
||||
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"
|
||||
import { dirname, join } from "node:path"
|
||||
import { cacheRoot } from "./browser.mjs"
|
||||
import { resolveIdentity, tokenProvider } from "./credentials.mjs"
|
||||
|
||||
// The list is Google's publisher catalog for the project, read once. It is
|
||||
// global, so it also names things this project cannot call (retired ids,
|
||||
// preview models, publishers not enabled); nothing here asks each model whether
|
||||
// it answers, because that is a round trip per model in front of the row's read
|
||||
// and a question the person answers better with Test models.
|
||||
const API = "https://aiplatform.googleapis.com/v1beta1"
|
||||
|
||||
// A location is a region name, or the global endpoint.
|
||||
const LOCATION = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
|
||||
// Everything Vertex publishes under google/ that is not a chat model: speech,
|
||||
// transcription, translation, embeddings, live audio and image generation.
|
||||
const NOT_CHAT = /tts|embedding|transcribe|live|translate|image|nano-banana|omni/
|
||||
|
||||
// Google keeps retired models in the publisher catalog: the listing still names
|
||||
// them, and calling one answers 404 NOT_FOUND, so taken at face value the list
|
||||
// offers models that cannot load. Nothing in the listing tells the two apart —
|
||||
// a retired model's launch stage and template read exactly like a live one's —
|
||||
// so the list is not taken at face value: each model is asked a question that
|
||||
// costs nothing (countTokens, not a generation), and the ones that say they are
|
||||
// not there are left out. Whether a model *answers well* is still the person's
|
||||
// to find out with Test models; this only drops the ones Google says are gone.
|
||||
export const isChatCandidate = (id) => id.startsWith("gemini-") && !NOT_CHAT.test(id)
|
||||
|
||||
async function call(token, project, path, init) {
|
||||
const response = await fetch(`${API}${path}`, {
|
||||
...init,
|
||||
headers: { authorization: `Bearer ${token}`, "x-goog-user-project": project, ...(init?.headers ?? {}) },
|
||||
// A caller that brought its own deadline keeps it.
|
||||
signal: init?.signal ?? AbortSignal.timeout(20000),
|
||||
})
|
||||
return response
|
||||
}
|
||||
|
||||
async function publisherModels(token, project) {
|
||||
const models = []
|
||||
let pageToken = ""
|
||||
// The endpoint pages at 200; more than one page means more models, not a
|
||||
// failure, so every page is read rather than the first one.
|
||||
for (let page = 0; page < 20; page++) {
|
||||
const query = `?pageSize=200${pageToken ? `&pageToken=${encodeURIComponent(pageToken)}` : ""}`
|
||||
const response = await call(token, project, `/publishers/google/models${query}`)
|
||||
if (!response.ok) throw new Error(`Vertex model catalog answered ${response.status}`)
|
||||
const body = await response.json()
|
||||
for (const model of body.publisherModels ?? []) models.push(model.name.split("/").pop())
|
||||
if (!body.nextPageToken) return models
|
||||
pageToken = body.nextPageToken
|
||||
}
|
||||
throw new Error("Vertex model catalog kept paging; refusing an incomplete list")
|
||||
}
|
||||
|
||||
// The catalog Magpie lists the official provider from adds what the Vertex API
|
||||
// doesn't say: context window, prices, modalities. Only model ids come from
|
||||
// Google; these numbers are decoration on top of them.
|
||||
async function catalog() {
|
||||
try {
|
||||
return JSON.parse(await readFile(join(cacheRoot(), "magpie", "models.json"), "utf8"))?.["google-vertex"]?.models ?? {}
|
||||
} catch { return {} }
|
||||
}
|
||||
|
||||
function locationOf(settings) {
|
||||
const location = settings.location || process.env.GOOGLE_VERTEX_LOCATION || "global"
|
||||
if (!LOCATION.test(location)) throw new Error("Invalid GOOGLE_VERTEX_LOCATION")
|
||||
return location
|
||||
}
|
||||
|
||||
// gone asks one model whether it is really there. countTokens is the cheapest
|
||||
// question a model answers: it reads the request and returns a number, without
|
||||
// generating anything or billing a token. Only NOT_FOUND drops a model — that
|
||||
// is Google saying the model is not deployed for this project, which is what a
|
||||
// retired id answers. Any other outcome (a 403 for a model this account may not
|
||||
// call, a rate limit, a network that dropped, a timeout) leaves the model on
|
||||
// the list: a question that could not be answered is not an answer, and
|
||||
// dropping models on a bad minute is how the row loses models that work.
|
||||
async function gone(token, project, location, id) {
|
||||
try {
|
||||
const response = await call(token, project, `/projects/${project}/locations/${location}/publishers/google/models/${id}:countTokens`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ contents: [{ role: "user", parts: [{ text: "x" }] }] }),
|
||||
// Short: this runs per model behind a cache the row is already reading.
|
||||
signal: AbortSignal.timeout(8000),
|
||||
})
|
||||
return response.status === 404
|
||||
} catch { return false }
|
||||
}
|
||||
|
||||
// inParallel runs work over items, a few at a time. The probes are independent
|
||||
// network round trips; doing them one after another is how a 15-model list
|
||||
// costs 15 timeouts before the row can show anything.
|
||||
async function inParallel(items, width, work) {
|
||||
const out = new Array(items.length)
|
||||
let next = 0
|
||||
const worker = async () => {
|
||||
for (let i = next++; i < items.length; i = next++) out[i] = await work(items[i], i)
|
||||
}
|
||||
await Promise.all(Array.from({ length: Math.min(width, items.length) }, worker))
|
||||
return out
|
||||
}
|
||||
|
||||
// The list is Google's own catalog for the project, read once and then asked
|
||||
// which of its models are really there. What comes back is what the project can
|
||||
// call, so nobody has to press Fetch models and then discover by testing that
|
||||
// half the row is retired.
|
||||
async function discover(settings) {
|
||||
const location = locationOf(settings)
|
||||
const identity = await resolveIdentity(settings)
|
||||
const token = await tokenProvider(identity)()
|
||||
const named = (await publisherModels(token, identity.project)).filter(isChatCandidate)
|
||||
if (!named.length) throw new Error(`Vertex lists no chat model in ${location} for ${identity.project}`)
|
||||
const absent = await inParallel(named, 6, (id) => gone(token, identity.project, location, id))
|
||||
const ids = named.filter((_, i) => !absent[i])
|
||||
// Every model saying 404 is not a model list, it is a broken read: a wrong
|
||||
// project or location answers NOT_FOUND for everything. Keep Google's names
|
||||
// rather than report an empty provider.
|
||||
if (!ids.length) return { project: identity.project, location, ids: named }
|
||||
return { project: identity.project, location, ids }
|
||||
}
|
||||
|
||||
// One refresh at a time per list: the host may ask twice before the first
|
||||
// answer is in (a second account, an editor and a request), and two identical
|
||||
// catalog reads are two chances to be rate limited.
|
||||
const refreshing = new Map()
|
||||
|
||||
async function writeList(file, result) {
|
||||
const temp = `${file}.${process.pid}.tmp`
|
||||
await mkdir(dirname(file), { recursive: true, mode: 0o700 })
|
||||
try {
|
||||
await writeFile(temp, JSON.stringify(result) + "\n", { mode: 0o600 })
|
||||
await rename(temp, file)
|
||||
} finally { await rm(temp, { force: true }) }
|
||||
}
|
||||
|
||||
export async function availableModels(settings = {}) {
|
||||
// The location is part of the identity: the same project serves a different
|
||||
// list in each one, so a list read for global is not one for a region.
|
||||
const location = locationOf(settings)
|
||||
const identity = JSON.stringify([settings.project ?? "", settings.account ?? "", settings.authMode ?? "", location])
|
||||
const digest = createHash("sha256").update(identity).digest("hex").slice(0, 16)
|
||||
const file = join(cacheRoot(), "magpie", "gcp-ai", `models-${digest}.json`)
|
||||
const ttl = Number(settings.ttl ?? process.env.VERTEX_MODELS_CACHE_TTL ?? 21600)
|
||||
if (!Number.isFinite(ttl) || ttl < 0) throw new Error("VERTEX_MODELS_CACHE_TTL must be a nonnegative number of seconds")
|
||||
let last
|
||||
try {
|
||||
const cached = JSON.parse(await readFile(file, "utf8"))
|
||||
// A list read before a retired model was known to be gone still names it:
|
||||
// the cached ids are filtered on the way out, so an old cache cannot put a
|
||||
// model back on the row after it stopped answering.
|
||||
const ids = (Array.isArray(cached?.ids) ? cached.ids : []).filter(isChatCandidate)
|
||||
if (ids.length) last = { ...cached, ids }
|
||||
} catch { last = undefined }
|
||||
const refresh = () => {
|
||||
let running = refreshing.get(file)
|
||||
if (!running) {
|
||||
running = discover(settings)
|
||||
.then((found) => writeList(file, { ...found, fetchedAt: new Date().toISOString() }))
|
||||
.finally(() => refreshing.delete(file))
|
||||
running.catch(() => {})
|
||||
refreshing.set(file, running)
|
||||
}
|
||||
return running
|
||||
}
|
||||
if (last && !settings.force) {
|
||||
const age = Date.now() - Date.parse(last.fetchedAt)
|
||||
// A list already known is answered at once, however old it is: this hook
|
||||
// runs inside Magpie's own provider read, which waits on every plugin at
|
||||
// once, so spending seconds here is how the row ends up with no models at
|
||||
// all. An old list is refreshed behind the answer instead of in front of
|
||||
// it, and the next read sees what that found.
|
||||
if (!(age >= 0 && age < ttl * 1000)) refresh().catch(() => {})
|
||||
return last
|
||||
}
|
||||
// Nothing cached: this read has to ask, and a failure here is the one case
|
||||
// the host reports as a list it could not get.
|
||||
try {
|
||||
const found = await refresh()
|
||||
return JSON.parse(await readFile(file, "utf8").catch(() => JSON.stringify(found)))
|
||||
} catch (error) {
|
||||
// A good list from an earlier read stands in for one that could not be
|
||||
// read now: a lapsed token or a flaky probe must not blank the models out.
|
||||
if (last) return last
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// The row's models before anything has been read from Google. Magpie lists a
|
||||
// plugin provider from what the config hook gives it, so a config hook with no
|
||||
// models is a row that stays empty until someone presses Fetch models — the
|
||||
// other plugins here (Kiro, WorkBuddy) hand over their own list for exactly
|
||||
// that reason, and the provider hook replaces it with the account's list once
|
||||
// it is signed in. These are the models Google's catalog names today; the
|
||||
// provider hook is what says what the signed-in project can actually call.
|
||||
//
|
||||
// The table carries only what the config hook can use (name, context, the
|
||||
// reasoning levels). Prices, modalities and the rest are decoration the
|
||||
// provider hook adds from the catalog, so they are not repeated here.
|
||||
const SEED = [
|
||||
["gemini-4-argon", "Gemini 4 Argon", 1048576, 65536, ["low", "medium", "high"]],
|
||||
["gemini-3.8-flash", "Gemini 3.8 Flash", 1048576, 65536, ["low", "medium", "high"]],
|
||||
["gemini-3.7-flash", "Gemini 3.7 Flash", 1048576, 65536, ["low", "medium", "high"]],
|
||||
["gemini-3.6-flash", "Gemini 3.6 Flash", 1048576, 65536, ["minimal", "low", "medium", "high"]],
|
||||
["gemini-3.5-flash-lite", "Gemini 3.5 Flash Lite", 1048576, 65536, ["minimal", "low", "medium", "high"]],
|
||||
["gemini-3.5-flash", "Gemini 3.5 Flash", 1048576, 65536, ["minimal", "low", "medium", "high"]],
|
||||
["gemini-3.1-flash-lite", "Gemini 3.1 Flash Lite", 1048576, 65536, ["minimal", "low", "medium", "high"]],
|
||||
["gemini-3.1-pro-preview", "Gemini 3.1 Pro Preview", 1048576, 65536, ["low", "medium", "high"]],
|
||||
["gemini-3-flash-preview", "Gemini 3 Flash Preview", 1048576, 65536, ["minimal", "low", "medium", "high"]],
|
||||
["gemini-2.5-flash-lite", "Gemini 2.5 Flash-Lite", 1048576, 65536, []],
|
||||
["gemini-2.5-flash", "Gemini 2.5 Flash", 1048576, 65536, []],
|
||||
["gemini-2.5-pro", "Gemini 2.5 Pro", 1048576, 65536, []],
|
||||
]
|
||||
|
||||
// seedModels is the config hook's models: the shape a row is configured with,
|
||||
// not the shape the provider hook returns.
|
||||
export function seedModels() {
|
||||
return Object.fromEntries(SEED.map(([id, name, context, output, efforts]) => [id, {
|
||||
id, name,
|
||||
// The same address the provider hook gives: Gemini's own protocol names the
|
||||
// model in the path without a publisher prefix, so a row that has not been
|
||||
// signed in yet sends the id as it stands rather than a prefixed guess.
|
||||
api: { id, npm: "@ai-sdk/google" },
|
||||
limit: { context, output },
|
||||
attachment: true,
|
||||
modalities: { input: ["text", "image", "video", "audio", "pdf"], output: ["text"] },
|
||||
tool_call: true,
|
||||
reasoning: efforts.length > 0,
|
||||
...(efforts.length ? { variants: Object.fromEntries(efforts.map((effort) => [effort, { reasoning_effort: effort }])) } : {}),
|
||||
}]))
|
||||
}
|
||||
|
||||
// providerModels is what the host's provider hook returns for a row: the ids
|
||||
// Google says the account can call, dressed with the catalog's numbers.
|
||||
// Nothing cached and Google unreachable makes this throw: the host keeps the
|
||||
// row's last list rather than read the failure as "no models".
|
||||
export async function providerModels(settings, id) {
|
||||
const { ids } = await availableModels(settings)
|
||||
return toProviderModels(ids, await catalog(), id)
|
||||
}
|
||||
|
||||
// Newest first. Google lists the catalog oldest first, and the catalog's
|
||||
// release date is what orders the ones it knows; a model it doesn't describe
|
||||
// is placed after them, in the reverse of the order Google listed it.
|
||||
function newestFirst(ids, catalogModels) {
|
||||
return ids
|
||||
.map((model, index) => ({ model, index, date: catalogModels[model]?.release_date ?? "" }))
|
||||
.sort((a, b) => (a.date === b.date ? b.index - a.index : a.date < b.date ? 1 : -1))
|
||||
.map(({ model }) => model)
|
||||
}
|
||||
|
||||
// toProviderModels is the discovered ids as the host's provider hook wants
|
||||
// them, with the catalog's numbers where it knows the model.
|
||||
export function toProviderModels(ids, catalogModels, id) {
|
||||
return Object.fromEntries(newestFirst(ids, catalogModels).map((model) => {
|
||||
const known = catalogModels[model] ?? {}
|
||||
const input = known.modalities?.input ?? ["text", "image", "audio", "video", "pdf"]
|
||||
const modalities = Object.fromEntries(["text", "image", "audio", "video", "pdf"].map((kind) => [kind, input.includes(kind)]))
|
||||
const efforts = known.reasoning_options?.find((option) => option.type === "effort")?.values
|
||||
return [model, {
|
||||
id: model, providerID: id, name: known.name ?? model,
|
||||
// Gemini's own API names the model in the path, without a publisher
|
||||
// prefix, and its body is the native request: the protocol the official
|
||||
// Vertex row speaks, where a tool call's thought signature travels with
|
||||
// the conversation instead of being dropped by an OpenAI-shaped shim. No
|
||||
// URL here: the account's loader gives the one base for its project and
|
||||
// location, which a per-model address would override with global's.
|
||||
api: { id: model, npm: "@ai-sdk/google" },
|
||||
status: "active", headers: {}, options: {},
|
||||
variants: efforts ? Object.fromEntries(efforts.map((effort) => [effort, { reasoning_effort: effort }])) : {},
|
||||
cost: { input: known.cost?.input ?? 0, output: known.cost?.output ?? 0, cache: { read: known.cost?.cache_read ?? 0, write: 0 } },
|
||||
limit: known.limit ?? { context: 1048576, output: 65536 },
|
||||
capabilities: {
|
||||
temperature: known.temperature !== false, reasoning: known.reasoning !== false,
|
||||
attachment: known.attachment !== false, toolcall: known.tool_call !== false,
|
||||
input: modalities, output: { ...modalities, image: false, audio: false, video: false, pdf: false }, interleaved: false,
|
||||
},
|
||||
release_date: known.release_date ?? "",
|
||||
}]
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-gcp-ai-auth",
|
||||
"version": "0.1.0",
|
||||
"description": "Vertex AI models and Google Cloud promotional credits, signed with your own gcloud / ADC login",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
"exports": "./index.mjs",
|
||||
"files": [
|
||||
"index.mjs",
|
||||
"lib/",
|
||||
"assets/",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"scripts": {
|
||||
"check": "node --check index.mjs && node --check lib/browser.mjs && node --check lib/credentials.mjs && node --check lib/credits.mjs && node --check lib/endpoint.mjs && node --check lib/models.mjs && node --check lib/fetch_credits.mjs",
|
||||
"models": "node lib/fetch_credits.mjs models",
|
||||
"test": "node --test test/*.test.mjs",
|
||||
"credits": "node lib/fetch_credits.mjs credits",
|
||||
"login": "node lib/fetch_credits.mjs login",
|
||||
"credentials": "node lib/fetch_credits.mjs credentials"
|
||||
},
|
||||
"keywords": [
|
||||
"opencode",
|
||||
"opencode-plugin",
|
||||
"magpie",
|
||||
"gcp-ai",
|
||||
"gcp",
|
||||
"vertex",
|
||||
"credits",
|
||||
"usage",
|
||||
"quota",
|
||||
"magpie-plugin",
|
||||
"google-cloud",
|
||||
"vertex-ai",
|
||||
"gemini",
|
||||
"adc",
|
||||
"gcloud"
|
||||
],
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/magpie-community/plugins.git",
|
||||
"directory": "packages/gcp-ai"
|
||||
},
|
||||
"magpie": {
|
||||
"icon": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAMAAAD04JH5AAABRFBMVEVHcEyHwD7utQMdg+3/PSUOhfsUmsIKifYHhv4Gu2QKhv3+SYv/ODntxgIHvlYXhPkLhv0Hhv7xzAEGhv0IprTpzwEOwFQXwk3/Kyz/N0X/TDX/QSRJzSn/JTLR1AT5zwD/qgBa0R//cAU/euj/hgKp1wj/fQP/XghvctcAh///Ii8AiP8Cv1EAi/4AvVoMwkj+0gD/ywAAjvv/KCf/JjwHhvz41QAAu2UAkfYAle/t1gAaxT4An9r/xQAApMwAqLwArawAmuYAuXEsyTMAsZvg1wEAtIz/LU262AX/LyL/lgD/igEAtn7P2AP/sgA/zSj/uQD/fgL/oQD/NR6i1wr/qgD/vwD/Oxn/dAOL1g//N2JS0CH/XQj/Tw1k0xn/SRF31RP/ZQb/Vgv/QXj/bAT3zwD/RBT/QhZrcdWRYbbOUJVHcEy+/fmgAAAAbHRSTlMADiQZRkInsPSr3PyQid6bwn1hV7DBQmixKGgSt9tD5t3aonfm3L/Xzv///////////////////////////////////////////////////////////////////////////////////////wBrqzMYAAAHzUlEQVR4nO2aCVdSWxiGRVCZxIFEBkkztSujoMcBtTQyzSnNMjXLa0RX/f8/4O7hnD3vM4mtddflPTiwBJ53v9+3B1j29HTVVVddddXVf1aZUDYej6fT4Fs2lPmj6Fwom/7w4cPZ2dnXr//c/L75/v37z5+vprOh3B/Bh9L5RSDk4Ctw8PvmBhr4eX17+2o69OT0eKFQMPm8gevr69tfv35dPKmHULpg8lUGbm+Bg4vT07nsE+Gz+QLi6xJA/Avg4GDmKSxk0OgLbARaAwf7c72dxscp3t7AKTRwsL8/3VELoXyBETVwpjfwaapzDnJpDo8z0BtA/P1P+58GO8TPcHzbBC4YA0CdcZAR8doE2AoAA1+AOlCG0FJBFLcQEANMC+AAAP/48Y0QkvDCQmAakFoAGjg+Pj55pAM4fnUEKgNcC3zBBh6XQWgJSJ3AotKAUIHjk5Pz80c4yOQhf0nOAOA5A0wPCgGcnJ+MBXwbgHxswSEB0QANACRwPuaXH981+VIGtgbYFkQGNn2uB9ldICuCJSkCwYC5F5+yFTD5m5ujvgwgPrVA8YoESA/SCuAOON+EBjb98NO7V9iCFIIiAdEAaUEUQK3mow2yV1fIgBmBUATOAJ6FXAvQCmwi1Z57NnAFDVwxDtgIoPLpeCgDzsE5cD6ffnWNW4CtwAkNoFab9MqPXyHtMiEwVVhcTPNvBXKhOakCpAOggZrHPsy0WowD2gfYQj6ues70DFMBIQAQgbcFMd5qsRaWuEZIa96AZOZOhQBQB0D8Qm3BWwQxyG+xfWCGADKwOfiHZg40AQAHXvjZFhbjwGrFvN0bj0DvDDVA+YAO5GE9zMViLSYDAod8p+dO4QqQKVjz4yATi8XMBFoP9/f3d3d34PsDKEDe8f1nbooNoLZp4r05iMegg9jD/V25XC4Wwc0olg2jbtwl+x2fnCMGaANYcjsVEP7+zigX56nA70ZxPjycdHr2KN8BZPzIgasVEVTgAYydpbMKjwTtnz/IB0D5y+ByMxuzD3eGjo4UHbF/AcUUsBwsLDs7CP5VtMWjFGwLMcoEwNLBtezsoD/qREeyCyEwxYy/TemAD7Rg3wcvDVd8UAebThhkO4CMn8huLrjmAwf6KRlAawDEg/G3OTiUzfFkwDUeqk/7OmMogHa7DR3w/MZyo6FdkYY88ecNrYNRFEAbWFgQ6YDfaGjeKgzNuy+AfQa9k2j8MIHltjVuRuoieKi/JV0n5sZMA22AtujEw05jRzUXffDD2j4cxPgGMNBmh75jSfGcsHe+vgufm3wlfGfnaEdeDIa98+32hMFJAG9LZAQ/ApLesvZ5LoDN+KF6BydhsSG9wbOxxAi88x32RKDRsR0V+uho72hvT5gILx33H2/jxwqMSmwER+IeGXS3AzF856MRtjAmgbE+73E1SHqrQNHV+JEB4GBPhn8G4tZjj1PQcDl+pFmRbGqWmQc5b3z744io3llEZtlAl5ezzK5sswkZwy9huwdH6Drhtv6WBjkwQJtimkC/CEVpsUd8jR/KBFP05d/wNk4e0KdrAYM/eEX9jB9GcMmiwYU1QQ3o5sAQ/0JBkJThefw9PSmTLIgaGHHH74G18j5+0IYvLOYPeFl6wbysugDyuSXodv7zAgZ+yKIGNC0gB+BXE5j4DV9E5O/qFtCf+Lwb+KaUgwG7g78/Ax/hDV1Y5O/qCgx3jB+Y+KiUg4GBjhnofwFoTXRDX1hN2oRPnEAg1cT6aH6ZouvAU/fARFOpiIMB13u+kwLN5joErsMf6/h3KLoXaNYBh48hXGti3VIT3prWnRR5hOY8ZnSGP76uVDNBV3X3e4EPpdarage0B3uSGgOd6IJUoirKdERbQHseMB6/Gqcgz+JCNLlbZfbVgHI7NIDCj2vEQKRUrZYUEYCvBPtAxZnQMBVN+lwOAv3jiVK1BG7osr4RjbMP7tMbABaGB2z0bOAZUeRZhCqxUjJVLTFGTDvVEn+yEZciw0Hlen11dW1tbXt7e2Nj4/XrN2+2tt69e/f+/fvDw7dvV1YqWCWqKuekVI1wfHki8jx0F/+hWCyXy3UDXKYDYmCLGAAOTA8l1gMn4bTVH9bj5w360VERqmzUYQC8ASuCQ8uBFYLKQrUkBODy8zFMxwmsGrQGr/kIDnEEKyZf5SEhn23VSGNeGD2qAOgAFAFNQBUB2wiihXGJr12OBTw2UCYGuBowEdAMrDKwHhIy3+kzIsoHDuplpgdIBFs0AqsNzCqYZajYFAAo6IpPAhASsI2A8M3fUiq+zTtEBk/5dSkBEgHbBmwVKvoGsG8DiV9mp6E2Aj4Daz5U5BlIpZ6LIp9UQEwAzgOxCBXGAc7Ahq92UJQM1OtSAhuqGggOsIeI/f/UyA5kPgnAbEIuAr2DCuoC2/Er+8DGwBrXA2IEdCas0AS0/UeVDDvgmQqs4gC4LhQiYHaFSiWhmX+82H2pqBk/TWCN9AAfAT8TcAYO5acasuMLBmgTWk3AF4HORXfDx+qLSnihAHWrAmu0BEwEUh+uVMa9/UdZckDDx6sQVwGcwIYYAesg4aL5pBSGNAZIAoIDbiZyRYikfJ5rkwNRQ8nnVgGGj7dENoJEJOKh9LKCfcmh4WiY8k0D1AFJQGhDYCERGU/1+/9fwq666qqrrrrqqqv/jf4Fbc63Vv5NI2IAAAAASUVORK5CYII="
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
import "./network.mjs"
|
||||
import assert from "node:assert/strict"
|
||||
import { mkdtemp, rm } from "node:fs/promises"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import test from "node:test"
|
||||
import { assertConsoleSession, chromeExecutable, closeKeptBrowsers as endKeptBrowsers, extractProjectId, extractAccount, openBrowser, routeAll, withPage } from "../lib/browser.mjs"
|
||||
|
||||
// A kept browser is meant to outlive one read; a test that opens several must
|
||||
// not leave them running behind it.
|
||||
process.env.VERTEX_CHROME_IDLE = "0"
|
||||
import { discoverBillingAccount, fetchCredits, usageOf } from "../lib/credits.mjs"
|
||||
|
||||
// Chrome's services run outside routeAll. Deny external name resolution at
|
||||
// launch, as one argv value (no shell quotes), for every test browser.
|
||||
const launchArgs = [
|
||||
"--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1",
|
||||
// Any request not served by routeAll is sent to a closed loopback port.
|
||||
// Chrome may still perform its own numeric IPv6 reachability probe.
|
||||
"--proxy-server=http://127.0.0.1:9",
|
||||
"--proxy-bypass-list=<-loopback>",
|
||||
]
|
||||
|
||||
// These tests drive the machine's own Chrome, which the plugin starts and
|
||||
// speaks to over its pipe transport. A machine with no Chrome can still load
|
||||
// the plugin and its hooks; it just cannot open a browser, and says so here
|
||||
// rather than failing as a broken test.
|
||||
const chrome = await chromeExecutable().then(() => true, () => false)
|
||||
const needsBrowser = { skip: chrome ? false : "Chrome is not installed; set VERTEX_CHROME_PATH to run the browser tests" }
|
||||
|
||||
// A stand-in for Google, served from inside the test: every request the page
|
||||
// makes is answered here, so nothing leaves the machine.
|
||||
function pageFor(answers) {
|
||||
return async (request) => {
|
||||
const url = new URL(request.url())
|
||||
if (url.hostname === "console.cloud.google.com") {
|
||||
const html = answers(url) ?? "<h1>Google Cloud Console</h1>"
|
||||
return request.fulfill({ body: `<!doctype html>${html}` })
|
||||
}
|
||||
if (url.hostname === "accounts.google.com") {
|
||||
const html = answers(url) ?? '<h1>Sign in with your Google Account</h1><input name="identifier">'
|
||||
return request.fulfill({ body: `<!doctype html>${html}` })
|
||||
}
|
||||
return request.abort()
|
||||
}
|
||||
}
|
||||
|
||||
// The timeout is stated because this test waits out a real passive sign-in
|
||||
// redirect: two seconds beyond the default a runner like Bun gives a test.
|
||||
test("Console session waits for passive sign-in, rejects persistent forms, and handles a closed page", { timeout: 40000, ...needsBrowser }, async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "vertex-browser-session-"))
|
||||
let browser
|
||||
try {
|
||||
browser = await openBrowser({ launchArgs, profile: join(directory, "profile") })
|
||||
const hosts = new Set()
|
||||
await routeAll(browser.page, pageFor((url) => {
|
||||
hosts.add(url.hostname)
|
||||
if (url.hostname === "accounts.google.com") {
|
||||
if (url.searchParams.has("passive")) return '<h1>Sign in with your Google Account</h1><input name="identifier"><script>setTimeout(()=>location.href="https://console.cloud.google.com/?project=example-project",9000)</script>'
|
||||
if (url.searchParams.has("project")) return '<h1>Sign in with your Google Account</h1><script>setTimeout(()=>location.href="https://console.cloud.google.com/?project=example-project",100)</script>'
|
||||
if (url.searchParams.has("billing")) return '<h1>Sign in with your Google Account</h1><script>setTimeout(()=>location.href="https://console.cloud.google.com/billing/linkedaccount?returned=true",100)</script>'
|
||||
return '<h1>Sign in with your Google Account</h1><input type="password">'
|
||||
}
|
||||
if (url.pathname === "/billing/linkedaccount") {
|
||||
return url.searchParams.has("returned")
|
||||
? '<script>setTimeout(()=>document.body.innerHTML+=\'<a href="/billing/AAAAAA-BBBBBB-CCCCCC">Billing account</a>\',100)</script>'
|
||||
: '<script>location.href="https://accounts.google.com/v3/signin/identifier?billing=true"</script>'
|
||||
}
|
||||
if (url.pathname === "/signin") return '<h1>Sign in with your Google Account</h1><input type="password">'
|
||||
if (url.pathname === "/denied") return "<h1>You need additional access</h1>"
|
||||
return undefined
|
||||
}))
|
||||
await browser.page.goto("https://accounts.google.com/v3/signin/identifier?passive=true")
|
||||
const start = Date.now()
|
||||
await assertConsoleSession(browser.page)
|
||||
assert.ok(Date.now() - start >= 8000)
|
||||
assert.equal(new URL(await browser.page.url()).hostname, "console.cloud.google.com")
|
||||
await browser.page.goto("https://accounts.google.com/v3/signin/identifier?project=true")
|
||||
assert.equal(await extractProjectId(browser.page), "example-project")
|
||||
assert.equal(await discoverBillingAccount(browser.page, "example-project"), "AAAAAA-BBBBBB-CCCCCC")
|
||||
for (const url of ["https://accounts.google.com/v3/signin/identifier", "https://console.cloud.google.com/signin", "https://accounts.google.com/v3/signin/identifier?continue=https://console.cloud.google.com"]) {
|
||||
await browser.page.goto(url)
|
||||
await assert.rejects(assertConsoleSession(browser.page, { timeout: 150 }), /Google session expired/)
|
||||
}
|
||||
await browser.page.goto("https://console.cloud.google.com/denied")
|
||||
await assert.rejects(assertConsoleSession(browser.page), /permission denied/)
|
||||
await assert.rejects(assertConsoleSession(browser.page, { timeout: 0 }), /positive number/)
|
||||
// Nothing reached a host this test did not answer.
|
||||
assert.deepEqual([...hosts].sort(), ["accounts.google.com", "console.cloud.google.com"])
|
||||
await browser.page.goto("https://accounts.google.com/v3/signin/identifier")
|
||||
const closed = assert.rejects(assertConsoleSession(browser.page), /page closed/)
|
||||
await browser.page.close()
|
||||
await closed
|
||||
} finally {
|
||||
if (browser) await browser.close()
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
// The Console names the signed-in account under an obfuscated key. A page that
|
||||
// has an address but not that key has no answer: another address on it could be
|
||||
// a project member, a billing contact, or a notification.
|
||||
test("the signed-in account is only read from the Console's own keyed field", { timeout: 40000, ...needsBrowser }, async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "vertex-browser-account-"))
|
||||
let browser
|
||||
try {
|
||||
browser = await openBrowser({ launchArgs, profile: join(directory, "profile"), headless: true })
|
||||
await routeAll(browser.page, async (request) => request.fulfill({ body: '<!doctype html><p>Contact billing@example.com or owner@example.com</p>' }))
|
||||
await browser.page.goto("https://console.cloud.google.com/")
|
||||
assert.equal(await extractAccount(browser.page, { timeout: 1000 }), undefined)
|
||||
// The keyed field arrives with the Console's own payload, a moment after
|
||||
// the document it is in.
|
||||
await routeAll(browser.page, async (request) => request.fulfill({
|
||||
body: '<!doctype html><p>contact billing@example.com</p><script>setTimeout(()=>{const s=document.createElement("script");s.textContent=\'var a={"oPEP7c":"me@example.com"}\';document.head.appendChild(s)},500)</script>',
|
||||
}))
|
||||
await browser.page.goto("https://console.cloud.google.com/")
|
||||
assert.equal(await extractAccount(browser.page, { timeout: 5000 }), "me@example.com")
|
||||
} finally {
|
||||
if (browser) await browser.close()
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
// Two accounts are two tabs of one Chrome, not two Chromes: the second read
|
||||
// must land in the browser the first one left open.
|
||||
test("a second read on one profile is a tab of the browser the first left open", { timeout: 60000, ...needsBrowser }, async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "vertex-browser-reuse-"))
|
||||
const previousIdle = process.env.VERTEX_CHROME_IDLE
|
||||
try {
|
||||
process.env.VERTEX_CHROME_IDLE = "60000"
|
||||
const profile = join(directory, "profile")
|
||||
const seen = []
|
||||
const read = (label) => withPage({ profile, launchArgs }, async (page) => {
|
||||
seen.push({ label, connection: page.connection, pid: page.connection.child.pid, targetId: page.targetId })
|
||||
await routeAll(page, pageFor(() => "<h1>Google Cloud Console</h1>"))
|
||||
await page.goto("https://console.cloud.google.com/")
|
||||
return label
|
||||
})
|
||||
assert.equal(await read("first"), "first")
|
||||
assert.equal(await read("second"), "second")
|
||||
assert.equal(seen.length, 2)
|
||||
// Same Chrome process, so the second read paid for a tab and nothing else.
|
||||
assert.equal(seen[0].pid, seen[1].pid)
|
||||
assert.equal(seen[0].connection, seen[1].connection)
|
||||
assert.equal(seen[0].connection.closed, false)
|
||||
// Each read got its own target, and the first one's is gone: what was kept
|
||||
// is the browser, never the tab a read used.
|
||||
assert.notEqual(seen[0].targetId, seen[1].targetId)
|
||||
let open = []
|
||||
for (let i = 0; i < 50; i++) {
|
||||
open = (await seen[0].connection.send("Target.getTargets")).targetInfos
|
||||
if (!open.some((target) => target.targetId === seen[0].targetId)) break
|
||||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||
}
|
||||
assert.ok(!open.some((target) => target.targetId === seen[0].targetId), "the first read's tab is still open")
|
||||
} finally {
|
||||
if (previousIdle === undefined) delete process.env.VERTEX_CHROME_IDLE
|
||||
else process.env.VERTEX_CHROME_IDLE = previousIdle
|
||||
await endKeptBrowsers()
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("Chrome credits scrape handles pagination, keeps cache isolated, and force refresh bypasses it", { timeout: 60000, ...needsBrowser }, async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "vertex-browser-credits-"))
|
||||
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 })
|
||||
let requests = 0
|
||||
await routeAll(browser.page, async (request) => {
|
||||
const url = new URL(request.url())
|
||||
assert.equal(url.origin, "https://console.cloud.google.com")
|
||||
assert.match(url.pathname, /^\/billing\//)
|
||||
assert.ok(url.searchParams.get("authuser").endsWith("@example.com"))
|
||||
requests++
|
||||
// The Console names the account it rendered for under its own obfuscated
|
||||
// key, which is what a credits read is checked against.
|
||||
const shown = url.searchParams.get("authuser")
|
||||
return request.fulfill({ body: `<!doctype html><script>var a={"oPEP7c":${JSON.stringify(shown)}}</script><table><thead><tr>
|
||||
<th>Credit name</th><th>Status</th><th>Remaining value</th><th>Original value</th><th>Credit ID</th>
|
||||
</tr></thead><tbody><tr><td>Benefit one</td><td>Available</td><td>$10.00</td><td>$10.00</td><td>one</td></tr></tbody></table>
|
||||
<button aria-label="Next page" onclick="document.querySelector('tbody').innerHTML='<tr><td>Benefit two</td><td>Available</td><td>$2.07</td><td>$10.00</td><td>two</td></tr>';this.disabled=true">Next</button>` })
|
||||
})
|
||||
const options = { profile, browser, billingAccount: "AAAAAA-BBBBBB-CCCCCC", account: "first@example.com" }
|
||||
const first = await fetchCredits(options)
|
||||
assert.equal(first.remaining, 12.07)
|
||||
assert.equal(first.original, 20)
|
||||
const count = requests
|
||||
const second = await fetchCredits(options)
|
||||
assert.equal(second.cached, true)
|
||||
assert.equal(requests, count)
|
||||
const forced = await fetchCredits({ ...options, force: true })
|
||||
assert.equal(forced.cached, false)
|
||||
assert.ok(requests > count)
|
||||
assert.equal(usageOf(forced).windows[0].amount, 7.93)
|
||||
const different = await fetchCredits({ ...options, billingAccount: "AAAAAA-BBBBBB-DDDDDD" })
|
||||
assert.equal(different.cached, false)
|
||||
const otherAccount = await fetchCredits({ ...options, account: "second@example.com" })
|
||||
assert.equal(otherAccount.cached, false)
|
||||
} 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 })
|
||||
}
|
||||
})
|
||||
|
||||
// A failed read is remembered, so a project that cannot read its credits does
|
||||
// not open a browser on every usage poll: the cache is what stands in for a
|
||||
// switch here, since asking again would cost a browser for the same answer.
|
||||
test("a failed credit read is cached instead of opening a browser each poll", { timeout: 30000, ...needsBrowser }, async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "vertex-browser-failure-"))
|
||||
const previousCache = process.env.XDG_CACHE_HOME
|
||||
let browser
|
||||
try {
|
||||
process.env.XDG_CACHE_HOME = directory
|
||||
const profile = join(directory, "profile")
|
||||
let requests = 0
|
||||
browser = await openBrowser({ profile, launchArgs })
|
||||
await routeAll(browser.page, async (request) => {
|
||||
requests++
|
||||
return request.fulfill({ body: "<!doctype html><h1>No credits table here</h1>" })
|
||||
})
|
||||
// The scrape gives up on a Console page that has no table rather than
|
||||
// waiting out the page's whole patience.
|
||||
const options = { profile, browser, billingAccount: "AAAAAA-BBBBBB-CCCCCC", scrapeTimeout: 3000 }
|
||||
await assert.rejects(fetchCredits(options), /Credits table was not found/)
|
||||
const afterFirst = requests
|
||||
assert.ok(afterFirst > 0)
|
||||
// The second poll answers from the remembered failure without a browser.
|
||||
await assert.rejects(fetchCredits(options), /Credits table was not found/)
|
||||
assert.equal(requests, afterFirst)
|
||||
// Asking again on purpose does try again.
|
||||
await assert.rejects(fetchCredits({ ...options, force: true }), /Credits table was not found/)
|
||||
assert.ok(requests > afterFirst)
|
||||
} 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 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,85 @@
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
|
||||
// An executable fixture exercises the real subprocess boundary without touching
|
||||
// the developer's gcloud configuration or making Google requests.
|
||||
export async function fakeGcloud() {
|
||||
const directory = await mkdtemp(join(tmpdir(), "vertex-gcloud-test-"))
|
||||
const names = ["PATH", "HOME", "USERPROFILE", "VERTEX_TEST_GCLOUD", "GOOGLE_VERTEX_PROJECT", "GOOGLE_VERTEX_LOCATION", "VERTEX_CHROME_PROFILE", "VERTEX_GCLOUD_ACCOUNT", "VERTEX_BILLING_ACCOUNT", "VERTEX_GCLOUD_AUTH_MODE", "GOOGLE_CLOUD_PROJECT", "CLOUDSDK_CONFIG", "GOOGLE_APPLICATION_CREDENTIALS", "XDG_CONFIG_HOME"]
|
||||
const previous = Object.fromEntries(names.map((name) => [name, process.env[name]]))
|
||||
const state = join(directory, "state.json")
|
||||
const log = join(directory, "calls.jsonl")
|
||||
// The plugin reads gcloud's default directory and never a machine-wide
|
||||
// CLOUDSDK_CONFIG, so the fixture moves HOME inside itself and lets both
|
||||
// sides meet at $HOME/.config/gcloud: the fake gcloud writes there, and so
|
||||
// does the plugin's own account directories stay out of it.
|
||||
const sdk = join(directory, ".config", "gcloud")
|
||||
await writeFile(join(directory, "gcloud"), `#!/usr/bin/env node
|
||||
import { appendFileSync, readFileSync } from "node:fs"
|
||||
import { join } from "node:path"
|
||||
const state = JSON.parse(readFileSync(process.env.VERTEX_TEST_GCLOUD, "utf8"))
|
||||
const config = process.env.CLOUDSDK_CONFIG || join(process.env.HOME, ".config", "gcloud")
|
||||
const args = process.argv.slice(2)
|
||||
appendFileSync(state.log, JSON.stringify(args) + "\\n")
|
||||
if (state.fail) { process.stderr.write("SECRET-ERROR-OUTPUT"); process.exit(1) }
|
||||
// A token belongs to the account whose ADC is in the directory it is read
|
||||
// from. An ADC login writes that account beside the file it writes, so the
|
||||
// token still names the right account after the directory is renamed.
|
||||
const written = (() => {
|
||||
try { return readFileSync(config + "/.fixture-account", "utf8").trim() } catch { return undefined }
|
||||
})()
|
||||
// ADC's token command fails when the directory holds no ADC, as gcloud's does.
|
||||
// A gcloud-user token (--account=...) does not depend on ADC.
|
||||
const hasAdc = (() => {
|
||||
try { readFileSync(config + "/application_default_credentials.json"); return true } catch { return false }
|
||||
})()
|
||||
if (args[0] === "config") console.log(state[args[2]] ?? "(unset)")
|
||||
else if (args.includes("print-access-token")) {
|
||||
if (!args.some((arg) => arg.startsWith("--account=")) && !hasAdc) { process.stderr.write("no ADC in this directory"); process.exit(1) }
|
||||
console.log(written ?? state.tokens?.[config] ?? state.token ?? "fixture-token")
|
||||
}
|
||||
// An ADC login is gcloud's own: the fixture only writes the file, into the
|
||||
// directory it was pointed at, as the real one does.
|
||||
else if (args[0] === "auth" && args[1] === "application-default" && args[2] === "login") {
|
||||
const { mkdirSync, writeFileSync } = await import("node:fs")
|
||||
// state.approved is who Google's consent page is approved as, which the
|
||||
// address the plugin opened asks for as authuser.
|
||||
const approved = state.approved?.[config] ?? state.approved ?? state.pendingToken
|
||||
mkdirSync(config, { recursive: true })
|
||||
writeFileSync(join(config, "application_default_credentials.json"), JSON.stringify({ type: "authorized_user", client_id: "id", client_secret: "secret", refresh_token: "refresh", approved }))
|
||||
// Who this directory's token now belongs to. It travels with the directory,
|
||||
// as gcloud's credentials do, so a rename does not change the answer.
|
||||
if (approved) writeFileSync(join(config, ".fixture-account"), approved)
|
||||
process.stderr.write("Your browser has been opened to visit:\\n\\n https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=x&state=y\\n\\n")
|
||||
process.exit(0)
|
||||
}
|
||||
else process.exit(2)
|
||||
`, { mode: 0o700 })
|
||||
process.env.PATH = `${directory}:${process.env.PATH}`
|
||||
process.env.VERTEX_TEST_GCLOUD = state
|
||||
// From VERTEX_TEST_GCLOUD on: the plugin's own variables, never the fixture's state path.
|
||||
for (const name of names.slice(4)) delete process.env[name]
|
||||
process.env.HOME = directory
|
||||
delete process.env.USERPROFILE
|
||||
// Keep ADC discovery inside the fixture: the developer's own ADC file must
|
||||
// never decide a test's auth mode.
|
||||
const set = (values = {}) => writeFile(state, JSON.stringify({ project: "example-project", account: "user@example.com", log, ...values }))
|
||||
await set()
|
||||
return {
|
||||
directory, set, sdk,
|
||||
async setAdc(values = { quota_project_id: "adc-project" }) {
|
||||
await mkdir(sdk, { recursive: true })
|
||||
await writeFile(join(sdk, "application_default_credentials.json"), JSON.stringify({ type: "authorized_user", client_id: "id", client_secret: "secret", refresh_token: "refresh", ...values }))
|
||||
},
|
||||
async clearAdc() { await rm(join(sdk, "application_default_credentials.json"), { force: true }) },
|
||||
async calls() { return (await readFile(log, "utf8")).trim().split("\n").filter(Boolean).map(JSON.parse) },
|
||||
async close() {
|
||||
for (const [name, value] of Object.entries(previous)) {
|
||||
if (value === undefined) delete process.env[name]
|
||||
else process.env[name] = value
|
||||
}
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import { mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { apart, take } from "../lib/lock.mjs"
|
||||
|
||||
// Two accounts on one Chrome profile are read one after the other, and magpie
|
||||
// may run each account's read in a process of its own — so the lock that keeps
|
||||
// them apart has to be a file, and a hold has to be something another process
|
||||
// waits on rather than fails on.
|
||||
|
||||
test("a lock held by another process is waited for, then taken", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "vertex-lock-"))
|
||||
try {
|
||||
const file = join(directory, "balance")
|
||||
const release = await take(file)
|
||||
// A second taker does not fail: it waits, and gets the lock once released.
|
||||
let taken = false
|
||||
const waiter = take(file, { poll: 20 }).then((done) => { taken = true; return done })
|
||||
await new Promise((resolve) => setTimeout(resolve, 150))
|
||||
assert.equal(taken, false)
|
||||
await release()
|
||||
const second = await waiter
|
||||
assert.equal(taken, true)
|
||||
await second()
|
||||
} finally { await rm(directory, { recursive: true, force: true }) }
|
||||
})
|
||||
|
||||
test("releasing twice frees the lock once, and the gap counts from the release", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "vertex-lock-"))
|
||||
try {
|
||||
const file = join(directory, "balance")
|
||||
const release = await take(file)
|
||||
await release()
|
||||
// A second release must not remove a lock someone else now holds.
|
||||
const held = await take(file)
|
||||
await release()
|
||||
await assert.rejects(take(file, { timeout: 50, poll: 10 }), /still using|retry shortly/)
|
||||
await held()
|
||||
// The recorded release time is what the next reader waits out.
|
||||
const before = Date.now()
|
||||
await apart(file, 300)
|
||||
assert.ok(Date.now() - before >= 250)
|
||||
await apart(file, 0)
|
||||
} finally { await rm(directory, { recursive: true, force: true }) }
|
||||
})
|
||||
|
||||
test("a live pid cannot keep an abandoned lock past fifteen minutes", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "vertex-lock-"))
|
||||
// With no /proc start time available, a reused pid is indistinguishable
|
||||
// from the holder. The age ceiling must still leave a full sign-in time.
|
||||
const original = process.platform
|
||||
Object.defineProperty(process, "platform", { value: "darwin", configurable: true })
|
||||
try {
|
||||
const file = join(directory, "balance")
|
||||
await writeFile(`${file}.lock`, String(process.pid))
|
||||
const recent = new Date(Date.now() - 11 * 60 * 1000)
|
||||
await utimes(`${file}.lock`, recent, recent)
|
||||
await assert.rejects(take(file, { timeout: 50, poll: 10 }), /retry shortly/)
|
||||
const stale = new Date(Date.now() - 16 * 60 * 1000)
|
||||
await utimes(`${file}.lock`, stale, stale)
|
||||
const release = await take(file, { timeout: 500, poll: 20 })
|
||||
assert.equal(await readFile(`${file}.lock`, "utf8"), String(process.pid))
|
||||
await release()
|
||||
} finally {
|
||||
Object.defineProperty(process, "platform", { value: original, configurable: true })
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("a lock left by a process that has ended is not waited on", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "vertex-lock-"))
|
||||
try {
|
||||
const file = join(directory, "balance")
|
||||
// A pid that cannot be running, as a crash or a reboot leaves behind.
|
||||
await writeFile(`${file}.lock`, String(2 ** 22 + 7))
|
||||
const release = await take(file, { timeout: 500, poll: 20 })
|
||||
await release()
|
||||
// A lock that is still empty is one just being created, not an abandoned
|
||||
// one, and it is waited on rather than swept away.
|
||||
await writeFile(`${file}.lock`, "")
|
||||
await assert.rejects(take(file, { timeout: 300, poll: 20 }), /retry shortly/)
|
||||
assert.equal(await readFile(`${file}.lock`, "utf8"), "")
|
||||
} finally { await rm(directory, { recursive: true, force: true }) }
|
||||
})
|
||||
|
||||
test("Linux keeps a live holder even when its lock is over fifteen minutes old", { skip: process.platform !== "linux" }, async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "vertex-lock-"))
|
||||
const original = Date.now
|
||||
let release
|
||||
try {
|
||||
const file = join(directory, "balance")
|
||||
release = await take(file)
|
||||
// Advance wall time without placing the lock before this process started.
|
||||
Date.now = () => original() + 16 * 60 * 1000
|
||||
await assert.rejects(take(file, { timeout: 50, poll: 10 }), /retry shortly/)
|
||||
assert.equal(await readFile(`${file}.lock`, "utf8"), String(process.pid))
|
||||
} finally {
|
||||
Date.now = original
|
||||
await release?.()
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,69 @@
|
||||
import dns from "node:dns"
|
||||
import http from "node:http"
|
||||
import https from "node:https"
|
||||
import net from "node:net"
|
||||
import tls from "node:tls"
|
||||
import { syncBuiltinESMExports } from "node:module"
|
||||
|
||||
// Importable by tests and as --import: never retain the real fetch for a test
|
||||
// to restore. Record violations too, since production fallbacks catch errors.
|
||||
const unexpected = []
|
||||
function refuse(kind, target) {
|
||||
const message = `Unexpected network ${kind} in test: ${target}`
|
||||
unexpected.push(message)
|
||||
throw new Error(message)
|
||||
}
|
||||
globalThis.fetch = (input) => refuse("fetch", input?.url ?? input)
|
||||
|
||||
const local = (host) => {
|
||||
const value = String(host ?? "localhost").replace(/^\[|\]$/g, "").toLowerCase()
|
||||
return value === "localhost" || value === "::1" || /^127(?:\.\d{1,3}){3}$/.test(value)
|
||||
}
|
||||
function check(kind, host) {
|
||||
if (!local(host)) refuse(kind, host)
|
||||
}
|
||||
function connectionHost(args) {
|
||||
const first = args[0]
|
||||
if (typeof first === "object") {
|
||||
if (first.path) return undefined // Unix pipe, including Chrome's CDP transport.
|
||||
return first.host ?? first.hostname
|
||||
}
|
||||
if (typeof first === "string" && !/^\d+$/.test(first)) return undefined // Unix socket.
|
||||
return typeof args[1] === "string" ? args[1] : undefined
|
||||
}
|
||||
for (const [owner, key] of [[net, "connect"], [net, "createConnection"], [net.Socket.prototype, "connect"], [tls, "connect"]]) {
|
||||
const original = owner[key]
|
||||
owner[key] = function (...args) {
|
||||
// Node may forward already-normalized connect arguments as one array.
|
||||
check(key, connectionHost(Array.isArray(args[0]) ? args[0] : args))
|
||||
return original.apply(this, args)
|
||||
}
|
||||
}
|
||||
for (const owner of [http, https]) {
|
||||
for (const key of ["request", "get"]) {
|
||||
const original = owner[key]
|
||||
owner[key] = function (...args) {
|
||||
const first = args[0]
|
||||
const url = typeof first === "string" || first instanceof URL ? new URL(first) : undefined
|
||||
const options = url ? (typeof args[1] === "object" ? args[1] : {}) : first ?? {}
|
||||
if (!options.socketPath) check(key, options.hostname ?? options.host ?? url?.hostname)
|
||||
return original.apply(this, args)
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const owner of [dns, dns.promises]) {
|
||||
const original = owner.lookup
|
||||
owner.lookup = function (host, ...args) {
|
||||
check("dns.lookup", host)
|
||||
return original.call(this, host, ...args)
|
||||
}
|
||||
}
|
||||
syncBuiltinESMExports()
|
||||
// Also covers caught errors and fixture subprocesses without importing node:test
|
||||
// there: its reporter would contaminate gcloud's token output.
|
||||
process.on("exit", () => {
|
||||
if (unexpected.length) {
|
||||
console.error(unexpected.join("\n"))
|
||||
process.exitCode = 1
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,985 @@
|
||||
import "./network.mjs"
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import plugin from "../index.mjs"
|
||||
import { createHash } from "node:crypto"
|
||||
import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"
|
||||
import { tmpdir } from "node:os"
|
||||
import { dirname, join } from "node:path"
|
||||
import { EventEmitter } from "node:events"
|
||||
import { accountOf, adcDirectoryFor, adcDirectoryOwnedBy, adcDirectoryToCreate, adcFile, adcSlug, beginAdcLogin, effectiveAuthMode, hasAdc, resolveAccount, resolveIdentity, resolveProject, runGcloud, startLogin, tokenProvider } from "../lib/credentials.mjs"
|
||||
import { fakeGcloud } from "./gcloud.mjs"
|
||||
import { 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"
|
||||
|
||||
const headers = ["Credit name", "Status", "Percent remaining", "Remaining value", "Original value", "Type", "Credit ID", "Usage scope", "Start date", "End date"]
|
||||
const row = (id, remaining, original = "$10.00", status = "Available", start = "July 15, 2026", end = "July 1, 2027") => ["Example benefit", status, "100%", remaining, original, "One-time", id, "All Google Cloud services", start, end]
|
||||
const now = Date.parse("2026-10-18T12:00:00Z")
|
||||
|
||||
test("credits sum active rows, deduplicate IDs, reject future/expired rows, and count exhausted grants", () => {
|
||||
const tables = [{ headers, rows: [row("a", "$10.00"), row("b", "$2.07"), row("b", "$2.07"), row("expired", "$262.09", "$300.00", "Expired"), row("future", "$10.00", "$10.00", "Available", "January 1, 2027"), row("used", "$0.00", "$10.00", "Exhausted")] }]
|
||||
const result = parseCreditTables(tables, { now })
|
||||
assert.equal(result.remaining, 12.07)
|
||||
assert.equal(result.original, 30)
|
||||
assert.equal(result.used, 17.93)
|
||||
assert.equal(result.runsOutAt, "2027-07-01T00:00:00.000Z")
|
||||
const usage = usageOf(result)
|
||||
assert.equal(usage.windows[0].amount, 17.93)
|
||||
assert.equal(usage.windows[0].limit, 30)
|
||||
assert.match(usage.windows[0].display, /\$12\.07 remaining/)
|
||||
})
|
||||
|
||||
test("Used credits count as fully spent and never increase eligible balance", () => {
|
||||
for (const status of ["Used", "used", "Exhausted", "Used up"]) {
|
||||
const result = parseCreditTables([{ headers, rows: [row("active", "$2.07"), row("spent", "$1.00", "$10.00", status)] }], { now })
|
||||
assert.equal(result.remaining, 2.07)
|
||||
assert.equal(result.original, 20)
|
||||
assert.equal(result.used, 17.93)
|
||||
assert.equal(result.credits.find((credit) => credit.id === "spent").remaining, 0)
|
||||
}
|
||||
const result = parseCreditTables([{ headers, rows: [row("used", "$0.00", "$10.00", "Used")] }], { now })
|
||||
assert.equal(result.remaining, 0)
|
||||
assert.equal(result.usedPercent, 100)
|
||||
})
|
||||
|
||||
test("credits fail closed on missing layout, unknown statuses, unsupported currencies and invalid amounts", () => {
|
||||
assert.throws(() => parseCreditTables([]), /not found/)
|
||||
assert.throws(() => parseCreditTables([{ headers, rows: [row("a", "$1.00", "$10.00", "Mystery")] }]), /Unknown/)
|
||||
assert.throws(() => parseCreditTables([{ headers, rows: [row("a", "€1.00")] }]), /currency/)
|
||||
assert.throws(() => parseCreditTables([{ headers, rows: [row("a", "$11.00")] }]), /Invalid/)
|
||||
assert.equal(parseCreditTables([{ headers, rows: [row("a", "$10.00", "$10.00", "Expired")] }], { now }).remaining, 0)
|
||||
})
|
||||
|
||||
test("session checking recovers from navigation context loss within the same deadline", async () => {
|
||||
let attempts = 0
|
||||
let disposed = false
|
||||
const timeouts = []
|
||||
await assertConsoleSession({
|
||||
isClosed: () => false,
|
||||
waitForFunction: async (_, argument, options) => {
|
||||
timeouts.push(options.timeout)
|
||||
if (++attempts === 1) throw new Error("Execution context was destroyed, most likely because of a navigation")
|
||||
return { jsonValue: async () => ({ text: "Google Cloud Console" }), dispose: async () => { disposed = true } }
|
||||
},
|
||||
}, { timeout: 1000 })
|
||||
assert.equal(attempts, 2)
|
||||
assert.equal(disposed, true)
|
||||
assert.ok(timeouts[1] <= timeouts[0])
|
||||
await assert.rejects(assertConsoleSession({ isClosed: () => false, waitForFunction: async () => { throw new Error("Unexpected protocol failure") } }), /Unexpected protocol failure/)
|
||||
})
|
||||
|
||||
test("gcloud resolves explicit and configured identities and rejects missing or malformed configuration", { timeout: 30000 }, async () => {
|
||||
const fixture = await fakeGcloud()
|
||||
try {
|
||||
assert.deepEqual(await resolveIdentity(), { project: "example-project", account: "user@example.com", source: "gcloud", authMode: "gcloud" })
|
||||
assert.equal(await resolveProject({ project: "custom-project" }, () => assert.fail("Explicit project should not query gcloud")), "custom-project")
|
||||
process.env.GOOGLE_VERTEX_PROJECT = "environment-project"
|
||||
assert.equal(await resolveProject(), "environment-project")
|
||||
delete process.env.GOOGLE_VERTEX_PROJECT
|
||||
process.env.GOOGLE_CLOUD_PROJECT = "cloud-project"
|
||||
assert.equal(await resolveProject(), "cloud-project")
|
||||
delete process.env.GOOGLE_CLOUD_PROJECT
|
||||
await fixture.set({ project: "(unset)", account: "(unset)" })
|
||||
await assert.rejects(resolveProject(), /No Google Cloud project/)
|
||||
// The project the signed-in Chrome is on beats anything gcloud remembers,
|
||||
// and an explicit project still beats both.
|
||||
assert.equal(await resolveProject({ chromeProject: "chrome-project" }), "chrome-project")
|
||||
assert.equal(await resolveProject({ project: "explicit-project", chromeProject: "chrome-project" }), "explicit-project")
|
||||
await assert.rejects(resolveAccount(), /No Google Cloud account/)
|
||||
await assert.rejects(resolveProject({ project: "bad/project" }), /project ID/)
|
||||
await assert.rejects(resolveAccount({ account: "--bad@example.com" }), /account email/)
|
||||
await fixture.set({ fail: true })
|
||||
await assert.rejects(runGcloud(["auth", "print-access-token"]), (error) => !error.message.includes("SECRET") && /gcloud auth login/.test(error.message))
|
||||
} finally { await fixture.close() }
|
||||
})
|
||||
|
||||
test("gcloud tokens merge concurrent requests and delegate expiry checks and renewal to gcloud", { timeout: 30000 }, async () => {
|
||||
const fixture = await fakeGcloud()
|
||||
try {
|
||||
const getToken = tokenProvider({ account: "pinned@example.com" })
|
||||
assert.deepEqual(await Promise.all([getToken(), getToken(), getToken()]), ["fixture-token", "fixture-token", "fixture-token"])
|
||||
let calls = (await fixture.calls()).filter((args) => args[1] === "print-access-token")
|
||||
assert.equal(calls.length, 1)
|
||||
assert.ok(calls[0].includes("--account=pinned@example.com"))
|
||||
await fixture.set({ token: "renewed-token" })
|
||||
assert.equal(await getToken(), "renewed-token")
|
||||
await fixture.set({ fail: true })
|
||||
await assert.rejects(getToken(), /gcloud could not/)
|
||||
await fixture.set({ token: "recovered-token" })
|
||||
assert.equal(await getToken(), "recovered-token")
|
||||
for (const token of ["", "bad token"]) {
|
||||
await fixture.set({ token })
|
||||
await assert.rejects(getToken(), /empty or invalid/)
|
||||
}
|
||||
} finally { await fixture.close() }
|
||||
})
|
||||
|
||||
test("CLI verifies gcloud without exposing tokens and rejects all removed key flags", { timeout: 30000 }, async () => {
|
||||
for (const flag of ["--source-key", "--key-path", "--service-account"]) {
|
||||
await assert.rejects(main(["credentials", flag, "/unused.json"]), /Unknown option/)
|
||||
}
|
||||
const fixture = await fakeGcloud()
|
||||
const originalLog = console.log
|
||||
let output
|
||||
try {
|
||||
console.log = (value) => { output = JSON.parse(value) }
|
||||
await main(["credentials", "--account", "selected@example.com"])
|
||||
assert.deepEqual(output, { project: "example-project", account: "selected@example.com", source: "gcloud", authMode: "gcloud", inferenceAuth: "token-verified" })
|
||||
assert.ok(!JSON.stringify(output).includes("fixture-token"))
|
||||
} finally { console.log = originalLog; await fixture.close() }
|
||||
})
|
||||
|
||||
test("ADC names its sign-in from the token, so the row shows the account and not \"Signed in\"", async () => {
|
||||
const asked = []
|
||||
const request = async (url, init) => {
|
||||
asked.push([url, init.headers.authorization])
|
||||
return { ok: true, json: async () => ({ email: "adc@example.com", email_verified: true }) }
|
||||
}
|
||||
assert.equal(await accountOf("fixture-token", request), "adc@example.com")
|
||||
assert.deepEqual(asked, [["https://openidconnect.googleapis.com/v1/userinfo", "Bearer fixture-token"]])
|
||||
// A refused or broken lookup leaves the sign-in working and unnamed.
|
||||
assert.equal(await accountOf("t", async () => ({ ok: false })), undefined)
|
||||
assert.equal(await accountOf("t", async () => { throw new Error("offline") }), undefined)
|
||||
assert.equal(await accountOf("t", async () => ({ ok: true, json: async () => ({ email: "--not-an-email" }) })), undefined)
|
||||
})
|
||||
|
||||
test("ADC setup reads gcloud's complete consent URL and distinguishes saved ADC from failed consent", { timeout: 30000 }, async () => {
|
||||
// gcloud writes its URL across several stderr chunks, as the real one does.
|
||||
const sibling = (pieces, code) => {
|
||||
const child = new EventEmitter()
|
||||
child.stdout = new EventEmitter()
|
||||
child.stderr = new EventEmitter()
|
||||
child.kill = () => {}
|
||||
setTimeout(() => { for (const piece of pieces) child.stderr.emit("data", piece); setTimeout(() => child.emit("exit", code), 10) }, 5)
|
||||
return child
|
||||
}
|
||||
const missing = () => {
|
||||
const child = new EventEmitter()
|
||||
child.stdout = new EventEmitter()
|
||||
child.stderr = new EventEmitter()
|
||||
child.kill = () => {}
|
||||
setTimeout(() => child.emit("error", Object.assign(new Error("no gcloud"), { code: "ENOENT" })), 5)
|
||||
return child
|
||||
}
|
||||
const calls = []
|
||||
const run = (command, args, options) => {
|
||||
calls.push({ command, args, env: options.env })
|
||||
return sibling([
|
||||
"Your browser has been opened to visit:\n\n https://accounts.google.com/o/oauth2/auth?response_type=code&cli",
|
||||
"ent_id=x&redirect_uri=http%3A%2F%2Flocalhost%3A8085%2F&state=y\n\n",
|
||||
], 0)
|
||||
}
|
||||
const fixture = await fakeGcloud()
|
||||
try {
|
||||
await fixture.clearAdc()
|
||||
const login = await beginAdcLogin({ project: "example-project" }, run)
|
||||
const url = await login.url
|
||||
await login.done
|
||||
// One URL opened, from gcloud's own flow; BROWSER is neutralised so the
|
||||
// plugin's Chrome, and not a second window gcloud starts, shows it.
|
||||
assert.match(url, /^https:\/\/accounts\.google\.com\/o\/oauth2\/auth\?response_type=code&client_id=x/)
|
||||
assert.equal(calls[0].command, "gcloud")
|
||||
assert.deepEqual(calls[0].args, ["auth", "application-default", "login", "--project=example-project", "--billing-project=example-project"])
|
||||
assert.equal(calls[0].env.BROWSER, "true")
|
||||
// A chunk boundary is not the end of the URL: nothing is opened until the
|
||||
// whole address has arrived.
|
||||
const split = (pieces, code) => {
|
||||
const child = new EventEmitter()
|
||||
child.stdout = new EventEmitter(); child.stderr = new EventEmitter(); child.kill = () => {}
|
||||
setTimeout(() => { for (const piece of pieces) child.stderr.emit("data", piece) }, 5)
|
||||
setTimeout(() => child.emit("exit", code), 40)
|
||||
return child
|
||||
}
|
||||
const slow = (pieces) => split([...pieces, "\n"], 0)
|
||||
const splitLogin = await beginAdcLogin({}, () => slow(["https://accounts.google.com/o/oauth2/auth?response_type=code", "&client_id=x&state=y"]))
|
||||
const splitUrl = await splitLogin.url
|
||||
await splitLogin.done
|
||||
// The newline gcloud ends the URL with is not part of the address.
|
||||
assert.match(splitUrl, /client_id=x&state=y$/)
|
||||
// ADC written before gcloud's own quota-project probe failed: the sign-in
|
||||
// worked, so the exit code is not the answer.
|
||||
await fixture.clearAdc()
|
||||
const writesThenFails = () => {
|
||||
const child = split(["https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=x&state=y\n"], 1)
|
||||
setTimeout(() => { void fixture.setAdc({ quota_project_id: "adc-project" }) }, 5)
|
||||
return child
|
||||
}
|
||||
await (await beginAdcLogin({}, writesThenFails)).done
|
||||
// Nothing written: that is a real failure.
|
||||
await fixture.clearAdc()
|
||||
await assert.rejects((await beginAdcLogin({}, () => split(["https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=x&state=y\n"], 1))).done, /gcloud could not set up ADC/)
|
||||
await assert.rejects((await beginAdcLogin({}, missing)).done, /gcloud CLI was not found/)
|
||||
} finally { await fixture.close() }
|
||||
})
|
||||
|
||||
test("ADC uses only its own token command, never assumes the active gcloud account, and adds ADC only when there is none", { timeout: 30000 }, async () => {
|
||||
const fixture = await fakeGcloud()
|
||||
let login
|
||||
try {
|
||||
await fixture.setAdc({})
|
||||
const identity = await resolveIdentity({ authMode: "adc" })
|
||||
assert.deepEqual(identity, { project: "example-project", source: "gcloud", authMode: "adc" })
|
||||
assert.equal(await tokenProvider(identity)(), "fixture-token")
|
||||
const calls = await fixture.calls()
|
||||
assert.ok(calls.some((args) => args.slice(0, 3).join(" ") === "auth application-default print-access-token"))
|
||||
// Merely reading an ADC identity never tries to create one.
|
||||
assert.ok(!calls.some((args) => args.includes("login")))
|
||||
await fixture.set({ fail: true })
|
||||
await assert.rejects(tokenProvider(identity)(), /gcloud auth application-default login/)
|
||||
// An explicit gcloud mode is the user's own sign-in to make: ADC is used
|
||||
// as it stands and never created by the plugin.
|
||||
await fixture.setAdc({ quota_project_id: "adc-project" })
|
||||
await fixture.set({ token: "fixture-token" })
|
||||
login = await startLogin({ project: "example-project", account: "user@example.com", authMode: "gcloud" }, signInWindowOf([]))
|
||||
const result = await login.result
|
||||
// An explicit gcloud sign-in is the user's own: the window opened and was
|
||||
// read for the gcloud identity, and no ADC login was run for them.
|
||||
assert.equal(result.project, "example-project")
|
||||
assert.equal(result.creditsSession, "ready")
|
||||
assert.ok(!(await fixture.calls()).some((args) => args.includes("login")))
|
||||
await assert.rejects(tokenProvider({ authMode: "unknown" })(), /must be auto, gcloud or adc/)
|
||||
} finally { await login?.close(); await fixture.close() }
|
||||
})
|
||||
|
||||
test("auto mode prefers ADC like official Vertex clients, takes its quota project, and falls back to gcloud", { timeout: 30000 }, async () => {
|
||||
const fixture = await fakeGcloud()
|
||||
try {
|
||||
// No ADC file: the gcloud user login remains the identity.
|
||||
assert.equal(await effectiveAuthMode(), "gcloud")
|
||||
assert.deepEqual(await resolveIdentity(), { project: "example-project", account: "user@example.com", source: "gcloud", authMode: "gcloud" })
|
||||
// ADC exists: it wins, and its project resolves from gcloud config (ADC's quota project is for billing quota, not Vertex project selection).
|
||||
await fixture.setAdc({ quota_project_id: "adc-project" })
|
||||
assert.equal(await effectiveAuthMode(), "adc")
|
||||
assert.deepEqual(await resolveIdentity(), { project: "example-project", source: "gcloud", authMode: "adc" })
|
||||
assert.equal(await tokenProvider({})() , "fixture-token")
|
||||
assert.ok((await fixture.calls()).some((args) => args.slice(0, 3).join(" ") === "auth application-default print-access-token"))
|
||||
// An explicit mode still overrides detection in both directions.
|
||||
assert.equal(await effectiveAuthMode({ authMode: "gcloud" }), "gcloud")
|
||||
await fixture.clearAdc()
|
||||
assert.equal(await effectiveAuthMode({ authMode: "adc" }), "adc")
|
||||
// GOOGLE_APPLICATION_CREDENTIALS points ADC at an explicit file.
|
||||
const explicit = join(fixture.directory, "service-account.json")
|
||||
await writeFile(explicit, JSON.stringify({ type: "service_account", project_id: "file-project" }))
|
||||
process.env.GOOGLE_APPLICATION_CREDENTIALS = explicit
|
||||
assert.equal(await effectiveAuthMode(), "adc")
|
||||
assert.equal(await adcFile(), explicit)
|
||||
} finally { await fixture.close() }
|
||||
})
|
||||
|
||||
test("a sign-in with an ADC the plugin already filed counts as an overwrite and fails", { timeout: 30000 }, async () => {
|
||||
const fixture = await fakeGcloud()
|
||||
let login
|
||||
const original = globalThis.fetch
|
||||
globalThis.fetch = mockFetch()
|
||||
const root = join(fixture.directory, "plugin")
|
||||
try {
|
||||
// The plugin's own ADC for this account is the overwrite. gcloud's
|
||||
// machine-wide one is not: it belongs to gcloud, is only ever read, and a
|
||||
// sign-in writes this plugin's credential beside it.
|
||||
const own = adcDirectoryFor("user@example.com", root)
|
||||
await mkdir(own, { recursive: true })
|
||||
await writeFile(join(own, "application_default_credentials.json"), JSON.stringify({ type: "authorized_user", client_id: "id", client_secret: "secret", refresh_token: "refresh" }))
|
||||
const visited = []
|
||||
const openWindow = async ({ url }) => {
|
||||
visited.push(new URL(url))
|
||||
return {
|
||||
ended: new Promise((resolve) => setTimeout(resolve, 5)),
|
||||
openTab: async () => true,
|
||||
close: async () => {},
|
||||
}
|
||||
}
|
||||
login = await startLogin({ adcRoot: root, account: "user@example.com" }, openWindow)
|
||||
const result = await login.result
|
||||
assert.equal(result.creditsSession, "unavailable")
|
||||
assert.match(result.warning, /already signed in|ADC already existed/i)
|
||||
// Refused before anything opened: no window, and the ADC is as it was.
|
||||
assert.deepEqual(visited, [])
|
||||
assert.equal(await readFile(join(own, "application_default_credentials.json"), "utf8").then((text) => JSON.parse(text).refresh_token), "refresh")
|
||||
} finally { await login?.close(); globalThis.fetch = original; await fixture.close() }
|
||||
})
|
||||
|
||||
test("ADC reads and new directories stay under the plugin root, independent of machine credentials", { timeout: 30000 }, async () => {
|
||||
const fixture = await fakeGcloud()
|
||||
const root = join(fixture.directory, "plugin")
|
||||
const original = globalThis.fetch
|
||||
globalThis.fetch = mockFetch()
|
||||
try {
|
||||
for (const account of ["first@example.com", "second@example.com"]) {
|
||||
const own = adcDirectoryFor(account, root)
|
||||
assert.equal(await adcDirectoryOwnedBy(account, root), own)
|
||||
assert.equal(await adcDirectoryToCreate(account, root), own)
|
||||
}
|
||||
const own = adcDirectoryFor("first@example.com", root)
|
||||
await mkdir(own, { recursive: true })
|
||||
await writeFile(join(own, "application_default_credentials.json"), "{}")
|
||||
await fixture.set({ token: "first@example.com" })
|
||||
assert.equal(await adcDirectoryOwnedBy("first@example.com", root), own)
|
||||
assert.equal(await adcDirectoryToCreate("first@example.com", root), own)
|
||||
assert.equal(await adcDirectoryOwnedBy("second@example.com", root), adcDirectoryFor("second@example.com", root))
|
||||
// A machine ADC is readable as an import, never the destination of a new
|
||||
// account, even when CLOUDSDK_CONFIG points somewhere else.
|
||||
await fixture.setAdc()
|
||||
process.env.CLOUDSDK_CONFIG = join(fixture.directory, "someone-elses-sdk")
|
||||
assert.equal(await adcFile(), join(fixture.sdk, "application_default_credentials.json"))
|
||||
assert.equal(await adcDirectoryToCreate("third@example.com", root), adcDirectoryFor("third@example.com", root))
|
||||
const named = join(fixture.directory, "own-sdk")
|
||||
process.env.GOOGLE_APPLICATION_CREDENTIALS = join(fixture.directory, "elsewhere.json")
|
||||
assert.equal(await adcFile({ cloudsdkConfig: named }), join(named, "application_default_credentials.json"))
|
||||
assert.equal(await hasAdc({ cloudsdkConfig: named }), false)
|
||||
} finally {
|
||||
globalThis.fetch = original
|
||||
await fixture.close()
|
||||
}
|
||||
})
|
||||
|
||||
// The one window a sign-in opens. Nothing is attached to it, so what it offers
|
||||
// is the address it was opened on, the tabs handed to it afterwards (gcloud's
|
||||
// consent page), and the moment it ends — which, for a person who has just
|
||||
// signed in, is immediately.
|
||||
function signInWindowOf(visited, tabs = []) {
|
||||
const opened = new Promise((resolve) => setTimeout(resolve, 5))
|
||||
return async ({ url }) => {
|
||||
visited.push(new URL(url))
|
||||
return {
|
||||
ended: opened,
|
||||
openTab: async (tabUrl) => { tabs.push(tabUrl); return true },
|
||||
close: async () => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// A page for a Chrome profile that holds several Google accounts. Google's
|
||||
// add-account page brings the browser back to the Console as the account that
|
||||
// was just signed in there, which is what `added` stands in for.
|
||||
function profileOf(accounts, project = "adc-project", added = accounts.at(-1)) {
|
||||
const visited = []
|
||||
const consolePage = () => new URL("https://console.cloud.google.com/?hl=en")
|
||||
const page = {
|
||||
goto: async (url) => { visited.push(new URL(url)) },
|
||||
url: () => String(visited.at(-1) ?? ""),
|
||||
isClosed: () => false,
|
||||
waitForFunction: async (fn) => {
|
||||
const source = String(fn)
|
||||
if ((visited.at(-1)?.host ?? "") === "accounts.google.com") {
|
||||
// Signing in on that page returns to the Console as the added account.
|
||||
if (source.includes("last_project_id")) {
|
||||
visited.push(consolePage())
|
||||
return { jsonValue: async () => project, dispose: async () => {} }
|
||||
}
|
||||
return { jsonValue: async () => ({ text: "Sign in with your Google Account" }), dispose: async () => {} }
|
||||
}
|
||||
if (source.includes("gserviceaccount")) {
|
||||
const at = visited.at(-1)
|
||||
const byEmail = accounts.find((account) => at?.searchParams.get("authuser") === account)
|
||||
return { jsonValue: async () => byEmail ?? added ?? accounts[0], dispose: async () => {} }
|
||||
}
|
||||
if (source.includes("last_project_id")) return { jsonValue: async () => project, dispose: async () => {} }
|
||||
return { jsonValue: async () => ({ text: "Google Cloud Console" }), dispose: async () => {} }
|
||||
},
|
||||
}
|
||||
return { page, visited, close: async () => {} }
|
||||
}
|
||||
|
||||
// Routes fetch requests by URL host for testing sign-in and project listing.
|
||||
const mockFetch = (projects = [{ projectId: "example-project", name: "Example Project", lifecycleState: "ACTIVE" }]) => async (url, init) => {
|
||||
const parsed = new URL(url)
|
||||
if (parsed.host === "openidconnect.googleapis.com") {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({ email: String(init.headers.authorization).replace(/^Bearer /, "") }),
|
||||
}
|
||||
}
|
||||
if (parsed.host === "cloudresourcemanager.googleapis.com") {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({ projects }),
|
||||
}
|
||||
}
|
||||
if (parsed.host === "serviceusage.googleapis.com") {
|
||||
const match = parsed.pathname.match(/\/v1\/projects\/([^/]+)\/services\/aiplatform\.googleapis\.com/)
|
||||
const projectId = match ? decodeURIComponent(match[1]) : undefined
|
||||
const candidate = projects.find((p) => p.projectId === projectId)
|
||||
const enabled = candidate ? candidate.vertexEnabled !== false : false
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({ state: enabled ? "ENABLED" : "DISABLED" }),
|
||||
}
|
||||
}
|
||||
return { ok: false, status: 404 }
|
||||
}
|
||||
|
||||
test("a named sign-in saves its own ADC and refuses a later duplicate", { timeout: 30000 }, async () => {
|
||||
const fixture = await fakeGcloud()
|
||||
let login
|
||||
let duplicate
|
||||
const original = globalThis.fetch
|
||||
globalThis.fetch = mockFetch()
|
||||
try {
|
||||
const account = "me@example.com"
|
||||
const root = join(fixture.directory, "plugin")
|
||||
const own = adcDirectoryFor(account, root)
|
||||
await fixture.set({ approved: account })
|
||||
const visited = []
|
||||
login = await startLogin({ adcRoot: root, account }, signInWindowOf(visited))
|
||||
assert.deepEqual(await login.result, {
|
||||
project: "example-project", account, source: "gcloud", authMode: "adc", cloudsdkConfig: own, creditsSession: "ready",
|
||||
})
|
||||
assert.equal(visited.length, 1)
|
||||
const file = join(own, "application_default_credentials.json")
|
||||
const saved = await readFile(file, "utf8")
|
||||
assert.equal(JSON.parse(saved).approved, account)
|
||||
assert.equal(await adcDirectoryOwnedBy(account, root), own)
|
||||
duplicate = await startLogin({ adcRoot: root, account }, signInWindowOf(visited))
|
||||
assert.match((await duplicate.result).warning, /already signed in/)
|
||||
assert.equal(visited.length, 1)
|
||||
assert.equal(await readFile(file, "utf8"), saved)
|
||||
assert.deepEqual(await readdir(root), ["adc-me-example-com"])
|
||||
} finally { await login?.close(); await duplicate?.close(); globalThis.fetch = original; await fixture.close() }
|
||||
})
|
||||
|
||||
for (const named of [true, false]) {
|
||||
test(`accounts with the same slug keep separate ADCs after ${named ? "named" : "unnamed"} sign-ins`, { timeout: 30000 }, async () => {
|
||||
const fixture = await fakeGcloud()
|
||||
const original = globalThis.fetch
|
||||
globalThis.fetch = mockFetch()
|
||||
try {
|
||||
const root = join(fixture.directory, "plugin")
|
||||
const first = "a.b@x.com"
|
||||
const second = "a-b@x.com"
|
||||
const plain = adcDirectoryFor(first, root)
|
||||
const hashed = `${plain}-${createHash("sha256").update(second).digest("hex").slice(0, 6)}`
|
||||
assert.equal(adcSlug(first), adcSlug(second))
|
||||
const visited = []
|
||||
const signIn = async (account) => {
|
||||
await fixture.set({ approved: account })
|
||||
const login = await startLogin({ adcRoot: root, ...(named ? { account } : {}) }, signInWindowOf(visited))
|
||||
try { return await login.result } finally { await login.close() }
|
||||
}
|
||||
const one = await signIn(first)
|
||||
assert.equal(one.account, first)
|
||||
assert.equal(one.cloudsdkConfig, plain)
|
||||
assert.equal(one.creditsSession, "ready")
|
||||
const saved = await readFile(join(plain, "application_default_credentials.json"), "utf8")
|
||||
// A definite mismatch chooses the second account's directory even before
|
||||
// it exists; reading must never borrow the first account's ADC.
|
||||
assert.equal(await adcDirectoryOwnedBy(second, root), hashed)
|
||||
assert.equal(await adcDirectoryToCreate(second, root), hashed)
|
||||
const two = await signIn(second)
|
||||
assert.equal(two.account, second)
|
||||
assert.equal(two.cloudsdkConfig, hashed)
|
||||
assert.equal(two.project, "example-project")
|
||||
assert.equal(two.creditsSession, "ready")
|
||||
assert.equal(visited.length, 2)
|
||||
for (const [account, directory] of [[first, plain], [second, hashed]]) {
|
||||
assert.equal(await adcDirectoryOwnedBy(account, root), directory)
|
||||
assert.equal(await adcDirectoryToCreate(account, root), directory)
|
||||
assert.equal(await tokenProvider({ authMode: "adc", cloudsdkConfig: directory })(), account)
|
||||
const duplicate = await signIn(account)
|
||||
assert.equal(duplicate.project, undefined)
|
||||
assert.match(duplicate.warning, /already signed in/)
|
||||
}
|
||||
assert.equal(await readFile(join(plain, "application_default_credentials.json"), "utf8"), saved)
|
||||
assert.equal(JSON.parse(await readFile(join(hashed, "application_default_credentials.json"), "utf8")).approved, second)
|
||||
assert.deepEqual((await readdir(root)).sort(), [plain, hashed].map((directory) => directory.slice(root.length + 1)).sort())
|
||||
} finally { globalThis.fetch = original; await fixture.close() }
|
||||
})
|
||||
}
|
||||
|
||||
test("a sign-in without gcloud finishes promptly, opens no window, and removes its directory", { timeout: 30000 }, async () => {
|
||||
const fixture = await fakeGcloud()
|
||||
const original = globalThis.fetch
|
||||
globalThis.fetch = async () => assert.fail("A missing gcloud must not make a Google request")
|
||||
try {
|
||||
const root = join(fixture.directory, "plugin")
|
||||
const empty = join(fixture.directory, "empty-path")
|
||||
await mkdir(empty)
|
||||
process.env.PATH = empty
|
||||
for (const account of [undefined, "me@example.com"]) {
|
||||
const visited = []
|
||||
const login = await startLogin({ adcRoot: root, account, loginTimeout: 20000 }, signInWindowOf(visited))
|
||||
let timer
|
||||
try {
|
||||
const result = await Promise.race([
|
||||
login.result,
|
||||
new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("Missing gcloud left sign-in pending")), 2000) }),
|
||||
])
|
||||
assert.equal(result.project, undefined)
|
||||
assert.equal(result.creditsSession, "unavailable")
|
||||
assert.match(result.warning, /gcloud CLI was not found/)
|
||||
assert.deepEqual(visited, [])
|
||||
assert.deepEqual(await readdir(root), [])
|
||||
} finally { clearTimeout(timer); await login.close() }
|
||||
}
|
||||
} finally { globalThis.fetch = original; await fixture.close() }
|
||||
})
|
||||
|
||||
test("a second sign-in opens Google's add-account page directly and takes the account it returns", { timeout: 30000 }, async () => {
|
||||
const fixture = await fakeGcloud()
|
||||
let login
|
||||
try {
|
||||
const first = "first@example.com"
|
||||
const second = "second@example.com"
|
||||
const root = join(fixture.directory, "plugin")
|
||||
const own = adcDirectoryFor(second, root)
|
||||
// The consent page is approved as the second account: that is the token the
|
||||
// staging directory prints, and the only place the account is learned from.
|
||||
await fixture.set({ token: first, pendingToken: second })
|
||||
const original = globalThis.fetch
|
||||
globalThis.fetch = mockFetch()
|
||||
try {
|
||||
// An account this plugin already filed is what makes a sign-in an
|
||||
// addition; the machine's own ADC is not this plugin's account list, so
|
||||
// it would not put the add-account page in front of the sign-in.
|
||||
const known = adcDirectoryFor(first, root)
|
||||
await mkdir(known, { recursive: true })
|
||||
await writeFile(join(known, "application_default_credentials.json"), JSON.stringify({ type: "authorized_user", client_id: "id", client_secret: "secret", refresh_token: "refresh" }))
|
||||
const visited = []
|
||||
const tabs = []
|
||||
login = await startLogin({ adcRoot: root, profile: join(fixture.directory, "profile") }, signInWindowOf(visited, tabs, second))
|
||||
const result = await login.result
|
||||
assert.equal(result.account, second)
|
||||
// The very first page is Google's add-account page; there is no address
|
||||
// to type and no account to pick from a list beforehand.
|
||||
assert.equal(visited[0].host, "accounts.google.com")
|
||||
assert.equal(visited[0].pathname, "/AddSession")
|
||||
// One window: the account is learned from the token the consent page
|
||||
// produced, so nothing else is opened to ask who it is.
|
||||
assert.equal(visited.length, 1)
|
||||
// (The consent tab itself is covered where gcloud's URL is read: the
|
||||
// fixture's gcloud writes ADC without printing one.)
|
||||
assert.deepEqual(tabs, [])
|
||||
// The second account's ADC went to its own directory, and no staging
|
||||
// directory was left behind.
|
||||
assert.equal(await adcFile({ cloudsdkConfig: own }), join(own, "application_default_credentials.json"))
|
||||
assert.deepEqual((await readdir(root)).filter((name) => name.includes("pending")), [])
|
||||
} finally { await login?.close(); globalThis.fetch = original }
|
||||
} finally { await fixture.close() }
|
||||
})
|
||||
|
||||
test("a sign-in whose ADC names an account not signed in here is a new account", { timeout: 30000 }, async () => {
|
||||
const fixture = await fakeGcloud()
|
||||
let login
|
||||
try {
|
||||
const email = "unwritten@example.com"
|
||||
const root = join(fixture.directory, "plugin")
|
||||
await fixture.clearAdc()
|
||||
await fixture.set({ token: email, pendingToken: email })
|
||||
const original = globalThis.fetch
|
||||
globalThis.fetch = mockFetch()
|
||||
try {
|
||||
login = await startLogin({ adcRoot: root, profile: join(fixture.directory, "profile") }, signInWindowOf([], []))
|
||||
const result = await login.result
|
||||
assert.equal(result.account, email)
|
||||
assert.equal(result.creditsSession, "ready")
|
||||
} finally { await login?.close(); globalThis.fetch = original }
|
||||
} finally { await fixture.close() }
|
||||
})
|
||||
|
||||
test("adding an account whose ADC lives in machine config succeeds", { timeout: 30000 }, async () => {
|
||||
const fixture = await fakeGcloud()
|
||||
let login
|
||||
try {
|
||||
const first = "first@example.com"
|
||||
const root = join(fixture.directory, "plugin")
|
||||
await fixture.set({ token: first, pendingToken: first })
|
||||
const original = globalThis.fetch
|
||||
globalThis.fetch = mockFetch()
|
||||
try {
|
||||
await fixture.setAdc()
|
||||
// Machine ADC does not make an account already signed in, so it can be added.
|
||||
login = await startLogin({ adcRoot: root, profile: join(fixture.directory, "profile") }, signInWindowOf([]))
|
||||
const result = await login.result
|
||||
assert.equal(result.account, first)
|
||||
assert.equal(result.creditsSession, "ready")
|
||||
} finally { await login?.close(); globalThis.fetch = original }
|
||||
} finally { await fixture.close() }
|
||||
})
|
||||
|
||||
test("an account whose project list has no Vertex-enabled project fails the sign-in, registers nothing, and leaves no ADC directory behind", { timeout: 30000 }, async () => {
|
||||
const fixture = await fakeGcloud()
|
||||
let login
|
||||
try {
|
||||
const email = "noproject@example.com"
|
||||
const root = join(fixture.directory, "plugin")
|
||||
await fixture.clearAdc()
|
||||
await fixture.set({ token: email, pendingToken: email })
|
||||
const original = globalThis.fetch
|
||||
globalThis.fetch = mockFetch([])
|
||||
try {
|
||||
login = await startLogin({ adcRoot: root, profile: join(fixture.directory, "profile") }, signInWindowOf([], []))
|
||||
const result = await login.result
|
||||
assert.equal(result.creditsSession, "unavailable")
|
||||
assert.match(result.warning, /has Vertex AI enabled|Create a Google Cloud project and enable the Vertex AI API/i)
|
||||
assert.deepEqual(await readdir(root).catch(() => []), [])
|
||||
} finally { await login?.close(); globalThis.fetch = original }
|
||||
} finally { await fixture.close() }
|
||||
})
|
||||
|
||||
test("a consent page approved as another account saves nothing and keeps no ADC for the wanted one", { timeout: 30000 }, async () => {
|
||||
const fixture = await fakeGcloud()
|
||||
let login
|
||||
try {
|
||||
const wanted = "wanted@example.com"
|
||||
const other = "other@example.com"
|
||||
const root = join(fixture.directory, "plugin")
|
||||
const own = adcDirectoryFor(wanted, root)
|
||||
// This machine's own gcloud sign-in is the account the row named; the
|
||||
// consent page is approved as someone else, and the token written for that
|
||||
// row says so.
|
||||
await fixture.set({ token: wanted, pendingToken: other })
|
||||
const original = globalThis.fetch
|
||||
globalThis.fetch = mockFetch()
|
||||
try {
|
||||
login = await startLogin({ adcRoot: root, account: wanted, profile: join(fixture.directory, "profile") }, signInWindowOf([]))
|
||||
const result = await login.result
|
||||
assert.equal(result.creditsSession, "unavailable")
|
||||
assert.match(result.warning, /consent page approved other@example\.com, not wanted@example\.com/)
|
||||
// Nothing was filed under the wanted account, and no directory is left
|
||||
// that a later sign-in would read as one already signed in.
|
||||
await assert.rejects(readFile(join(own, "application_default_credentials.json")))
|
||||
for (const name of await readdir(root).catch(() => [])) {
|
||||
await assert.rejects(readFile(join(root, name, "application_default_credentials.json")), `${name} still holds an ADC`)
|
||||
}
|
||||
} finally { await login?.close(); globalThis.fetch = original }
|
||||
} finally { await fixture.close() }
|
||||
})
|
||||
|
||||
// A gcloud config directory holds far more than ADC: the named configurations
|
||||
// and the credential database behind every `gcloud auth login` on the machine.
|
||||
// A sign-in that has to undo what it wrote must undo exactly one file.
|
||||
test("a sign-in that saves nothing leaves the user's gcloud config directory untouched", { timeout: 30000 }, async () => {
|
||||
const fixture = await fakeGcloud()
|
||||
let login
|
||||
const sdk = join(fixture.directory, "users-gcloud")
|
||||
try {
|
||||
await mkdir(join(sdk, "configurations"), { recursive: true })
|
||||
await writeFile(join(sdk, "configurations", "config_default"), "[core]\nproject = kept-project\n")
|
||||
await writeFile(join(sdk, "credentials.db"), "kept-credential-database")
|
||||
// The consent page approves someone other than the account the row named.
|
||||
await fixture.set({ token: "other@example.com", pendingToken: "other@example.com" })
|
||||
const original = globalThis.fetch
|
||||
globalThis.fetch = mockFetch()
|
||||
try {
|
||||
login = await startLogin({ adcRoot: join(fixture.directory, "plugin"), cloudsdkConfig: sdk, account: "me@example.com", profile: join(fixture.directory, "profile") }, signInWindowOf([]))
|
||||
const result = await login.result
|
||||
assert.equal(result.creditsSession, "unavailable")
|
||||
assert.match(result.warning, /consent page approved other@example\.com, not me@example\.com/)
|
||||
// Nothing of the user's was removed.
|
||||
assert.equal(await readFile(join(sdk, "credentials.db"), "utf8"), "kept-credential-database")
|
||||
assert.equal(await readFile(join(sdk, "configurations", "config_default"), "utf8"), "[core]\nproject = kept-project\n")
|
||||
// And the ADC file this run wrote is gone, with the directory it made.
|
||||
await assert.rejects(readFile(join(fixture.directory, "plugin", "adc-me-example-com", "application_default_credentials.json")))
|
||||
} finally { await login?.close(); globalThis.fetch = original }
|
||||
} finally { await fixture.close() }
|
||||
})
|
||||
|
||||
test("a sign-in refuses to file one account's ADC and cookies under another", { timeout: 30000 }, async () => {
|
||||
const fixture = await fakeGcloud()
|
||||
let login
|
||||
try {
|
||||
// No ADC yet, so this run would write one; the consent page approves
|
||||
// someone else, and the token is the only thing that can say so. That
|
||||
// account is not one this machine already signed in with, so the refusal
|
||||
// is about the mismatch and not about adding a duplicate.
|
||||
await fixture.clearAdc()
|
||||
await fixture.set({ token: "someone-else@example.com", pendingToken: "someone-else@example.com", approved: "someone-else@example.com" })
|
||||
const original = globalThis.fetch
|
||||
globalThis.fetch = mockFetch()
|
||||
try {
|
||||
let closed = 0
|
||||
const openWindow = async () => ({
|
||||
ended: new Promise((resolve) => setTimeout(resolve, 5)),
|
||||
openTab: async () => true,
|
||||
close: async () => { closed++ },
|
||||
})
|
||||
const root = join(fixture.directory, "plugin")
|
||||
login = await startLogin({ account: "intended@example.com", adcRoot: root, profile: join(fixture.directory, "profile") }, openWindow)
|
||||
const result = await login.result
|
||||
// The consent page approved another account: the sign-in fails instead of
|
||||
// recording intended@example.com over the wrong cookies and ADC.
|
||||
assert.equal(result.creditsSession, "unavailable")
|
||||
assert.match(result.warning, /consent page approved someone-else@example\.com, not intended@example\.com/)
|
||||
// Nothing was filed under the account that was wanted.
|
||||
assert.deepEqual(await readdir(root).catch(() => []), [])
|
||||
await login.close()
|
||||
assert.equal(closed, 1)
|
||||
} finally { await login?.close(); globalThis.fetch = original }
|
||||
} finally { await fixture.close() }
|
||||
})
|
||||
|
||||
// Exercise the model fallback with a real fixture token and an offline response;
|
||||
// "invalid" is syntactically a valid project ID, so it does not stop discovery.
|
||||
test("plugin is its own gcp-ai row, not Magpie's built-in Vertex provider", { timeout: 30000 }, async () => {
|
||||
const hooks = await plugin()
|
||||
// The built-in google-vertex row keeps its own project, location and ADC
|
||||
// path; nothing here renames itself onto it.
|
||||
assert.equal(hooks.provider.id, "gcp-ai")
|
||||
assert.equal(hooks.auth.provider, "gcp-ai")
|
||||
assert.equal(typeof hooks.auth.usage, "function")
|
||||
assert.equal(typeof hooks.auth.loader, "function")
|
||||
assert.equal(hooks.auth.methods[0].type, "oauth")
|
||||
assert.match(hooks.auth.icon, /^data:image\/png;base64,/)
|
||||
// No switches: there is nothing for a user to turn on before the row works.
|
||||
assert.equal(hooks.auth.options, undefined)
|
||||
const config = {}
|
||||
await hooks.config(config)
|
||||
assert.equal(config.provider["gcp-ai"].name, "GCP AI")
|
||||
assert.equal(config.provider["gcp-ai"].npm, "@ai-sdk/google")
|
||||
// A row Magpie configured with no models stays empty until someone presses
|
||||
// Fetch models, so the config hook hands over Google's current catalog. The
|
||||
// provider hook replaces it with what the signed-in project can call.
|
||||
const seeded = config.provider["gcp-ai"].models
|
||||
assert.equal(seeded["gemini-4-argon"].name, "Gemini 4 Argon")
|
||||
assert.deepEqual(seeded["gemini-4-argon"].variants, { low: { reasoning_effort: "low" }, medium: { reasoning_effort: "medium" }, high: { reasoning_effort: "high" } })
|
||||
assert.equal(seeded["gemini-2.5-pro"].reasoning, false)
|
||||
// Retired models are in no list: the catalog still names them and calling one
|
||||
// answers 404, so a seed carrying them would offer models that cannot load.
|
||||
for (const gone of ["gemini-1.5-pro-002", "gemini-2.5-flash-preview-04-17", "gemini-2.5-pro-exp-03-25"]) assert.equal(seeded[gone], undefined)
|
||||
// Twelve chat models, and no speech, image, transcription or embedding model.
|
||||
assert.equal(Object.keys(seeded).length, 12)
|
||||
assert.equal(Object.keys(seeded).filter((id) => /tts|embedding|transcribe|image|live|translate|nano-banana|omni/.test(id)).length, 0)
|
||||
// The provider hook is handed the whole provider info, not its models. A
|
||||
// failure must give back provider.models: handing back the object made
|
||||
// magpie read its keys as model ids and offer "id", "name" and "source" as
|
||||
// models on the row.
|
||||
const previousCache = process.env.XDG_CACHE_HOME
|
||||
const directory = await mkdtemp(join(tmpdir(), "vertex-fallback-"))
|
||||
process.env.XDG_CACHE_HOME = join(directory, "cache")
|
||||
const fixture = await fakeGcloud()
|
||||
const original = globalThis.fetch
|
||||
let requests = 0
|
||||
globalThis.fetch = async () => { requests++; return { ok: false, status: 403 } }
|
||||
try {
|
||||
await fixture.setAdc()
|
||||
const info = { id: "gcp-ai", name: "GCP AI", source: "config", models: { "gemini-2.5-flash": { id: "gemini-2.5-flash" } } }
|
||||
const fallback = await hooks.provider.models(info, { auth: { authMode: "adc", project: "invalid" } })
|
||||
assert.deepEqual(fallback, info.models)
|
||||
assert.equal(fallback.id, undefined)
|
||||
assert.equal(fallback.source, undefined)
|
||||
assert.equal(requests, 1)
|
||||
} finally {
|
||||
globalThis.fetch = original
|
||||
await fixture.close()
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
if (previousCache === undefined) delete process.env.XDG_CACHE_HOME
|
||||
else process.env.XDG_CACHE_HOME = previousCache
|
||||
}
|
||||
const usageFixture = await fakeGcloud()
|
||||
try {
|
||||
// No switch stands between the row and its balance: asking for usage reads
|
||||
// the Console, which here reaches the billing-account check.
|
||||
const usage = await hooks.auth.usage(async () => ({ type: "oauth" }), { options: { billingAccount: "invalid" } })
|
||||
assert.equal(usage.signIn, "kept")
|
||||
assert.match(usage.error, /billing account ID/)
|
||||
// Nothing magpie hands the plugin turns the read off: a plugin options JSON
|
||||
// and a row option both leave it reading.
|
||||
const fromOptions = await plugin({}, { credits: false })
|
||||
const still = await fromOptions.auth.usage(async () => ({ type: "oauth" }), { options: { billingAccount: "invalid" } })
|
||||
assert.match(still.error, /billing account ID/)
|
||||
const fromRow = await plugin({ magpie: { option: () => false } })
|
||||
const reads = await fromRow.auth.usage(async () => ({ type: "oauth" }), { options: { billingAccount: "invalid" } })
|
||||
assert.match(reads.error, /billing account ID/)
|
||||
} finally { await usageFixture.close() }
|
||||
})
|
||||
|
||||
test("models are Google's catalog per project and location, newest first, dressed with the catalog's numbers", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "vertex-models-test-"))
|
||||
const previousCache = process.env.XDG_CACHE_HOME
|
||||
process.env.XDG_CACHE_HOME = directory
|
||||
try {
|
||||
// A cached discovery is returned as it was read, without asking Google.
|
||||
// The location is part of the cache's identity, because the same project
|
||||
// serves a different list in each one.
|
||||
const key = (location) => "models-" + createHash("sha256").update(JSON.stringify(["", "", "", location])).digest("hex").slice(0, 16) + ".json"
|
||||
const file = join(directory, "magpie", "gcp-ai", key("global"))
|
||||
await mkdir(dirname(file), { recursive: true })
|
||||
await writeFile(file, JSON.stringify({ project: "example-project", ids: ["gemini-4-argon", "gemini-3.8-flash"], fetchedAt: new Date().toISOString() }))
|
||||
assert.deepEqual((await availableModels({ location: "global" })).ids, ["gemini-4-argon", "gemini-3.8-flash"])
|
||||
// A region's list is not the global one: it is asked for separately.
|
||||
await writeFile(join(directory, "magpie", "gcp-ai", key("us-central1")), JSON.stringify({ project: "example-project", ids: ["gemini-regional"], fetchedAt: new Date().toISOString() }))
|
||||
assert.deepEqual((await availableModels({ location: "us-central1" })).ids, ["gemini-regional"])
|
||||
await assert.rejects(availableModels({ location: "not a region" }), /GOOGLE_VERTEX_LOCATION/)
|
||||
// Speech, transcription, translation, embeddings, live and image models
|
||||
// are not chat models, however Google lists them.
|
||||
const models = toProviderModels(["gemini-4-argon", "gemini-3.8-flash"], { "gemini-4-argon": { name: "Gemini 4 Argon", limit: { context: 1048576, output: 65536 }, cost: { input: 2, output: 10, cache_read: 0.1 }, reasoning_options: [{ type: "effort", values: ["low", "high"] }] } }, "gcp-ai")
|
||||
assert.deepEqual(Object.keys(models).sort(), ["gemini-3.8-flash", "gemini-4-argon"])
|
||||
// Newest first, by the catalog's release date; a model it doesn't describe
|
||||
// goes after the ones it does.
|
||||
const dated = { "gemini-2.5-pro": { release_date: "2025-06-17" }, "gemini-4-argon": { release_date: "2026-10-13" } }
|
||||
assert.deepEqual(Object.keys(toProviderModels(["gemini-2.5-pro", "undated", "gemini-4-argon"], dated, "gcp-ai")), ["gemini-4-argon", "gemini-2.5-pro", "undated"])
|
||||
assert.equal(models["gemini-4-argon"].api.id, "gemini-4-argon")
|
||||
assert.equal(models["gemini-4-argon"].api.npm, "@ai-sdk/google")
|
||||
assert.equal(models["gemini-4-argon"].limit.context, 1048576)
|
||||
assert.deepEqual(Object.keys(models["gemini-4-argon"].variants), ["low", "high"])
|
||||
// A model the catalog doesn't know is still listed, from Google's id alone.
|
||||
assert.equal(models["gemini-3.8-flash"].name, "gemini-3.8-flash")
|
||||
assert.equal(models["gemini-3.8-flash"].api.id, "gemini-3.8-flash")
|
||||
} finally {
|
||||
if (previousCache === undefined) delete process.env.XDG_CACHE_HOME
|
||||
else process.env.XDG_CACHE_HOME = previousCache
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("a retired model Google still lists is left out, and only a 404 counts as gone", { timeout: 30000 }, async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "vertex-probe-test-"))
|
||||
const previousCache = process.env.XDG_CACHE_HOME
|
||||
process.env.XDG_CACHE_HOME = directory
|
||||
const original = globalThis.fetch
|
||||
const fixture = await fakeGcloud()
|
||||
try {
|
||||
await fixture.setAdc()
|
||||
// The catalog names four models. probed answers for each: a live model
|
||||
// takes the token count, a retired one is NOT_FOUND, one this account may
|
||||
// not call is FORBIDDEN, and one drops the connection.
|
||||
const catalog = ["gemini-4-argon", "gemini-1.5-pro-002", "gemini-3.5-flash", "gemini-2.5-pro"]
|
||||
const answer = { "gemini-4-argon": 200, "gemini-1.5-pro-002": 404, "gemini-3.5-flash": 403, "gemini-2.5-pro": -1 }
|
||||
const asked = []
|
||||
globalThis.fetch = async (url) => {
|
||||
const parsed = new URL(url)
|
||||
if (parsed.host !== "aiplatform.googleapis.com") return { ok: false, status: 404, json: async () => ({}) }
|
||||
if (parsed.pathname.endsWith("/publishers/google/models")) {
|
||||
return { ok: true, json: async () => ({ publisherModels: catalog.map((id) => ({ name: `publishers/google/models/${id}` })) }) }
|
||||
}
|
||||
const id = parsed.pathname.match(/models\/([^:]+):countTokens$/)?.[1]
|
||||
asked.push(id)
|
||||
const status = answer[id]
|
||||
if (status === -1) throw Object.assign(new Error("fetch failed"), { name: "TimeoutError" })
|
||||
return { ok: status === 200, status, json: async () => ({ totalTokens: 1 }) }
|
||||
}
|
||||
const listed = await availableModels({ project: "example-project", location: "global", authMode: "adc", force: true })
|
||||
// A model answering NOT_FOUND is not deployed and is dropped. FORBIDDEN, a
|
||||
// dropped connection and a timeout are not answers about the model, so
|
||||
// those stay: losing a working model to a bad minute is worse than listing
|
||||
// one that may refuse.
|
||||
assert.deepEqual(listed.ids, ["gemini-4-argon", "gemini-3.5-flash", "gemini-2.5-pro"])
|
||||
assert.deepEqual(asked.sort(), [...catalog].sort())
|
||||
// Nothing was generated: the probe reads the request, it does not bill one.
|
||||
assert.equal(asked.length, catalog.length)
|
||||
} finally {
|
||||
globalThis.fetch = original
|
||||
if (previousCache === undefined) delete process.env.XDG_CACHE_HOME
|
||||
else process.env.XDG_CACHE_HOME = previousCache
|
||||
await fixture.close()
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("every model answering 404 is a broken read, not an empty provider", { timeout: 30000 }, async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "vertex-probe-all-test-"))
|
||||
const previousCache = process.env.XDG_CACHE_HOME
|
||||
process.env.XDG_CACHE_HOME = directory
|
||||
const original = globalThis.fetch
|
||||
const fixture = await fakeGcloud()
|
||||
try {
|
||||
await fixture.setAdc()
|
||||
// A wrong project or location answers NOT_FOUND for the whole catalog. That
|
||||
// is the read being wrong, not the project having no models, so Google's
|
||||
// names are kept rather than the row being emptied.
|
||||
globalThis.fetch = async (url) => {
|
||||
const parsed = new URL(url)
|
||||
if (parsed.host !== "aiplatform.googleapis.com") return { ok: false, status: 404, json: async () => ({}) }
|
||||
if (parsed.pathname.endsWith("/publishers/google/models")) {
|
||||
return { ok: true, json: async () => ({ publisherModels: [{ name: "publishers/google/models/gemini-4-argon" }, { name: "publishers/google/models/gemini-2.5-pro" }] }) }
|
||||
}
|
||||
return { ok: false, status: 404, json: async () => ({}) }
|
||||
}
|
||||
const listed = await availableModels({ project: "example-project", location: "global", authMode: "adc", force: true })
|
||||
assert.deepEqual(listed.ids, ["gemini-4-argon", "gemini-2.5-pro"])
|
||||
} finally {
|
||||
globalThis.fetch = original
|
||||
if (previousCache === undefined) delete process.env.XDG_CACHE_HOME
|
||||
else process.env.XDG_CACHE_HOME = previousCache
|
||||
await fixture.close()
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("closing a login waits for its pending identity work before fetch is restored", { timeout: 30000 }, async () => {
|
||||
const fixture = await fakeGcloud()
|
||||
const original = globalThis.fetch
|
||||
const entered = Promise.withResolvers()
|
||||
const release = Promise.withResolvers()
|
||||
let login
|
||||
globalThis.fetch = async (...args) => {
|
||||
entered.resolve()
|
||||
await release.promise
|
||||
return mockFetch()(...args)
|
||||
}
|
||||
try {
|
||||
await fixture.set({ approved: "closing@example.com" })
|
||||
login = await startLogin({ adcRoot: join(fixture.directory, "plugin"), account: "closing@example.com" }, signInWindowOf([]))
|
||||
await entered.promise
|
||||
let closed = false
|
||||
const closing = login.close().then(() => { closed = true })
|
||||
await new Promise((resolve) => setTimeout(resolve, 20))
|
||||
assert.equal(closed, false, "close returned while identity lookup was still running")
|
||||
release.resolve()
|
||||
await closing
|
||||
assert.equal(closed, true)
|
||||
assert.equal((await login.result).project, undefined)
|
||||
} finally {
|
||||
release.resolve()
|
||||
await login?.close()
|
||||
globalThis.fetch = original
|
||||
await fixture.close()
|
||||
}
|
||||
})
|
||||
|
||||
test("account settings beat the row, and row settings beat environment defaults", { timeout: 30000 }, async () => {
|
||||
const fixture = await fakeGcloud()
|
||||
const original = globalThis.fetch
|
||||
const previousCache = process.env.XDG_CACHE_HOME
|
||||
const options = {
|
||||
project: "row-project", location: "us-central1", account: "row@example.com", authMode: "gcloud",
|
||||
billingAccount: "AAAAAA-BBBBBB-CCCCCC", profile: join(fixture.directory, "row-profile"), cloudsdkConfig: fixture.sdk,
|
||||
}
|
||||
const auth = {
|
||||
project: "account-project", location: "europe-west1", accountId: "account@example.com", account: "legacy@example.com", authMode: "adc",
|
||||
billingAccount: "DDDDDD-EEEEEE-FFFFFF", profile: join(fixture.directory, "account-profile"), cloudsdkConfig: join(fixture.directory, "account-sdk"),
|
||||
}
|
||||
const requests = []
|
||||
globalThis.fetch = async (input) => {
|
||||
requests.push(String(input))
|
||||
return { ok: true, status: 200, json: async () => ({}) }
|
||||
}
|
||||
try {
|
||||
process.env.XDG_CACHE_HOME = join(fixture.directory, "cache")
|
||||
process.env.GOOGLE_VERTEX_PROJECT = "environment-project"
|
||||
process.env.GOOGLE_VERTEX_LOCATION = "asia-east1"
|
||||
process.env.VERTEX_GCLOUD_ACCOUNT = "environment@example.com"
|
||||
process.env.VERTEX_GCLOUD_AUTH_MODE = "invalid-mode"
|
||||
process.env.VERTEX_BILLING_ACCOUNT = "invalid-billing"
|
||||
process.env.VERTEX_CHROME_PROFILE = join(fixture.directory, "environment-profile")
|
||||
await mkdir(auth.cloudsdkConfig)
|
||||
await writeFile(join(auth.cloudsdkConfig, "application_default_credentials.json"), "{}")
|
||||
await fixture.set({ tokens: { [auth.cloudsdkConfig]: "account-token" } })
|
||||
const hooks = await plugin()
|
||||
for (const [record, expected] of [[auth, { ...auth, account: auth.accountId }], [{ ...auth, accountId: undefined }, auth], [{}, options]]) {
|
||||
const loaded = await hooks.auth.loader(async () => record, { options })
|
||||
assert.ok(loaded.baseURL.includes(`/projects/${expected.project}/locations/${expected.location}/`))
|
||||
const calls = await fixture.calls()
|
||||
assert.ok(calls.some((args) => expected.authMode === "adc" ? args.includes("application-default") : args.includes(`--account=${expected.account}`)))
|
||||
// The cache identifies project, billing account, profile, account and ADC
|
||||
// together. A cached failure lets the public usage hook verify that choice
|
||||
// without opening a browser or relying on any machine credentials.
|
||||
const identity = JSON.stringify([expected.profile, expected.project, expected.billingAccount, expected.account, expected.cloudsdkConfig])
|
||||
const digest = createHash("sha256").update(identity).digest("hex").slice(0, 24)
|
||||
const file = join(process.env.XDG_CACHE_HOME, "magpie", "gcp-ai", `credits-${digest}.json`)
|
||||
await mkdir(dirname(file), { recursive: true })
|
||||
await writeFile(file, JSON.stringify({ failedAt: new Date().toISOString(), error: `cached settings for ${expected.account}` }))
|
||||
const usage = await hooks.auth.usage(async () => ({ ...record, accountId: expected.account }), { options })
|
||||
assert.equal(usage.error, `cached settings for ${expected.account}`)
|
||||
}
|
||||
assert.ok(requests.some((url) => url.includes("/projects/account-project/locations/europe-west1")))
|
||||
assert.ok(requests.some((url) => url.includes("/projects/row-project/locations/us-central1")))
|
||||
} finally {
|
||||
globalThis.fetch = original
|
||||
if (previousCache === undefined) delete process.env.XDG_CACHE_HOME
|
||||
else process.env.XDG_CACHE_HOME = previousCache
|
||||
await fixture.close()
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,31 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import { mkdtemp, rm } from "node:fs/promises"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { take, wanted } from "../lib/lock.mjs"
|
||||
|
||||
// A browser kept between reads still holds the profile's lock. Another process
|
||||
// that wants the profile must not have to wait out the whole idle window, so
|
||||
// the waiter says so on disk and the holder steps aside.
|
||||
|
||||
test("a waiter is visible to the holder, and taking the lock clears it", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "vertex-want-"))
|
||||
try {
|
||||
const file = join(directory, "profile")
|
||||
const release = await take(file)
|
||||
const takenAt = Date.now()
|
||||
assert.equal(await wanted(file), 0)
|
||||
|
||||
// A second taker cannot have the lock, and leaves a mark that it is waiting.
|
||||
const waiter = take(file, { timeout: 5000, poll: 20 })
|
||||
await new Promise((resolve) => setTimeout(resolve, 200))
|
||||
assert.ok((await wanted(file)) > takenAt, "the wait is not visible to the holder")
|
||||
|
||||
await release()
|
||||
const second = await waiter
|
||||
// The waiter now holds it, so nobody is waiting any more.
|
||||
assert.equal(await wanted(file), 0)
|
||||
await second()
|
||||
} finally { await rm(directory, { recursive: true, force: true }) }
|
||||
})
|
||||
@@ -44,6 +44,8 @@
|
||||
"summary": { "en": "AutoClaw (Zhipu OpenClaw) cloud accounts: oversea web sign-in (Google/z.ai) or CN phone SMS, credit balance and daily check-in.", "zh": "AutoClaw(智谱澳龙/OpenClaw)云端账号:国际版网页登录(Google/z.ai)或国内手机验证码,积分余额与每日签到。" } },
|
||||
{ "package": "@magpie-community/opencode-codearts-auth", "name": "CodeArts", "providers": ["codearts"], "community": true,
|
||||
"summary": { "en": "Unofficial: Huawei Cloud CodeArts (码道) coding plans with Huawei Cloud OAuth sign-in — GLM, DeepSeek, openPangu, live models and credit rates, credit usage and daily check-in.", "zh": "非官方:华为云码道(CodeArts)编码套餐,华为云 OAuth 登录;GLM、DeepSeek、openPangu 等模型,实时模型与积分倍率、积分用量和每日签到。" } },
|
||||
{ "package": "@magpie-community/opencode-gcp-ai-auth", "name": "GCP AI", "providers": ["gcp-ai"], "community": true,
|
||||
"summary": { "en": "Vertex AI models and Google Cloud promotional credits, signed with your own gcloud or ADC login. Lists only the models your project can call.", "zh": "用本机 gcloud / ADC 登录使用 Vertex AI 模型,并读取 Google Cloud 促销赠金;只列出项目实际能调用的模型。" } },
|
||||
{ "package": "@magpie-community/middleware-param-override", "name": "Param Override", "kind": "middleware", "community": true,
|
||||
"summary": { "en": "New API's parameter override: set, delete, move or rewrite fields of every request, by model or by condition.", "zh": "New API 的参数覆盖:按模型或条件设置、删除、移动或改写每个请求的字段。" } },
|
||||
{ "package": "@magpie-community/middleware-model-map", "name": "Model Map", "kind": "middleware", "community": true,
|
||||
|
||||
Reference in New Issue
Block a user