@lexapi/mcp 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,149 @@
1
+ // OAuth configuration of the hosted server.
2
+ //
3
+ // OAuth is ON when LEXAPI_OAUTH_CLIENT_SECRET is set; every other value has
4
+ // the production default. Without the secret the server runs as 0.3.0 did:
5
+ // API keys only, the old 401, no metadata documents. Setting any other OAuth
6
+ // variable WITHOUT the secret refuses to start (a deploy that meant to turn
7
+ // OAuth on but lost the secret must fail loudly, not run with sign-in off).
8
+ import { DEFAULT_BASE_URL } from '../client.js';
9
+ export const OAUTH_SCOPE = 'lex';
10
+ export const DEFAULT_ISSUER = 'https://lex-api.com';
11
+ export const DEFAULT_RESOURCE = 'https://mcp.lex-api.com/v1';
12
+ export const DEFAULT_CLIENT_ID = 'lexapi-mcp-server';
13
+ /** Shortest accepted client secret. */
14
+ export const MIN_SECRET_LENGTH = 32;
15
+ /** Default per-user cap on new token exchanges a minute; one per connection every ~4.5 min is normal. */
16
+ export const DEFAULT_EXCHANGES_PER_USER_PER_MIN = 20;
17
+ /** Variables that only mean something with OAuth on. */
18
+ const OAUTH_ONLY_VARS = ['LEXAPI_OAUTH_ISSUER', 'LEXAPI_OAUTH_RESOURCE', 'LEXAPI_OAUTH_CLIENT_ID', 'LEXAPI_API_BASE'];
19
+ export class OAuthConfigError extends Error {
20
+ constructor(message) {
21
+ super(message);
22
+ this.name = 'OAuthConfigError';
23
+ }
24
+ }
25
+ const LOOPBACK = new Set(['127.0.0.1', 'localhost', '[::1]', '::1']);
26
+ /** An absolute https URL (http only on loopback, for local tests), no query / fragment / credentials. */
27
+ function parseUrl(name, raw) {
28
+ let u;
29
+ try {
30
+ u = new URL(raw);
31
+ }
32
+ catch {
33
+ throw new OAuthConfigError(`${name} is not a URL`);
34
+ }
35
+ if (u.username || u.password)
36
+ throw new OAuthConfigError(`${name} must not contain credentials`);
37
+ if (u.search || u.hash || raw.includes('#') || raw.includes('?'))
38
+ throw new OAuthConfigError(`${name} must not have a query or fragment`);
39
+ if (u.protocol !== 'https:' && !(u.protocol === 'http:' && LOOPBACK.has(u.hostname))) {
40
+ throw new OAuthConfigError(`${name} must be an https URL`);
41
+ }
42
+ return u;
43
+ }
44
+ /** Trailing slashes dropped — LexAPI canonicalises issuer / resource the same way. */
45
+ function trimSlash(s) {
46
+ return s.replace(/\/+$/, '');
47
+ }
48
+ /**
49
+ * The OAuth configuration from env, or null when OAuth is off (no client
50
+ * secret). Throws OAuthConfigError when the secret is set but a value is
51
+ * unusable — the hosted server must not start half-configured.
52
+ */
53
+ export function oauthConfigFromEnv(env = process.env) {
54
+ const secret = (env.LEXAPI_OAUTH_CLIENT_SECRET ?? '').trim();
55
+ if (!secret) {
56
+ const set = OAUTH_ONLY_VARS.filter((name) => (env[name] ?? '').trim());
57
+ if (set.length) {
58
+ throw new OAuthConfigError(`${set.join(', ')} ${set.length === 1 ? 'is' : 'are'} set but LEXAPI_OAUTH_CLIENT_SECRET is not: set the secret to turn sign-in with LexAPI on, or remove ${set.length === 1 ? 'it' : 'them'} to run with API keys only`);
59
+ }
60
+ return null;
61
+ }
62
+ if (secret.length < MIN_SECRET_LENGTH) {
63
+ throw new OAuthConfigError(`LEXAPI_OAUTH_CLIENT_SECRET must be at least ${MIN_SECRET_LENGTH} characters`);
64
+ }
65
+ const issuerRaw = trimSlash((env.LEXAPI_OAUTH_ISSUER ?? '').trim() || DEFAULT_ISSUER);
66
+ const issuerUrl = parseUrl('LEXAPI_OAUTH_ISSUER', issuerRaw);
67
+ if (issuerUrl.pathname !== '/' && issuerUrl.pathname !== '') {
68
+ // The issuer is an origin; its endpoints are `${issuer}/oauth/…`.
69
+ throw new OAuthConfigError('LEXAPI_OAUTH_ISSUER must be an origin (no path), e.g. https://lex-api.com');
70
+ }
71
+ const issuer = issuerRaw;
72
+ // The resource is compared byte for byte (PRM `resource`, token `aud`), so
73
+ // it is used exactly as configured — apart from a trailing slash, which
74
+ // the canonical form drops.
75
+ const resource = trimSlash((env.LEXAPI_OAUTH_RESOURCE ?? '').trim() || DEFAULT_RESOURCE);
76
+ const resourceUrl = parseUrl('LEXAPI_OAUTH_RESOURCE', resource);
77
+ // `origin` + `pathname` is the canonical form (lowercase scheme + host, no
78
+ // default port, no dot-segments or other path the URL parser rewrites) —
79
+ // the form used in `aud`. Anything else would make the PRM
80
+ // `resource` and the token `aud` disagree.
81
+ if (resource !== `${resourceUrl.origin}${resourceUrl.pathname}`) {
82
+ throw new OAuthConfigError(`LEXAPI_OAUTH_RESOURCE must be canonical (lowercase scheme and host, no default port, no dot-segments): ${resourceUrl.origin}${resourceUrl.pathname}`);
83
+ }
84
+ const resourcePath = resourceUrl.pathname === '/' ? '' : resourceUrl.pathname;
85
+ if (!resourcePath)
86
+ throw new OAuthConfigError('LEXAPI_OAUTH_RESOURCE must include the MCP path, e.g. https://mcp.lex-api.com/v1');
87
+ const clientId = (env.LEXAPI_OAUTH_CLIENT_ID ?? '').trim() || DEFAULT_CLIENT_ID;
88
+ if (!/^[\x21-\x7e]+$/.test(clientId))
89
+ throw new OAuthConfigError('LEXAPI_OAUTH_CLIENT_ID must be printable ASCII without spaces');
90
+ if (!/^[\x20-\x7e]+$/.test(secret))
91
+ throw new OAuthConfigError('LEXAPI_OAUTH_CLIENT_SECRET must be printable ASCII');
92
+ // The API base: what the API-key path uses (LEXAPI_BASE_URL as 0.3.0 read
93
+ // it, else the default). LEXAPI_API_BASE, an older alias, may only repeat
94
+ // it — never redirect OAuth traffic alone.
95
+ const baseRaw = env.LEXAPI_BASE_URL ? env.LEXAPI_BASE_URL : DEFAULT_BASE_URL;
96
+ const apiBase = trimSlash(baseRaw.trim());
97
+ const alias = (env.LEXAPI_API_BASE ?? '').trim();
98
+ if (alias && trimSlash(alias) !== apiBase) {
99
+ throw new OAuthConfigError('LEXAPI_API_BASE differs from LEXAPI_BASE_URL (or its default): LEXAPI_BASE_URL is the variable; remove LEXAPI_API_BASE');
100
+ }
101
+ const apiUrl = parseUrl('LEXAPI_BASE_URL', apiBase);
102
+ if (apiUrl.origin !== issuerUrl.origin) {
103
+ throw new OAuthConfigError(`LEXAPI_BASE_URL must be on the issuer's origin (${issuerUrl.origin}) when OAuth is on: exchanged API tokens are sent there`);
104
+ }
105
+ const hopsRaw = (env.LEXAPI_MCP_TRUST_PROXY_HOPS ?? '').trim();
106
+ const trustProxyHops = hopsRaw ? Number(hopsRaw) : 0;
107
+ if (!Number.isInteger(trustProxyHops) || trustProxyHops < 0 || trustProxyHops > 10) {
108
+ throw new OAuthConfigError('LEXAPI_MCP_TRUST_PROXY_HOPS must be a whole number from 0 to 10');
109
+ }
110
+ const perUserRaw = (env.LEXAPI_MCP_EXCHANGES_PER_USER_PER_MIN ?? '').trim();
111
+ const exchangesPerUserPerMin = perUserRaw ? Number(perUserRaw) : DEFAULT_EXCHANGES_PER_USER_PER_MIN;
112
+ if (!Number.isInteger(exchangesPerUserPerMin) || exchangesPerUserPerMin < 1 || exchangesPerUserPerMin > 1000) {
113
+ throw new OAuthConfigError('LEXAPI_MCP_EXCHANGES_PER_USER_PER_MIN must be a whole number from 1 to 1000');
114
+ }
115
+ return {
116
+ issuer,
117
+ resource,
118
+ clientId,
119
+ clientSecret: secret,
120
+ apiAudience: `${issuer}/api/v1`,
121
+ tokenEndpoint: `${issuer}/oauth/token`,
122
+ jwksUri: `${issuer}/.well-known/jwks.json`,
123
+ resourcePath,
124
+ resourceMetadataUrl: `${resourceUrl.origin}/.well-known/oauth-protected-resource${resourcePath}`,
125
+ apiBase,
126
+ trustProxyHops,
127
+ exchangesPerUserPerMin,
128
+ };
129
+ }
130
+ /** RFC 9728 Protected Resource Metadata. */
131
+ export function protectedResourceMetadata(cfg) {
132
+ return {
133
+ resource: cfg.resource,
134
+ authorization_servers: [cfg.issuer],
135
+ scopes_supported: [OAUTH_SCOPE],
136
+ bearer_methods_supported: ['header'],
137
+ resource_name: 'LexAPI MCP server',
138
+ resource_documentation: 'https://lex-api.com/docs#mcp-oauth',
139
+ };
140
+ }
141
+ /** A quoted-string-safe value for a WWW-Authenticate parameter. */
142
+ export function authParam(value) {
143
+ return value.replace(/[\\"\r\n]/g, ' ').replace(/[^\x20-\x7e]/g, '').slice(0, 200);
144
+ }
145
+ /** The RFC 6750 / MCP authorization challenge; `error` is set when a Bearer token was presented and refused. */
146
+ export function bearerChallenge(cfg, error) {
147
+ const base = `Bearer realm="lexapi", resource_metadata="${cfg.resourceMetadataUrl}", scope="${OAUTH_SCOPE}"`;
148
+ return error ? `${base}, error="${error.code}", error_description="${authParam(error.description)}"` : base;
149
+ }
@@ -0,0 +1,196 @@
1
+ export declare const TOKEN_EXCHANGE_GRANT = "urn:ietf:params:oauth:grant-type:token-exchange";
2
+ export declare const ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
3
+ /** A cached API token is dropped this long before its `exp`. */
4
+ export declare const EXPIRY_MARGIN_MS = 30000;
5
+ export declare const DEFAULT_MAX_ENTRIES = 10000;
6
+ /**
7
+ * One exchange (both attempts, the backoff between them included) never
8
+ * takes longer than this: under the first progress frame (10 s) and the SSE
9
+ * keep-alive (15 s), so a refusal found by the exchange is still answered
10
+ * with its HTTP status rather than as a tool error after the 200.
11
+ */
12
+ export declare const EXCHANGE_DEADLINE_MS = 9000;
13
+ /** Local limits. Windows are fixed, one minute unless stated. */
14
+ export declare const LIMITS: {
15
+ /** Exchanges started for one subject token per minute (normal use: one per ~4.5 min, two after an API 401). */
16
+ perTokenPerMin: number;
17
+ /**
18
+ * Exchanges LexAPI refused (user-token rejections) per client IP per minute;
19
+ * past it, accounts with a recent refusal of their own are cut off from that
20
+ * address (never an account with a clean record).
21
+ */
22
+ refusedPerIpPerMin: number;
23
+ /** …and per user (`sub`) per 10 minutes. */
24
+ refusedPerSubPer10Min: number;
25
+ /**
26
+ * NEW exchanges started for one user (`sub`) per minute, successful or
27
+ * refused (LEXAPI_MCP_EXCHANGES_PER_USER_PER_MIN). Normal use is one
28
+ * per connection every ~4.5 min; cached tokens never count.
29
+ */
30
+ exchangesPerSubPerMin: number;
31
+ /**
32
+ * A slow-down (429 / 503 temporarily_unavailable) is treated as about one
33
+ * user until this many distinct users got one within a minute: then it is
34
+ * global, and every new exchange waits.
35
+ */
36
+ slowDownGlobalAfterUsers: number;
37
+ /** Backoff after a 429 / 503 temporarily_unavailable: doubles per consecutive one; Retry-After is a floor. */
38
+ throttleMinMs: number;
39
+ throttleMaxMs: number;
40
+ /** A refusal is remembered no longer than this (the subject's `exp` normally ends it sooner). */
41
+ negativeMaxMs: number;
42
+ };
43
+ /**
44
+ * How the token endpoint says "the subject token is not usable" (revoked,
45
+ * expired …): `400 invalid_request` whose description begins with exactly
46
+ * this prefix (RFC 8693 §2.2.2 leaves no distinct error code). Only this is
47
+ * the USER's problem (→ 401 invalid_token, refresh / re-authorize); every
48
+ * other 400 means our
49
+ * exchange request is wrong (→ 500, logged, counted) — mapping those to 401
50
+ * would push every user into a re-auth loop while hiding the bug.
51
+ */
52
+ export declare const SUBJECT_REJECTED_PREFIX = "subject_token rejected: ";
53
+ export type ExchangeFailure = 'invalid_token' | 'config' | 'client_auth' | 'unavailable' | 'rate_limited' | 'upstream';
54
+ export declare class ExchangeError extends Error {
55
+ readonly kind: ExchangeFailure;
56
+ /** Token-free description (the AS's error_description, or ours). */
57
+ readonly description: string;
58
+ readonly retryAfterSeconds?: number | undefined;
59
+ constructor(kind: ExchangeFailure,
60
+ /** Token-free description (the AS's error_description, or ours). */
61
+ description: string, retryAfterSeconds?: number | undefined);
62
+ }
63
+ export interface TokenExchangerOptions {
64
+ tokenEndpoint: string;
65
+ clientId: string;
66
+ clientSecret: string;
67
+ /** `resource` of the requested token — the LexAPI API audience. */
68
+ apiAudience: string;
69
+ maxEntries?: number;
70
+ fetch?: typeof fetch;
71
+ now?: () => number;
72
+ sleep?: (ms: number) => Promise<void>;
73
+ limits?: Partial<typeof LIMITS>;
74
+ /** Overall bound of one exchange (default EXCHANGE_DEADLINE_MS; tests shorten it). */
75
+ deadlineMs?: number;
76
+ }
77
+ /** Who is asking — for the per-IP / per-user limits. */
78
+ export interface ExchangeCaller {
79
+ ip?: string;
80
+ sub?: string;
81
+ }
82
+ /** Counters exposed on /health (no identifiers, no tokens). */
83
+ export interface ExchangeStats {
84
+ /** Requests sent to the token endpoint, retries included. */
85
+ requests: number;
86
+ succeeded: number;
87
+ /** LexAPI refused the subject token (user-side: revoked / expired …). */
88
+ userTokenRejected: number;
89
+ /** Refusals answered from the negative cache (no request sent). */
90
+ negativeCacheHits: number;
91
+ /** 400s that are NOT a subject_token rejection: our request is wrong. */
92
+ configErrors: number;
93
+ /** 401/403 from the token endpoint: our client credentials. */
94
+ clientAuthErrors: number;
95
+ /** The token endpoint's 429. */
96
+ rateLimited: number;
97
+ /** The token endpoint's 503 temporarily_unavailable. */
98
+ unavailable: number;
99
+ /** 5xx / network / malformed answers, after the retry. */
100
+ upstreamErrors: number;
101
+ /** Exchanges refused locally (per-token / per-IP / per-user limit, or backoff). */
102
+ locallyLimited: number;
103
+ cacheSize: number;
104
+ negativeCacheSize: number;
105
+ /** Seconds left of a requested backoff that holds back EVERY user (0: none). */
106
+ backoffSeconds: number;
107
+ /** Users whose own new exchanges are held back right now (per-user slow-down). */
108
+ usersBackingOff: number;
109
+ }
110
+ /**
111
+ * Cache key of a subject token: sha256 of its signed part (`header.payload`),
112
+ * never the token itself. The signature segment is left out on purpose: an
113
+ * ECDSA signature has a second valid form (s → n − s) for the same signed
114
+ * bytes, so keying on the whole
115
+ * string would let one token occupy two entries. Two tokens with the same
116
+ * signed part ARE the same token. Only used on tokens that passed local
117
+ * signature verification.
118
+ */
119
+ export declare function subjectKey(subjectToken: string): string;
120
+ /**
121
+ * Exchanges subject tokens and caches the resulting API tokens per subject
122
+ * token until 30 s before they expire, in a bounded in-memory LRU; refused
123
+ * subject tokens are remembered until they expire. Concurrent requests
124
+ * carrying the same subject token share one exchange. Nothing is persisted
125
+ * or logged.
126
+ */
127
+ export declare class TokenExchanger {
128
+ private readonly opts;
129
+ private readonly cache;
130
+ private readonly refused;
131
+ private readonly inflight;
132
+ private readonly fetchImpl;
133
+ private readonly now;
134
+ private readonly sleep;
135
+ private readonly maxEntries;
136
+ private readonly basic;
137
+ private readonly limits;
138
+ private readonly perToken;
139
+ private readonly refusedPerIp;
140
+ private readonly refusedPerSub;
141
+ private readonly exchangesPerSub;
142
+ /** Backoff after a 429 / 503 temporarily_unavailable, for everyone. */
143
+ private throttle;
144
+ /** …or for one user (`sub`): only that user's new exchanges wait. Bounded, oldest first. */
145
+ private readonly subThrottle;
146
+ /** Users slowed down in the last minute (sub → expiry), to tell a per-user slow-down from a global one. */
147
+ private readonly slowedSubs;
148
+ private readonly counters;
149
+ private readonly loud;
150
+ private lastClientAuthFailureAt;
151
+ constructor(opts: TokenExchangerOptions);
152
+ get size(): number;
153
+ get negativeSize(): number;
154
+ /** Requests sent to the token endpoint, retries included. */
155
+ get exchanges(): number;
156
+ stats(): ExchangeStats;
157
+ /**
158
+ * An API token for this subject token: cached, or exchanged now.
159
+ * `subjectExpS` (the subject's `exp`) caps both caches. Throws
160
+ * ExchangeError; aborts with `signal` (the shared exchange keeps running
161
+ * for other waiters).
162
+ */
163
+ getApiToken(subjectToken: string, subjectExpS: number, signal?: AbortSignal, caller?: ExchangeCaller): Promise<string>;
164
+ /**
165
+ * Forget the cached API token of this subject after the API refused it
166
+ * (401 invalid_token) — only if it is still the one that was refused, so
167
+ * a fresher token another request just obtained survives.
168
+ */
169
+ invalidate(subjectToken: string, apiToken: string | undefined): void;
170
+ /** Local limits before a NEW exchange is started; throws a rate_limited ExchangeError. */
171
+ private admit;
172
+ private store;
173
+ private remember;
174
+ private exchange;
175
+ /** How long to hold back after the `consecutive`-th slow-down in a row: doubling, Retry-After as a floor. */
176
+ private holdMs;
177
+ /** Hold every new exchange back (a global slow-down). */
178
+ private backOff;
179
+ /**
180
+ * The token endpoint answered 429 / 503 `temporarily_unavailable`
181
+ * (+ Retry-After). Returns the seconds the caller must wait and whether it
182
+ * was global.
183
+ *
184
+ * The answer alone does not say whether it concerns one user or everyone.
185
+ * The rule: a slow-down is about THIS user — only their new
186
+ * exchanges wait, other users carry on — unless it is clearly global:
187
+ * - no user is known for the exchange;
188
+ * - it follows refused client authentication (that affects every user);
189
+ * - `slowDownGlobalAfterUsers` distinct users were slowed down within a
190
+ * minute.
191
+ * A global slow-down holds every new exchange back, then lets one probe go
192
+ * first (as before). Either way the answer is a 429 / 503, never a re-auth.
193
+ */
194
+ private slowDown;
195
+ private attempts;
196
+ }