Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

auth.ts

154 lines4.9 KB

1export class MistralVertexAuthError extends Error {
2 constructor(message: string, options?: ErrorOptions) {
3 super(message, options)
4 this.name = 'MistralVertexAuthError'
5 }
6}
7​
8const MISTRAL_VERTEX_LOCATIONS = ['us-central1', 'europe-west4'] as const
9​
10function isMistralVertexLocation(
11 location: string,
12): location is (typeof MISTRAL_VERTEX_LOCATIONS)[number] {
13 return (MISTRAL_VERTEX_LOCATIONS as ReadonlyArray<string>).includes(location)
15​
16function isMissingGoogleAuthLibrary(error: unknown): boolean {
17 if (!(error instanceof Error) || !('code' in error)) {
18 return false
19 }
20 const code = error.code
21 if (code !== 'ERR_MODULE_NOT_FOUND' && code !== 'MODULE_NOT_FOUND') {
22 return false
23 }
24 return error.message.includes('google-auth-library')
26​
27export type VertexAuthClient = {
28 getRequestHeaders: (url?: string | URL) => Promise<Headers>
30​
31/**
32 * Public Vertex config for Mistral. `project` and `location` match the
33 * Gemini Vertex factories so one auth object works for both.
34 *
35 * Mistral on Vertex is regional only (`us-central1`, `europe-west4`).
36 * There is no global endpoint.
37 */
38export type MistralVertexConfig = {
39 project?: string
40 location?: string
41 /**
42 * Override the chat completions URL. When set, the Vertex
43 * `:rawPredict` / `:streamRawPredict` rewrite is skipped. Used by e2e.
44 */
45 resolveRequestUrl?: (stream: boolean) => string
46 getAccessToken?: () => Promise<string>
47 authClient?: VertexAuthClient
48 defaultHeaders?: Record<string, string>
50​
51function nonEmpty(value: string | undefined): string | undefined {
52 if (value === undefined || value.length === 0) {
53 return undefined
54 }
55 return value
57​
58function readEnv(name: string): string | undefined {
59 if (typeof process === 'undefined' || process.env === undefined) {
60 return undefined
61 }
62 return nonEmpty(process.env[name])
64​
65export function resolveMistralVertexProject(
66 config: MistralVertexConfig,
67): string | undefined {
68 return (
69 nonEmpty(config.project) ??
70 readEnv('GOOGLE_CLOUD_PROJECT') ??
71 readEnv('GOOGLE_VERTEX_PROJECT')
72 )
74​
75export function resolveMistralVertexLocation(
76 config: MistralVertexConfig,
77): string {
78 const location =
79 nonEmpty(config.location) ??
80 readEnv('GOOGLE_CLOUD_LOCATION') ??
81 readEnv('GOOGLE_VERTEX_LOCATION')
82 if (location === undefined) {
83 throw new MistralVertexAuthError(
84 'Mistral Vertex needs a location. Pass location on the factory, or set GOOGLE_CLOUD_LOCATION or GOOGLE_VERTEX_LOCATION. Use us-central1 or europe-west4.',
85 )
86 }
87 if (!isMistralVertexLocation(location)) {
88 throw new MistralVertexAuthError(
89 'Mistral Vertex location must be us-central1 or europe-west4. There is no global endpoint.',
90 )
91 }
92 return location
94​
95export function resolveMistralVertexModelUrl(
96 model: string,
97 config: MistralVertexConfig,
98): string {
99 const project = resolveMistralVertexProject(config)
100 if (project === undefined) {
101 throw new MistralVertexAuthError(
102 'Mistral Vertex needs a project. Pass project on the factory, or set GOOGLE_CLOUD_PROJECT or GOOGLE_VERTEX_PROJECT.',
103 )
104 }
105 const location = resolveMistralVertexLocation(config)
106 return `https://${location}-aiplatform.googleapis.com/v1/projects/${project}/locations/${location}/publishers/mistralai/models/${model}`
108​
109export async function resolveMistralVertexAccessToken(
110 config: MistralVertexConfig,
111): Promise<string> {
112 if (config.getAccessToken !== undefined) {
113 return config.getAccessToken()
114 }
115​
116 if (config.authClient !== undefined) {
117 const headers = await config.authClient.getRequestHeaders()
118 const authorization = headers.get('Authorization')
119 if (authorization === null || !authorization.startsWith('Bearer ')) {
120 throw new MistralVertexAuthError(
121 'Mistral Vertex authClient.getRequestHeaders() must return an Authorization Bearer token.',
122 )
123 }
124 return authorization.slice('Bearer '.length)
125 }
126​
127 try {
128 const { GoogleAuth } = await import('google-auth-library')
129 const auth = new GoogleAuth({
130 scopes: ['https://www.googleapis.com/auth/cloud-platform'],
131 })
132 const client = await auth.getClient()
133 const token = await client.getAccessToken()
134 if (token.token === null || token.token === undefined) {
135 throw new MistralVertexAuthError(
136 'Mistral Vertex could not load a Google access token from Application Default Credentials.',
137 )
138 }
139 return token.token
140 } catch (error) {
141 if (error instanceof MistralVertexAuthError) {
142 throw error
143 }
144 if (isMissingGoogleAuthLibrary(error)) {
145 throw new MistralVertexAuthError(
146 'Mistral Vertex needs google-auth-library, or pass authClient or getAccessToken. Install google-auth-library next to @tanstack/ai-mistral.',
147 )
148 }
149 throw new MistralVertexAuthError(
150 'Mistral Vertex could not load a Google access token from Application Default Credentials.',
151 { cause: error },
152 )
153 }