-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathnutrient-oauth.ts
More file actions
407 lines (353 loc) · 14 KB
/
nutrient-oauth.ts
File metadata and controls
407 lines (353 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
import { randomBytes, createHash } from 'node:crypto'
import { readFile, writeFile, mkdir, unlink } from 'node:fs/promises'
import { homedir } from 'node:os'
import { join, dirname } from 'node:path'
import { z } from 'zod'
import { logger } from '../logger.js'
function escapeHtml(s: string): string {
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
}
export type NutrientOAuthConfig = {
/** Nutrient OAuth authorize endpoint. */
authorizeUrl: string
/** Nutrient OAuth token endpoint. */
tokenUrl: string
/** OAuth client ID. If omitted, the server registers via DCR using `registrationUrl`. */
clientId?: string
/** OAuth Dynamic Client Registration endpoint. Required when `clientId` is not set. */
registrationUrl?: string
/** Human-readable client name sent during DCR. */
clientName?: string
/** OAuth scopes to request. */
scopes: string[]
/** Path to cache credentials. Defaults to `$XDG_CONFIG_HOME/nutrient/credentials.json` or `~/.config/nutrient/credentials.json`. */
credentialsPath?: string
/** OAuth resource parameter (RFC 8707). Identifies the target API. */
resource?: string
}
const CachedCredentialsSchema = z.object({
accessToken: z.string(),
refreshToken: z.string().optional(),
expiresAt: z.number().optional(),
clientId: z.string().optional(),
})
type CachedCredentials = z.infer<typeof CachedCredentialsSchema>
const FETCH_TIMEOUT_MS = 15_000
const CALLBACK_TIMEOUT_MS = 5 * 60 * 1000
export function getDefaultCredentialsPath(
env: NodeJS.ProcessEnv = process.env,
homeDirectory: string = homedir(),
): string {
const configHome = env.XDG_CONFIG_HOME || join(homeDirectory, '.config')
return join(configHome, 'nutrient', 'credentials.json')
}
export function generateCodeVerifier(): string {
return randomBytes(32).toString('base64url')
}
export function generateCodeChallenge(verifier: string): string {
return createHash('sha256').update(verifier).digest('base64url')
}
export async function readCachedCredentials(credentialsPath: string): Promise<CachedCredentials | null> {
try {
const content = await readFile(credentialsPath, 'utf-8')
const result = CachedCredentialsSchema.safeParse(JSON.parse(content))
if (!result.success) {
logger.warn('Cached credentials file is malformed, ignoring', { path: credentialsPath })
return null
}
return result.data
} catch (err: unknown) {
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
logger.warn('Failed to read cached credentials, ignoring', { path: credentialsPath, err })
}
return null
}
}
async function writeCachedCredentials(credentialsPath: string, credentials: CachedCredentials): Promise<void> {
const dir = dirname(credentialsPath)
await mkdir(dir, { recursive: true, mode: 0o700 })
await writeFile(credentialsPath, JSON.stringify(credentials, null, 2), { mode: 0o600 })
}
async function registerClient(config: NutrientOAuthConfig, redirectUri: string): Promise<string> {
if (!config.registrationUrl) {
throw new Error('DCR requires registrationUrl when clientId is not configured')
}
const registrationPayload = {
client_name: config.clientName ?? 'Nutrient DWS MCP Server',
redirect_uris: [redirectUri],
grant_types: ['authorization_code', 'refresh_token'],
response_types: ['code'],
token_endpoint_auth_method: 'none',
}
logger.info('Registering OAuth client via DCR', { registrationUrl: config.registrationUrl })
logger.debug('DCR payload', registrationPayload)
const response = await fetch(config.registrationUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(registrationPayload),
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
})
if (!response.ok) {
const errorText = await response.text()
logger.error('DCR failed', { status: response.status, body: errorText })
throw new Error(`Dynamic client registration failed (${response.status})`)
}
const data = (await response.json()) as { client_id: string }
if (!data.client_id) {
throw new Error('DCR response missing client_id')
}
logger.info('OAuth client registered', { clientId: data.client_id })
return data.client_id
}
const DEFAULT_TOKEN_TTL_MS = 60 * 60 * 1000 // 1 hour
export function isTokenExpired(credentials: CachedCredentials): boolean {
// Treat missing expiresAt as "unknown TTL" — assume 1 hour from now is generous
// but still requires re-auth rather than using a potentially stale token forever
if (!credentials.expiresAt) {
return true
}
// Consider expired 60 seconds early to avoid edge cases
return Date.now() >= (credentials.expiresAt - 60_000)
}
async function refreshAccessToken(
config: NutrientOAuthConfig,
clientId: string,
refreshToken: string,
): Promise<CachedCredentials | null> {
try {
logger.debug('Attempting token refresh', { tokenUrl: config.tokenUrl, clientId })
const response = await fetch(config.tokenUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'refresh_token',
client_id: clientId,
refresh_token: refreshToken,
}),
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
})
if (!response.ok) {
logger.warn('Token refresh failed', { status: response.status, statusText: response.statusText })
return null
}
const data = (await response.json()) as {
access_token: string
refresh_token?: string
expires_in?: number
}
return {
accessToken: data.access_token,
refreshToken: data.refresh_token ?? refreshToken,
expiresAt: Date.now() + (data.expires_in ? data.expires_in * 1000 : DEFAULT_TOKEN_TTL_MS),
}
} catch {
return null
}
}
async function exchangeCodeForToken(
config: NutrientOAuthConfig,
clientId: string,
code: string,
codeVerifier: string,
redirectUri: string,
): Promise<CachedCredentials> {
const response = await fetch(config.tokenUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
client_id: clientId,
code,
redirect_uri: redirectUri,
code_verifier: codeVerifier,
}),
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
})
if (!response.ok) {
const errorText = await response.text()
logger.error('Token exchange failed', { status: response.status, body: errorText })
throw new Error(`Token exchange failed (${response.status})`)
}
const data = (await response.json()) as {
access_token: string
refresh_token?: string
expires_in?: number
}
return {
accessToken: data.access_token,
refreshToken: data.refresh_token,
expiresAt: data.expires_in ? Date.now() + data.expires_in * 1000 : undefined,
clientId
}
}
function buildAuthorizeUrl(
config: NutrientOAuthConfig,
clientId: string,
redirectUri: string,
codeChallenge: string,
state: string,
): string {
const url = new URL(config.authorizeUrl)
url.searchParams.set('response_type', 'code')
url.searchParams.set('client_id', clientId)
url.searchParams.set('redirect_uri', redirectUri)
url.searchParams.set('code_challenge', codeChallenge)
url.searchParams.set('code_challenge_method', 'S256')
url.searchParams.set('state', state)
if (config.scopes.length > 0) {
url.searchParams.set('scope', config.scopes.join(' '))
}
if (config.resource) {
url.searchParams.set('resource', config.resource)
}
return url.toString()
}
/**
* Starts the callback server on a random available port and returns the server + assigned port.
*/
function startCallbackServer(): Promise<{ server: ReturnType<typeof createServer>; port: number }> {
return new Promise((resolve, reject) => {
const server = createServer()
server.listen(0, '127.0.0.1', () => {
const addr = server.address()
if (!addr || typeof addr === 'string') {
server.close()
reject(new Error('Failed to get callback server address'))
return
}
resolve({ server, port: addr.port })
})
server.on('error', reject)
})
}
async function performBrowserOAuthFlow(config: NutrientOAuthConfig): Promise<CachedCredentials> {
const codeVerifier = generateCodeVerifier()
const codeChallenge = generateCodeChallenge(codeVerifier)
const state = randomBytes(16).toString('hex')
// 1. Start callback server on a random available port
const { server, port } = await startCallbackServer()
const redirectUri = `http://localhost:${port}/callback`
logger.info('OAuth callback server listening', { port, redirectUri })
// 2. Register client via DCR (or use static clientId) with the actual redirect URI
const clientId = config.clientId ?? await registerClient(config, redirectUri)
// 3. Open browser for authorization
const authorizeUrl = buildAuthorizeUrl(config, clientId, redirectUri, codeChallenge, state)
logger.debug('Authorize URL', { authorizeUrl })
const { default: open } = await import('open')
logger.info('Opening browser for Nutrient authentication...')
await open(authorizeUrl)
// 4. Wait for the OAuth callback (with timeout)
return new Promise<CachedCredentials>((resolve, reject) => {
const timeout = setTimeout(() => {
server.close()
reject(new Error('OAuth authentication timed out after 5 minutes'))
}, CALLBACK_TIMEOUT_MS)
server.on('request', async (req: IncomingMessage, res: ServerResponse) => {
try {
const url = new URL(req.url ?? '/', `http://localhost`)
if (url.pathname !== '/callback') {
res.writeHead(404)
res.end('Not found')
return
}
const error = url.searchParams.get('error')
if (error) {
const description = url.searchParams.get('error_description') ?? error
res.writeHead(400, { 'Content-Type': 'text/html' })
res.end(`<html><body><h1>Authorization Failed</h1><p>${escapeHtml(description)}</p><p>You can close this tab.</p></body></html>`)
clearTimeout(timeout)
server.close()
reject(new Error(`OAuth authorization failed: ${description}`))
return
}
const returnedState = url.searchParams.get('state')
if (returnedState !== state) {
res.writeHead(400, { 'Content-Type': 'text/html' })
res.end('<html><body><h1>Invalid State</h1><p>OAuth state mismatch. Please try again.</p></body></html>')
clearTimeout(timeout)
server.close()
reject(new Error('OAuth state mismatch'))
return
}
const code = url.searchParams.get('code')
if (!code) {
res.writeHead(400, { 'Content-Type': 'text/html' })
res.end('<html><body><h1>Missing Code</h1><p>No authorization code received.</p></body></html>')
clearTimeout(timeout)
server.close()
reject(new Error('No authorization code received'))
return
}
const credentials = await exchangeCodeForToken(config, clientId, code, codeVerifier, redirectUri)
res.writeHead(200, { 'Content-Type': 'text/html' })
res.end('<html><body><h1>Authenticated!</h1><p>You can close this tab and return to your terminal.</p></body></html>')
clearTimeout(timeout)
server.close()
resolve(credentials)
} catch (err) {
res.writeHead(500, { 'Content-Type': 'text/html' })
res.end('<html><body><h1>Error</h1><p>Something went wrong during authentication.</p></body></html>')
clearTimeout(timeout)
server.close()
reject(err)
}
})
})
}
/**
* Deletes the cached credentials file so the next `getToken` call
* is forced to refresh or re-authenticate.
*/
export async function invalidateCachedToken(config: NutrientOAuthConfig): Promise<void> {
const credentialsPath = config.credentialsPath ?? getDefaultCredentialsPath()
try {
await unlink(credentialsPath)
logger.info('Invalidated cached token', { credentialsPath })
} catch (err: unknown) {
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
logger.warn('Failed to delete cached credentials', { credentialsPath, err })
}
}
}
/**
* Returns a valid Nutrient DWS API access token.
*
* Checks cached credentials first, attempts token refresh if expired,
* and falls back to a browser-based OAuth flow if no valid token is available.
*/
export async function getToken(config: NutrientOAuthConfig): Promise<string> {
const credentialsPath = config.credentialsPath ?? getDefaultCredentialsPath()
logger.debug('getToken called', { credentialsPath })
// 1. Check cached token
const cached = await readCachedCredentials(credentialsPath)
if (cached) {
// 2. Valid token — return it
if (!isTokenExpired(cached)) {
logger.debug('Using cached token (not expired)')
return cached.accessToken
}
logger.debug('Cached token expired', { expiresAt: cached.expiresAt ? new Date(cached.expiresAt).toISOString() : 'unknown' })
// 3. Expired but has refresh token — try refresh
const effectiveClientId = config.clientId ?? cached.clientId
if (cached.refreshToken && effectiveClientId) {
logger.info('Attempting token refresh')
const refreshed = await refreshAccessToken(config, effectiveClientId, cached.refreshToken)
if (refreshed) {
logger.info('Token refreshed successfully')
refreshed.clientId = effectiveClientId
await writeCachedCredentials(credentialsPath, refreshed)
return refreshed.accessToken
}
logger.warn('Token refresh failed, falling back to browser flow')
}
} else {
logger.info('No cached credentials found')
}
// 4. No valid token — browser OAuth flow (includes DCR if needed)
logger.info('Starting browser OAuth flow', { authorizeUrl: config.authorizeUrl })
const credentials = await performBrowserOAuthFlow(config)
logger.info('Browser OAuth flow completed successfully')
await writeCachedCredentials(credentialsPath, credentials)
return credentials.accessToken
}