@nera-static/mcp 1.3.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,376 @@
1
+ // The hosted mode's OAuth 2.1 authorization server logic (L7b):
2
+ // the `OAuthServerProvider` the SDK's `mcpAuthRouter` drives, over the token
3
+ // store. We are the authorization server for claude.ai and ChatGPT (they
4
+ // register via DCR), and delegate the login itself to GitHub:
5
+ //
6
+ // client → /authorize → authorize() saves the request, shows our consent
7
+ // page (src/hosted/consent.js) and sets the browser cookie
8
+ // user → POST /oauth/consent → handleConsent(): Approve redirects to
9
+ // GitHub, Deny back to the client with `access_denied`
10
+ // GitHub → /oauth/github/callback → handleGitHubCallback() takes only an
11
+ // approved request of the same browser, saves the GitHub user,
12
+ // issues our code, redirects to the client with its `state`
13
+ // client → /token → challengeForAuthorizationCode() (the SDK checks PKCE),
14
+ // then exchangeAuthorizationCode() / exchangeRefreshToken()
15
+ //
16
+ // A code is bound to the client, its redirect URI, its PKCE challenge and its
17
+ // resource — always our own `/mcp`, the only one we issue tokens for — and is
18
+ // single use; refresh tokens rotate on every use. A code or refresh token
19
+ // presented a second time revokes every token of its grant (the store). The
20
+ // GitHub user token stays on the server — `githubToken(userId)` hands it to the tools
21
+ // and refreshes it when it is about to expire. No token is ever logged.
22
+ import { timingSafeEqual } from 'node:crypto'
23
+ import { InvalidGrantError, InvalidTargetError, InvalidTokenError } from '@modelcontextprotocol/sdk/server/auth/errors.js'
24
+ import { CONSENT_HEADERS, consentCookie, readConsentCookie, renderConsentPage } from './consent.js'
25
+ import { TTL } from './store.js'
26
+
27
+ /** Refresh the GitHub token this many seconds before it expires. */
28
+ const GITHUB_REFRESH_MARGIN = 5 * 60
29
+
30
+ /** Shown when the GitHub callback cannot be tied to a client's request. */
31
+ const EXPIRED_SIGN_IN = 'This sign-in link has expired or was already used. Start the connection again from your AI assistant.'
32
+
33
+ /** Shown when a consent POST does not come from the page this browser was shown. */
34
+ const FOREIGN_CONSENT = 'This approval did not come from the consent page shown in this browser, so it was refused. Start the connection again from your AI assistant.'
35
+
36
+ /** True for two equal non-empty strings, compared in constant time. */
37
+ function sameToken(a, b) {
38
+ if (typeof a !== 'string' || typeof b !== 'string' || !a) return false
39
+ // Compare byte lengths: a non-ASCII field of the same string length would make timingSafeEqual throw.
40
+ const left = Buffer.from(a)
41
+ const right = Buffer.from(b)
42
+ return left.length === right.length && timingSafeEqual(left, right)
43
+ }
44
+
45
+ /**
46
+ * A resource URL as the `/mcp` guard (`requireBearerAuth`) compares it: the
47
+ * serialised value without its fragment and without one trailing slash.
48
+ *
49
+ * @param {string|URL} value
50
+ */
51
+ function comparableResource(value) {
52
+ const url = new URL(value)
53
+ url.hash = ''
54
+ return url.href.replace(/\/$/, '')
55
+ }
56
+
57
+ /** The user has to sign in with GitHub again; the message says so. */
58
+ export class SignInRequiredError extends Error {
59
+ constructor(message) {
60
+ super(message)
61
+ this.name = 'SignInRequiredError'
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Creates the provider.
67
+ *
68
+ * @param {object} options
69
+ * @param {ReturnType<import('./store.js').createStore>} options.store
70
+ * @param {ReturnType<import('./github.js').createGitHubClient>} options.github
71
+ * @param {string|URL} options.resource the protected resource we issue tokens for, `<issuer>/mcp`
72
+ * @param {() => number} [options.now] the clock in milliseconds
73
+ * @param {(message: string) => void} [options.log] where failures are reported (never with a token in them)
74
+ */
75
+ export function createProvider({ store, github, resource, now = Date.now, log = () => {} }) {
76
+ if (!resource) throw new Error('createProvider needs the protected resource it issues tokens for (<issuer>/mcp).')
77
+ const hostedResource = new URL(resource)
78
+ const seconds = () => Math.floor(now() / 1000)
79
+ /** In-flight GitHub refreshes per user: GitHub rotates the refresh token, so a second concurrent refresh would fail. */
80
+ const refreshing = new Map()
81
+
82
+ const clientsStore = {
83
+ getClient: (clientId) => store.getClient(clientId),
84
+ // The SDK's `/register` handler has already validated the metadata and
85
+ // filled in `client_id`, `client_id_issued_at` and the secret.
86
+ registerClient: (client) => store.saveClient(client),
87
+ }
88
+
89
+ /**
90
+ * Redirects to the client's redirect URI with an OAuth result.
91
+ *
92
+ * @param {import('express').Response} res
93
+ * @param {string} redirectUri
94
+ * @param {Record<string, string|undefined>} params
95
+ */
96
+ function redirectToClient(res, redirectUri, params) {
97
+ res.setHeader('Set-Cookie', consentCookie('', 0))
98
+ const url = new URL(redirectUri)
99
+ for (const [name, value] of Object.entries(params)) {
100
+ if (value !== undefined) url.searchParams.set(name, value)
101
+ }
102
+ res.redirect(302, url.href)
103
+ }
104
+
105
+ /**
106
+ * An error page of the consent flow, uncached and unframeable.
107
+ *
108
+ * @param {import('express').Response} res
109
+ * @param {number} status
110
+ * @param {string} message
111
+ */
112
+ function errorPage(res, status, message) {
113
+ for (const [name, value] of Object.entries(CONSENT_HEADERS)) res.setHeader(name, value)
114
+ res.setHeader('Set-Cookie', consentCookie('', 0))
115
+ res.status(status).type('text/plain').send(message)
116
+ }
117
+
118
+ /** Our token response (RFC 6749 §5.1) for a pair from the store. */
119
+ function tokenResponse(tokens) {
120
+ return {
121
+ access_token: tokens.accessToken,
122
+ token_type: 'Bearer',
123
+ expires_in: tokens.expiresIn,
124
+ refresh_token: tokens.refreshToken,
125
+ ...(tokens.scopes.length ? { scope: tokens.scopes.join(' ') } : {}),
126
+ }
127
+ }
128
+
129
+ /** True when a requested resource names a different one than the grant's. */
130
+ const otherResource = (requested, granted) => requested !== undefined && granted !== undefined
131
+ && comparableResource(requested) !== comparableResource(granted)
132
+
133
+ /**
134
+ * The code's record when it belongs to this client and is still valid.
135
+ *
136
+ * @param {object|null} record from the store
137
+ * @param {{client_id: string}} client
138
+ */
139
+ function ownCode(record, client) {
140
+ if (!record || record.clientId !== client.client_id) throw new InvalidGrantError('The authorization code is invalid, expired or was already used.')
141
+ return record
142
+ }
143
+
144
+ async function refreshGitHubToken(user) {
145
+ try {
146
+ const tokens = await github.refresh(user.refreshToken)
147
+ store.saveGithubUser({ id: user.id, login: user.login, ...tokens })
148
+ return tokens.accessToken
149
+ } catch (error) {
150
+ log(`GitHub token refresh failed for user ${user.id}: ${error.code || error.message}`)
151
+ throw new SignInRequiredError('GitHub no longer accepts the saved sign-in. Sign in again: remove the Nera connector in your AI assistant and connect it once more.')
152
+ }
153
+ }
154
+
155
+ return {
156
+ get clientsStore() {
157
+ return clientsStore
158
+ },
159
+
160
+ /**
161
+ * Starts the login: remembers the client's request under a fresh state
162
+ * and shows our consent page, bound to this browser by a cookie. Nobody
163
+ * goes to GitHub before they approve (the confused-deputy guard).
164
+ *
165
+ * The request is bound to our `/mcp`: a missing `resource` means it, any
166
+ * other one is refused with `invalid_target` (the SDK redirects that to
167
+ * the client) before the consent page, since `/mcp` would refuse every
168
+ * token issued for it.
169
+ */
170
+ async authorize(client, params, res) {
171
+ if (params.resource && comparableResource(params.resource) !== comparableResource(hostedResource)) {
172
+ throw new InvalidTargetError(`This server issues tokens only for ${hostedResource.href}; the ` +
173
+ 'requested resource is another one.')
174
+ }
175
+ const { state, browserToken } = store.savePending({
176
+ clientId: client.client_id,
177
+ params: {
178
+ codeChallenge: params.codeChallenge,
179
+ redirectUri: params.redirectUri,
180
+ state: params.state,
181
+ scopes: params.scopes ?? [],
182
+ resource: hostedResource.href,
183
+ },
184
+ })
185
+ for (const [name, value] of Object.entries(CONSENT_HEADERS)) res.setHeader(name, value)
186
+ res.setHeader('Set-Cookie', consentCookie(browserToken, TTL.pending))
187
+ res.status(200).type('html').send(renderConsentPage({
188
+ clientName: client.client_name,
189
+ clientId: client.client_id,
190
+ redirectUri: params.redirectUri,
191
+ state,
192
+ csrfToken: browserToken,
193
+ }))
194
+ },
195
+
196
+ /**
197
+ * The consent form's POST (`/oauth/consent`, urlencoded body). The
198
+ * form's `csrf_token` must equal this browser's consent cookie, and the
199
+ * cookie must be the one the state was issued to — a page opened in an
200
+ * attacker's browser cannot be approved from the victim's. Approve
201
+ * redirects to GitHub, Deny to the client with `access_denied`.
202
+ *
203
+ * @param {{body?: Record<string, unknown>, headers?: Record<string, unknown>}} req
204
+ * @param {import('express').Response} res
205
+ */
206
+ async handleConsent(req, res) {
207
+ const field = (name) => (typeof req.body?.[name] === 'string' ? req.body[name] : undefined)
208
+ const browserToken = readConsentCookie(req.headers?.cookie)
209
+ const state = field('state')
210
+ if (!state) {
211
+ errorPage(res, 400, EXPIRED_SIGN_IN)
212
+ return
213
+ }
214
+ if (!sameToken(field('csrf_token'), browserToken)) {
215
+ errorPage(res, 403, FOREIGN_CONSENT)
216
+ return
217
+ }
218
+ const decision = field('decision')
219
+ if (decision === 'deny') {
220
+ const pending = store.takePending(state, browserToken)
221
+ if (!pending) {
222
+ errorPage(res, 400, EXPIRED_SIGN_IN)
223
+ return
224
+ }
225
+ redirectToClient(res, pending.params.redirectUri, { error: 'access_denied', error_description: 'The connection was denied on the consent page.', state: pending.params.state })
226
+ return
227
+ }
228
+ if (decision !== 'approve') {
229
+ errorPage(res, 400, 'The consent form was sent without Approve or Deny. Start the connection again from your AI assistant.')
230
+ return
231
+ }
232
+ if (!store.approvePending(state, browserToken)) {
233
+ errorPage(res, 400, EXPIRED_SIGN_IN)
234
+ return
235
+ }
236
+ res.redirect(302, github.authorizeUrl(state))
237
+ },
238
+
239
+ /**
240
+ * GitHub's redirect back to us (`/oauth/github/callback`). Ends with a
241
+ * redirect to the client — our code and its `state`, or an OAuth error —
242
+ * or, when the state is unknown, was never approved or was approved in
243
+ * another browser (we cannot know where to send the user safely), a 400
244
+ * page that says what to do.
245
+ *
246
+ * @param {{query?: Record<string, unknown>, headers?: Record<string, unknown>}} req
247
+ * @param {import('express').Response} res
248
+ */
249
+ async handleGitHubCallback(req, res) {
250
+ const text = (name) => (typeof req.query?.[name] === 'string' ? req.query[name] : undefined)
251
+ const browserToken = readConsentCookie(req.headers?.cookie)
252
+ const pending = text('state') ? store.takePending(text('state'), browserToken) : null
253
+ if (!pending?.approved) {
254
+ errorPage(res, 400, EXPIRED_SIGN_IN)
255
+ return
256
+ }
257
+ const { clientId, params } = pending
258
+ const fail = (error, description) => redirectToClient(res, params.redirectUri, {
259
+ error, error_description: description, state: params.state,
260
+ })
261
+
262
+ if (text('error')) {
263
+ if (text('error') === 'access_denied') fail('access_denied', 'The GitHub sign-in was cancelled.')
264
+ else fail('server_error', `GitHub reported an error during sign-in: ${text('error')}.`)
265
+ return
266
+ }
267
+ if (!text('code')) {
268
+ fail('server_error', 'GitHub returned without an authorization code.')
269
+ return
270
+ }
271
+
272
+ let user
273
+ try {
274
+ const tokens = await github.exchangeCode(text('code'))
275
+ const profile = await github.getUser(tokens.accessToken)
276
+ user = { ...profile, ...tokens }
277
+ } catch (error) {
278
+ log(`GitHub sign-in failed: ${error.code || error.message}`)
279
+ fail('server_error', 'The GitHub sign-in could not be completed. Try connecting again.')
280
+ return
281
+ }
282
+ store.saveGithubUser(user)
283
+ const code = store.saveCode({ clientId, userId: user.id, params })
284
+ redirectToClient(res, params.redirectUri, { code, state: params.state })
285
+ },
286
+
287
+ /** The PKCE challenge of the code's request, for the SDK's check. */
288
+ async challengeForAuthorizationCode(client, authorizationCode) {
289
+ return ownCode(store.getCode(authorizationCode), client).codeChallenge
290
+ },
291
+
292
+ /**
293
+ * Exchanges a code for our tokens. The code is used up first, so even
294
+ * a request that fails the checks below cannot try it again; a code
295
+ * presented again revokes the tokens of its first use (the store).
296
+ */
297
+ async exchangeAuthorizationCode(client, authorizationCode, _codeVerifier, redirectUri, resource) {
298
+ const record = ownCode(store.takeCode(authorizationCode), client)
299
+ if (redirectUri !== undefined && redirectUri !== record.redirectUri) {
300
+ throw new InvalidGrantError('redirect_uri does not match the one of the authorization request.')
301
+ }
302
+ if (otherResource(resource, record.resource)) {
303
+ throw new InvalidTargetError('resource does not match the one of the authorization request.')
304
+ }
305
+ const tokens = store.issueTokens({
306
+ clientId: client.client_id,
307
+ userId: record.userId,
308
+ scopes: record.scopes ?? [],
309
+ resource: record.resource,
310
+ grantId: record.grantId,
311
+ })
312
+ return tokenResponse(tokens)
313
+ },
314
+
315
+ /**
316
+ * Rotates a refresh token: the old one is refused from now on, and
317
+ * presenting it again revokes the grant's current pair (the store).
318
+ */
319
+ async exchangeRefreshToken(client, refreshToken, scopes, resource) {
320
+ const tokens = store.rotateRefreshToken(refreshToken, { clientId: client.client_id, scopes })
321
+ if (!tokens) throw new InvalidGrantError('The refresh token is invalid, expired or was already used. Sign in again.')
322
+ const granted = store.getAccessToken(tokens.accessToken)
323
+ if (otherResource(resource, granted.resource)) {
324
+ store.revokeToken(tokens.refreshToken, { clientId: client.client_id })
325
+ throw new InvalidTargetError('resource does not match the one the refresh token was issued for. Sign in again.')
326
+ }
327
+ return tokenResponse(tokens)
328
+ },
329
+
330
+ /** What `requireBearerAuth` checks; the user id travels in `extra`. */
331
+ async verifyAccessToken(token) {
332
+ const record = store.getAccessToken(token)
333
+ if (!record) throw new InvalidTokenError('The access token is invalid, expired or revoked.')
334
+ return {
335
+ token,
336
+ clientId: record.clientId,
337
+ scopes: record.scopes,
338
+ expiresAt: record.expiresAt,
339
+ resource: record.resource ? new URL(record.resource) : undefined,
340
+ extra: { userId: record.userId },
341
+ }
342
+ },
343
+
344
+ /**
345
+ * RFC 7009: a refresh token revokes its whole grant, an access token
346
+ * only itself; an unknown or another client's token is silently ignored.
347
+ */
348
+ async revokeToken(client, request) {
349
+ store.revokeToken(request.token, { clientId: client.client_id })
350
+ },
351
+
352
+ /**
353
+ * The user's GitHub token for the tools, refreshed when it expires
354
+ * within five minutes.
355
+ *
356
+ * @param {string} userId
357
+ * @returns {Promise<string>}
358
+ * @throws {SignInRequiredError} when there is no usable sign-in left
359
+ */
360
+ async githubToken(userId) {
361
+ const user = store.getGithubUser(userId)
362
+ if (!user) throw new SignInRequiredError('No GitHub sign-in is saved for this user. Sign in again by reconnecting the Nera connector.')
363
+ const fresh = user.accessTokenExpiresAt === undefined
364
+ || user.accessTokenExpiresAt > seconds() + GITHUB_REFRESH_MARGIN
365
+ if (fresh) return user.accessToken
366
+ const refreshExpired = user.refreshTokenExpiresAt !== undefined && user.refreshTokenExpiresAt <= seconds()
367
+ if (!user.refreshToken || refreshExpired) {
368
+ throw new SignInRequiredError('The GitHub sign-in has expired. Sign in again: remove the Nera connector in your AI assistant and connect it once more.')
369
+ }
370
+ if (!refreshing.has(user.id)) {
371
+ refreshing.set(user.id, refreshGitHubToken(user).finally(() => refreshing.delete(user.id)))
372
+ }
373
+ return refreshing.get(user.id)
374
+ },
375
+ }
376
+ }