@nera-static/mcp 1.3.0 → 1.4.0

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,369 @@
1
+ // The hosted mode's OAuth 2.1 authorization server logic (L7b, plan D1/D4):
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 && comparableResource(requested) !== comparableResource(granted)
131
+
132
+ /**
133
+ * The code's record when it belongs to this client and is still valid.
134
+ *
135
+ * @param {object|null} record from the store
136
+ * @param {{client_id: string}} client
137
+ */
138
+ function ownCode(record, client) {
139
+ if (!record || record.clientId !== client.client_id) throw new InvalidGrantError('The authorization code is invalid, expired or was already used.')
140
+ return record
141
+ }
142
+
143
+ async function refreshGitHubToken(user) {
144
+ try {
145
+ const tokens = await github.refresh(user.refreshToken)
146
+ store.saveGithubUser({ id: user.id, login: user.login, ...tokens })
147
+ return tokens.accessToken
148
+ } catch (error) {
149
+ log(`GitHub token refresh failed for user ${user.id}: ${error.code || error.message}`)
150
+ 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.')
151
+ }
152
+ }
153
+
154
+ return {
155
+ get clientsStore() {
156
+ return clientsStore
157
+ },
158
+
159
+ /**
160
+ * Starts the login: remembers the client's request under a fresh state
161
+ * and shows our consent page, bound to this browser by a cookie. Nobody
162
+ * goes to GitHub before they approve (the confused-deputy guard).
163
+ *
164
+ * The request is bound to our `/mcp`: a missing `resource` means it, any
165
+ * other one is refused with `invalid_target` (the SDK redirects that to
166
+ * the client) before the consent page, since `/mcp` would refuse every
167
+ * token issued for it.
168
+ */
169
+ async authorize(client, params, res) {
170
+ if (params.resource && comparableResource(params.resource) !== comparableResource(hostedResource)) {
171
+ throw new InvalidTargetError(`This server issues tokens only for ${hostedResource.href}; the requested resource is another one.`)
172
+ }
173
+ const { state, browserToken } = store.savePending({
174
+ clientId: client.client_id,
175
+ params: {
176
+ codeChallenge: params.codeChallenge,
177
+ redirectUri: params.redirectUri,
178
+ state: params.state,
179
+ scopes: params.scopes ?? [],
180
+ resource: hostedResource.href,
181
+ },
182
+ })
183
+ for (const [name, value] of Object.entries(CONSENT_HEADERS)) res.setHeader(name, value)
184
+ res.setHeader('Set-Cookie', consentCookie(browserToken, TTL.pending))
185
+ res.status(200).type('html').send(renderConsentPage({
186
+ clientName: client.client_name,
187
+ clientId: client.client_id,
188
+ redirectUri: params.redirectUri,
189
+ state,
190
+ csrfToken: browserToken,
191
+ }))
192
+ },
193
+
194
+ /**
195
+ * The consent form's POST (`/oauth/consent`, urlencoded body). The
196
+ * form's `csrf_token` must equal this browser's consent cookie, and the
197
+ * cookie must be the one the state was issued to — a page opened in an
198
+ * attacker's browser cannot be approved from the victim's. Approve
199
+ * redirects to GitHub, Deny to the client with `access_denied`.
200
+ *
201
+ * @param {{body?: Record<string, unknown>, headers?: Record<string, unknown>}} req
202
+ * @param {import('express').Response} res
203
+ */
204
+ async handleConsent(req, res) {
205
+ const field = (name) => (typeof req.body?.[name] === 'string' ? req.body[name] : undefined)
206
+ const browserToken = readConsentCookie(req.headers?.cookie)
207
+ const state = field('state')
208
+ if (!state) {
209
+ errorPage(res, 400, EXPIRED_SIGN_IN)
210
+ return
211
+ }
212
+ if (!sameToken(field('csrf_token'), browserToken)) {
213
+ errorPage(res, 403, FOREIGN_CONSENT)
214
+ return
215
+ }
216
+ const decision = field('decision')
217
+ if (decision === 'deny') {
218
+ const pending = store.takePending(state, browserToken)
219
+ if (!pending) {
220
+ errorPage(res, 400, EXPIRED_SIGN_IN)
221
+ return
222
+ }
223
+ redirectToClient(res, pending.params.redirectUri, { error: 'access_denied', error_description: 'The connection was denied on the consent page.', state: pending.params.state })
224
+ return
225
+ }
226
+ if (decision !== 'approve') {
227
+ errorPage(res, 400, 'The consent form was sent without Approve or Deny. Start the connection again from your AI assistant.')
228
+ return
229
+ }
230
+ if (!store.approvePending(state, browserToken)) {
231
+ errorPage(res, 400, EXPIRED_SIGN_IN)
232
+ return
233
+ }
234
+ res.redirect(302, github.authorizeUrl(state))
235
+ },
236
+
237
+ /**
238
+ * GitHub's redirect back to us (`/oauth/github/callback`). Ends with a
239
+ * redirect to the client — our code and its `state`, or an OAuth error —
240
+ * or, when the state is unknown, was never approved or was approved in
241
+ * another browser (we cannot know where to send the user safely), a 400
242
+ * page that says what to do.
243
+ *
244
+ * @param {{query?: Record<string, unknown>, headers?: Record<string, unknown>}} req
245
+ * @param {import('express').Response} res
246
+ */
247
+ async handleGitHubCallback(req, res) {
248
+ const text = (name) => (typeof req.query?.[name] === 'string' ? req.query[name] : undefined)
249
+ const browserToken = readConsentCookie(req.headers?.cookie)
250
+ const pending = text('state') ? store.takePending(text('state'), browserToken) : null
251
+ if (!pending?.approved) {
252
+ errorPage(res, 400, EXPIRED_SIGN_IN)
253
+ return
254
+ }
255
+ const { clientId, params } = pending
256
+ const fail = (error, description) => redirectToClient(res, params.redirectUri, { error, error_description: description, state: params.state })
257
+
258
+ if (text('error')) {
259
+ if (text('error') === 'access_denied') fail('access_denied', 'The GitHub sign-in was cancelled.')
260
+ else fail('server_error', `GitHub reported an error during sign-in: ${text('error')}.`)
261
+ return
262
+ }
263
+ if (!text('code')) {
264
+ fail('server_error', 'GitHub returned without an authorization code.')
265
+ return
266
+ }
267
+
268
+ let user
269
+ try {
270
+ const tokens = await github.exchangeCode(text('code'))
271
+ const profile = await github.getUser(tokens.accessToken)
272
+ user = { ...profile, ...tokens }
273
+ } catch (error) {
274
+ log(`GitHub sign-in failed: ${error.code || error.message}`)
275
+ fail('server_error', 'The GitHub sign-in could not be completed. Try connecting again.')
276
+ return
277
+ }
278
+ store.saveGithubUser(user)
279
+ const code = store.saveCode({ clientId, userId: user.id, params })
280
+ redirectToClient(res, params.redirectUri, { code, state: params.state })
281
+ },
282
+
283
+ /** The PKCE challenge of the code's request, for the SDK's check. */
284
+ async challengeForAuthorizationCode(client, authorizationCode) {
285
+ return ownCode(store.getCode(authorizationCode), client).codeChallenge
286
+ },
287
+
288
+ /**
289
+ * Exchanges a code for our tokens. The code is used up first, so even
290
+ * a request that fails the checks below cannot try it again; a code
291
+ * presented again revokes the tokens of its first use (the store).
292
+ */
293
+ async exchangeAuthorizationCode(client, authorizationCode, _codeVerifier, redirectUri, resource) {
294
+ const record = ownCode(store.takeCode(authorizationCode), client)
295
+ if (redirectUri !== undefined && redirectUri !== record.redirectUri) {
296
+ throw new InvalidGrantError('redirect_uri does not match the one of the authorization request.')
297
+ }
298
+ if (otherResource(resource, record.resource)) {
299
+ throw new InvalidTargetError('resource does not match the one of the authorization request.')
300
+ }
301
+ const tokens = store.issueTokens({
302
+ clientId: client.client_id,
303
+ userId: record.userId,
304
+ scopes: record.scopes ?? [],
305
+ resource: record.resource,
306
+ grantId: record.grantId,
307
+ })
308
+ return tokenResponse(tokens)
309
+ },
310
+
311
+ /**
312
+ * Rotates a refresh token: the old one is refused from now on, and
313
+ * presenting it again revokes the grant's current pair (the store).
314
+ */
315
+ async exchangeRefreshToken(client, refreshToken, scopes, resource) {
316
+ const tokens = store.rotateRefreshToken(refreshToken, { clientId: client.client_id, scopes })
317
+ if (!tokens) throw new InvalidGrantError('The refresh token is invalid, expired or was already used. Sign in again.')
318
+ const granted = store.getAccessToken(tokens.accessToken)
319
+ if (otherResource(resource, granted.resource)) {
320
+ store.revokeToken(tokens.refreshToken, { clientId: client.client_id })
321
+ throw new InvalidTargetError('resource does not match the one the refresh token was issued for. Sign in again.')
322
+ }
323
+ return tokenResponse(tokens)
324
+ },
325
+
326
+ /** What `requireBearerAuth` checks; the user id travels in `extra`. */
327
+ async verifyAccessToken(token) {
328
+ const record = store.getAccessToken(token)
329
+ if (!record) throw new InvalidTokenError('The access token is invalid, expired or revoked.')
330
+ return {
331
+ token,
332
+ clientId: record.clientId,
333
+ scopes: record.scopes,
334
+ expiresAt: record.expiresAt,
335
+ resource: record.resource ? new URL(record.resource) : undefined,
336
+ extra: { userId: record.userId },
337
+ }
338
+ },
339
+
340
+ /**
341
+ * RFC 7009: a refresh token revokes its whole grant, an access token
342
+ * only itself; an unknown or another client's token is silently ignored.
343
+ */
344
+ async revokeToken(client, request) {
345
+ store.revokeToken(request.token, { clientId: client.client_id })
346
+ },
347
+
348
+ /**
349
+ * The user's GitHub token for the tools, refreshed when it expires
350
+ * within five minutes.
351
+ *
352
+ * @param {string} userId
353
+ * @returns {Promise<string>}
354
+ * @throws {SignInRequiredError} when there is no usable sign-in left
355
+ */
356
+ async githubToken(userId) {
357
+ const user = store.getGithubUser(userId)
358
+ if (!user) throw new SignInRequiredError('No GitHub sign-in is saved for this user. Sign in again by reconnecting the Nera connector.')
359
+ if (user.accessTokenExpiresAt === undefined || user.accessTokenExpiresAt > seconds() + GITHUB_REFRESH_MARGIN) return user.accessToken
360
+ if (!user.refreshToken || (user.refreshTokenExpiresAt !== undefined && user.refreshTokenExpiresAt <= seconds())) {
361
+ 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.')
362
+ }
363
+ if (!refreshing.has(user.id)) {
364
+ refreshing.set(user.id, refreshGitHubToken(user).finally(() => refreshing.delete(user.id)))
365
+ }
366
+ return refreshing.get(user.id)
367
+ },
368
+ }
369
+ }