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