@lostgradient/mcp 0.2.5 → 0.3.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 (123) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +15 -173
  3. package/dist/http.d.ts +35 -0
  4. package/dist/http.js +251 -0
  5. package/dist/internal/cryptography/encryption.d.ts +108 -0
  6. package/dist/internal/cryptography/encryption.js +241 -0
  7. package/dist/internal/cryptography/hash.d.ts +72 -0
  8. package/dist/internal/cryptography/hash.js +233 -0
  9. package/dist/internal/cryptography/index.d.ts +4 -0
  10. package/dist/internal/cryptography/index.js +2 -0
  11. package/dist/oauth/canonicalize-ip-address.d.ts +0 -6
  12. package/dist/oauth/canonicalize-ip-address.js +113 -0
  13. package/dist/oauth/client-metadata-documents.d.ts +2 -22
  14. package/dist/oauth/client-metadata-documents.js +205 -19
  15. package/dist/oauth/index.d.ts +9 -213
  16. package/dist/oauth/index.js +6 -69
  17. package/dist/oauth/issuer.d.ts +103 -0
  18. package/dist/oauth/issuer.js +564 -0
  19. package/dist/oauth/postgres.d.ts +12 -0
  20. package/dist/oauth/postgres.js +76 -0
  21. package/dist/oauth/safe-public-https-fetch.d.ts +3 -5
  22. package/dist/oauth/safe-public-https-fetch.js +114 -0
  23. package/dist/oauth/security-utilities.d.ts +0 -3
  24. package/dist/oauth/security-utilities.js +93 -0
  25. package/dist/oauth-store.d.ts +108 -0
  26. package/dist/oauth-store.js +321 -0
  27. package/package.json +50 -124
  28. package/dist/chunk-3ek3knfm.js +0 -73
  29. package/dist/chunk-3rr24vhh.js +0 -28
  30. package/dist/chunk-6ekjtvcq.js +0 -273
  31. package/dist/chunk-88nhf6xt.js +0 -449
  32. package/dist/chunk-en76akaq.js +0 -1107
  33. package/dist/chunk-k6fm3cmk.js +0 -132
  34. package/dist/chunk-qxwd8est.js +0 -916
  35. package/dist/chunk-rxnyn7tf.js +0 -19
  36. package/dist/chunk-taxyscge.js +0 -67
  37. package/dist/chunk-wsnfttyg.js +0 -4
  38. package/dist/chunk-xcf742mf.js +0 -14
  39. package/dist/conformance-fixture-registration.d.ts +0 -30
  40. package/dist/conformance-server.d.ts +0 -1
  41. package/dist/conformance.d.ts +0 -43
  42. package/dist/env.d.ts +0 -59
  43. package/dist/env.js +0 -9
  44. package/dist/environment-schema.d.ts +0 -29
  45. package/dist/environment-schema.js +0 -6
  46. package/dist/golden-prompts.d.ts +0 -42
  47. package/dist/handler-context.d.ts +0 -16
  48. package/dist/http/authenticate.d.ts +0 -35
  49. package/dist/http/authorization-header.d.ts +0 -5
  50. package/dist/http/grant-revocation-channel.d.ts +0 -24
  51. package/dist/http/handler.d.ts +0 -32
  52. package/dist/http/index.d.ts +0 -27
  53. package/dist/http/index.js +0 -870
  54. package/dist/http/listen-inspection.d.ts +0 -11
  55. package/dist/http/request-context.d.ts +0 -17
  56. package/dist/http/responses.d.ts +0 -13
  57. package/dist/http/serving-layer.d.ts +0 -25
  58. package/dist/http/user-handler-cache.d.ts +0 -37
  59. package/dist/http/user-server-event-bus.d.ts +0 -35
  60. package/dist/index.d.ts +0 -29
  61. package/dist/index.js +0 -616
  62. package/dist/localhost-request-validation.d.ts +0 -2
  63. package/dist/logger.d.ts +0 -59
  64. package/dist/logger.js +0 -18
  65. package/dist/long-running-operation-support.d.ts +0 -34
  66. package/dist/metrics.d.ts +0 -64
  67. package/dist/metrics.js +0 -6
  68. package/dist/oauth/authorize-endpoint.d.ts +0 -5
  69. package/dist/oauth/client-authentication.d.ts +0 -10
  70. package/dist/oauth/discovery-metadata.d.ts +0 -19
  71. package/dist/oauth/endpoint-rate-limits.d.ts +0 -10
  72. package/dist/oauth/endpoint-responses.d.ts +0 -10
  73. package/dist/oauth/network-identity.d.ts +0 -32
  74. package/dist/oauth/pkce-validation.d.ts +0 -2
  75. package/dist/oauth/postgres/client-store.d.ts +0 -12
  76. package/dist/oauth/postgres/code-store.d.ts +0 -14
  77. package/dist/oauth/postgres/database.d.ts +0 -59
  78. package/dist/oauth/postgres/index.d.ts +0 -11
  79. package/dist/oauth/postgres/index.js +0 -616
  80. package/dist/oauth/postgres/schema.d.ts +0 -1476
  81. package/dist/oauth/postgres/token-store.d.ts +0 -16
  82. package/dist/oauth/postgres/transaction-store.d.ts +0 -14
  83. package/dist/oauth/redirect-uri-matching.d.ts +0 -2
  84. package/dist/oauth/registration-endpoint.d.ts +0 -2
  85. package/dist/oauth/request-body.d.ts +0 -14
  86. package/dist/oauth/revocation-endpoint.d.ts +0 -2
  87. package/dist/oauth/scope-utilities.d.ts +0 -15
  88. package/dist/oauth/stores.d.ts +0 -225
  89. package/dist/oauth/stores.js +0 -0
  90. package/dist/oauth/testing/contract-fixtures.d.ts +0 -134
  91. package/dist/oauth/testing/index.d.ts +0 -56
  92. package/dist/oauth/testing/index.js +0 -330
  93. package/dist/oauth/token-endpoint.d.ts +0 -2
  94. package/dist/oauth-scope-configuration.d.ts +0 -3
  95. package/dist/prompts/index.d.ts +0 -5
  96. package/dist/prompts/summarize.d.ts +0 -4
  97. package/dist/rate-limit/in-memory-sliding-window-store.d.ts +0 -3
  98. package/dist/rate-limit/index.d.ts +0 -23
  99. package/dist/rate-limit/index.js +0 -29
  100. package/dist/rate-limit/mcp-concurrency-limiter.d.ts +0 -26
  101. package/dist/rate-limit/rate-limit-response.d.ts +0 -1
  102. package/dist/rate-limit/redis-sliding-window-store.d.ts +0 -2
  103. package/dist/rate-limit/request-rate-limiter.d.ts +0 -10
  104. package/dist/rate-limit/sliding-window-rate-limiter.d.ts +0 -16
  105. package/dist/resources/index.d.ts +0 -4
  106. package/dist/resources/user-profile.d.ts +0 -1
  107. package/dist/scope-vocabulary.d.ts +0 -127
  108. package/dist/scopes.d.ts +0 -49
  109. package/dist/server.d.ts +0 -113
  110. package/dist/supported-scopes.d.ts +0 -25
  111. package/dist/sveltekit-mount-state.d.ts +0 -4
  112. package/dist/sveltekit-mount.d.ts +0 -43
  113. package/dist/sveltekit-mount.js +0 -344
  114. package/dist/template-registry.d.ts +0 -16
  115. package/dist/tool-response.d.ts +0 -100
  116. package/dist/tools/get-user-profile.d.ts +0 -8
  117. package/dist/tools/index.d.ts +0 -16
  118. package/dist/tools/list-audit-events.d.ts +0 -11
  119. package/dist/type-assertions.d.ts +0 -1
  120. package/dist/types/primitives.d.ts +0 -130
  121. package/dist/ui-extension-support.d.ts +0 -20
  122. package/dist/version.d.ts +0 -23
  123. package/dist/version.js +0 -6
@@ -0,0 +1,113 @@
1
+ import { isIPv4, isIPv6 } from 'node:net';
2
+ /**
3
+ * Expands an IPv6 address (including one with an embedded IPv4 dotted-quad
4
+ * suffix, e.g. `::ffff:192.168.1.1`) into its eight zero-padded hextet
5
+ * groups. Exported so trusted-proxy CIDR matching can reuse the same
6
+ * parsing instead of re-deriving it.
7
+ */
8
+ export function expandIpv6Groups(address) {
9
+ let workingAddress = address;
10
+ const lastColonIndex = workingAddress.lastIndexOf(':');
11
+ const tail = workingAddress.slice(lastColonIndex + 1);
12
+ if (tail.includes('.') && isIPv4(tail)) {
13
+ const octets = tail.split('.').map(Number);
14
+ const highGroup = ((octets[0] << 8) | octets[1]).toString(16).padStart(4, '0');
15
+ const lowGroup = ((octets[2] << 8) | octets[3]).toString(16).padStart(4, '0');
16
+ workingAddress = `${workingAddress.slice(0, lastColonIndex + 1)}${highGroup}:${lowGroup}`;
17
+ }
18
+ let groups;
19
+ if (workingAddress.includes('::')) {
20
+ const [head, tailPart] = workingAddress.split('::');
21
+ const headGroups = head ? head.split(':').filter(Boolean) : [];
22
+ const tailGroups = tailPart ? tailPart.split(':').filter(Boolean) : [];
23
+ const missingGroupCount = 8 - headGroups.length - tailGroups.length;
24
+ groups = [...headGroups, ...Array(missingGroupCount).fill('0'), ...tailGroups];
25
+ }
26
+ else {
27
+ groups = workingAddress.split(':');
28
+ }
29
+ return groups.map((group) => group.padStart(4, '0').toLowerCase());
30
+ }
31
+ function compressIpv6Groups(groups) {
32
+ const stripped = groups.map((group) => group.replace(/^0+(?=.)/, ''));
33
+ let bestStart = -1;
34
+ let bestLength = 0;
35
+ let currentStart = -1;
36
+ let currentLength = 0;
37
+ for (let index = 0; index < stripped.length; index += 1) {
38
+ if (stripped[index] === '0') {
39
+ if (currentStart === -1)
40
+ currentStart = index;
41
+ currentLength += 1;
42
+ if (currentLength > bestLength) {
43
+ bestLength = currentLength;
44
+ bestStart = currentStart;
45
+ }
46
+ }
47
+ else {
48
+ currentStart = -1;
49
+ currentLength = 0;
50
+ }
51
+ }
52
+ if (bestLength < 2) {
53
+ return stripped.join(':');
54
+ }
55
+ const before = stripped.slice(0, bestStart).join(':');
56
+ const after = stripped.slice(bestStart + bestLength).join(':');
57
+ return `${before}::${after}`;
58
+ }
59
+ /**
60
+ * Extracts the IPv4 address embedded in an IPv4-mapped IPv6 address
61
+ * (`::ffff:a.b.c.d`), given its expanded, zero-padded hextet groups.
62
+ * Returns `null` when the groups do not represent a mapped address.
63
+ */
64
+ function extractIpv4MappedAddress(groups) {
65
+ const isMapped = groups.slice(0, 5).every((group) => group === '0000') && groups[5] === 'ffff';
66
+ if (!isMapped)
67
+ return null;
68
+ const highGroup = Number.parseInt(groups[6], 16);
69
+ const lowGroup = Number.parseInt(groups[7], 16);
70
+ return [highGroup >> 8, highGroup & 0xff, lowGroup >> 8, lowGroup & 0xff].join('.');
71
+ }
72
+ /**
73
+ * Strips a trailing `:port` suffix from an address/port pair, handling
74
+ * both bracketed IPv6 (`[2001:db8::1]:4711`) and IPv4 (`1.2.3.4:5678`)
75
+ * forms. Returns the input unchanged when no port suffix is present.
76
+ */
77
+ function stripPort(input) {
78
+ const trimmed = input.trim();
79
+ const bracketedMatch = /^\[([^\]]+)]:\d+$/.exec(trimmed);
80
+ if (bracketedMatch) {
81
+ return bracketedMatch[1];
82
+ }
83
+ if (/^\[[^\]]+]$/.test(trimmed)) {
84
+ return trimmed.slice(1, -1);
85
+ }
86
+ const ipv4WithPortMatch = /^(\d{1,3}(?:\.\d{1,3}){3}):\d+$/.exec(trimmed);
87
+ if (ipv4WithPortMatch) {
88
+ return ipv4WithPortMatch[1];
89
+ }
90
+ return trimmed;
91
+ }
92
+ /**
93
+ * Canonicalizes an IPv4, IPv4-mapped IPv6, or IPv6 address string into one
94
+ * consistent representation: lowercase, zone-id stripped, IPv4-mapped IPv6
95
+ * collapsed to plain IPv4, and IPv6 compressed per RFC 5952. Addresses that
96
+ * are not valid IPv4/IPv6 are returned lowercased and trimmed as-is.
97
+ */
98
+ export function canonicalizeIpAddress(input) {
99
+ const withoutPort = stripPort(input);
100
+ const withoutZone = withoutPort.split('%')[0]?.trim().toLowerCase() ?? '';
101
+ if (isIPv4(withoutZone)) {
102
+ return withoutZone;
103
+ }
104
+ if (isIPv6(withoutZone)) {
105
+ const groups = expandIpv6Groups(withoutZone);
106
+ const mappedIpv4 = extractIpv4MappedAddress(groups);
107
+ if (mappedIpv4) {
108
+ return mappedIpv4;
109
+ }
110
+ return compressIpv6Groups(groups);
111
+ }
112
+ return withoutZone;
113
+ }
@@ -1,8 +1,6 @@
1
- import { type DnsLookupAllFunction } from './safe-public-https-fetch.js';
2
- export { ClientMetadataDocumentFetchError, resetDnsLookupConcurrencyLimiterForTests, safeFetchPublicHttpsUrl, } from './safe-public-https-fetch.js';
3
- export type { DnsLookupAllFunction, SafePublicHttpsFetchOptions, } from './safe-public-https-fetch.js';
1
+ import { type DnsLookupAllFunction } from "./safe-public-https-fetch.js";
4
2
  export type ClientMetadataDocumentFetchDependencies = {
5
- fetchImpl?: typeof fetch;
3
+ fetchImpl?: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
6
4
  lookupImpl?: DnsLookupAllFunction;
7
5
  now?: () => number;
8
6
  /**
@@ -14,15 +12,6 @@ export type ClientMetadataDocumentFetchDependencies = {
14
12
  */
15
13
  dnsTimeoutMs?: number;
16
14
  };
17
- /**
18
- * A `client_id` is a Client ID Metadata Document identifier only if it is
19
- * an HTTPS URL with a non-root path component (the MCP spec's own
20
- * requirement, matching the CIMD draft: `https://example.com/client.json`,
21
- * never bare `https://example.com`), no fragment, and no embedded userinfo.
22
- * A DCR `client_id` is always a `randomUUID()`, so this never collides with
23
- * one.
24
- */
25
- export declare function isClientIdMetadataDocumentUrl(clientId: string): boolean;
26
15
  export type ClientIdMetadataDocument = {
27
16
  clientId: string;
28
17
  clientName: string;
@@ -41,12 +30,3 @@ export type ClientIdMetadataDocument = {
41
30
  * could use to probe internal network shape.
42
31
  */
43
32
  export declare function fetchClientIdMetadataDocument(clientId: string, dependencies?: ClientMetadataDocumentFetchDependencies): Promise<ClientIdMetadataDocument | null>;
44
- /** Test-only: clears the module-local cache so tests don't leak state across files/cases. */
45
- export declare function clearClientIdMetadataDocumentCacheForTests(): void;
46
- /**
47
- * Test-only: resets the DNS lookup concurrency limiter's process-global
48
- * state. `outstandingDnsLookupCount` and `inFlightDnsLookupsByHostname` are
49
- * shared across every test file in the same process -- without this, a test
50
- * that saturates the limiter (or leaves a lookup in flight past its own
51
- * test's lifetime) would leak that state into the next test file's run.
52
- */
@@ -1,19 +1,205 @@
1
- import {
2
- ClientMetadataDocumentFetchError,
3
- clearClientIdMetadataDocumentCacheForTests,
4
- fetchClientIdMetadataDocument,
5
- isClientIdMetadataDocumentUrl,
6
- resetDnsLookupConcurrencyLimiterForTests,
7
- safeFetchPublicHttpsUrl
8
- } from "../chunk-88nhf6xt.js";
9
- import"../chunk-k6fm3cmk.js";
10
- import"../chunk-3rr24vhh.js";
11
- import"../chunk-xcf742mf.js";
12
- export {
13
- ClientMetadataDocumentFetchError,
14
- clearClientIdMetadataDocumentCacheForTests,
15
- fetchClientIdMetadataDocument,
16
- isClientIdMetadataDocumentUrl,
17
- resetDnsLookupConcurrencyLimiterForTests,
18
- safeFetchPublicHttpsUrl
19
- };
1
+ import { z } from 'zod';
2
+ import { ClientMetadataDocumentFetchError, safeFetchPublicHttpsUrl, } from "./safe-public-https-fetch.js";
3
+ import { isExactContentType, isValidClientName, isValidRedirectUri } from "./security-utilities.js";
4
+ const cimdMaxResponseBytes = 16 * 1024;
5
+ const cimdCacheTtlMs = 10 * 60 * 1_000;
6
+ const cimdCacheMaxEntries = 1_000;
7
+ const oauthMaxClientNameLength = 200;
8
+ const oauthMaxGrantTypeCount = 5;
9
+ const oauthMaxRedirectUriCount = 10;
10
+ const oauthMaxRedirectUriLength = 2_048;
11
+ const oauthMaxResponseTypeCount = 5;
12
+ function isClientIdMetadataDocumentUrl(clientId) {
13
+ let parsed;
14
+ try {
15
+ parsed = new URL(clientId);
16
+ }
17
+ catch {
18
+ return false;
19
+ }
20
+ return (parsed.protocol === 'https:' &&
21
+ !parsed.hash &&
22
+ !parsed.username &&
23
+ !parsed.password &&
24
+ parsed.pathname !== '/');
25
+ }
26
+ const applicationTypes = ['web', 'native'];
27
+ /**
28
+ * `application_type` is DCR/OIDC vocabulary (SEP-837), not part of the
29
+ * CIMD draft itself, but a document may still declare it and this server
30
+ * honors the same web/native redirect-URI distinction either way: a
31
+ * `web` document's `redirect_uris` must all be HTTPS (no loopback).
32
+ */
33
+ function documentRedirectUrisMatchApplicationType(redirectUris, applicationType) {
34
+ if (applicationType !== 'web')
35
+ return true;
36
+ return redirectUris.every((uri) => new URL(uri).protocol === 'https:');
37
+ }
38
+ const clientMetadataDocumentSchema = z
39
+ .object({
40
+ client_id: z.string().url(),
41
+ client_name: z
42
+ .string()
43
+ .min(1)
44
+ .max(oauthMaxClientNameLength)
45
+ .refine(isValidClientName, 'client_name must not contain control or confusable characters'),
46
+ redirect_uris: z
47
+ .array(z.string().url().max(oauthMaxRedirectUriLength))
48
+ .min(1, 'At least one redirect URI is required')
49
+ .max(oauthMaxRedirectUriCount)
50
+ .refine((uris) => uris.every(isValidRedirectUri), 'Redirect URIs must use HTTPS (or http://localhost for development)'),
51
+ grant_types: z
52
+ // Client metadata may advertise grants this server does not implement.
53
+ // The token endpoint still accepts only authorization_code and refresh_token.
54
+ .array(z
55
+ .string()
56
+ .min(1)
57
+ .max(256)
58
+ .regex(/^[\x21-\x7e]+$/))
59
+ .max(oauthMaxGrantTypeCount)
60
+ .default(['authorization_code', 'refresh_token']),
61
+ response_types: z
62
+ .array(z.enum(['code']))
63
+ .max(oauthMaxResponseTypeCount)
64
+ .default(['code']),
65
+ // A CIMD identifier is a self-hosted, publicly readable document with
66
+ // no mechanism for conveying or verifying a client secret. Only
67
+ // `none` (PKCE-only, public client) is trustworthy here; anything
68
+ // else this server cannot verify, so it is rejected rather than
69
+ // silently defaulted or trusted.
70
+ token_endpoint_auth_method: z.literal('none').default('none'),
71
+ application_type: z.enum(applicationTypes).optional(),
72
+ })
73
+ .superRefine((data, ctx) => {
74
+ if (!documentRedirectUrisMatchApplicationType(data.redirect_uris, data.application_type)) {
75
+ ctx.addIssue({
76
+ code: 'custom',
77
+ message: 'application_type "web" requires every redirect_uri to use HTTPS.',
78
+ path: ['redirect_uris'],
79
+ });
80
+ }
81
+ });
82
+ /**
83
+ * Bounded, in-memory, process-local cache — not Redis. A stale or evicted
84
+ * entry only costs one extra fetch to the client's own endpoint on the
85
+ * next authorization request; it is never a correctness hazard, so a
86
+ * process-local cache (simpler, no new infrastructure dependency) is
87
+ * sufficient. Insertion-order eviction (delete the oldest key once the cap
88
+ * is hit) keeps this bounded without needing a full LRU.
89
+ */
90
+ const documentCache = new Map();
91
+ function cacheDocument(document, expiresAt) {
92
+ documentCache.delete(document.clientId);
93
+ documentCache.set(document.clientId, { document, expiresAt });
94
+ while (documentCache.size > cimdCacheMaxEntries) {
95
+ const oldestKey = documentCache.keys().next().value;
96
+ if (oldestKey === undefined)
97
+ break;
98
+ documentCache.delete(oldestKey);
99
+ }
100
+ }
101
+ async function readBoundedResponseText(response, maxBytes) {
102
+ const declaredLength = response.headers.get('content-length');
103
+ if (declaredLength !== null) {
104
+ const declaredBytes = Number(declaredLength);
105
+ if (Number.isFinite(declaredBytes) && declaredBytes > maxBytes) {
106
+ throw new ClientMetadataDocumentFetchError('response_too_large');
107
+ }
108
+ }
109
+ if (!response.body)
110
+ return '';
111
+ const reader = response.body.getReader();
112
+ const chunks = [];
113
+ let receivedBytes = 0;
114
+ while (true) {
115
+ const { done, value } = await reader.read();
116
+ if (done)
117
+ break;
118
+ receivedBytes += value.byteLength;
119
+ if (receivedBytes > maxBytes) {
120
+ await reader.cancel(new Error('response too large')).catch(() => { });
121
+ throw new ClientMetadataDocumentFetchError('response_too_large');
122
+ }
123
+ chunks.push(value);
124
+ }
125
+ const combined = new Uint8Array(receivedBytes);
126
+ let offset = 0;
127
+ for (const chunk of chunks) {
128
+ combined.set(chunk, offset);
129
+ offset += chunk.byteLength;
130
+ }
131
+ try {
132
+ return new TextDecoder('utf-8', { fatal: true }).decode(combined);
133
+ }
134
+ catch {
135
+ throw new ClientMetadataDocumentFetchError('invalid_encoding');
136
+ }
137
+ }
138
+ /**
139
+ * Fetches, validates, and caches the Client ID Metadata Document at
140
+ * `clientId`. Returns `null` for every failure mode (not publicly
141
+ * routable, unreachable, wrong content type, oversized, malformed JSON,
142
+ * schema violation, a `client_id` field that does not exactly match this
143
+ * URL) rather than throwing, so every caller has exactly one branch to
144
+ * handle: "no usable document" — never a distinguishable error a caller
145
+ * could use to probe internal network shape.
146
+ */
147
+ export async function fetchClientIdMetadataDocument(clientId, dependencies = {}) {
148
+ if (!isClientIdMetadataDocumentUrl(clientId))
149
+ return null;
150
+ const now = dependencies.now ?? Date.now;
151
+ const cached = documentCache.get(clientId);
152
+ if (cached && cached.expiresAt > now()) {
153
+ return cached.document;
154
+ }
155
+ const url = new URL(clientId);
156
+ let response;
157
+ try {
158
+ response = await safeFetchPublicHttpsUrl(url, {
159
+ fetchImpl: dependencies.fetchImpl,
160
+ lookupImpl: dependencies.lookupImpl,
161
+ dnsTimeoutMs: dependencies.dnsTimeoutMs,
162
+ headers: { accept: 'application/json' },
163
+ });
164
+ }
165
+ catch {
166
+ return null;
167
+ }
168
+ if (!response.ok)
169
+ return null;
170
+ if (!isExactContentType(response.headers.get('content-type'), 'application/json'))
171
+ return null;
172
+ let bodyText;
173
+ try {
174
+ bodyText = await readBoundedResponseText(response, cimdMaxResponseBytes);
175
+ }
176
+ catch {
177
+ return null;
178
+ }
179
+ let parsedJson;
180
+ try {
181
+ parsedJson = JSON.parse(bodyText);
182
+ }
183
+ catch {
184
+ return null;
185
+ }
186
+ const parsed = clientMetadataDocumentSchema.safeParse(parsedJson);
187
+ if (!parsed.success)
188
+ return null;
189
+ // draft-ietf-oauth-client-id-metadata-document-00 §2: the authorization
190
+ // server MUST validate the document's own `client_id` field matches the
191
+ // URL it was fetched from exactly — otherwise a document could be
192
+ // hosted at one URL and claim to speak for another.
193
+ if (parsed.data.client_id !== clientId)
194
+ return null;
195
+ const document = {
196
+ clientId,
197
+ clientName: parsed.data.client_name,
198
+ redirectUris: parsed.data.redirect_uris,
199
+ grantTypes: parsed.data.grant_types,
200
+ responseTypes: parsed.data.response_types,
201
+ applicationType: parsed.data.application_type ?? null,
202
+ };
203
+ cacheDocument(document, now() + cimdCacheTtlMs);
204
+ return document;
205
+ }
@@ -1,214 +1,10 @@
1
- import type { McpScopeVocabulary } from '../scope-vocabulary.js';
2
- import type { McpUserProfile } from '../types/primitives.js';
3
- import type { ClientStore, CodeStore, OAuthStores, TokenStore } from './stores.js';
4
- import type { ClientIdMetadataDocument } from './client-metadata-documents.js';
5
- import * as clientMetadataDocuments from './client-metadata-documents.js';
6
- import * as securityUtilities from './security-utilities.js';
7
- import * as canonicalAddressUtilities from './canonicalize-ip-address.js';
8
- export { handleOauthAuthorizationMetadataGet, handleOauthProtectedResourceMetadataGet, handleOauthProtectedResourceMcpMetadataGet, oauthCorsHeaders, } from './discovery-metadata.js';
9
- export type { OAuthDiscoveryConfiguration } from './discovery-metadata.js';
10
- export declare const fetchClientIdMetadataDocument: typeof clientMetadataDocuments.fetchClientIdMetadataDocument;
11
- export declare const isClientIdMetadataDocumentUrl: typeof clientMetadataDocuments.isClientIdMetadataDocumentUrl;
12
- export declare const safeFetchPublicHttpsUrl: typeof clientMetadataDocuments.safeFetchPublicHttpsUrl;
13
- export declare const isAddressInCidr: typeof securityUtilities.isAddressInCidr;
14
- export declare const isValidCidr: typeof securityUtilities.isValidCidr;
15
- export declare const isValidRedirectUri: typeof securityUtilities.isValidRedirectUri;
16
- export declare const isValidClientName: typeof securityUtilities.isValidClientName;
17
- export declare const isExactContentType: typeof securityUtilities.isExactContentType;
18
- export declare const withDeadline: typeof securityUtilities.withDeadline;
19
- export declare const canonicalizeIpAddress: typeof canonicalAddressUtilities.canonicalizeIpAddress;
20
- export declare const expandIpv6Groups: typeof canonicalAddressUtilities.expandIpv6Groups;
21
- export declare const stripPort: typeof canonicalAddressUtilities.stripPort;
22
- export type { ClientIdMetadataDocument, ClientMetadataDocumentFetchDependencies, DnsLookupAllFunction, SafePublicHttpsFetchOptions, } from './client-metadata-documents.js';
23
- export type TrustedProxyHeader = 'x-forwarded-for' | 'forwarded' | 'cf-connecting-ip' | 'fly-client-ip';
24
- export type TrustedProxyConfiguration = {
25
- /** CIDR blocks whose immediate socket peer may supply the configured forwarding header. */
26
- trustedProxyCidrs: string[];
27
- /** Undefined means forwarding headers are never trusted. */
28
- trustedProxyHeader: TrustedProxyHeader | undefined;
29
- /** Number of trusted proxy hops preceding the client in a multi-value header. */
30
- trustedProxyHopCount: number;
31
- };
32
- export type OAuthRequestContext = {
33
- request: Request;
34
- requestUrl: URL;
35
- requestId: string;
36
- /**
37
- * The immediate socket peer, not an adapter-resolved forwarding header.
38
- * The library combines this with `request.headers` and the trusted-proxy
39
- * configuration before deriving a rate-limit or lockout identity.
40
- */
41
- socketAddress?: string;
42
- /** Durable host subject and opaque consent binding, resolved together. */
43
- identity: OAuthIdentity | null;
44
- };
45
- export type OAuthIdentity = {
46
- /** Durable subject identifier persisted on grants and tokens. */
47
- subjectId: string;
48
- /** Opaque account or session value used only to bind consent. */
49
- consentBinding: string;
50
- };
51
- /** Resolves durable attribution and an opaque consent binding in one host lookup. */
52
- export type ResolveIdentityBinding = (request: Request) => Promise<OAuthIdentity | null>;
53
- /** Resolves the host profile required to construct MCP context for a token subject. */
54
- export type ResolveUserProfile = (subjectId: string) => Promise<McpUserProfile | null>;
55
- /** Starts or otherwise handles host authentication for an authorization request. */
56
- export type HandleUnauthenticatedAuthorization = (request: Request) => Response | Promise<Response>;
57
- export type ConsentPresentation = {
58
- mode: 'error';
59
- error: string;
60
- } | {
61
- mode: 'prompt';
62
- transactionId: string;
63
- /** One-time plaintext value rendered into approve and deny submissions. */
64
- csrfToken: string;
65
- /** Verified client redirect URI shown as consent destination context. */
66
- redirectUri: string;
67
- client: {
68
- id: string;
69
- name: string;
70
- };
71
- requester: McpUserProfile;
72
- scopes: Array<{
73
- scope: string;
74
- description: string;
75
- }>;
76
- };
77
- export type RenderConsent = (presentation: ConsentPresentation) => Response | Promise<Response>;
78
- export type OAuthScopeConfiguration<Scope extends string> = {
79
- vocabulary: McpScopeVocabulary<Scope>;
80
- /** Production scopes mechanically derived from the registry being served. */
81
- supportedScopes: readonly Scope[];
82
- };
83
- export type SlidingWindowRateLimiterResult = {
84
- allowed: boolean;
85
- retryAfterSeconds: number;
86
- remainingRequests: number;
87
- };
88
- /**
89
- * Performs one indivisible prune-count-admit operation. Splitting admission
90
- * across remove, count, and add round trips reopens the concurrency race this
91
- * contract exists to prevent.
92
- */
93
- export type AtomicSlidingWindowStore = {
94
- consume(input: {
95
- key: string;
96
- nowMilliseconds: number;
97
- windowMilliseconds: number;
98
- maximumRequests: number;
99
- member: string;
100
- }): Promise<{
101
- allowed: boolean;
102
- retryAfterMilliseconds: number;
103
- remainingRequests: number;
104
- }>;
105
- /**
106
- * Best-effort and non-atomic. This is suitable only for advisory checks
107
- * that tolerate an off-by-one race, never for admission control.
108
- */
109
- peek(input: {
110
- key: string;
111
- nowMilliseconds: number;
112
- windowMilliseconds: number;
113
- }): Promise<number>;
114
- };
115
- export type ConcurrencySlot = {
116
- readonly id: string;
117
- };
118
- export interface ConcurrencySlotStore {
119
- acquire(key: string, maximumConcurrent: number, ttlMilliseconds: number): Promise<ConcurrencySlot | null>;
120
- renew(key: string, slot: ConcurrencySlot, ttlMilliseconds: number): Promise<boolean>;
121
- release(key: string, slot: ConcurrencySlot): Promise<void>;
122
- }
123
- export type RateLimitCategoryConfiguration = {
124
- maximumRequests: number;
125
- windowSeconds: number;
126
- };
127
- export type OAuthRateLimitCategory = 'oauth_authorize' | 'oauth_register' | 'oauth_token_network' | 'oauth_token_client' | 'oauth_revoke' | 'mcp_network' | 'mcp_user' | 'failed_authentication';
128
- export type RateLimitConfiguration = {
129
- categories: Readonly<Record<OAuthRateLimitCategory, RateLimitCategoryConfiguration>>;
130
- /** Maximum live operations admitted through the concurrency slot store. */
131
- maximumConcurrent: number;
132
- /**
133
- * Optional isolation for shared backing stores. Real deployments leave it
134
- * empty; concurrent test runs use distinct values instead of weakening the
135
- * limits they are meant to exercise.
136
- */
137
- keyNamespace?: string;
138
- };
139
- /** Only the Redis operations required by the library-provided store factories. */
140
- export interface MinimalRedisClient {
141
- eval(script: string, options: {
142
- keys: string[];
143
- arguments: string[];
144
- }): Promise<unknown>;
145
- zRem(key: string, member: string): Promise<number>;
146
- }
147
- export type OAuthConfiguration = {
148
- /** Exact OAuth issuer identifier. Consumers must use this same value in authorization responses. */
1
+ import type { Principal, VerifiedGrant } from "../http.js";
2
+ export { OAuthStore, type OAuthGrant } from "../oauth-store.js";
3
+ export { hostedOAuth } from "./issuer.js";
4
+ /** Configure a resource to advertise and verify an external authorization server. */
5
+ export declare function externalOAuth<T extends Principal>(authority: {
149
6
  issuer: string;
150
- baseUrl: URL;
151
- /** Canonical RFC 8707 resource identifier accepted by both token grants. */
152
- resource: URL;
153
- accessTokenTtlSeconds: number;
154
- refreshTokenTtlSeconds: number;
155
- clientSecretTtlSeconds: number;
156
- isTrustedOrigin(origin: string): boolean;
157
- trustedProxy: TrustedProxyConfiguration;
158
- rateLimits: RateLimitConfiguration;
159
- /**
160
- * Authorization-server metadata advertises MCP Apps support only when this
161
- * is enabled and the injected registry contains an MCP App resource.
162
- */
163
- mcpUiExtension: {
164
- enabled: boolean;
165
- };
166
- rateLimitStores?: {
167
- slidingWindow: AtomicSlidingWindowStore;
168
- concurrencySlots?: ConcurrencySlotStore;
169
- };
170
- };
171
- export type CrossInstanceMessaging = {
172
- publish(channel: string, message: string): Promise<void>;
173
- subscribe(channel: string, onMessage: (message: string) => void): Promise<() => Promise<void>>;
174
- };
175
- export type OAuthHostSeams<Scope extends string> = {
176
- fetchClientIdMetadataDocument(clientId: string): Promise<ClientIdMetadataDocument | null>;
177
- resolveIdentityBinding: ResolveIdentityBinding;
178
- resolveUserProfile: ResolveUserProfile;
179
- handleUnauthenticatedAuthorization: HandleUnauthenticatedAuthorization;
180
- renderConsent: RenderConsent;
181
- stores: OAuthStores;
182
- scopes: OAuthScopeConfiguration<Scope>;
183
- configuration: OAuthConfiguration;
184
- /** Existing host credential hash function; plaintext authorization codes never enter stores. */
185
- hashCredential(value: string): string;
186
- crossInstanceMessaging?: CrossInstanceMessaging;
187
- /** Preserve host metrics and structured logs without coupling the library to a logger. */
188
- recordEvent?(event: {
189
- category: 'authorization' | 'registration' | 'client_authentication' | 'token_exchange' | 'refresh' | 'revocation';
190
- outcome: string;
191
- attributes?: Readonly<Record<string, string | boolean>>;
192
- }): void;
193
- };
194
- /** Host capabilities needed by endpoints that do not render application UI. */
195
- export type OAuthStatelessHostSeams<Scope extends string> = Pick<OAuthHostSeams<Scope>, 'scopes' | 'configuration' | 'crossInstanceMessaging' | 'recordEvent'> & {
196
- stores: {
197
- clients: ClientStore;
198
- codes: CodeStore;
199
- tokens: TokenStore;
200
- };
201
- /** Existing host credential hash function; plaintext credentials never cross into stores. */
202
- hashCredential(value: string): string;
203
- /** Disconnect or notify live grants after a replay or explicit revocation. */
204
- publishGrantRevocation?(subjectId: string): Promise<void>;
205
- };
206
- export { authenticateOauthClient } from './client-authentication.js';
207
- export { constantTimeEquals } from './security-utilities.js';
208
- export { handleOauthRegisterPost } from './registration-endpoint.js';
209
- export { handleOauthTokenPost } from './token-endpoint.js';
210
- export { handleOauthRevokePost } from './revocation-endpoint.js';
211
- export { authorizeFormParameterNames, handleOauthAuthorizeApprove, handleOauthAuthorizeDeny, handleOauthAuthorizeGet, } from './authorize-endpoint.js';
212
- export { isValidPkceCodeChallenge, isValidPkceCodeVerifier } from './pkce-validation.js';
213
- export { isSocketPeerTrusted, resolveOauthNetworkIdentity } from './network-identity.js';
214
- export type { AccessToken, AuthorizationCode, AuthorizationTransaction, RefreshToken, RegisteredClient, } from './stores.js';
7
+ verifyAccessToken(token: string): Promise<VerifiedGrant | null>;
8
+ resolvePrincipal(grant: VerifiedGrant): Promise<T | null>;
9
+ subscribeGrantRevocation?(grantId: string, listener: () => void): () => void;
10
+ }): typeof authority;
@@ -1,69 +1,6 @@
1
- import {
2
- authenticateOauthClient,
3
- authorizeFormParameterNames,
4
- canonicalizeIpAddress,
5
- expandIpv6Groups,
6
- fetchClientIdMetadataDocument,
7
- handleOauthAuthorizationMetadataGet,
8
- handleOauthAuthorizeApprove,
9
- handleOauthAuthorizeDeny,
10
- handleOauthAuthorizeGet,
11
- handleOauthProtectedResourceMcpMetadataGet,
12
- handleOauthProtectedResourceMetadataGet,
13
- handleOauthRegisterPost,
14
- handleOauthRevokePost,
15
- handleOauthTokenPost,
16
- isAddressInCidr,
17
- isClientIdMetadataDocumentUrl,
18
- isExactContentType,
19
- isSocketPeerTrusted,
20
- isValidCidr,
21
- isValidClientName,
22
- isValidPkceCodeChallenge,
23
- isValidPkceCodeVerifier,
24
- isValidRedirectUri,
25
- oauthCorsHeaders,
26
- resolveOauthNetworkIdentity,
27
- safeFetchPublicHttpsUrl,
28
- stripPort,
29
- withDeadline
30
- } from "../chunk-en76akaq.js";
31
- import {
32
- constantTimeEquals
33
- } from "../chunk-88nhf6xt.js";
34
- import"../chunk-3ek3knfm.js";
35
- import"../chunk-rxnyn7tf.js";
36
- import"../chunk-k6fm3cmk.js";
37
- import"../chunk-3rr24vhh.js";
38
- import"../chunk-xcf742mf.js";
39
- export {
40
- authenticateOauthClient,
41
- authorizeFormParameterNames,
42
- canonicalizeIpAddress,
43
- constantTimeEquals,
44
- expandIpv6Groups,
45
- fetchClientIdMetadataDocument,
46
- handleOauthAuthorizationMetadataGet,
47
- handleOauthAuthorizeApprove,
48
- handleOauthAuthorizeDeny,
49
- handleOauthAuthorizeGet,
50
- handleOauthProtectedResourceMcpMetadataGet,
51
- handleOauthProtectedResourceMetadataGet,
52
- handleOauthRegisterPost,
53
- handleOauthRevokePost,
54
- handleOauthTokenPost,
55
- isAddressInCidr,
56
- isClientIdMetadataDocumentUrl,
57
- isExactContentType,
58
- isSocketPeerTrusted,
59
- isValidCidr,
60
- isValidClientName,
61
- isValidPkceCodeChallenge,
62
- isValidPkceCodeVerifier,
63
- isValidRedirectUri,
64
- oauthCorsHeaders,
65
- resolveOauthNetworkIdentity,
66
- safeFetchPublicHttpsUrl,
67
- stripPort,
68
- withDeadline
69
- };
1
+ export { OAuthStore } from "../oauth-store.js";
2
+ export { hostedOAuth } from "./issuer.js";
3
+ /** Configure a resource to advertise and verify an external authorization server. */
4
+ export function externalOAuth(authority) {
5
+ return authority;
6
+ }