hmcp-gateway 0.0.2 → 0.1.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.
Files changed (102) hide show
  1. package/LICENSE +77 -0
  2. package/README.md +41 -9
  3. package/bin/hmcp-gateway.js +20 -0
  4. package/catalog/atlassian.yaml +41 -0
  5. package/catalog/brave-search.yaml +57 -0
  6. package/catalog/context7.yaml +42 -0
  7. package/catalog/fetch.yaml +37 -0
  8. package/catalog/figma.yaml +48 -0
  9. package/catalog/filesystem.yaml +48 -0
  10. package/catalog/git.yaml +48 -0
  11. package/catalog/github.yaml +103 -0
  12. package/catalog/huggingface.yaml +59 -0
  13. package/catalog/linear.yaml +47 -0
  14. package/catalog/memory.yaml +47 -0
  15. package/catalog/notion.yaml +41 -0
  16. package/catalog/playwright.yaml +38 -0
  17. package/catalog/postgres.yaml +66 -0
  18. package/catalog/sentry.yaml +39 -0
  19. package/catalog/sequential-thinking.yaml +29 -0
  20. package/catalog/stripe.yaml +41 -0
  21. package/catalog/supabase.yaml +45 -0
  22. package/catalog/time.yaml +49 -0
  23. package/dist/adopt-cli.d.ts +351 -0
  24. package/dist/adopt-cli.js +1857 -0
  25. package/dist/adopt-emit.d.ts +64 -0
  26. package/dist/adopt-emit.js +248 -0
  27. package/dist/adopt-plan.d.ts +108 -0
  28. package/dist/adopt-plan.js +386 -0
  29. package/dist/catalog.d.ts +140 -0
  30. package/dist/catalog.js +250 -0
  31. package/dist/classify.d.ts +23 -0
  32. package/dist/classify.js +47 -0
  33. package/dist/cli.d.ts +2 -0
  34. package/dist/cli.js +535 -0
  35. package/dist/client-allow.d.ts +42 -0
  36. package/dist/client-allow.js +95 -0
  37. package/dist/client-config.d.ts +200 -0
  38. package/dist/client-config.js +784 -0
  39. package/dist/config-source.d.ts +106 -0
  40. package/dist/config-source.js +156 -0
  41. package/dist/config.d.ts +159 -0
  42. package/dist/config.js +330 -0
  43. package/dist/connect-client.d.ts +49 -0
  44. package/dist/connect-client.js +249 -0
  45. package/dist/contracts.d.ts +251 -0
  46. package/dist/contracts.js +9 -0
  47. package/dist/credential.d.ts +63 -0
  48. package/dist/credential.js +136 -0
  49. package/dist/draft.d.ts +71 -0
  50. package/dist/draft.js +596 -0
  51. package/dist/exposure-cli.d.ts +28 -0
  52. package/dist/exposure-cli.js +119 -0
  53. package/dist/gateway.d.ts +756 -0
  54. package/dist/gateway.js +2106 -0
  55. package/dist/index.d.ts +26 -0
  56. package/dist/index.js +26 -0
  57. package/dist/notify.d.ts +44 -0
  58. package/dist/notify.js +93 -0
  59. package/dist/oauth.d.ts +139 -0
  60. package/dist/oauth.js +641 -0
  61. package/dist/observe.d.ts +10 -0
  62. package/dist/observe.js +26 -0
  63. package/dist/open.d.ts +24 -0
  64. package/dist/open.js +31 -0
  65. package/dist/packs.d.ts +119 -0
  66. package/dist/packs.js +131 -0
  67. package/dist/pin-cli.d.ts +28 -0
  68. package/dist/pin-cli.js +103 -0
  69. package/dist/probe-upstream.d.ts +31 -0
  70. package/dist/probe-upstream.js +377 -0
  71. package/dist/registry-map.d.ts +39 -0
  72. package/dist/registry-map.js +390 -0
  73. package/dist/rule-cli.d.ts +51 -0
  74. package/dist/rule-cli.js +412 -0
  75. package/dist/serve-http.d.ts +67 -0
  76. package/dist/serve-http.js +478 -0
  77. package/dist/snippet.d.ts +20 -0
  78. package/dist/snippet.js +826 -0
  79. package/dist/status-cli.d.ts +61 -0
  80. package/dist/status-cli.js +195 -0
  81. package/dist/suggest-cli.d.ts +43 -0
  82. package/dist/suggest-cli.js +279 -0
  83. package/dist/toolname.d.ts +47 -0
  84. package/dist/toolname.js +149 -0
  85. package/dist/upstream-errors.d.ts +54 -0
  86. package/dist/upstream-errors.js +330 -0
  87. package/dist/upstream.d.ts +128 -0
  88. package/dist/upstream.js +413 -0
  89. package/dist/version.d.ts +10 -0
  90. package/dist/version.js +11 -0
  91. package/package.json +50 -6
  92. package/packs/brave-search.yaml +20 -0
  93. package/packs/context7.yaml +13 -0
  94. package/packs/fetch.yaml +14 -0
  95. package/packs/filesystem.yaml +79 -0
  96. package/packs/git.yaml +29 -0
  97. package/packs/github.yaml +47 -0
  98. package/packs/huggingface.yaml +16 -0
  99. package/packs/memory.yaml +23 -0
  100. package/packs/playwright.yaml +41 -0
  101. package/packs/sequential-thinking.yaml +13 -0
  102. package/packs/time.yaml +14 -0
package/dist/oauth.js ADDED
@@ -0,0 +1,641 @@
1
+ /**
2
+ * Signing in to remote MCP servers (OAuth 2.1 + PKCE + dynamic client
3
+ * registration, per the MCP authorization spec). CONTRACT (phase 0);
4
+ * implemented by workstream C, on the SDK's client/auth functions with a
5
+ * fetch that goes through the egress guard.
6
+ *
7
+ * The protocol itself is the SDK's: discovery, registration, the PKCE
8
+ * challenge, the code exchange and refresh are its functions, called one at a
9
+ * time. What is ours is everything around them -- the network path (every
10
+ * request through an EgressGuard, redirects refused), where the result is kept
11
+ * (the locked-keys file, never memory alone, because several gateway
12
+ * processes share one sign-in) and what happens when refresh races another
13
+ * process or the provider withdraws the sign-in.
14
+ *
15
+ * The SDK's stateful `auth()`/`OAuthClientProvider` is deliberately not used:
16
+ * it wants to own storage and redirection, and here storage is a file other
17
+ * processes rewrite and redirection is a browser tab the console opens.
18
+ */
19
+ import { randomBytes } from "node:crypto";
20
+ import { discoverAuthorizationServerMetadata, discoverOAuthProtectedResourceMetadata, exchangeAuthorization, extractWWWAuthenticateParams, refreshAuthorization, registerClient, startAuthorization } from "@modelcontextprotocol/sdk/client/auth.js";
21
+ import { checkResourceAllowed, resourceUrlFromServerUrl } from "@modelcontextprotocol/sdk/shared/auth-utils.js";
22
+ import { OAuthError } from "@modelcontextprotocol/sdk/server/auth/errors.js";
23
+ import { EgressDenied, EgressGuard, classifyAddress, isIpLiteral, withFileLockAsync } from "hmcp-core";
24
+ import { NeedsSignIn } from "./contracts.js";
25
+ export class NoDynamicRegistration extends Error {
26
+ authorizationServer;
27
+ constructor(authorizationServer) {
28
+ super(`${authorizationServer} does not let apps register themselves; an app ID from the provider is needed`);
29
+ this.authorizationServer = authorizationServer;
30
+ this.name = "NoDynamicRegistration";
31
+ }
32
+ }
33
+ export class SignInProblem extends Error {
34
+ code;
35
+ oauthError;
36
+ detail;
37
+ /**
38
+ * `message` is the plain sentence a person reads. `detail` carries the
39
+ * technical reason (a library's own words, the address refused) for
40
+ * support; it is never shown as the main text.
41
+ */
42
+ constructor(code, message, oauthError, detail) {
43
+ super(message);
44
+ this.code = code;
45
+ this.oauthError = oauthError;
46
+ this.detail = detail;
47
+ this.name = "SignInProblem";
48
+ }
49
+ }
50
+ /** Statuses a Response may not be constructed with a body for. */
51
+ const NULL_BODY = new Set([101, 204, 205, 304]);
52
+ /**
53
+ * A fetch for the SDK's auth helpers that goes through `guard` and refuses redirects.
54
+ *
55
+ * The SDK calls fetch with `Headers` objects and `URLSearchParams` bodies; the
56
+ * guard takes plain records and strings, so both are converted here, and a
57
+ * form body gets its content type if the caller did not set one.
58
+ *
59
+ * Redirects are refused outright, whatever the guard's own `max_redirects`
60
+ * says: a token endpoint that answers with a redirect is asking for the code
61
+ * or refresh token to be re-sent somewhere else, and nothing in OAuth needs a
62
+ * back-channel request to follow one.
63
+ */
64
+ export function egressFetchLike(guard) {
65
+ return async (url, init) => {
66
+ const target = typeof url === "string" ? url : url.href;
67
+ const method = (init?.method ?? "GET").toUpperCase();
68
+ const headers = {};
69
+ new Headers(init?.headers ?? undefined).forEach((value, key) => {
70
+ headers[key] = value;
71
+ });
72
+ let body;
73
+ const raw = init?.body;
74
+ if (raw === undefined || raw === null)
75
+ body = undefined;
76
+ else if (raw instanceof URLSearchParams) {
77
+ body = raw.toString();
78
+ headers["content-type"] ??= "application/x-www-form-urlencoded";
79
+ }
80
+ else if (typeof raw === "string")
81
+ body = raw;
82
+ else if (raw instanceof ArrayBuffer)
83
+ body = Buffer.from(raw);
84
+ else if (ArrayBuffer.isView(raw))
85
+ body = Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength);
86
+ else
87
+ throw new TypeError("egressFetchLike: unsupported request body type");
88
+ // Read the config at call time: the guard may have been reconfigured live.
89
+ const noRedirects = guard.config.max_redirects === 0 ? guard : new EgressGuard({ ...guard.config, max_redirects: 0 });
90
+ try {
91
+ const res = await noRedirects.fetch(target, {
92
+ method,
93
+ headers,
94
+ ...(body !== undefined ? { body } : {}),
95
+ ...(init?.signal ? { signal: init.signal } : {})
96
+ });
97
+ const out = new Headers();
98
+ for (const [key, value] of Object.entries(res.headers)) {
99
+ if (value === undefined)
100
+ continue;
101
+ for (const v of Array.isArray(value) ? value : [value])
102
+ out.append(key, v);
103
+ }
104
+ return new Response(NULL_BODY.has(res.status) ? null : new Uint8Array(res.body), { status: res.status, headers: out });
105
+ }
106
+ finally {
107
+ if (noRedirects !== guard)
108
+ await noRedirects.close();
109
+ }
110
+ };
111
+ }
112
+ /* ---------------------------------------------------------------- discovery */
113
+ const sameIssuer = (a, b) => a.replace(/\/$/, "") === b.replace(/\/$/, "");
114
+ const isLoopbackHost = (host) => host === "127.0.0.1" || host === "localhost" || host === "[::1]" || host === "::1";
115
+ /**
116
+ * An endpoint the browser will be sent to, or the gateway will talk to, must
117
+ * be https. Plain http is tolerated only on this computer, which is where the
118
+ * test fixtures live; the egress guard separately refuses http unless told.
119
+ */
120
+ function assertWebUrl(value, what) {
121
+ let url;
122
+ try {
123
+ url = new URL(value);
124
+ }
125
+ catch {
126
+ throw new SignInProblem("unsafe", `The server's ${what} is not a web address.`);
127
+ }
128
+ if (url.protocol === "https:")
129
+ return url;
130
+ if (url.protocol === "http:" && isLoopbackHost(url.hostname))
131
+ return url;
132
+ throw new SignInProblem("unsafe", `The server's ${what} is not a secure (https) address, so it was not used.`);
133
+ }
134
+ const bareHost = (hostname) => hostname.replace(/^\[|\]$/g, "").toLowerCase();
135
+ const isLoopbackLiteral = (ip) => /^127\./.test(ip) || ip === "::1" || /^::ffff:127\./i.test(ip);
136
+ /** Whether a URL's host is this computer, by its spelling (no lookup). */
137
+ function onThisComputer(url) {
138
+ const host = bareHost(url.hostname);
139
+ return host === "localhost" || (isIpLiteral(host) && isLoopbackLiteral(host));
140
+ }
141
+ /**
142
+ * The rule every discovered address is held to, whatever the caller adds:
143
+ * never an address on a private or link-local network (10.x, 192.168.x,
144
+ * 169.254.x -- where a cloud's metadata service lives -- fd00::/8, ...), and
145
+ * an address on this computer only when the server itself is on this
146
+ * computer, so a server on the internet can't point the console at a local
147
+ * service. Names are resolved and checked again by the guard when contacted.
148
+ */
149
+ async function assertSafeAddress(value, what, server, options) {
150
+ const url = assertWebUrl(value, what);
151
+ const host = bareHost(url.hostname);
152
+ if (onThisComputer(url)) {
153
+ if (!onThisComputer(server)) {
154
+ throw new SignInProblem("unsafe", `The server's ${what} points at this computer, which a server on the internet must not do. The sign-in was stopped.`, undefined, `${what}: ${url.host} is on this computer, and the server (${server.host}) is not`);
155
+ }
156
+ }
157
+ else if (isIpLiteral(host)) {
158
+ const verdict = classifyAddress(host);
159
+ if (verdict.blocked) {
160
+ throw new SignInProblem("unsafe", `The server's ${what} points at an address on a private network, so the sign-in was stopped. Check the server's address, or ask its maker.`, undefined, `${what}: ${verdict.reason ?? url.host}`);
161
+ }
162
+ }
163
+ await options.checkAddress?.(url, what);
164
+ }
165
+ /**
166
+ * What an unauthenticated request to the MCP server says about signing in.
167
+ *
168
+ * Used only when the well-known metadata is not where RFC 9728 puts it: a 401
169
+ * may name the metadata document in `WWW-Authenticate`, and may say which
170
+ * scopes it wants.
171
+ */
172
+ async function probeForChallenge(serverUrl, fetchFn) {
173
+ const res = await fetchFn(serverUrl, {
174
+ method: "POST",
175
+ headers: { "content-type": "application/json", accept: "application/json, text/event-stream" },
176
+ body: JSON.stringify({
177
+ jsonrpc: "2.0",
178
+ id: 0,
179
+ method: "initialize",
180
+ params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "hardened-mcp", version: "0" } }
181
+ })
182
+ });
183
+ await res.body?.cancel().catch(() => undefined);
184
+ if (res.status !== 401)
185
+ return { status: res.status };
186
+ const params = extractWWWAuthenticateParams(res);
187
+ return {
188
+ status: 401,
189
+ ...(params.resourceMetadataUrl ? { resourceMetadataUrl: params.resourceMetadataUrl } : {}),
190
+ ...(params.scope ? { scope: params.scope } : {})
191
+ };
192
+ }
193
+ /**
194
+ * Protected resource metadata (RFC 9728), then the authorization server's own
195
+ * (RFC 8414, with the OIDC fallback the SDK implements).
196
+ *
197
+ * The resource the server claims is checked against the URL we were given:
198
+ * otherwise a server could have us ask for a token meant for some other
199
+ * service, and the token would be handed to it on the next request.
200
+ */
201
+ export async function discover(serverUrl, fetchFn, options = {}) {
202
+ const server = assertWebUrl(serverUrl, "address");
203
+ let prm;
204
+ let scopeHint;
205
+ try {
206
+ prm = await discoverOAuthProtectedResourceMetadata(serverUrl, {}, fetchFn);
207
+ }
208
+ catch (wellKnownErr) {
209
+ let challenge;
210
+ try {
211
+ challenge = await probeForChallenge(serverUrl, fetchFn);
212
+ }
213
+ catch (err) {
214
+ // A refusal by the caller's guard already says why, in its own words.
215
+ if (err instanceof EgressDenied)
216
+ throw err;
217
+ throw new SignInProblem("discovery", "Couldn't reach the server to read its sign-in details. Check the address and try again.", undefined, plain(wellKnownErr));
218
+ }
219
+ if (challenge.status !== 401) {
220
+ throw new SignInProblem("not-oauth", challenge.status >= 200 && challenge.status < 300
221
+ ? "This server does not ask for a sign-in."
222
+ : `This server does not offer a sign-in (it answered ${challenge.status}).`);
223
+ }
224
+ scopeHint = challenge.scope;
225
+ if (challenge.resourceMetadataUrl) {
226
+ await assertSafeAddress(challenge.resourceMetadataUrl.href, "sign-in details address", server, options);
227
+ try {
228
+ prm = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: challenge.resourceMetadataUrl }, fetchFn);
229
+ }
230
+ catch (err) {
231
+ if (err instanceof EgressDenied)
232
+ throw err;
233
+ throw new SignInProblem("discovery", "The server's sign-in details couldn't be read.", undefined, plain(err));
234
+ }
235
+ }
236
+ // No metadata anywhere: the older MCP convention, where the server's own
237
+ // origin is the authorization server. Handled below.
238
+ }
239
+ let resource;
240
+ if (prm) {
241
+ if (!checkResourceAllowed({ requestedResource: serverUrl, configuredResource: prm.resource })) {
242
+ throw new SignInProblem("unsafe", `The server says its sign-in is for ${prm.resource}, which is not ${serverUrl}. It was not used.`);
243
+ }
244
+ // Sent verbatim, as the SDK does (#1968): `new URL()` would add a slash.
245
+ resource = prm.resource;
246
+ }
247
+ else {
248
+ resource = resourceUrlFromServerUrl(serverUrl).href;
249
+ }
250
+ const authorizationServer = prm?.authorization_servers?.[0] ?? new URL("/", serverUrl).href;
251
+ await assertSafeAddress(authorizationServer, "sign-in address", server, options);
252
+ let as;
253
+ try {
254
+ as = await discoverAuthorizationServerMetadata(authorizationServer, { fetchFn });
255
+ }
256
+ catch (err) {
257
+ if (err instanceof EgressDenied)
258
+ throw err;
259
+ throw new SignInProblem("discovery", "The sign-in service's details couldn't be read, or aren't in a form the console can use. The server may be set up wrongly.", undefined, plain(err));
260
+ }
261
+ if (!as)
262
+ throw new SignInProblem("discovery", "The sign-in service did not publish its details.");
263
+ // RFC 8414 section 3.3: the issuer must be the address we asked. A mismatch
264
+ // is the mix-up attack, where one provider's metadata points at another's.
265
+ if (!sameIssuer(as.issuer, authorizationServer)) {
266
+ throw new SignInProblem("unsafe", `The sign-in service calls itself ${as.issuer}, not ${authorizationServer}. It was not used.`);
267
+ }
268
+ await assertSafeAddress(as.authorization_endpoint, "sign-in page", server, options);
269
+ await assertSafeAddress(as.token_endpoint, "token address", server, options);
270
+ if (as.registration_endpoint)
271
+ await assertSafeAddress(as.registration_endpoint, "registration address", server, options);
272
+ // Scope selection as the spec orders it: what the 401 asked for, then what
273
+ // the resource advertises; otherwise none, and the provider decides.
274
+ const scopeList = scopeHint ? scopeHint.split(/\s+/).filter(Boolean) : prm?.scopes_supported;
275
+ const metadata = {
276
+ issuer: as.issuer,
277
+ authorization_endpoint: as.authorization_endpoint,
278
+ token_endpoint: as.token_endpoint,
279
+ ...(as.registration_endpoint ? { registration_endpoint: as.registration_endpoint } : {}),
280
+ ...(as.token_endpoint_auth_methods_supported
281
+ ? { token_endpoint_auth_methods_supported: as.token_endpoint_auth_methods_supported }
282
+ : {}),
283
+ ...(as.scopes_supported ? { scopes_supported: as.scopes_supported } : {})
284
+ };
285
+ return {
286
+ resource,
287
+ authorizationServer,
288
+ metadata,
289
+ ...(scopeList && scopeList.length > 0 ? { scopes: scopeList } : {}),
290
+ ...(as.code_challenge_methods_supported ? { codeChallengeMethods: as.code_challenge_methods_supported } : {}),
291
+ ...(as.response_types_supported ? { responseTypes: as.response_types_supported } : {})
292
+ };
293
+ }
294
+ /** The SDK's metadata type wants fields we do not keep; they are not consulted past discovery. */
295
+ function sdkMetadata(metadata, d) {
296
+ return {
297
+ ...metadata,
298
+ response_types_supported: d?.responseTypes ?? ["code"],
299
+ ...(d?.codeChallengeMethods ? { code_challenge_methods_supported: d.codeChallengeMethods } : {})
300
+ };
301
+ }
302
+ /* ------------------------------------------------------------- registration */
303
+ /**
304
+ * Dynamic client registration (RFC 7591). A public client ("none") whenever
305
+ * the provider allows it: there is no server-side place to keep a client
306
+ * secret, and PKCE is what protects the code.
307
+ */
308
+ export async function register(d, redirectUri, fetchFn, clientName = "hardened-mcp") {
309
+ if (!d.metadata.registration_endpoint)
310
+ throw new NoDynamicRegistration(d.authorizationServer);
311
+ const supported = d.metadata.token_endpoint_auth_methods_supported;
312
+ const authMethod = !supported || supported.includes("none")
313
+ ? "none"
314
+ : supported.includes("client_secret_post")
315
+ ? "client_secret_post"
316
+ : "client_secret_basic";
317
+ const full = await registerClient(d.authorizationServer, {
318
+ metadata: sdkMetadata(d.metadata, d),
319
+ clientMetadata: {
320
+ client_name: clientName,
321
+ redirect_uris: [redirectUri],
322
+ grant_types: ["authorization_code", "refresh_token"],
323
+ response_types: ["code"],
324
+ token_endpoint_auth_method: authMethod
325
+ },
326
+ ...(d.scopes ? { scope: d.scopes.join(" ") } : {}),
327
+ fetchFn
328
+ });
329
+ return {
330
+ client_id: full.client_id,
331
+ ...(full.client_secret ? { client_secret: full.client_secret } : {}),
332
+ ...(full.client_secret_expires_at !== undefined ? { client_secret_expires_at: full.client_secret_expires_at } : {}),
333
+ redirect_uris: full.redirect_uris?.length ? full.redirect_uris.map(String) : [redirectUri],
334
+ ...(full.token_endpoint_auth_method ?? authMethod ? { token_endpoint_auth_method: full.token_endpoint_auth_method ?? authMethod } : {})
335
+ };
336
+ }
337
+ /** A fresh `state`: 32 random bytes, so it cannot be guessed or replayed. */
338
+ export function newState() {
339
+ return randomBytes(32).toString("base64url");
340
+ }
341
+ /**
342
+ * The page to send the person to. PKCE S256 always (the SDK sends nothing
343
+ * else), the caller's `state`, and the RFC 8707 `resource` always, so the
344
+ * token is bound to this server and useless anywhere else.
345
+ */
346
+ export async function begin(d, client, redirectUri, state) {
347
+ if (d.codeChallengeMethods && !d.codeChallengeMethods.includes("S256")) {
348
+ throw new SignInProblem("unsafe", "The sign-in service does not support the protection this console requires (PKCE S256).");
349
+ }
350
+ if (!state)
351
+ throw new SignInProblem("state", "A sign-in must carry a state.");
352
+ const { authorizationUrl, codeVerifier } = await startAuthorization(d.authorizationServer, {
353
+ metadata: sdkMetadata(d.metadata, d),
354
+ clientInformation: client,
355
+ redirectUrl: redirectUri,
356
+ state,
357
+ resource: d.resource,
358
+ ...(d.scopes ? { scope: d.scopes.join(" ") } : {})
359
+ });
360
+ return { authorizeUrl: authorizationUrl.href, codeVerifier, state };
361
+ }
362
+ /**
363
+ * The code from a callback URL, once its `state` is checked. A provider
364
+ * error (the person pressed Cancel) and a state that is not ours both throw.
365
+ */
366
+ export function readCallback(callbackUrl, expectedState) {
367
+ const url = new URL(callbackUrl);
368
+ const state = url.searchParams.get("state");
369
+ if (!state || state !== expectedState) {
370
+ throw new SignInProblem("state", "This sign-in reply does not belong to the sign-in that was started.");
371
+ }
372
+ const error = url.searchParams.get("error");
373
+ if (error)
374
+ throw new SignInProblem("denied", "The provider said no.", error);
375
+ const code = url.searchParams.get("code");
376
+ if (!code)
377
+ throw new SignInProblem("rejected", "The provider's reply carried no sign-in code.");
378
+ return code;
379
+ }
380
+ /* -------------------------------------------------------------- tokens */
381
+ function storedTokens(t, now) {
382
+ return {
383
+ access_token: t.access_token,
384
+ token_type: t.token_type,
385
+ ...(t.refresh_token ? { refresh_token: t.refresh_token } : {}),
386
+ ...(typeof t.expires_in === "number" ? { expires_at: now + t.expires_in * 1000 } : {}),
387
+ ...(t.scope ? { scope: t.scope } : {})
388
+ };
389
+ }
390
+ /** The OAuth error code of an SDK failure, if it was one. */
391
+ export function oauthErrorCode(err) {
392
+ if (err instanceof OAuthError)
393
+ return err.errorCode;
394
+ return undefined;
395
+ }
396
+ /** An error's message, unless it might be a server's raw body. */
397
+ function plain(err) {
398
+ const code = oauthErrorCode(err);
399
+ if (code)
400
+ return code;
401
+ const message = err instanceof Error ? err.message : String(err);
402
+ // The SDK quotes a non-OAuth error body verbatim; that is the server's text
403
+ // and could be anything, so it is cut rather than repeated.
404
+ const cut = message.split(" Raw body:")[0];
405
+ return cut.length > 200 ? `${cut.slice(0, 200)}...` : cut;
406
+ }
407
+ /** Exchange the code and store the `oauth` entry under `secretName`. */
408
+ export async function complete(args, store, fetchFn) {
409
+ const { d, client } = args;
410
+ const tokens = await exchangeAuthorization(d.authorizationServer, {
411
+ metadata: sdkMetadata(d.metadata, d),
412
+ clientInformation: client,
413
+ authorizationCode: args.code,
414
+ codeVerifier: args.codeVerifier,
415
+ redirectUri: args.redirectUri,
416
+ resource: d.resource,
417
+ fetchFn
418
+ });
419
+ const now = Date.now();
420
+ const stamp = new Date(now).toISOString();
421
+ const previous = store.get(args.secretName);
422
+ const label = args.label ?? previous?.label;
423
+ const entry = {
424
+ kind: "oauth",
425
+ ...(label ? { label } : {}),
426
+ created_at: previous?.created_at ?? stamp,
427
+ updated_at: stamp,
428
+ server_url: args.serverUrl,
429
+ resource: d.resource,
430
+ ...(d.scopes ? { scopes: d.scopes } : {}),
431
+ authorization_server: d.authorizationServer,
432
+ metadata: d.metadata,
433
+ client,
434
+ tokens: storedTokens(tokens, now),
435
+ status: "signed-in"
436
+ };
437
+ store.set(args.secretName, entry);
438
+ }
439
+ /** Origin plus path, without a trailing slash: how two server addresses are compared. */
440
+ function sameServerUrl(a, b) {
441
+ const canon = (u) => {
442
+ try {
443
+ const url = resourceUrlFromServerUrl(u);
444
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
445
+ }
446
+ catch {
447
+ return undefined;
448
+ }
449
+ };
450
+ const ca = canon(a);
451
+ return ca !== undefined && ca === canon(b);
452
+ }
453
+ const NEEDS_SIGN_IN_ERRORS = new Set(["invalid_grant", "invalid_client", "unauthorized_client"]);
454
+ /**
455
+ * The gateway's token source for an upstream configured with `oauth: { secret }`.
456
+ *
457
+ * Several gateway processes (one per AI app) share one sign-in, and a refresh
458
+ * token that rotates can be spent only once. The file lock is synchronous and
459
+ * a refresh is a network call, so the lock cannot be held across it. Instead:
460
+ *
461
+ * 1. Re-read under the lock first. If another process has already refreshed,
462
+ * its token is used and nothing is spent.
463
+ * 2. Otherwise refresh, and write the new pair under the lock.
464
+ * 3. If the provider says the refresh token is no good, that may only mean
465
+ * another process spent it a moment earlier. Watch the file briefly; if a
466
+ * newer pair appears, use it. Only if none does is the sign-in marked
467
+ * as needing a person.
468
+ *
469
+ * Within one process, concurrent callers share one refresh.
470
+ */
471
+ export function oauthTokenSource(secretName, store, fetchFn, options = {}) {
472
+ const skew = options.skewMs ?? 60_000;
473
+ const rotationWait = options.rotationWaitMs ?? 2_000;
474
+ const now = options.now ?? Date.now;
475
+ /** The access token most recently handed out: the one a 401 is about. */
476
+ let lastAccess;
477
+ let inflight;
478
+ const isFresh = (t) => !!t?.access_token && (t.expires_at === undefined || t.expires_at - now() > skew);
479
+ const asOAuth = (e) => {
480
+ if (!e)
481
+ throw new NeedsSignIn(secretName, "there is no sign-in saved under this name");
482
+ if (e.kind !== "oauth")
483
+ throw new NeedsSignIn(secretName, "this locked key is not a sign-in");
484
+ if (options.expectedUrl !== undefined) {
485
+ // Checked on every read, not once: the entry can be replaced by a
486
+ // sign-in to some other server at any time. The resource is held to the
487
+ // same rule discover() applied when the sign-in was made.
488
+ let resourceOk = !e.resource;
489
+ try {
490
+ resourceOk ||= checkResourceAllowed({ requestedResource: options.expectedUrl, configuredResource: e.resource });
491
+ }
492
+ catch {
493
+ resourceOk = false;
494
+ }
495
+ if (!sameServerUrl(e.server_url, options.expectedUrl) || !resourceOk) {
496
+ throw new NeedsSignIn(secretName, "this sign-in belongs to another server");
497
+ }
498
+ }
499
+ return e;
500
+ };
501
+ /** Marks the entry, unless someone has since replaced the refresh token we judged. */
502
+ const markNeedsSignIn = (reason, judged) => {
503
+ store.update(secretName, (cur) => {
504
+ if (!cur || cur.kind !== "oauth")
505
+ return cur;
506
+ if (judged !== undefined && cur.tokens?.refresh_token !== judged)
507
+ return cur;
508
+ return { ...cur, status: "needs-sign-in", last_error: reason, updated_at: new Date(now()).toISOString() };
509
+ });
510
+ };
511
+ const waitForRotation = async (spent) => {
512
+ const deadline = now() + rotationWait;
513
+ for (;;) {
514
+ const cur = store.get(secretName);
515
+ if (cur?.kind === "oauth") {
516
+ if (cur.tokens?.refresh_token !== spent && isFresh(cur.tokens))
517
+ return cur.tokens.access_token;
518
+ if (cur.status === "needs-sign-in")
519
+ return undefined;
520
+ }
521
+ if (now() >= deadline)
522
+ return undefined;
523
+ await new Promise((r) => setTimeout(r, 50));
524
+ }
525
+ };
526
+ const doRefresh = async (stale) => {
527
+ // 1. Re-read, so this sees any write that finished before it. A plain
528
+ // read is enough: `get` goes to the file every time and writes land by
529
+ // atomic rename, so it sees the last finished write whole. Holding the
530
+ // store's write lock here (as an identity `update` would) adds nothing
531
+ // and rewrites the file, which moves its stamp and makes every gateway
532
+ // retry its waiting servers. Other refreshers are kept out by the
533
+ // refresh lock this runs under, and the write below re-reads under the
534
+ // store lock, so a sign-out landing meanwhile is not undone.
535
+ const cur = asOAuth(store.get(secretName));
536
+ if (cur.status === "needs-sign-in")
537
+ throw new NeedsSignIn(secretName, cur.last_error ?? "the sign-in has run out");
538
+ if (isFresh(cur.tokens) && cur.tokens.access_token !== stale)
539
+ return cur.tokens.access_token;
540
+ const spent = cur.tokens?.refresh_token;
541
+ if (!spent) {
542
+ const reason = "the provider did not allow staying signed in (no refresh token)";
543
+ markNeedsSignIn(reason, undefined);
544
+ throw new NeedsSignIn(secretName, reason);
545
+ }
546
+ // 2. The network call, outside the lock.
547
+ let fresh;
548
+ try {
549
+ fresh = await refreshAuthorization(cur.authorization_server, {
550
+ metadata: sdkMetadata(cur.metadata),
551
+ clientInformation: cur.client,
552
+ refreshToken: spent,
553
+ ...(cur.resource ? { resource: cur.resource } : {}),
554
+ fetchFn
555
+ });
556
+ }
557
+ catch (err) {
558
+ const code = oauthErrorCode(err);
559
+ if (!code || !NEEDS_SIGN_IN_ERRORS.has(code))
560
+ throw err;
561
+ // 3. Possibly just a race lost to another process.
562
+ const winner = await waitForRotation(spent);
563
+ if (winner)
564
+ return winner;
565
+ const reason = code === "invalid_grant"
566
+ ? "the provider withdrew the sign-in or it ran out (invalid_grant)"
567
+ : `the provider no longer accepts this app (${code})`;
568
+ markNeedsSignIn(reason, spent);
569
+ throw new NeedsSignIn(secretName, reason);
570
+ }
571
+ const at = now();
572
+ let replaced = false;
573
+ const saved = store.update(secretName, (c) => {
574
+ // Signed out (or replaced by a value) while we refreshed: do not resurrect it.
575
+ if (!c || c.kind !== "oauth")
576
+ return c;
577
+ // Signed in again while we refreshed -- only the console does that, and
578
+ // not under the refresh lock. The new sign-in wins, and may be for a
579
+ // different server: the old grant's tokens must not land under it.
580
+ if (c.tokens?.refresh_token !== spent) {
581
+ replaced = true;
582
+ return c;
583
+ }
584
+ const { last_error: _drop, ...rest } = c;
585
+ return { ...rest, tokens: storedTokens(fresh, at), status: "signed-in", updated_at: new Date(at).toISOString() };
586
+ });
587
+ if (!saved || saved.kind !== "oauth")
588
+ throw new NeedsSignIn(secretName, "the sign-in was removed");
589
+ if (replaced) {
590
+ // Through asOAuth, so the new entry is held to the same server check.
591
+ const current = asOAuth(saved);
592
+ if (current.status === "needs-sign-in" || !current.tokens?.access_token) {
593
+ throw new NeedsSignIn(secretName, current.last_error ?? "the sign-in was replaced");
594
+ }
595
+ return current.tokens.access_token;
596
+ }
597
+ return fresh.access_token;
598
+ };
599
+ /*
600
+ * One refresh at a time per sign-in across every process on this computer.
601
+ * Each AI app runs its own gateway, and refresh tokens rotate: two processes
602
+ * spending the same one means one of them is refused, and some providers
603
+ * revoke the whole chain when they see a spent token come back. Under this
604
+ * lock the second process re-reads the file in doRefresh's first step and
605
+ * finds the token the first one just saved. It is a separate lock file from
606
+ * the store's own write lock (which doRefresh takes briefly inside), so the
607
+ * two cannot deadlock. The rotation wait in doRefresh stays as the fallback
608
+ * for a lock that went stale mid-refresh.
609
+ */
610
+ const lockedRefresh = (stale) => withFileLockAsync(`${store.path}.refresh-${secretName}`, () => doRefresh(stale), {
611
+ timeoutMs: 45_000,
612
+ what: "the sign-in refresh"
613
+ });
614
+ const refresh = (stale) => {
615
+ inflight ??= lockedRefresh(stale).finally(() => {
616
+ inflight = undefined;
617
+ });
618
+ return inflight;
619
+ };
620
+ return {
621
+ async header() {
622
+ const entry = asOAuth(store.get(secretName));
623
+ if (entry.status === "needs-sign-in")
624
+ throw new NeedsSignIn(secretName, entry.last_error ?? "the sign-in has run out");
625
+ const access = isFresh(entry.tokens) ? entry.tokens.access_token : await refresh(undefined);
626
+ lastAccess = access;
627
+ return `Bearer ${access}`;
628
+ },
629
+ async onUnauthorized() {
630
+ try {
631
+ lastAccess = await refresh(lastAccess);
632
+ return true;
633
+ }
634
+ catch (err) {
635
+ if (err instanceof NeedsSignIn)
636
+ return false;
637
+ throw err;
638
+ }
639
+ }
640
+ };
641
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * What a gateway says when it is only observing.
3
+ *
4
+ * Observe mode enforces nothing, so the one way it does harm is by being left
5
+ * on by someone who believes they are protected. This is the first thing the
6
+ * process prints and it is printed again whenever a policy edit switches
7
+ * enforcement off, as a block rather than a line so that it survives a screen
8
+ * of other startup output.
9
+ */
10
+ export declare function observeBanner(policyHint?: string): string[];
@@ -0,0 +1,26 @@
1
+ /**
2
+ * What a gateway says when it is only observing.
3
+ *
4
+ * Observe mode enforces nothing, so the one way it does harm is by being left
5
+ * on by someone who believes they are protected. This is the first thing the
6
+ * process prints and it is printed again whenever a policy edit switches
7
+ * enforcement off, as a block rather than a line so that it survives a screen
8
+ * of other startup output.
9
+ */
10
+ export function observeBanner(policyHint = "the policy file") {
11
+ const rule = "=".repeat(78);
12
+ return [
13
+ rule,
14
+ " OBSERVE MODE -- the policy is NOT ENFORCED",
15
+ "",
16
+ " Every call runs, including ones the policy would refuse or hold for a human.",
17
+ " Each is recorded with what the policy would have decided.",
18
+ "",
19
+ " Still in force: a tool you have switched off stays off, injected text in a",
20
+ " tool's description is still handled, and egress rules still apply.",
21
+ "",
22
+ " See what would have happened: hmcp-gateway suggest",
23
+ ` Start enforcing: set "enforcement: enforce" in ${policyHint}`,
24
+ rule
25
+ ];
26
+ }