@seatable/mcp-seatable 1.5.2 → 1.6.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.
@@ -1,20 +1,148 @@
1
- import { createHash, randomBytes } from 'node:crypto';
1
+ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
2
2
  import { logger } from '../logger.js';
3
+ import { TokenCipher } from './tokenCipher.js';
3
4
  const CODE_TTL_MS = 5 * 60 * 1000; // 5 minutes
5
+ const DEFAULT_ACCESS_TOKEN_TTL_MS = 60 * 60 * 1000; // 1 hour
6
+ const MIN_REFRESH_TOKEN_TTL_MS = 14 * 24 * 60 * 60 * 1000; // 14 days
7
+ const CLIENT_TTL_MS = 365 * 24 * 60 * 60 * 1000; // 1 year
4
8
  const CLEANUP_INTERVAL_MS = 60 * 1000;
9
+ function parseRedirectUri(raw) {
10
+ try {
11
+ const url = new URL(raw);
12
+ return url.hash ? undefined : url;
13
+ }
14
+ catch {
15
+ return undefined;
16
+ }
17
+ }
18
+ const LOOPBACK_HOSTS = new Set(['127.0.0.1', '::1', '[::1]', 'localhost']);
19
+ /**
20
+ * Hosted MCP clients whose callbacks live on their own servers. These are the
21
+ * only destinations that receive an authorization code over the network, so
22
+ * they are curated rather than open. Operators extend or replace this via
23
+ * SEATABLE_OAUTH_TRUSTED_REDIRECT_HOSTS.
24
+ */
25
+ export const DEFAULT_TRUSTED_REDIRECT_HOSTS = ['claude.ai', 'claude.com', 'chatgpt.com'];
26
+ /** The protected resource clients authorize against — the Streamable HTTP endpoint. */
27
+ export const MCP_RESOURCE_PATH = '/mcp';
28
+ /** RFC 9728 well-known prefix. The resource path is appended to it. */
29
+ export const PROTECTED_RESOURCE_PATH = '/.well-known/oauth-protected-resource';
30
+ /** Schemes that can execute or read local content and must never be a callback. */
31
+ const FORBIDDEN_SCHEMES = new Set(['javascript', 'data', 'file', 'blob', 'vbscript', 'about', 'view-source']);
32
+ function isLoopback(url) {
33
+ return LOOPBACK_HOSTS.has(url.hostname);
34
+ }
35
+ /**
36
+ * Exact string match, with the RFC 8252 §7.3 carve-out: a loopback client may
37
+ * use a different port than it registered, because the port is picked at runtime.
38
+ */
39
+ function redirectUriMatches(registered, candidate) {
40
+ if (registered === candidate)
41
+ return true;
42
+ try {
43
+ const a = new URL(registered);
44
+ const b = new URL(candidate);
45
+ if (!isLoopback(a) || !isLoopback(b))
46
+ return false;
47
+ return a.protocol === b.protocol && a.hostname === b.hostname && a.pathname === b.pathname;
48
+ }
49
+ catch {
50
+ return false;
51
+ }
52
+ }
5
53
  export class OAuthProvider {
6
54
  codes = new Map();
7
55
  cleanupInterval;
8
56
  configuredHostname;
9
57
  validateToken;
58
+ cipher;
59
+ trustedRedirectHosts;
60
+ getClientIp;
61
+ accessTokenTtlMs;
62
+ refreshTokenTtlMs;
63
+ looksLikeAccountToken;
10
64
  constructor(options) {
11
65
  this.configuredHostname = options?.hostname;
12
66
  this.validateToken = options?.validateToken;
67
+ this.getClientIp = options?.getClientIp;
68
+ this.accessTokenTtlMs = options?.accessTokenTtlMs ?? DEFAULT_ACCESS_TOKEN_TTL_MS;
69
+ // A refresh token that outlives its access token is the whole point, so
70
+ // never let a long access lifetime silently invert the relationship.
71
+ this.refreshTokenTtlMs = Math.max(MIN_REFRESH_TOKEN_TTL_MS, this.accessTokenTtlMs);
72
+ this.looksLikeAccountToken = options?.looksLikeAccountToken;
73
+ this.trustedRedirectHosts = new Set((options?.trustedRedirectHosts ?? DEFAULT_TRUSTED_REDIRECT_HOSTS)
74
+ .map((host) => host.trim().toLowerCase())
75
+ .filter(Boolean));
76
+ // Without a configured secret, fall back to an ephemeral one. Tokens then
77
+ // stop working after a restart, which is acceptable for dev/test but not
78
+ // for production — startHttpServer refuses to boot managed mode without it.
79
+ this.cipher = new TokenCipher(options?.secret || randomBytes(32).toString('hex'));
13
80
  this.cleanupInterval = setInterval(() => this.cleanup(), CLEANUP_INTERVAL_MS);
14
81
  if (this.cleanupInterval.unref) {
15
82
  this.cleanupInterval.unref();
16
83
  }
17
84
  }
85
+ clientIp(req) {
86
+ return this.getClientIp?.(req) ?? 'unknown';
87
+ }
88
+ /**
89
+ * May this callback be used at all?
90
+ *
91
+ * Rejects only destinations that can never be safe: schemes that execute or
92
+ * read local content, and plaintext http to a remote host. An unknown https
93
+ * host is permitted — it meets the acknowledgement instead (see below).
94
+ */
95
+ isPermittedRedirectUri(raw) {
96
+ const url = parseRedirectUri(raw);
97
+ if (!url)
98
+ return false;
99
+ const scheme = url.protocol.replace(/:$/, '').toLowerCase();
100
+ if (FORBIDDEN_SCHEMES.has(scheme))
101
+ return false;
102
+ if (scheme === 'http')
103
+ return isLoopback(url);
104
+ if (scheme === 'https')
105
+ return true;
106
+ // Private-use / app scheme (RFC 8252 §7.1): the code is handed to a
107
+ // locally installed application, never transmitted to a remote host.
108
+ return /^[a-z][a-z0-9+.-]*$/.test(scheme);
109
+ }
110
+ /**
111
+ * May this callback receive an authorization code without further friction?
112
+ *
113
+ * The question is not whether we recognise the client — with open dynamic
114
+ * registration an attacker registers honestly — but whether the code would
115
+ * leave the user's machine:
116
+ *
117
+ * loopback stays on the user's own machine
118
+ * private-use scheme goes to a locally installed app
119
+ * https + curated host a known hosted client (ChatGPT, Claude, ...)
120
+ *
121
+ * Everything else is still allowed, but only after the user has explicitly
122
+ * acknowledged where their token is about to be sent. Curation therefore
123
+ * removes friction; it is not a gate, and an empty list breaks nothing.
124
+ */
125
+ isTrustedRedirectUri(raw) {
126
+ if (!this.isPermittedRedirectUri(raw))
127
+ return false;
128
+ const url = parseRedirectUri(raw);
129
+ const scheme = url.protocol.replace(/:$/, '').toLowerCase();
130
+ if (scheme !== 'https')
131
+ return true;
132
+ if (isLoopback(url))
133
+ return true;
134
+ if (this.trustedRedirectHosts.has('*'))
135
+ return true;
136
+ return this.trustedRedirectHosts.has(url.hostname.toLowerCase());
137
+ }
138
+ /**
139
+ * Resolves one of our own access tokens back to the SeaTable API token it seals.
140
+ * Returns undefined for anything we did not issue, or that has expired.
141
+ */
142
+ resolveAccessToken(accessToken) {
143
+ const payload = this.cipher.open('access', accessToken);
144
+ return typeof payload?.t === 'string' ? payload.t : undefined;
145
+ }
18
146
  /**
19
147
  * Derive the base URL from SEATABLE_MCP_HOSTNAME or the incoming Host header.
20
148
  */
@@ -39,13 +167,63 @@ export class OAuthProvider {
39
167
  response_types_supported: ['code'],
40
168
  grant_types_supported: ['authorization_code', 'refresh_token'],
41
169
  token_endpoint_auth_methods_supported: ['none'],
42
- code_challenge_methods_supported: ['S256', 'plain'],
170
+ // S256 only — 'plain' offers no protection against a stolen code.
171
+ code_challenge_methods_supported: ['S256'],
172
+ };
173
+ res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(metadata));
174
+ }
175
+ /**
176
+ * The resource identifier clients authorize against: the MCP endpoint itself.
177
+ */
178
+ resourceIdentifier(req) {
179
+ return `${this.resolveBaseUrl(req)}${MCP_RESOURCE_PATH}`;
180
+ }
181
+ /**
182
+ * Where the protected resource metadata for that identifier lives.
183
+ *
184
+ * RFC 9728 section 3.1: the resource's path is appended to the well-known
185
+ * suffix, so `https://host/mcp` is described at
186
+ * `https://host/.well-known/oauth-protected-resource/mcp`.
187
+ */
188
+ resourceMetadataUrl(req) {
189
+ return `${this.resolveBaseUrl(req)}${PROTECTED_RESOURCE_PATH}${MCP_RESOURCE_PATH}`;
190
+ }
191
+ /**
192
+ * GET /.well-known/oauth-protected-resource[/mcp] — RFC 9728 metadata
193
+ *
194
+ * `authorization_servers` MUST agree with the issuer that handleMetadata()
195
+ * reports. A conformant client follows this document INSTEAD of probing
196
+ * /.well-known/oauth-authorization-server, so a disagreement here breaks
197
+ * clients that work today. Both derive from resolveBaseUrl() for that reason.
198
+ */
199
+ handleProtectedResourceMetadata(req, res) {
200
+ const metadata = {
201
+ resource: this.resourceIdentifier(req),
202
+ authorization_servers: [this.resolveBaseUrl(req)],
203
+ bearer_methods_supported: ['header'],
204
+ resource_documentation: 'https://github.com/seatable/seatable-mcp',
43
205
  };
44
206
  res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(metadata));
45
207
  }
208
+ /**
209
+ * The WWW-Authenticate challenge for a 401, pointing at the metadata above.
210
+ *
211
+ * RFC 6750 section 3.1: a request that carried no credential at all gets no
212
+ * error code — only one that presented a credential we rejected does.
213
+ */
214
+ challenge(req, error) {
215
+ const params = [`resource_metadata="${this.resourceMetadataUrl(req)}"`];
216
+ if (error)
217
+ params.unshift(`error="${error}"`);
218
+ return `Bearer ${params.join(', ')}`;
219
+ }
46
220
  /**
47
221
  * POST /register — Dynamic Client Registration (RFC 7591)
48
- * Returns a generated client_id. We don't validate client credentials.
222
+ *
223
+ * The returned client_id is a sealed envelope containing the client's name and
224
+ * its redirect_uris. That makes the registration tamper-proof and verifiable at
225
+ * /authorize without any server-side storage: a client_id we did not issue
226
+ * cannot be opened, and the callback list inside it cannot be edited.
49
227
  */
50
228
  async handleRegister(req, res) {
51
229
  if (req.method !== 'POST') {
@@ -53,86 +231,160 @@ export class OAuthProvider {
53
231
  return;
54
232
  }
55
233
  const body = await this.parseBody(req);
56
- const clientName = body.get('client_name') ?? 'mcp-client';
57
- const redirectUris = body.get('redirect_uris') ?? '';
58
- const clientId = randomBytes(16).toString('hex');
59
- logger.info({ clientName }, 'OAuth dynamic client registration');
60
- const response = {
234
+ const clientName = (body.get('client_name') ?? 'mcp-client').slice(0, 200);
235
+ const redirectUris = this.parseRedirectUris(body.get('redirect_uris'));
236
+ if (redirectUris.length === 0) {
237
+ this.registrationError(res, 'invalid_redirect_uri', 'At least one redirect_uri is required');
238
+ return;
239
+ }
240
+ const rejected = redirectUris.filter((uri) => !this.isPermittedRedirectUri(uri));
241
+ if (rejected.length > 0) {
242
+ logger.warn({ clientName, count: rejected.length }, 'OAuth registration rejected: callback not permitted');
243
+ this.registrationError(res, 'invalid_redirect_uri', 'A callback must use https, a private-use application scheme, or http on a loopback address.');
244
+ return;
245
+ }
246
+ const registration = { n: clientName, r: redirectUris };
247
+ const clientId = this.cipher.seal('client', registration, CLIENT_TTL_MS);
248
+ // The registered callbacks are what /authorize later checks against, so a
249
+ // rejected authorization is only explainable if they were recorded here.
250
+ // Both fields come from an unauthenticated caller: cap count and length.
251
+ logger.info({
252
+ clientName,
253
+ callbacks: redirectUris.slice(0, 5).map((uri) => uri.slice(0, 120)),
254
+ ip: this.clientIp(req),
255
+ }, 'OAuth dynamic client registration');
256
+ res.writeHead(201, { 'content-type': 'application/json' }).end(JSON.stringify({
61
257
  client_id: clientId,
62
258
  client_name: clientName,
259
+ redirect_uris: redirectUris,
63
260
  token_endpoint_auth_method: 'none',
64
- };
65
- if (redirectUris) {
66
- response.redirect_uris = typeof redirectUris === 'string' && redirectUris.startsWith('[')
67
- ? JSON.parse(redirectUris)
68
- : [redirectUris];
69
- }
70
- res.writeHead(201, { 'content-type': 'application/json' }).end(JSON.stringify(response));
261
+ grant_types: ['authorization_code', 'refresh_token'],
262
+ response_types: ['code'],
263
+ client_id_issued_at: Math.floor(Date.now() / 1000),
264
+ }));
71
265
  }
72
266
  /**
73
267
  * GET /authorize — renders the authorization form
74
268
  * POST /authorize — processes the form submission
269
+ *
270
+ * Both paths validate the request the same way, and neither shows the token
271
+ * prompt until the client, the callback and the PKCE challenge all check out.
75
272
  */
76
273
  async handleAuthorize(req, res, url) {
77
- const clientId = url.searchParams.get('client_id') ?? '';
78
- const redirectUri = url.searchParams.get('redirect_uri') ?? '';
79
- const state = url.searchParams.get('state') ?? '';
80
- const responseType = url.searchParams.get('response_type') ?? '';
81
- const codeChallenge = url.searchParams.get('code_challenge') ?? '';
82
- const codeChallengeMethod = url.searchParams.get('code_challenge_method') ?? '';
274
+ if (req.method !== 'GET' && req.method !== 'POST') {
275
+ res.writeHead(405, { 'content-type': 'text/plain' }).end('Method not allowed');
276
+ return;
277
+ }
278
+ const form = req.method === 'POST' ? await this.parseFormBody(req) : new Map();
279
+ const pick = (key) => form.get(key) ?? url.searchParams.get(key) ?? '';
280
+ const clientId = pick('client_id');
281
+ const redirectUri = pick('redirect_uri');
282
+ const state = pick('state');
283
+ const responseType = pick('response_type');
284
+ const codeChallenge = pick('code_challenge');
285
+ const codeChallengeMethod = pick('code_challenge_method');
286
+ const client = clientId ? this.cipher.open('client', clientId) : undefined;
287
+ if (!client) {
288
+ logger.warn('OAuth authorize rejected: unknown or expired client registration');
289
+ this.authorizeError(res, 'Unknown client', 'This application is not registered with SeaTable MCP, or its registration has expired. Nothing has been sent to it.');
290
+ return;
291
+ }
292
+ if (responseType !== 'code') {
293
+ this.authorizeError(res, 'Unsupported request', 'Only the authorization code flow is supported.');
294
+ return;
295
+ }
296
+ if (redirectUri && !this.isPermittedRedirectUri(redirectUri)) {
297
+ logger.warn({ clientName: client.n, callback: safeCallback(redirectUri), ip: this.clientIp(req) }, 'OAuth authorize rejected: callback not permitted');
298
+ this.authorizeError(res, 'Callback not permitted', 'SeaTable does not deliver authorizations to this kind of address. Nothing has been sent.');
299
+ return;
300
+ }
301
+ if (!redirectUri || !client.r.some((registered) => redirectUriMatches(registered, redirectUri))) {
302
+ logger.warn({ clientName: client.n, callback: safeCallback(redirectUri), ip: this.clientIp(req) }, 'OAuth authorize rejected: redirect_uri not registered');
303
+ this.authorizeError(res, 'Unregistered callback address', 'This application asked SeaTable to send your authorization to an address it never registered. This is what a phishing attempt looks like — nothing has been sent.');
304
+ return;
305
+ }
306
+ if (!codeChallenge || codeChallengeMethod !== 'S256') {
307
+ logger.warn({ clientName: client.n, ip: this.clientIp(req) }, 'OAuth authorize rejected: missing or downgraded PKCE');
308
+ this.authorizeError(res, 'Insecure request', 'This application did not provide a valid PKCE challenge (S256 is required).');
309
+ return;
310
+ }
311
+ const callbackOrigin = new URL(redirectUri).origin;
312
+ const pageOpts = { client, clientId, redirectUri, callbackOrigin, state, responseType, codeChallenge, codeChallengeMethod };
313
+ /*
314
+ * An unfamiliar remote destination must be acknowledged before the token
315
+ * field appears. The attacker writes the entry link, so the acknowledgement
316
+ * is read from our own form body only — never from the query string — and
317
+ * a POST auto-submitted by a foreign page is refused via Sec-Fetch-Site.
318
+ */
319
+ const needsAcknowledgement = !this.isTrustedRedirectUri(redirectUri);
320
+ const acknowledged = needsAcknowledgement
321
+ ? form.get('acknowledged') === 'yes' && req.headers['sec-fetch-site'] === 'same-origin'
322
+ : true;
323
+ if (!acknowledged) {
324
+ if (req.method === 'POST') {
325
+ logger.warn({ clientName: client.n, callback: safeCallback(redirectUri), ip: this.clientIp(req) }, 'OAuth authorize: unacknowledged destination');
326
+ }
327
+ // 200 on first view, 400 when a submission tried to skip the step.
328
+ res.writeHead(req.method === 'POST' ? 400 : 200, { 'content-type': 'text/html; charset=utf-8' });
329
+ res.end(this.renderAcknowledgementPage(pageOpts));
330
+ return;
331
+ }
83
332
  if (req.method === 'GET') {
84
333
  res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
85
- res.end(this.renderAuthorizePage(clientId, redirectUri, state, responseType, codeChallenge, codeChallengeMethod));
334
+ res.end(this.renderAuthorizePage({ ...pageOpts, acknowledged: needsAcknowledgement }));
86
335
  return;
87
336
  }
88
- if (req.method === 'POST') {
89
- const body = await this.parseFormBody(req);
90
- const apiToken = body.get('api_token') ?? '';
91
- const formRedirectUri = body.get('redirect_uri') ?? redirectUri;
92
- const formState = body.get('state') ?? state;
93
- const formCodeChallenge = body.get('code_challenge') ?? codeChallenge;
94
- const formCodeChallengeMethod = body.get('code_challenge_method') ?? codeChallengeMethod;
95
- if (!apiToken) {
96
- res.writeHead(400, { 'content-type': 'text/html; charset=utf-8' });
97
- res.end(this.renderAuthorizePage(clientId, formRedirectUri, formState, responseType, formCodeChallenge, formCodeChallengeMethod, 'Please enter your API token.'));
98
- return;
99
- }
100
- // Validate token against SeaTable before issuing a code
101
- if (this.validateToken) {
102
- const valid = await this.validateToken(apiToken);
103
- if (!valid) {
104
- logger.warn('OAuth authorization rejected: invalid API token');
105
- res.writeHead(400, { 'content-type': 'text/html; charset=utf-8' });
106
- res.end(this.renderAuthorizePage(clientId, formRedirectUri, formState, responseType, formCodeChallenge, formCodeChallengeMethod, 'Invalid API token. Please check your token and try again.'));
107
- return;
108
- }
109
- }
110
- if (!formRedirectUri) {
111
- res.writeHead(400, { 'content-type': 'text/plain' }).end('Missing redirect_uri');
337
+ // POST that passed the acknowledgement: the token itself is the payload.
338
+ const apiToken = (form.get('api_token') ?? '').trim();
339
+ const renderWithError = (message) => {
340
+ res.writeHead(400, { 'content-type': 'text/html; charset=utf-8' });
341
+ res.end(this.renderAuthorizePage({ ...pageOpts, acknowledged: needsAcknowledgement, error: message }));
342
+ };
343
+ if (!apiToken) {
344
+ // Coming straight from the acknowledgement page there is nothing to
345
+ // complain about yet — this is the first sight of the token field.
346
+ if (!form.has('api_token')) {
347
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
348
+ res.end(this.renderAuthorizePage({ ...pageOpts, acknowledged: needsAcknowledgement }));
112
349
  return;
113
350
  }
114
- const code = randomBytes(32).toString('hex');
115
- this.codes.set(code, {
116
- apiToken,
117
- redirectUri: formRedirectUri,
118
- codeChallenge: formCodeChallenge || undefined,
119
- codeChallengeMethod: formCodeChallengeMethod || undefined,
120
- expiresAt: Date.now() + CODE_TTL_MS,
121
- });
122
- logger.info('OAuth authorization code issued');
123
- const redirect = new URL(formRedirectUri);
124
- redirect.searchParams.set('code', code);
125
- if (formState) {
126
- redirect.searchParams.set('state', formState);
127
- }
128
- res.writeHead(302, { location: redirect.toString() });
129
- res.end();
351
+ renderWithError('Please enter your API token.');
352
+ return;
353
+ }
354
+ if (this.validateToken && !(await this.validateToken(apiToken))) {
355
+ // Half of all real rejections are the wrong *kind* of token, not a
356
+ // wrong token. Say which, instead of leaving the user guessing.
357
+ const isAccountToken = this.looksLikeAccountToken
358
+ ? await this.looksLikeAccountToken(apiToken).catch(() => false)
359
+ : false;
360
+ logger.warn({ ip: this.clientIp(req), clientName: client.n, kind: isAccountToken ? 'account_token' : 'unknown' }, 'OAuth authorization rejected: invalid API token');
361
+ renderWithError(isAccountToken
362
+ ? 'That is an account API token. This connection needs a base API token: open the base, then Advanced \u2192 API Tokens \u2192 Add API Token.'
363
+ : 'Invalid API token. Please check your token and try again.');
130
364
  return;
131
365
  }
132
- res.writeHead(405, { 'content-type': 'text/plain' }).end('Method not allowed');
366
+ const code = randomBytes(32).toString('hex');
367
+ this.codes.set(code, {
368
+ apiToken,
369
+ clientId,
370
+ redirectUri,
371
+ codeChallenge,
372
+ expiresAt: Date.now() + CODE_TTL_MS,
373
+ });
374
+ logger.info({ flow: flowId(code), clientName: client.n, callback: safeCallback(redirectUri), ip: this.clientIp(req) }, 'OAuth authorization code issued');
375
+ const redirect = new URL(redirectUri);
376
+ redirect.searchParams.set('code', code);
377
+ if (state) {
378
+ redirect.searchParams.set('state', state);
379
+ }
380
+ res.writeHead(302, { location: redirect.toString() });
381
+ res.end();
133
382
  }
134
383
  /**
135
- * POST /token — exchanges authorization code for access token
384
+ * POST /token — exchanges an authorization code (or refresh token) for an access token.
385
+ *
386
+ * The issued access token is a sealed envelope around the SeaTable API token,
387
+ * never the API token itself.
136
388
  */
137
389
  async handleToken(req, res) {
138
390
  if (req.method !== 'POST') {
@@ -141,84 +393,124 @@ export class OAuthProvider {
141
393
  }
142
394
  const body = await this.parseFormBody(req);
143
395
  const grantType = body.get('grant_type');
144
- const code = body.get('code');
145
- const redirectUri = body.get('redirect_uri');
146
- const codeVerifier = body.get('code_verifier');
147
- // Refresh token grant — the refresh token IS the API token
148
396
  if (grantType === 'refresh_token') {
149
- const refreshToken = body.get('refresh_token') ?? '';
150
- if (!refreshToken) {
151
- res.writeHead(400, { 'content-type': 'application/json' })
152
- .end(JSON.stringify({ error: 'invalid_request', error_description: 'Missing refresh_token' }));
153
- return;
154
- }
155
- res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' });
156
- res.end(JSON.stringify({
157
- access_token: refreshToken,
158
- token_type: 'Bearer',
159
- refresh_token: refreshToken,
160
- }));
397
+ this.handleRefreshGrant(body, res);
161
398
  return;
162
399
  }
163
400
  if (grantType !== 'authorization_code') {
164
- res.writeHead(400, { 'content-type': 'application/json' })
165
- .end(JSON.stringify({ error: 'unsupported_grant_type' }));
401
+ logger.warn({ grantType: String(grantType ?? '(none)').slice(0, 40) }, 'OAuth token exchange rejected: unsupported grant_type');
402
+ this.tokenError(res, 'unsupported_grant_type');
166
403
  return;
167
404
  }
405
+ const code = body.get('code');
406
+ const clientId = body.get('client_id');
407
+ const redirectUri = body.get('redirect_uri');
408
+ const codeVerifier = body.get('code_verifier');
168
409
  if (!code) {
169
- res.writeHead(400, { 'content-type': 'application/json' })
170
- .end(JSON.stringify({ error: 'invalid_request', error_description: 'Missing code' }));
410
+ this.tokenError(res, 'invalid_request', 'Missing code');
171
411
  return;
172
412
  }
173
413
  const stored = this.codes.get(code);
414
+ // Single-use: consume the code before any further check, so a failed
415
+ // attempt cannot be retried with different parameters.
416
+ this.codes.delete(code);
174
417
  if (!stored) {
175
- logger.warn('OAuth token exchange with invalid/expired code');
176
- res.writeHead(400, { 'content-type': 'application/json' })
177
- .end(JSON.stringify({ error: 'invalid_grant', error_description: 'Invalid or expired authorization code' }));
418
+ logger.warn({ flow: flowId(code) }, 'OAuth token exchange with invalid/expired code');
419
+ this.tokenError(res, 'invalid_grant', 'Invalid or expired authorization code');
178
420
  return;
179
421
  }
180
- // Single-use: delete immediately
181
- this.codes.delete(code);
182
422
  if (Date.now() > stored.expiresAt) {
183
- res.writeHead(400, { 'content-type': 'application/json' })
184
- .end(JSON.stringify({ error: 'invalid_grant', error_description: 'Authorization code expired' }));
423
+ logger.warn({ flow: flowId(code) }, 'OAuth token exchange rejected: authorization code expired');
424
+ this.tokenError(res, 'invalid_grant', 'Authorization code expired');
185
425
  return;
186
426
  }
187
- // Validate redirect_uri
188
- if (redirectUri && redirectUri !== stored.redirectUri) {
189
- res.writeHead(400, { 'content-type': 'application/json' })
190
- .end(JSON.stringify({ error: 'invalid_grant', error_description: 'redirect_uri mismatch' }));
427
+ // The code belongs to one client only.
428
+ if (!clientId || !constantTimeEquals(clientId, stored.clientId)) {
429
+ logger.warn({ flow: flowId(code) }, 'OAuth token exchange rejected: client_id does not match the code');
430
+ this.tokenError(res, 'invalid_grant', 'client_id does not match the authorization code');
191
431
  return;
192
432
  }
193
- // PKCE verification
194
- if (stored.codeChallenge) {
195
- if (!codeVerifier) {
196
- res.writeHead(400, { 'content-type': 'application/json' })
197
- .end(JSON.stringify({ error: 'invalid_request', error_description: 'Missing code_verifier' }));
198
- return;
199
- }
200
- const expected = stored.codeChallengeMethod === 'plain'
201
- ? codeVerifier
202
- : base64UrlEncode(createHash('sha256').update(codeVerifier).digest());
203
- if (expected !== stored.codeChallenge) {
204
- logger.warn('OAuth PKCE verification failed');
205
- res.writeHead(400, { 'content-type': 'application/json' })
206
- .end(JSON.stringify({ error: 'invalid_grant', error_description: 'PKCE verification failed' }));
207
- return;
208
- }
433
+ // redirect_uri is required here, not optional — omitting it must not skip the check.
434
+ if (!redirectUri || redirectUri !== stored.redirectUri) {
435
+ logger.warn({ flow: flowId(code) }, 'OAuth token exchange rejected: redirect_uri missing or mismatched');
436
+ this.tokenError(res, 'invalid_grant', 'redirect_uri mismatch');
437
+ return;
209
438
  }
210
- logger.info('OAuth token exchange successful');
211
- // Return the API token as the OAuth access token
439
+ if (!codeVerifier) {
440
+ logger.warn({ flow: flowId(code) }, 'OAuth token exchange rejected: missing code_verifier');
441
+ this.tokenError(res, 'invalid_grant', 'Missing code_verifier');
442
+ return;
443
+ }
444
+ const expected = base64UrlEncode(createHash('sha256').update(codeVerifier).digest());
445
+ if (!constantTimeEquals(expected, stored.codeChallenge)) {
446
+ logger.warn({ flow: flowId(code) }, 'OAuth token exchange rejected: PKCE verification failed');
447
+ this.tokenError(res, 'invalid_grant', 'PKCE verification failed');
448
+ return;
449
+ }
450
+ logger.info({ flow: flowId(code) }, 'OAuth token exchange successful');
451
+ this.issueTokens(res, stored.apiToken, stored.clientId);
452
+ }
453
+ destroy() {
454
+ clearInterval(this.cleanupInterval);
455
+ this.codes.clear();
456
+ }
457
+ handleRefreshGrant(body, res) {
458
+ const refreshToken = body.get('refresh_token') ?? '';
459
+ if (!refreshToken) {
460
+ this.tokenError(res, 'invalid_request', 'Missing refresh_token');
461
+ return;
462
+ }
463
+ const payload = this.cipher.open('refresh', refreshToken);
464
+ if (!payload || typeof payload.t !== 'string') {
465
+ logger.warn('OAuth refresh rejected: unknown or expired refresh token');
466
+ this.tokenError(res, 'invalid_grant', 'Invalid or expired refresh token');
467
+ return;
468
+ }
469
+ const clientId = body.get('client_id');
470
+ if (clientId && !constantTimeEquals(clientId, payload.c)) {
471
+ logger.warn('OAuth refresh rejected: client_id does not match the refresh token');
472
+ this.tokenError(res, 'invalid_grant', 'client_id does not match the refresh token');
473
+ return;
474
+ }
475
+ // A silent refresh is the normal, healthy case -- and therefore the one
476
+ // worth being able to see. Without this line there is no way to tell a
477
+ // client that renews cleanly from one that re-prompts its user hourly.
478
+ logger.info({ clientId: fingerprint(payload.c) }, 'OAuth access token refreshed');
479
+ this.issueTokens(res, payload.t, payload.c);
480
+ }
481
+ issueTokens(res, apiToken, clientId) {
482
+ const accessToken = this.cipher.seal('access', { t: apiToken }, this.accessTokenTtlMs);
483
+ const refreshToken = this.cipher.seal('refresh', { t: apiToken, c: clientId }, this.refreshTokenTtlMs);
212
484
  res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' });
213
485
  res.end(JSON.stringify({
214
- access_token: stored.apiToken,
486
+ access_token: accessToken,
215
487
  token_type: 'Bearer',
216
- refresh_token: stored.apiToken,
488
+ expires_in: Math.floor(this.accessTokenTtlMs / 1000),
489
+ refresh_token: refreshToken,
217
490
  }));
218
491
  }
219
- destroy() {
220
- clearInterval(this.cleanupInterval);
221
- this.codes.clear();
492
+ tokenError(res, error, description) {
493
+ res.writeHead(400, { 'content-type': 'application/json', 'cache-control': 'no-store' })
494
+ .end(JSON.stringify(description ? { error, error_description: description } : { error }));
495
+ }
496
+ registrationError(res, error, description) {
497
+ res.writeHead(400, { 'content-type': 'application/json' })
498
+ .end(JSON.stringify({ error, error_description: description }));
499
+ }
500
+ parseRedirectUris(raw) {
501
+ if (!raw)
502
+ return [];
503
+ let value = raw;
504
+ if (raw.startsWith('[')) {
505
+ try {
506
+ value = JSON.parse(raw);
507
+ }
508
+ catch {
509
+ return [];
510
+ }
511
+ }
512
+ const list = Array.isArray(value) ? value : [value];
513
+ return list.filter((entry) => typeof entry === 'string' && entry.length > 0).slice(0, 20);
222
514
  }
223
515
  cleanup() {
224
516
  const now = Date.now();
@@ -270,83 +562,131 @@ export class OAuthProvider {
270
562
  readBody(req) {
271
563
  return new Promise((resolve, reject) => {
272
564
  const chunks = [];
273
- req.on('data', (chunk) => chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk));
565
+ let size = 0;
566
+ req.on('data', (chunk) => {
567
+ const buf = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
568
+ size += buf.length;
569
+ if (size > 64 * 1024) {
570
+ req.destroy();
571
+ reject(new Error('Request body too large'));
572
+ return;
573
+ }
574
+ chunks.push(buf);
575
+ });
274
576
  req.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')));
275
577
  req.on('error', reject);
276
578
  });
277
579
  }
278
- renderAuthorizePage(clientId, redirectUri, state, responseType, codeChallenge, codeChallengeMethod, error) {
279
- const errorHtml = error ? `<div class="error">${this.escapeHtml(error)}</div>` : '';
280
- return `<!DOCTYPE html>
580
+ /** An error page that deliberately does not render the API token prompt. */
581
+ authorizeError(res, heading, message) {
582
+ res.writeHead(400, { 'content-type': 'text/html; charset=utf-8' });
583
+ res.end(`<!DOCTYPE html>
281
584
  <html lang="en">
282
585
  <head>
283
586
  <meta charset="utf-8">
284
587
  <meta name="viewport" content="width=device-width, initial-scale=1">
285
- <title>SeaTable MCP — Authorize</title>
588
+ <title>SeaTable MCP — Authorization refused</title>
286
589
  <style>
287
590
  * { box-sizing: border-box; margin: 0; padding: 0; }
288
- body {
289
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
290
- background: #f5f5f5;
291
- display: flex;
292
- justify-content: center;
293
- align-items: center;
294
- min-height: 100vh;
295
- padding: 20px;
296
- }
297
- .card {
298
- background: white;
299
- border-radius: 12px;
300
- box-shadow: 0 2px 12px rgba(0,0,0,0.1);
301
- padding: 40px;
302
- max-width: 440px;
303
- width: 100%;
304
- }
305
- h1 { font-size: 1.4em; margin-bottom: 8px; color: #333; }
306
- .subtitle { color: #666; margin-bottom: 24px; font-size: 0.95em; line-height: 1.5; }
307
- label { display: block; font-weight: 600; margin-bottom: 6px; color: #444; font-size: 0.9em; }
308
- input[type="password"] {
309
- width: 100%;
310
- padding: 10px 12px;
311
- border: 1px solid #ddd;
312
- border-radius: 6px;
313
- font-size: 1em;
314
- margin-bottom: 20px;
315
- }
316
- input[type="password"]:focus { outline: none; border-color: #ff8c00; box-shadow: 0 0 0 3px rgba(255,140,0,0.15); }
317
- button {
318
- width: 100%;
319
- padding: 12px;
320
- background: #ff8c00;
321
- color: white;
322
- border: none;
323
- border-radius: 6px;
324
- font-size: 1em;
325
- font-weight: 600;
326
- cursor: pointer;
327
- }
328
- button:hover { background: #e07b00; }
329
- .error { background: #fee; color: #c00; padding: 10px 12px; border-radius: 6px; margin-bottom: 16px; font-size: 0.9em; }
330
- .hint { margin-top: 16px; font-size: 0.8em; color: #999; line-height: 1.4; }
591
+ body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #f5f5f5; display: flex; justify-content: center; align-items: center; min-height: 100vh; padding: 20px; }
592
+ .card { background: white; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); padding: 40px; max-width: 440px; width: 100%; }
593
+ h1 { font-size: 1.3em; margin-bottom: 12px; color: #c00; }
594
+ p { color: #555; line-height: 1.6; font-size: 0.95em; }
331
595
  </style>
332
596
  </head>
333
597
  <body>
334
598
  <div class="card">
599
+ <h1>${this.escapeHtml(heading)}</h1>
600
+ <p>${this.escapeHtml(message)}</p>
601
+ </div>
602
+ </body>
603
+ </html>`);
604
+ }
605
+ renderAcknowledgementPage(opts) {
606
+ return this.page(`
607
+ <h1>Where is this going?</h1>
608
+ <p class="subtitle">Before you enter anything, check the destination.</p>
609
+ <div class="destination">
610
+ <span class="destination-label">Your API token will be sent to</span>
611
+ <span class="destination-host">${this.escapeHtml(opts.callbackOrigin)}</span>
612
+ </div>
613
+ <div class="warning">
614
+ SeaTable does not recognise this destination. That does not necessarily mean it is
615
+ malicious — but it does mean we cannot vouch for it. Only continue if
616
+ <strong>you</strong> started this connection yourself, from software you trust.
617
+ If you arrived here from a link or a message, close this page.
618
+ </div>
619
+ <p class="claimed">The application calls itself
620
+ &ldquo;${this.escapeHtml(opts.client.n)}&rdquo; &mdash; self-reported, not verified by SeaTable.</p>
621
+ <form method="POST" action="/authorize">
622
+ ${this.hiddenFlowFields(opts)}
623
+ <input type="hidden" name="acknowledged" value="yes">
624
+ <button type="submit">I started this connection</button>
625
+ </form>
626
+ <p class="hint">If you did not, simply close this page. Nothing has been sent yet.</p>`);
627
+ }
628
+ renderAuthorizePage(opts) {
629
+ const errorHtml = opts.error ? `<div class="error">${this.escapeHtml(opts.error)}</div>` : '';
630
+ return this.page(`
335
631
  <h1>SeaTable MCP</h1>
336
- <p class="subtitle">Enter your SeaTable API token to authorize access to your base.</p>
632
+ <p class="subtitle">An application is asking for access to your SeaTable base.</p>
633
+ <div class="destination">
634
+ <span class="destination-label">Your authorization will be sent to</span>
635
+ <span class="destination-host">${this.escapeHtml(opts.callbackOrigin)}</span>
636
+ </div>
637
+ <p class="claimed">The application calls itself
638
+ &ldquo;${this.escapeHtml(opts.client.n)}&rdquo; &mdash; self-reported, not verified by SeaTable.</p>
337
639
  ${errorHtml}
338
640
  <form method="POST" action="/authorize">
339
- <input type="hidden" name="redirect_uri" value="${this.escapeHtml(redirectUri)}">
340
- <input type="hidden" name="state" value="${this.escapeHtml(state)}">
341
- <input type="hidden" name="client_id" value="${this.escapeHtml(clientId)}">
342
- <input type="hidden" name="response_type" value="${this.escapeHtml(responseType)}">
343
- <input type="hidden" name="code_challenge" value="${this.escapeHtml(codeChallenge)}">
344
- <input type="hidden" name="code_challenge_method" value="${this.escapeHtml(codeChallengeMethod)}">
641
+ ${this.hiddenFlowFields(opts)}
642
+ ${opts.acknowledged ? '<input type="hidden" name="acknowledged" value="yes">' : ''}
345
643
  <label for="api_token">API Token</label>
346
644
  <input type="password" id="api_token" name="api_token" placeholder="Enter your SeaTable API token" required autofocus>
347
645
  <button type="submit">Authorize</button>
348
- <p class="hint">Your API token will be used as your access credential. Use a read-only token for minimal permissions.</p>
349
- </form>
646
+ <p class="hint">Use a base API token, not your account token. A read-only token keeps the permissions minimal.</p>
647
+ </form>`);
648
+ }
649
+ hiddenFlowFields(opts) {
650
+ const field = (name, value) => `<input type="hidden" name="${name}" value="${this.escapeHtml(value)}">`;
651
+ return [
652
+ field('redirect_uri', opts.redirectUri),
653
+ field('state', opts.state),
654
+ field('client_id', opts.clientId),
655
+ field('response_type', opts.responseType),
656
+ field('code_challenge', opts.codeChallenge),
657
+ field('code_challenge_method', opts.codeChallengeMethod),
658
+ ].join('\n ');
659
+ }
660
+ /** Shared chrome for every page this provider renders. */
661
+ page(body) {
662
+ return `<!DOCTYPE html>
663
+ <html lang="en">
664
+ <head>
665
+ <meta charset="utf-8">
666
+ <meta name="viewport" content="width=device-width, initial-scale=1">
667
+ <title>SeaTable MCP &mdash; Authorize</title>
668
+ <style>
669
+ * { box-sizing: border-box; margin: 0; padding: 0; }
670
+ body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #f5f5f5; display: flex; justify-content: center; align-items: center; min-height: 100vh; padding: 20px; }
671
+ .card { background: white; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); padding: 40px; max-width: 460px; width: 100%; }
672
+ h1 { font-size: 1.4em; margin-bottom: 8px; color: #333; }
673
+ .subtitle { color: #666; margin-bottom: 20px; font-size: 0.95em; line-height: 1.5; }
674
+ .destination { display: block; background: #f7f9fb; border: 1px solid #e3e8ee; border-radius: 8px; padding: 14px 16px; margin-bottom: 14px; }
675
+ .destination-label { display: block; color: #789; font-size: 0.8em; text-transform: uppercase; letter-spacing: 0.04em; margin-bottom: 4px; }
676
+ .destination-host { display: block; font-size: 1.05em; font-weight: 700; color: #1a2b3c; word-break: break-all; }
677
+ .warning { background: #fff4e5; color: #8a4b00; border: 1px solid #ffcc80; padding: 12px 14px; border-radius: 6px; margin-bottom: 14px; font-size: 0.88em; line-height: 1.55; }
678
+ .claimed { color: #888; font-size: 0.82em; line-height: 1.5; margin-bottom: 18px; }
679
+ label { display: block; font-weight: 600; margin-bottom: 6px; color: #444; font-size: 0.9em; }
680
+ input[type="password"] { width: 100%; padding: 10px 12px; border: 1px solid #ddd; border-radius: 6px; font-size: 1em; margin-bottom: 20px; }
681
+ input[type="password"]:focus { outline: none; border-color: #ff8c00; box-shadow: 0 0 0 3px rgba(255,140,0,0.15); }
682
+ button { width: 100%; padding: 12px; background: #ff8c00; color: white; border: none; border-radius: 6px; font-size: 1em; font-weight: 600; cursor: pointer; }
683
+ button:hover { background: #e07b00; }
684
+ .error { background: #fee; color: #c00; padding: 10px 12px; border-radius: 6px; margin-bottom: 16px; font-size: 0.9em; }
685
+ .hint { margin-top: 16px; font-size: 0.8em; color: #999; line-height: 1.4; }
686
+ </style>
687
+ </head>
688
+ <body>
689
+ <div class="card">${body}
350
690
  </div>
351
691
  </body>
352
692
  </html>`;
@@ -355,10 +695,37 @@ export class OAuthProvider {
355
695
  return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
356
696
  }
357
697
  }
698
+ /**
699
+ * Correlation id for one authorization, derived from the code so that the
700
+ * /authorize and /token log lines can be paired without ever writing the code
701
+ * itself (or a prefix of it) to disk.
702
+ */
703
+ /**
704
+ * A callback as written to the log: the full destination, because for an
705
+ * incident the question is where the code actually went, not just which host.
706
+ * The value comes from an unauthenticated caller, so it is capped.
707
+ */
708
+ function safeCallback(raw) {
709
+ return raw.slice(0, 200);
710
+ }
711
+ /** Short, non-reversible handle for a sealed value that is too long to log. */
712
+ function fingerprint(value) {
713
+ return createHash('sha256').update(value).digest('hex').slice(0, 12);
714
+ }
715
+ function flowId(code) {
716
+ return createHash('sha256').update(`flow:${code}`).digest('hex').slice(0, 12);
717
+ }
358
718
  function base64UrlEncode(buffer) {
359
719
  return buffer.toString('base64')
360
720
  .replace(/\+/g, '-')
361
721
  .replace(/\//g, '_')
362
722
  .replace(/=+$/, '');
363
723
  }
724
+ function constantTimeEquals(a, b) {
725
+ const bufA = Buffer.from(a, 'utf-8');
726
+ const bufB = Buffer.from(b, 'utf-8');
727
+ if (bufA.length !== bufB.length)
728
+ return false;
729
+ return timingSafeEqual(bufA, bufB);
730
+ }
364
731
  //# sourceMappingURL=oauthProvider.js.map