inistate-mcp 1.3.2 → 1.3.3

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,3 @@
1
+ import { type Express } from "express";
2
+ import { type InistateOAuthProvider } from "./oauth-provider.js";
3
+ export declare function registerAppAuthorizeRoutes(app: Express, provider: InistateOAuthProvider, issuerUrl: string): void;
@@ -0,0 +1,90 @@
1
+ import express from "express";
2
+ import { browserSecretCookieName, browserSecretCookieOptions, readCookie, } from "./oauth-provider.js";
3
+ /**
4
+ * SS06370: the Inistate App approves a flow natively (no cookie), then hands the user to the
5
+ * browser that started it. See ParkedApproval in oauth-provider.ts for why both the cookie and
6
+ * the finish token are required.
7
+ *
8
+ * POST /authorize/app-callback the App: nonce, jwt, refreshToken -> 302 to /authorize/finish
9
+ * GET /authorize/finish the browser: confirmation page (cookie + token)
10
+ * POST /authorize/finish the browser: Confirm -> 302 to the client with the code
11
+ */
12
+ const escapeHtml = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
13
+ function page(res, status, title, body) {
14
+ res
15
+ .status(status)
16
+ .set({
17
+ "Content-Type": "text/html; charset=utf-8",
18
+ "Cache-Control": "no-store",
19
+ "Referrer-Policy": "no-referrer",
20
+ // The Confirm button must not be clickjackable from another origin.
21
+ "X-Frame-Options": "DENY",
22
+ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'",
23
+ })
24
+ .send(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">` +
25
+ `<title>${escapeHtml(title)}</title><style>body{font:16px system-ui,sans-serif;max-width:28rem;margin:3rem auto;padding:0 1rem}` +
26
+ `button{font:inherit;padding:.6rem 1.2rem}</style></head><body>${body}</body></html>`);
27
+ }
28
+ function failure(res, error) {
29
+ const message = error instanceof Error ? error.message : "Authorization failed";
30
+ if (/does not belong to this browser|Invalid finish token/.test(message)) {
31
+ page(res, 400, "Open this link in the original browser", `<h1>Open this link in the original browser</h1><p>Finish connecting in the same browser where you started from ChatGPT or Claude, then try again.</p>`);
32
+ return;
33
+ }
34
+ res.status(400).type("text/plain").send(message);
35
+ }
36
+ export function registerAppAuthorizeRoutes(app, provider, issuerUrl) {
37
+ const secure = issuerUrl.startsWith("https:");
38
+ const base = issuerUrl.replace(/\/$/, "");
39
+ app.post("/authorize/app-callback", express.urlencoded({ extended: false }), async (req, res) => {
40
+ try {
41
+ const { nonce, jwt, refreshToken } = req.body ?? {};
42
+ if (!nonce || !jwt) {
43
+ res.status(400).send("Missing nonce or jwt");
44
+ return;
45
+ }
46
+ const { finishToken } = await provider.parkAppApproval(String(nonce), String(jwt), refreshToken ? String(refreshToken) : undefined);
47
+ const finish = new URL(`${base}/authorize/finish`);
48
+ finish.searchParams.set("nonce", String(nonce));
49
+ finish.searchParams.set("token", finishToken);
50
+ res.redirect(302, finish.toString());
51
+ }
52
+ catch (error) {
53
+ console.error("App authorize callback error:", error);
54
+ const message = error instanceof Error ? error.message : "Authorization failed";
55
+ // The App maps a 401 to "sign in again" and the exact nonce message to "expired or used".
56
+ res.status(/^Bearer token is invalid/.test(message) ? 401 : 400).send(message);
57
+ }
58
+ });
59
+ app.get("/authorize/finish", (req, res) => {
60
+ try {
61
+ const nonce = String(req.query.nonce ?? "");
62
+ const token = String(req.query.token ?? "");
63
+ const cookie = readCookie(req.headers.cookie, browserSecretCookieName(nonce));
64
+ const info = provider.getFinishInfo(nonce, token, cookie);
65
+ page(res, 200, "Confirm connection", `<h1>Connect ${escapeHtml(info.clientName || "this app")}?</h1>` +
66
+ `<p>It will act as <strong>${escapeHtml(info.account)}</strong> in Inistate.</p>` +
67
+ `<p>Only continue if you just started this from ChatGPT or Claude.</p>` +
68
+ `<form method="post" action="/authorize/finish">` +
69
+ `<input type="hidden" name="nonce" value="${escapeHtml(nonce)}">` +
70
+ `<input type="hidden" name="token" value="${escapeHtml(token)}">` +
71
+ `<button type="submit">Confirm</button></form>`);
72
+ }
73
+ catch (error) {
74
+ failure(res, error);
75
+ }
76
+ });
77
+ app.post("/authorize/finish", express.urlencoded({ extended: false }), (req, res) => {
78
+ try {
79
+ const nonce = String(req.body?.nonce ?? "");
80
+ const token = String(req.body?.token ?? "");
81
+ const cookieName = browserSecretCookieName(nonce);
82
+ const { redirectUrl } = provider.completeParkedAuthorization(nonce, token, readCookie(req.headers.cookie, cookieName));
83
+ res.clearCookie(cookieName, { path: browserSecretCookieOptions(secure).path });
84
+ res.redirect(302, redirectUrl);
85
+ }
86
+ catch (error) {
87
+ failure(res, error);
88
+ }
89
+ });
90
+ }
package/build/http.js CHANGED
@@ -11,6 +11,7 @@ import { createServer } from "./server.js";
11
11
  import { requestContext } from "./context.js";
12
12
  import { InistateOAuthProvider, decodeJwtSub, isConnectionToken, connectionModeKey, browserSecretCookieName, browserSecretCookieOptions, readCookie, SUPPORTED_SCOPES, } from "./oauth-provider.js";
13
13
  import { getUserMode } from "./mode-store.js";
14
+ import { registerAppAuthorizeRoutes } from "./authorize-app-routes.js";
14
15
  const PORT = parseInt(process.env.PORT || "3000", 10);
15
16
  const BASE_URL = process.env.INISTATE_API_BASE ||
16
17
  process.env.INISTATE_API_URL ||
@@ -82,6 +83,8 @@ app.post("/authorize/callback", express.urlencoded({ extended: false }), (req, r
82
83
  res.status(400).send(error instanceof Error ? error.message : "Authorization failed");
83
84
  }
84
85
  });
86
+ // SS06370: the Inistate App approves natively (no cookie); the originating browser finishes.
87
+ registerAppAuthorizeRoutes(app, oauthProvider, ISSUER_URL);
85
88
  /* ------------------------------------------------------------------ */
86
89
  /* Health check */
87
90
  /* ------------------------------------------------------------------ */
@@ -82,6 +82,26 @@ export declare class InistateOAuthProvider implements OAuthServerProvider {
82
82
  completeAuthorization(nonce: string, jwt: string, refreshToken?: string, browserSecret?: string): {
83
83
  redirectUrl: string;
84
84
  };
85
+ private issueCode;
86
+ /**
87
+ * SS06370: the Inistate App approves a flow it did not start. No cookie is needed (it has
88
+ * none); the approval is parked and the one-time token returned goes back to the App only.
89
+ * The JWT is checked against the backend first so the finish page can name a real account.
90
+ */
91
+ parkAppApproval(nonce: string, jwt: string, refreshToken?: string): Promise<{
92
+ finishToken: string;
93
+ }>;
94
+ /** What the finish page shows before the user confirms. Needs the cookie and the token. */
95
+ getFinishInfo(nonce: string, finishToken: string, browserSecret?: string): {
96
+ clientName: string;
97
+ account: string;
98
+ };
99
+ /** Finish an App-approved flow: the originating browser (cookie) plus the App's token. */
100
+ completeParkedAuthorization(nonce: string, finishToken: string, browserSecret?: string): {
101
+ redirectUrl: string;
102
+ };
103
+ private livePending;
104
+ private finishablePending;
85
105
  challengeForAuthorizationCode(_client: OAuthClientInformationFull, authorizationCode: string): Promise<string>;
86
106
  exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string): Promise<OAuthTokens>;
87
107
  /**
@@ -1,4 +1,4 @@
1
- import { createHash, randomUUID } from "node:crypto";
1
+ import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
2
2
  import { FileClientsStore } from "./client-store.js";
3
3
  import { InvalidGrantError, TemporarilyUnavailableError } from "@modelcontextprotocol/sdk/server/auth/errors.js";
4
4
  const CODE_TTL_MS = 5 * 60 * 1000; // 5 minutes
@@ -133,6 +133,12 @@ function expiresInFromExp(exp) {
133
133
  export function browserSecretCookieName(nonce) {
134
134
  return `mcp_auth_${nonce}`;
135
135
  }
136
+ /** Constant-time string comparison for secrets. */
137
+ function safeEqual(a, b) {
138
+ const x = Buffer.from(a);
139
+ const y = Buffer.from(b);
140
+ return x.length === y.length && timingSafeEqual(x, y);
141
+ }
136
142
  /** The value of one cookie out of a raw Cookie header, or undefined. */
137
143
  export function readCookie(header, name) {
138
144
  if (!header)
@@ -198,6 +204,7 @@ export class InistateOAuthProvider {
198
204
  const browserSecret = randomUUID();
199
205
  this.pendingAuth.set(nonce, {
200
206
  clientId: client.client_id,
207
+ clientName: client.client_name,
201
208
  params,
202
209
  createdAt: Date.now(),
203
210
  browserSecret,
@@ -249,6 +256,9 @@ export class InistateOAuthProvider {
249
256
  throw new Error("Authorization session does not belong to this browser");
250
257
  }
251
258
  this.pendingAuth.delete(nonce);
259
+ return this.issueCode(pending, jwt, refreshToken);
260
+ }
261
+ issueCode(pending, jwt, refreshToken) {
252
262
  const code = randomUUID();
253
263
  this.codes.set(code, {
254
264
  codeChallenge: pending.params.codeChallenge,
@@ -266,6 +276,62 @@ export class InistateOAuthProvider {
266
276
  url.searchParams.set("state", pending.params.state);
267
277
  return { redirectUrl: url.toString() };
268
278
  }
279
+ /**
280
+ * SS06370: the Inistate App approves a flow it did not start. No cookie is needed (it has
281
+ * none); the approval is parked and the one-time token returned goes back to the App only.
282
+ * The JWT is checked against the backend first so the finish page can name a real account.
283
+ */
284
+ async parkAppApproval(nonce, jwt, refreshToken) {
285
+ const pending = this.livePending(nonce);
286
+ if (pending.parked)
287
+ throw new Error("This authorization was already approved");
288
+ const res = await fetch(`${this.baseUrl}/v1/whoami`, {
289
+ headers: { Authorization: `Bearer ${jwt}`, Accept: "application/json" },
290
+ });
291
+ if (!res.ok)
292
+ throw new Error("Bearer token is invalid or expired");
293
+ const who = (await res.json().catch(() => ({})));
294
+ const account = String(who.userName || who.userId || "your Inistate account");
295
+ // The whoami round trip is a window: re-check, the first approval wins.
296
+ const current = this.livePending(nonce);
297
+ if (current.parked)
298
+ throw new Error("This authorization was already approved");
299
+ const finishToken = randomUUID();
300
+ current.parked = { jwt, refreshToken, finishToken, account };
301
+ return { finishToken };
302
+ }
303
+ /** What the finish page shows before the user confirms. Needs the cookie and the token. */
304
+ getFinishInfo(nonce, finishToken, browserSecret) {
305
+ const pending = this.finishablePending(nonce, finishToken, browserSecret);
306
+ return { clientName: pending.clientName, account: pending.parked.account };
307
+ }
308
+ /** Finish an App-approved flow: the originating browser (cookie) plus the App's token. */
309
+ completeParkedAuthorization(nonce, finishToken, browserSecret) {
310
+ const pending = this.finishablePending(nonce, finishToken, browserSecret);
311
+ this.pendingAuth.delete(nonce);
312
+ return this.issueCode(pending, pending.parked.jwt, pending.parked.refreshToken);
313
+ }
314
+ livePending(nonce) {
315
+ const pending = this.pendingAuth.get(nonce);
316
+ if (!pending)
317
+ throw new Error("Invalid or expired authorization nonce");
318
+ if (Date.now() - pending.createdAt > CODE_TTL_MS) {
319
+ this.pendingAuth.delete(nonce);
320
+ throw new Error("Authorization session expired");
321
+ }
322
+ return pending;
323
+ }
324
+ finishablePending(nonce, finishToken, browserSecret) {
325
+ const pending = this.livePending(nonce);
326
+ if (!browserSecret || browserSecret !== pending.browserSecret) {
327
+ throw new Error("Authorization session does not belong to this browser");
328
+ }
329
+ const parked = pending.parked;
330
+ if (!parked || !finishToken || !safeEqual(finishToken, parked.finishToken)) {
331
+ throw new Error("Invalid finish token");
332
+ }
333
+ return { ...pending, parked, clientName: pending.clientName ?? "" };
334
+ }
269
335
  /* ---- PKCE ---- */
270
336
  async challengeForAuthorizationCode(_client, authorizationCode) {
271
337
  const stored = this.codes.get(authorizationCode);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "inistate-mcp",
3
3
  "mcpName": "io.github.Inistate/inistate-mcp",
4
- "version": "1.3.2",
4
+ "version": "1.3.3",
5
5
  "description": "MCP server for the Inistate platform — no-code apps creation powered by AI",
6
6
  "type": "module",
7
7
  "author": "Inistate",
package/server.json CHANGED
@@ -8,13 +8,13 @@
8
8
  "url": "https://github.com/inistate/inistate-mcp",
9
9
  "source": "github"
10
10
  },
11
- "version": "1.3.2",
11
+ "version": "1.3.3",
12
12
  "packages": [
13
13
  {
14
14
  "registryType": "npm",
15
15
  "registryBaseUrl": "https://registry.npmjs.org",
16
16
  "identifier": "inistate-mcp",
17
- "version": "1.3.2",
17
+ "version": "1.3.3",
18
18
  "transport": {
19
19
  "type": "stdio"
20
20
  },