Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/openai-tunnel.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ The MCP server can be started and tested before the tunnel exists:

```bash
docker compose up -d seatable-mcp
docker compose logs seatable-mcp # expect "Streamable HTTP server listening"
docker compose logs seatable-mcp # expect "seatable-mcp started"

docker run --rm --network seatable-mcp_mcp-net curlimages/curl -s \
-X POST http://seatable-mcp:3000/mcp \
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@seatable/mcp-seatable",
"version": "1.9.7",
"version": "1.9.8",
"type": "module",
"license": "MIT",
"mcpName": "io.github.seatable/seatable",
Expand Down
19 changes: 16 additions & 3 deletions src/auth/oauthProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -383,12 +383,25 @@ export class OAuthProvider {
const codeChallenge = pick('code_challenge')
const codeChallengeMethod = pick('code_challenge_method')

const client = clientId ? this.cipher.open<ClientRegistration>('client', clientId) : undefined
if (!client) {
logger.warn('OAuth authorize rejected: unknown or expired client registration')
const opened = this.cipher.inspect<ClientRegistration>('client', clientId)
if (!('payload' in opened)) {
// A client that keeps presenting a stale client_id shows up as a burst
// of these. `clientId` (the same fingerprint as in the refresh log)
// groups the burst; `reason` says whether the registration expired,
// was sealed under another secret, or was never ours.
logger.warn(
{
reason: opened.reason,
ip: this.clientIp(req),
...(clientId && { clientId: fingerprint(clientId) }),
...(redirectUri && { callback: safeCallback(redirectUri) }),
},
'OAuth authorize rejected: unknown or expired client registration'
)
this.authorizeError(res, 'Unknown client', 'This application is not registered with SeaTable MCP, or its registration has expired. Nothing has been sent to it.')
return
}
const client = opened.payload

if (responseType !== 'code') {
this.authorizeError(res, 'Unsupported request', 'Only the authorization code flow is supported.')
Expand Down
35 changes: 28 additions & 7 deletions src/auth/tokenCipher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ export interface SealedPayload {
[key: string]: unknown
}

export type RejectReason = 'missing' | 'foreign' | 'invalid' | 'expired'

export class TokenCipher {
private readonly key: Buffer

Expand All @@ -51,12 +53,31 @@ export class TokenCipher {

/** Returns the payload, or undefined if the value is forged, tampered with, of the wrong kind, or expired. */
open<T extends Record<string, unknown> = Record<string, unknown>>(kind: TokenKind, value: string): (T & SealedPayload) | undefined {
const result = this.inspect<T>(kind, value)
return 'payload' in result ? result.payload : undefined
}

/**
* Like open(), but says why a value was rejected, for logs:
* - `missing`: empty.
* - `foreign`: not one of our envelopes of this kind — typically a value
* issued by another server, or a different kind of ours.
* - `invalid`: our prefix, but it doesn't authenticate. Forged, truncated,
* or sealed under a different SEATABLE_TOKEN_SECRET.
* - `expired`: genuine, but past its expiry.
*/
inspect<T extends Record<string, unknown> = Record<string, unknown>>(
kind: TokenKind,
value: string
): { payload: T & SealedPayload } | { reason: RejectReason } {
if (typeof value !== 'string' || value === '') return { reason: 'missing' }
const prefix = PREFIX[kind]
if (typeof value !== 'string' || !value.startsWith(prefix)) return undefined
if (!value.startsWith(prefix)) return { reason: 'foreign' }

let payload: T & SealedPayload
try {
const raw = Buffer.from(value.slice(prefix.length), 'base64url')
if (raw.length <= NONCE_BYTES + TAG_BYTES) return undefined
if (raw.length <= NONCE_BYTES + TAG_BYTES) return { reason: 'invalid' }

const nonce = raw.subarray(0, NONCE_BYTES)
const ciphertext = raw.subarray(NONCE_BYTES, raw.length - TAG_BYTES)
Expand All @@ -66,13 +87,13 @@ export class TokenCipher {
decipher.setAAD(Buffer.from(kind))
decipher.setAuthTag(tag)
const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf-8')

const payload = JSON.parse(plaintext) as T & SealedPayload
if (typeof payload.exp !== 'number' || Date.now() >= payload.exp) return undefined
return payload
payload = JSON.parse(plaintext) as T & SealedPayload
} catch {
// Any failure — bad base64, failed auth tag, malformed JSON — is a rejection.
return undefined
return { reason: 'invalid' }
}
if (typeof payload.exp !== 'number') return { reason: 'invalid' }
if (Date.now() >= payload.exp) return { reason: 'expired' }
return { payload }
}
}
45 changes: 43 additions & 2 deletions src/http/httpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,28 @@ async function parseJsonBody(req: IncomingMessage): Promise<unknown> {
})
}

/**
* The JSON-RPC method(s) of a request body, for logs. A POST without a session
* ID is treated as initialize; when it is something else the SDK answers 400,
* and the method says what the client was really trying to do. Method names are
* protocol vocabulary, never customer content, but they come from the caller,
* so anything that doesn't look like one is reduced to `invalid`.
*/
export function jsonRpcMethods(body: unknown): string {
const one = (message: unknown): string => {
if (typeof message !== 'object' || message === null) return 'invalid'
const method = (message as { method?: unknown }).method
if (method === undefined) return 'result' in message || 'error' in message ? 'response' : 'invalid'
return typeof method === 'string' && /^[A-Za-z0-9_./-]{1,64}$/.test(method) ? method : 'invalid'
}
if (Array.isArray(body)) {
const methods = body.slice(0, 5).map(one)
if (body.length > 5) methods.push('...')
return methods.join(',') || 'empty'
}
return body === undefined ? 'empty' : one(body)
}

/**
* Hosts allowed as remote https callbacks in the OAuth flow. Unset means the
* built-in list of hosted MCP clients; '*' disables curation (dangerous).
Expand Down Expand Up @@ -380,6 +402,13 @@ export async function startHttpServer(options: StartHttpServerOptions = {}) {
void cleanup()
}

// Set before connect(): the SDK chains its own handler onto this one.
// It is the only place the reason for an SDK-generated 400 surfaces.
let transportError: string | undefined
transport.onerror = (error) => {
transportError ??= error.message.slice(0, 200)
}

/*
* An initialize request that never produces a session — a malformed
* body the SDK rejects, a client that hangs up, a transport error —
Expand All @@ -393,7 +422,13 @@ export async function startHttpServer(options: StartHttpServerOptions = {}) {
return
}
logger.info(
{ ip: getClientIp(req), status: res.statusCode, ...(apiToken && { token: tokenFingerprint(apiToken) }) },
{
ip: getClientIp(req),
status: res.statusCode,
method: jsonRpcMethods(body),
...(transportError && { reason: transportError }),
...(apiToken && { token: tokenFingerprint(apiToken) }),
},
'Initialize request ended without a session'
)
void cleanup()
Expand Down Expand Up @@ -603,7 +638,13 @@ export async function startHttpServer(options: StartHttpServerOptions = {}) {
server.listen(port, host)
})

logger.info({ host, port, endpoint: '/mcp' }, 'Streamable HTTP server listening')
logger.info({
mode: env.SEATABLE_MOCK ? 'mock' : mode,
tools: getStaticToolDefinitions().length,
host,
port,
endpoint: '/mcp',
}, 'seatable-mcp started')

// Idle session cleanup. Sessions that crowd the connection pool sooner than
// this are evicted on demand, see evictIdlestSession().
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ async function main() {
}

await server.connect(transport)
logger.info({ transport: 'stdio', tools: server.getToolDefinitions().length }, 'seatable-mcp started')
}

// Exported CLI entry for bin launcher (used by npx)
Expand Down
7 changes: 3 additions & 4 deletions src/mcp/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -385,10 +385,9 @@ export function buildServer(options?: BuildServerOptions) {
mode = 'selfhosted'
}

logger.info({
mode,
tools: server.getToolDefinitions().length,
}, 'seatable-mcp started')
// Called once per HTTP session, so this is not the startup line: that is
// logged once per process by main() (stdio) and startHttpServer().
logger.debug({ mode, tools: server.getToolDefinitions().length }, 'MCP server built')

return server
}
Expand Down
23 changes: 22 additions & 1 deletion tests/connectionSlots.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ vi.mock('../src/metrics/metricsServer', () => ({
startMetricsServer: vi.fn().mockResolvedValue(undefined),
}))

const VALID_TOKENS = new Set(['slot-token-1', 'slot-token-2', 'slot-token-3', 'slot-token-4'])
const VALID_TOKENS = new Set(['slot-token-1', 'slot-token-2', 'slot-token-3', 'slot-token-4', 'slot-token-log'])

vi.mock('../src/auth/tokenValidator', () => ({
TokenValidator: class {
Expand Down Expand Up @@ -106,6 +106,27 @@ describe('Connection slot accounting', () => {
expect(res.headers.get('mcp-session-id')).toBeTruthy()
})

/**
* In production most sessions were preceded by one of these 400s, and the
* log said nothing about why. The method and the SDK's reason say whether a
* client is replaying a request without its session or speaking a protocol
* version we don't support.
*/
it('logs the method and reason of a POST without session ID that is not initialize', async () => {
const res = await fetch(`${baseUrl}/mcp`, {
method: 'POST',
headers: { ...JSON_HEADERS, authorization: 'Bearer slot-token-log', 'x-forwarded-for': '198.51.100.9' },
body: JSON.stringify({ jsonrpc: '2.0', id: 7, method: 'tools/call', params: { name: 'list_tables', arguments: {} } }),
})
expect(res.status).toBe(400)
await res.text()
await vi.waitFor(() => expect(find('Initialize request ended without a session')).toHaveLength(1))

const [entry] = find('Initialize request ended without a session')
expect(entry.fields).toMatchObject({ status: 400, method: 'tools/call', reason: 'Bad Request: Server not initialized' })
expect(JSON.stringify(entry.fields)).not.toContain('list_tables')
})

it('releases the slot when a session is closed with DELETE', async () => {
const token = 'slot-token-2'
const ip = '198.51.100.2'
Expand Down
41 changes: 41 additions & 0 deletions tests/oauthObservability.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ vi.mock('../src/logger', () => {
})

import { OAuthProvider } from '../src/auth/oauthProvider.js'
import { TokenCipher } from '../src/auth/tokenCipher.js'

/**
* After the external report, the forensic questions could not be answered from
Expand Down Expand Up @@ -281,3 +282,43 @@ describe('no rejection path is silent', () => {
expect(rejected[0].fields.ip).toBe('198.51.100.66')
})
})

describe('a stale client registration is attributable', () => {
/*
* Production showed bursts of "unknown or expired client registration",
* three every few seconds, with no field at all: neither who sent them nor
* whether the registration had expired or was sealed under another secret.
*/
async function authorizeWith(clientId: string) {
await fetch(base(
`/authorize?response_type=code&client_id=${encodeURIComponent(clientId)}`
+ `&redirect_uri=${encodeURIComponent(CB)}&code_challenge=${CHALLENGE}&code_challenge_method=S256`,
), { headers: { 'x-forwarded-for': '198.51.100.42' } })
return find('unknown or expired client registration')
}

it('records reason, IP, callback and a fingerprint of the client_id', async () => {
const stale = new TokenCipher('the-secret-before-it-was-rotated-long-enough')
.seal('client', { n: 'Old Client', r: [CB] }, 60_000)
const rejected = await authorizeWith(stale)

expect(rejected).toHaveLength(1)
expect(rejected[0].fields).toMatchObject({ reason: 'invalid', ip: '198.51.100.42', callback: CB })
expect(rejected[0].fields.clientId).toMatch(/^[0-9a-f]{12}$/)
expect(JSON.stringify(rejected[0].fields)).not.toContain(stale)
})

it('tells an expired registration apart', async () => {
const expired = new TokenCipher(SECRET).seal('client', { n: 'Old Client', r: [CB] }, -1)
const [rejected] = await authorizeWith(expired)
expect(rejected.fields.reason).toBe('expired')
})

it('gives the same client_id the same fingerprint, so a burst groups', async () => {
const [a] = await authorizeWith('not-one-of-ours')
logCalls.length = 0
const [b] = await authorizeWith('not-one-of-ours')
expect(a.fields.reason).toBe('foreign')
expect(a.fields.clientId).toBe(b.fields.clientId)
})
})
27 changes: 27 additions & 0 deletions tests/tokenCipher.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,31 @@ describe('TokenCipher', () => {
expect(cipher.open('access', '')).toBeUndefined()
expect(cipher.open('access', 'stmcp1.AAAA')).toBeUndefined()
})

describe('inspect() names the reason for a rejection', () => {
const cipher = new TokenCipher(SECRET)

it('missing', () => {
expect(cipher.inspect('client', '')).toEqual({ reason: 'missing' })
})

it('foreign: not our envelope, or another kind of ours', () => {
expect(cipher.inspect('client', 'some-other-servers-client-id')).toEqual({ reason: 'foreign' })
expect(cipher.inspect('client', cipher.seal('access', {}, 60_000))).toEqual({ reason: 'foreign' })
})

it('invalid: sealed under another secret', () => {
const other = new TokenCipher('a-different-secret-that-is-also-long-enough')
expect(cipher.inspect('client', other.seal('client', {}, 60_000))).toEqual({ reason: 'invalid' })
})

it('expired', () => {
expect(cipher.inspect('client', cipher.seal('client', {}, -1))).toEqual({ reason: 'expired' })
})

it('returns the payload of a valid value, like open()', () => {
const result = cipher.inspect('client', cipher.seal('client', { n: 'x' }, 60_000))
expect('payload' in result && result.payload.n).toBe('x')
})
})
})
Loading