Open History to see the last commit
1export class GrokVertexAuthError extends Error {
2 constructor(message: string, options?: ErrorOptions) {
3 super(message, options)
4 this.name = 'GrokVertexAuthError'
5 }
6}
7
8function isMissingGoogleAuthLibrary(error: unknown): boolean {
9 if (!(error instanceof Error) || !('code' in error)) {
10 return false
11 }
12 const code = error.code
13 if (code !== 'ERR_MODULE_NOT_FOUND' && code !== 'MODULE_NOT_FOUND') {
14 return false
15 }
16 return error.message.includes('google-auth-library')
17}
18
19export type VertexAuthClient = {
20 getRequestHeaders: (url?: string | URL) => Promise<Headers>
21}
22
23/**
24 * Public Vertex config for Grok. `project` and `location` match the Gemini
25 * Vertex factories so one auth object works for both.
26 *
27 * Default location is `global`. Grok on Vertex uses the OpenAI-compatible
28 * Responses endpoint under `/endpoints/openapi`.
29 */
30export type GrokVertexConfig = {
31 project?: string
32 location?: string
33 /** Override the OpenAI-compatible Vertex base URL. Used by e2e. */
34 baseURL?: string
35 getAccessToken?: () => Promise<string>
36 authClient?: VertexAuthClient
37 defaultHeaders?: Record<string, string>
38}
39
40function nonEmpty(value: string | undefined): string | undefined {
41 if (value === undefined || value.length === 0) {
42 return undefined
43 }
44 return value
45}
46
47function readEnv(name: string): string | undefined {
48 if (typeof process === 'undefined' || process.env === undefined) {
49 return undefined
50 }
51 return nonEmpty(process.env[name])
52}
53
54export function toVertexGrokModelId(model: string): string {
55 if (model.startsWith('xai/')) {
56 return model
57 }
58 return `xai/${model}`
59}
60
61export function resolveGrokVertexProject(
62 config: GrokVertexConfig,
63): string | undefined {
64 return (
65 nonEmpty(config.project) ??
66 readEnv('GOOGLE_CLOUD_PROJECT') ??
67 readEnv('GOOGLE_VERTEX_PROJECT')
68 )
69}
70
71export function resolveGrokVertexLocation(config: GrokVertexConfig): string {
72 return (
73 nonEmpty(config.location) ??
74 readEnv('GOOGLE_CLOUD_LOCATION') ??
75 readEnv('GOOGLE_VERTEX_LOCATION') ??
76 'global'
77 )
78}
79
80export function resolveGrokVertexBaseURL(config: GrokVertexConfig): string {
81 if (config.baseURL !== undefined && config.baseURL.length > 0) {
82 return config.baseURL.replace(/\/+$/, '')
83 }
84
85 const project = resolveGrokVertexProject(config)
86 if (project === undefined) {
87 throw new GrokVertexAuthError(
88 'Grok Vertex needs a project, or a baseURL. Pass project on the factory, or set GOOGLE_CLOUD_PROJECT or GOOGLE_VERTEX_PROJECT.',
89 )
90 }
91
92 const location = resolveGrokVertexLocation(config)
93 if (location === 'global') {
94 return `https://aiplatform.googleapis.com/v1/projects/${project}/locations/global/endpoints/openapi`
95 }
96 return `https://${location}-aiplatform.googleapis.com/v1/projects/${project}/locations/${location}/endpoints/openapi`
97}
98
99export async function resolveGrokVertexAccessToken(
100 config: GrokVertexConfig,
101): Promise<string> {
102 if (config.getAccessToken !== undefined) {
103 return config.getAccessToken()
104 }
105
106 if (config.authClient !== undefined) {
107 const headers = await config.authClient.getRequestHeaders()
108 const authorization = headers.get('Authorization')
109 if (authorization === null || !authorization.startsWith('Bearer ')) {
110 throw new GrokVertexAuthError(
111 'Grok Vertex authClient.getRequestHeaders() must return an Authorization Bearer token.',
112 )
113 }
114 return authorization.slice('Bearer '.length)
115 }
116
117 try {
118 const { GoogleAuth } = await import('google-auth-library')
119 const auth = new GoogleAuth({
120 scopes: ['https://www.googleapis.com/auth/cloud-platform'],
121 })
122 const client = await auth.getClient()
123 const token = await client.getAccessToken()
124 if (token.token === null || token.token === undefined) {
125 throw new GrokVertexAuthError(
126 'Grok Vertex could not load a Google access token from Application Default Credentials.',
127 )
128 }
129 return token.token
130 } catch (error) {
131 if (error instanceof GrokVertexAuthError) {
132 throw error
133 }
134 if (isMissingGoogleAuthLibrary(error)) {
135 throw new GrokVertexAuthError(
136 'Grok Vertex needs google-auth-library, or pass authClient or getAccessToken. Install google-auth-library next to @tanstack/ai-grok.',
137 )
138 }
139 throw new GrokVertexAuthError(
140 'Grok Vertex could not load a Google access token from Application Default Credentials.',
141 { cause: error },
142 )
143 }
144}