lkpgestao-mcp 0.35.0 → 0.36.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.
package/README.md CHANGED
@@ -52,7 +52,7 @@ próprio token, e o servidor **recusa** subir com `LKP_API_TOKEN` definido.
52
52
 
53
53
  ## Instalação
54
54
 
55
- > ### A 0.34.x e a 0.35.x falam o contrato 5.0 — em produção desde a release v4.0.2 do backend (2026-11-11)
55
+ > ### A 0.34.x, a 0.35.x e a 0.36.x falam o contrato 5.0 — em produção desde a release v4.0.2 do backend (2026-11-11)
56
56
  >
57
57
  > Até a 0.33.0 a linha publicada seguia o contrato 4.8 de produção; da 0.34.0 em diante o pacote espera o **5.0**, que o PRD (`lkpgestao.linkupconsultoria.com`) e o DEV servem hoje. Apontar uma build nova para um backend defasado não derruba o servidor na configuração padrão — o check de contrato só registra um `warn` e as tools falham depois, sob demanda.
58
58
  >
package/dist/index.js CHANGED
@@ -192,7 +192,7 @@ async function checkContractVersion(client, logger, expected = EXPECTED_CONTRACT
192
192
 
193
193
  // src/config.ts
194
194
  var SERVER_NAME = "lkpgestao-mcp";
195
- var SERVER_VERSION = "0.35.0";
195
+ var SERVER_VERSION = "0.36.0";
196
196
  var ConfigSchema = z.object({
197
197
  LKP_API_BASE_URL: z.string().url("must be a valid URL").refine((u) => u.startsWith("https://"), {
198
198
  message: "must use https:// (TLS is mandatory)"
@@ -4613,16 +4613,54 @@ function registerAllPrompts(server) {
4613
4613
  }
4614
4614
 
4615
4615
  // src/http/start.ts
4616
- import { createHash as createHash2 } from "crypto";
4617
4616
  import { homedir } from "os";
4618
4617
  import { join as join2 } from "path";
4619
4618
 
4619
+ // src/http/lkp-access.ts
4620
+ import { createHash } from "crypto";
4621
+ var DEFAULT_MAX_CACHED = 500;
4622
+ function createLkpAccess(opts) {
4623
+ const max = opts.maxCached ?? DEFAULT_MAX_CACHED;
4624
+ const cache = /* @__PURE__ */ new Map();
4625
+ const make = (lkpToken) => new LkpClient({
4626
+ baseUrl: opts.baseUrl,
4627
+ token: lkpToken,
4628
+ timeoutMs: opts.timeoutMs,
4629
+ retryAttempts: opts.retryAttempts,
4630
+ userAgent: opts.userAgent,
4631
+ logger: opts.logger
4632
+ });
4633
+ return {
4634
+ clientFor(lkpToken) {
4635
+ const k = createHash("sha256").update(lkpToken).digest("hex");
4636
+ let c = cache.get(k);
4637
+ if (c) {
4638
+ cache.delete(k);
4639
+ cache.set(k, c);
4640
+ return c;
4641
+ }
4642
+ c = make(lkpToken);
4643
+ cache.set(k, c);
4644
+ if (cache.size > max) {
4645
+ const oldest = cache.keys().next().value;
4646
+ if (oldest !== void 0) cache.delete(oldest);
4647
+ }
4648
+ return c;
4649
+ },
4650
+ async validateToken(lkpToken) {
4651
+ const raw = await make(lkpToken).get("/api/v1/ping");
4652
+ return raw?.data?.user ?? {};
4653
+ },
4654
+ cachedCount: () => cache.size
4655
+ };
4656
+ }
4657
+
4620
4658
  // src/http/seal.ts
4621
- import { createCipheriv, createDecipheriv, createHash, randomBytes } from "crypto";
4659
+ import { createCipheriv, createDecipheriv, createHash as createHash2, randomBytes } from "crypto";
4622
4660
  var IV_BYTES = 12;
4623
4661
  var TAG_BYTES = 16;
4624
4662
  function deriveKey(secret) {
4625
- return createHash("sha256").update(secret, "utf8").digest();
4663
+ return createHash2("sha256").update(secret, "utf8").digest();
4626
4664
  }
4627
4665
  function seal(key, claims) {
4628
4666
  const iv = randomBytes(IV_BYTES);
@@ -4666,6 +4704,7 @@ function unseal(key, token, expected, nowSeconds = Math.floor(Date.now() / 1e3))
4666
4704
 
4667
4705
  // src/http/server.ts
4668
4706
  import express from "express";
4707
+ import { rateLimit as expressRateLimit } from "express-rate-limit";
4669
4708
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4670
4709
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
4671
4710
  import { authorizationHandler } from "@modelcontextprotocol/sdk/server/auth/handlers/authorize.js";
@@ -4682,12 +4721,17 @@ import {
4682
4721
  InvalidClientMetadataError,
4683
4722
  InvalidGrantError,
4684
4723
  InvalidTargetError,
4685
- InvalidTokenError
4724
+ InvalidTokenError,
4725
+ ServerError
4686
4726
  } from "@modelcontextprotocol/sdk/server/auth/errors.js";
4687
4727
  var ACCESS_TTL_SECONDS = 60 * 60;
4688
4728
  var REFRESH_TTL_SECONDS = 30 * 24 * 60 * 60;
4689
4729
  var CODE_TTL_MS = 5 * 60 * 1e3;
4690
4730
  var PENDING_TTL_MS = 15 * 60 * 1e3;
4731
+ var MAX_CONSENT_ATTEMPTS = 5;
4732
+ function isCredentialRejection(e) {
4733
+ return e instanceof LkpError && (e.code === "auth_failed" || e.code === "permission_denied");
4734
+ }
4691
4735
  var DEFAULT_ALLOWED_REDIRECTS = [
4692
4736
  "https://claude.ai/api/mcp/auth_callback",
4693
4737
  "https://claude.com/api/mcp/auth_callback"
@@ -4708,7 +4752,7 @@ var FileClientsStore = class {
4708
4752
  this.allowedRedirects = allowedRedirects;
4709
4753
  if (path && existsSync(path)) {
4710
4754
  const raw = JSON.parse(readFileSync(path, "utf8"));
4711
- for (const c of raw) this.clients.set(c.client_id, c);
4755
+ for (const c of raw) this.clients.set(c.client_id, { ...c, client_secret_expires_at: 0 });
4712
4756
  }
4713
4757
  }
4714
4758
  path;
@@ -4776,7 +4820,8 @@ var TokenPasteProvider = class {
4776
4820
  this.pending.set(requestId, {
4777
4821
  client,
4778
4822
  params,
4779
- expiresAt: this.now() + PENDING_TTL_MS
4823
+ expiresAt: this.now() + PENDING_TTL_MS,
4824
+ attempts: 0
4780
4825
  });
4781
4826
  sendConsentPage(res, {
4782
4827
  requestId,
@@ -4821,8 +4866,10 @@ var TokenPasteProvider = class {
4821
4866
  try {
4822
4867
  user = await this.opts.validateToken(lkpToken);
4823
4868
  } catch (e) {
4869
+ pending.attempts += 1;
4870
+ if (pending.attempts >= MAX_CONSENT_ATTEMPTS) this.pending.delete(requestId);
4824
4871
  this.opts.logger.warn(
4825
- { client_id: client.client_id, err: e.message },
4872
+ { client_id: client.client_id, err: e.message, attempts: pending.attempts },
4826
4873
  "oauth_consent_token_rejected"
4827
4874
  );
4828
4875
  sendConsentPage(res, {
@@ -4887,8 +4934,15 @@ var TokenPasteProvider = class {
4887
4934
  let user;
4888
4935
  try {
4889
4936
  user = await this.opts.validateToken(claims.lkp);
4890
- } catch {
4891
- throw new InvalidGrantError("the LKPGest\xE3o API token behind this grant is no longer valid");
4937
+ } catch (e) {
4938
+ if (isCredentialRejection(e)) {
4939
+ throw new InvalidGrantError("the LKPGest\xE3o API token behind this grant is no longer valid");
4940
+ }
4941
+ this.opts.logger.warn(
4942
+ { client_id: client.client_id, err: e.message },
4943
+ "oauth_refresh_backend_unavailable"
4944
+ );
4945
+ throw new ServerError("LKPGest\xE3o is temporarily unavailable; retry the refresh");
4892
4946
  }
4893
4947
  return this.issue(client.client_id, claims.lkp, user.id);
4894
4948
  }
@@ -5027,7 +5081,18 @@ function createHttpApp(opts) {
5027
5081
  logger: opts.logger,
5028
5082
  onFirstValidToken: opts.onFirstValidToken
5029
5083
  });
5030
- const rateLimit = opts.disableRateLimit ? { rateLimit: false } : {};
5084
+ const limits = opts.disableRateLimit ? { authorize: false, token: false, register: false } : {
5085
+ authorize: void 0,
5086
+ token: { windowMs: 15 * 60 * 1e3, max: 2e3 },
5087
+ register: { windowMs: 60 * 60 * 1e3, max: 500 }
5088
+ };
5089
+ const consentLimiter = opts.disableRateLimit ? (_req, _res, next) => next() : expressRateLimit({
5090
+ windowMs: 15 * 60 * 1e3,
5091
+ limit: 20,
5092
+ standardHeaders: true,
5093
+ legacyHeaders: false,
5094
+ message: "Muitas tentativas. Aguarde alguns minutos e tente de novo."
5095
+ });
5031
5096
  const app = express();
5032
5097
  app.set("trust proxy", 1);
5033
5098
  app.disable("x-powered-by");
@@ -5049,11 +5114,21 @@ function createHttpApp(opts) {
5049
5114
  };
5050
5115
  for (const p of [r.asm.pathname, ...r.asmAliases]) app.use(p, metadataHandler(asMetadata));
5051
5116
  for (const p of [r.prm.pathname, ...r.prmAliases]) app.use(p, metadataHandler(prMetadata));
5052
- app.use(r.authorize.pathname, authorizationHandler({ provider, ...rateLimit }));
5053
- app.use(r.token.pathname, tokenHandler({ provider, ...rateLimit }));
5054
- app.use(r.register.pathname, clientRegistrationHandler({ clientsStore, ...rateLimit }));
5117
+ app.use(r.authorize.pathname, authorizationHandler({ provider, rateLimit: limits.authorize }));
5118
+ app.use(r.token.pathname, tokenHandler({ provider, rateLimit: limits.token }));
5119
+ app.use(
5120
+ r.register.pathname,
5121
+ clientRegistrationHandler({
5122
+ clientsStore,
5123
+ rateLimit: limits.register,
5124
+ // Segredo de cliente sem vencimento (o padrão do SDK é 30 dias): vencido,
5125
+ // todo refresh daria invalid_client e desconectaria todo mundo de uma vez.
5126
+ clientSecretExpirySeconds: 0
5127
+ })
5128
+ );
5055
5129
  app.post(
5056
5130
  r.consent.pathname,
5131
+ consentLimiter,
5057
5132
  express.urlencoded({ extended: false, limit: "16kb" }),
5058
5133
  (req, res) => {
5059
5134
  provider.handleConsent(req.body ?? {}, res).catch((e) => {
@@ -5136,43 +5211,19 @@ function listen(app, host, port) {
5136
5211
  }
5137
5212
 
5138
5213
  // src/http/start.ts
5139
- var MAX_CACHED_CLIENTS = 500;
5140
5214
  async function startHttp(config, logger) {
5141
5215
  if (!config.LKP_PUBLIC_URL || !config.LKP_HTTP_SECRET) {
5142
5216
  throw new Error("LKP_PUBLIC_URL and LKP_HTTP_SECRET are required for the http transport");
5143
5217
  }
5144
5218
  const publicUrl = new URL(config.LKP_PUBLIC_URL);
5145
5219
  const dataDir = config.LKP_HTTP_DATA_DIR ?? join2(homedir(), ".local", "state", "lkpgestao-mcp");
5146
- const clients = /* @__PURE__ */ new Map();
5147
- const clientFor = (lkpToken) => {
5148
- const k = createHash2("sha256").update(lkpToken).digest("hex");
5149
- let c = clients.get(k);
5150
- if (c) {
5151
- clients.delete(k);
5152
- clients.set(k, c);
5153
- return c;
5154
- }
5155
- c = new LkpClient({
5156
- baseUrl: config.LKP_API_BASE_URL,
5157
- token: lkpToken,
5158
- timeoutMs: config.LKP_REQUEST_TIMEOUT_MS,
5159
- retryAttempts: config.LKP_RETRY_ATTEMPTS,
5160
- userAgent: `${SERVER_NAME}/${SERVER_VERSION} (+node ${process.version}; http)`,
5161
- logger
5162
- });
5163
- clients.set(k, c);
5164
- if (clients.size > MAX_CACHED_CLIENTS) {
5165
- const oldest = clients.keys().next().value;
5166
- if (oldest !== void 0) clients.delete(oldest);
5167
- }
5168
- return c;
5169
- };
5170
- const validateToken = async (lkpToken) => {
5171
- const raw = await clientFor(lkpToken).get(
5172
- "/api/v1/ping"
5173
- );
5174
- return raw?.data?.user ?? {};
5175
- };
5220
+ const { clientFor, validateToken } = createLkpAccess({
5221
+ baseUrl: config.LKP_API_BASE_URL,
5222
+ timeoutMs: config.LKP_REQUEST_TIMEOUT_MS,
5223
+ retryAttempts: config.LKP_RETRY_ATTEMPTS,
5224
+ userAgent: `${SERVER_NAME}/${SERVER_VERSION} (+node ${process.version}; http)`,
5225
+ logger
5226
+ });
5176
5227
  let contractChecked = false;
5177
5228
  const onFirstValidToken = (lkpToken) => {
5178
5229
  if (contractChecked) return;