@jangmanj/mcp 0.0.0-stage → 0.13.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 (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +337 -2
  3. package/adapters/pi/bridge.ts +721 -0
  4. package/adapters/pi/config.ts +364 -0
  5. package/adapters/pi/content-offloaded.ts +53 -0
  6. package/adapters/pi/content.ts +78 -0
  7. package/adapters/pi/diagnostics.ts +26 -0
  8. package/adapters/pi/elicitation.ts +133 -0
  9. package/adapters/pi/index.ts +210 -0
  10. package/adapters/pi/oauth.ts +219 -0
  11. package/adapters/pi/pi-api.ts +133 -0
  12. package/adapters/pi/resources.ts +177 -0
  13. package/adapters/pi/result-files.ts +32 -0
  14. package/adapters/pi/tasks.ts +49 -0
  15. package/dist/auth/client-credentials.d.ts +65 -0
  16. package/dist/auth/client-credentials.js +388 -0
  17. package/dist/auth/discovery.d.ts +28 -0
  18. package/dist/auth/discovery.js +125 -0
  19. package/dist/auth/index.d.ts +9 -0
  20. package/dist/auth/index.js +5 -0
  21. package/dist/auth/node-ports.d.ts +8 -0
  22. package/dist/auth/node-ports.js +67 -0
  23. package/dist/auth/protocol.d.ts +12 -0
  24. package/dist/auth/protocol.js +39 -0
  25. package/dist/auth/provider.d.ts +114 -0
  26. package/dist/auth/provider.js +407 -0
  27. package/dist/auth/safe-fetch.d.ts +14 -0
  28. package/dist/auth/safe-fetch.js +130 -0
  29. package/dist/client/events.d.ts +33 -0
  30. package/dist/client/events.js +84 -0
  31. package/dist/client/index.d.ts +65 -0
  32. package/dist/client/index.js +128 -0
  33. package/dist/core/auth-types.d.ts +36 -0
  34. package/dist/core/auth-types.js +11 -0
  35. package/dist/core/bearer-challenge.d.ts +3 -0
  36. package/dist/core/bearer-challenge.js +63 -0
  37. package/dist/core/cancel.d.ts +70 -0
  38. package/dist/core/cancel.js +177 -0
  39. package/dist/core/extension.d.ts +33 -0
  40. package/dist/core/extension.js +145 -0
  41. package/dist/core/index.d.ts +73 -0
  42. package/dist/core/index.js +129 -0
  43. package/dist/core/jsonrpc.d.ts +49 -0
  44. package/dist/core/jsonrpc.js +80 -0
  45. package/dist/core/lifecycle.d.ts +128 -0
  46. package/dist/core/lifecycle.js +251 -0
  47. package/dist/core/outcome.d.ts +98 -0
  48. package/dist/core/outcome.js +32 -0
  49. package/dist/core/ports.d.ts +144 -0
  50. package/dist/core/ports.js +67 -0
  51. package/dist/core/progress.d.ts +81 -0
  52. package/dist/core/progress.js +205 -0
  53. package/dist/core/request.d.ts +108 -0
  54. package/dist/core/request.js +578 -0
  55. package/dist/core/schema/index.d.ts +1 -0
  56. package/dist/core/schema/index.js +1 -0
  57. package/dist/core/schema/types.d.ts +4154 -0
  58. package/dist/core/schema/types.js +6 -0
  59. package/dist/core/telemetry.d.ts +25 -0
  60. package/dist/core/telemetry.js +37 -0
  61. package/dist/ext-events/index.d.ts +79 -0
  62. package/dist/ext-events/index.js +218 -0
  63. package/dist/ext-events/model.d.ts +10 -0
  64. package/dist/ext-events/model.js +6 -0
  65. package/dist/ext-events/push.d.ts +18 -0
  66. package/dist/ext-events/push.js +101 -0
  67. package/dist/ext-events/stream.d.ts +6 -0
  68. package/dist/ext-events/stream.js +60 -0
  69. package/dist/ext-server-cards/index.d.ts +107 -0
  70. package/dist/ext-server-cards/index.js +249 -0
  71. package/dist/ext-skills/cache.d.ts +20 -0
  72. package/dist/ext-skills/cache.js +101 -0
  73. package/dist/ext-skills/client.d.ts +82 -0
  74. package/dist/ext-skills/client.js +292 -0
  75. package/dist/ext-skills/extension.d.ts +16 -0
  76. package/dist/ext-skills/extension.js +29 -0
  77. package/dist/ext-skills/index.d.ts +4 -0
  78. package/dist/ext-skills/index.js +4 -0
  79. package/dist/ext-skills/verify.d.ts +57 -0
  80. package/dist/ext-skills/verify.js +168 -0
  81. package/dist/index.d.ts +1 -0
  82. package/dist/index.js +1 -0
  83. package/dist/mrtr-cache/cache.d.ts +51 -0
  84. package/dist/mrtr-cache/cache.js +295 -0
  85. package/dist/mrtr-cache/client.d.ts +24 -0
  86. package/dist/mrtr-cache/client.js +44 -0
  87. package/dist/mrtr-cache/common.d.ts +10 -0
  88. package/dist/mrtr-cache/common.js +9 -0
  89. package/dist/mrtr-cache/elicitation.d.ts +42 -0
  90. package/dist/mrtr-cache/elicitation.js +221 -0
  91. package/dist/mrtr-cache/index.d.ts +9 -0
  92. package/dist/mrtr-cache/index.js +8 -0
  93. package/dist/mrtr-cache/mrtr.d.ts +37 -0
  94. package/dist/mrtr-cache/mrtr.js +250 -0
  95. package/dist/mrtr-cache/refresh.d.ts +8 -0
  96. package/dist/mrtr-cache/refresh.js +30 -0
  97. package/dist/mrtr-cache/stream.d.ts +5 -0
  98. package/dist/mrtr-cache/stream.js +18 -0
  99. package/dist/mrtr-cache/subscriptions.d.ts +96 -0
  100. package/dist/mrtr-cache/subscriptions.js +288 -0
  101. package/dist/mrtr-cache/tasks.d.ts +103 -0
  102. package/dist/mrtr-cache/tasks.js +444 -0
  103. package/dist/ops/common.d.ts +18 -0
  104. package/dist/ops/common.js +39 -0
  105. package/dist/ops/completion.d.ts +44 -0
  106. package/dist/ops/completion.js +65 -0
  107. package/dist/ops/content.d.ts +40 -0
  108. package/dist/ops/content.js +117 -0
  109. package/dist/ops/icons.d.ts +29 -0
  110. package/dist/ops/icons.js +82 -0
  111. package/dist/ops/index.d.ts +30 -0
  112. package/dist/ops/index.js +28 -0
  113. package/dist/ops/pagination.d.ts +32 -0
  114. package/dist/ops/pagination.js +65 -0
  115. package/dist/ops/prompts.d.ts +32 -0
  116. package/dist/ops/prompts.js +68 -0
  117. package/dist/ops/resources.d.ts +42 -0
  118. package/dist/ops/resources.js +104 -0
  119. package/dist/ops/schema.d.ts +39 -0
  120. package/dist/ops/schema.js +163 -0
  121. package/dist/ops/tools.d.ts +88 -0
  122. package/dist/ops/tools.js +169 -0
  123. package/dist/ops/uri-template.d.ts +3 -0
  124. package/dist/ops/uri-template.js +101 -0
  125. package/dist/server/index.d.ts +5 -0
  126. package/dist/server/index.js +5 -0
  127. package/dist/server/mrtr.d.ts +38 -0
  128. package/dist/server/mrtr.js +99 -0
  129. package/dist/server/protocol.d.ts +21 -0
  130. package/dist/server/protocol.js +49 -0
  131. package/dist/server/server.d.ts +105 -0
  132. package/dist/server/server.js +383 -0
  133. package/dist/server/skills.d.ts +45 -0
  134. package/dist/server/skills.js +73 -0
  135. package/dist/server/uri.d.ts +2 -0
  136. package/dist/server/uri.js +27 -0
  137. package/dist/server-events/bus.d.ts +40 -0
  138. package/dist/server-events/bus.js +84 -0
  139. package/dist/server-events/events.d.ts +36 -0
  140. package/dist/server-events/events.js +108 -0
  141. package/dist/server-events/index.d.ts +6 -0
  142. package/dist/server-events/index.js +6 -0
  143. package/dist/server-events/notices.d.ts +24 -0
  144. package/dist/server-events/notices.js +31 -0
  145. package/dist/server-events/subscriptions.d.ts +33 -0
  146. package/dist/server-events/subscriptions.js +77 -0
  147. package/dist/server-events/tasks.d.ts +43 -0
  148. package/dist/server-events/tasks.js +101 -0
  149. package/dist/server-events/types.d.ts +25 -0
  150. package/dist/server-events/types.js +34 -0
  151. package/dist/server-transport/auth.d.ts +20 -0
  152. package/dist/server-transport/auth.js +29 -0
  153. package/dist/server-transport/channel.d.ts +17 -0
  154. package/dist/server-transport/channel.js +47 -0
  155. package/dist/server-transport/http.d.ts +19 -0
  156. package/dist/server-transport/http.js +209 -0
  157. package/dist/server-transport/index.d.ts +4 -0
  158. package/dist/server-transport/index.js +4 -0
  159. package/dist/server-transport/stdio.d.ts +16 -0
  160. package/dist/server-transport/stdio.js +83 -0
  161. package/dist/telemetry-otel/index.d.ts +64 -0
  162. package/dist/telemetry-otel/index.js +196 -0
  163. package/dist/testing/index.d.ts +36 -0
  164. package/dist/testing/index.js +140 -0
  165. package/dist/transport-http/headers.d.ts +24 -0
  166. package/dist/transport-http/headers.js +140 -0
  167. package/dist/transport-http/index.d.ts +3 -0
  168. package/dist/transport-http/index.js +3 -0
  169. package/dist/transport-http/sse.d.ts +33 -0
  170. package/dist/transport-http/sse.js +152 -0
  171. package/dist/transport-http/transport.d.ts +66 -0
  172. package/dist/transport-http/transport.js +854 -0
  173. package/dist/transport-stdio/framing.d.ts +50 -0
  174. package/dist/transport-stdio/framing.js +154 -0
  175. package/dist/transport-stdio/index.d.ts +4 -0
  176. package/dist/transport-stdio/index.js +4 -0
  177. package/dist/transport-stdio/stderr-ring.d.ts +27 -0
  178. package/dist/transport-stdio/stderr-ring.js +105 -0
  179. package/dist/transport-stdio/transport.d.ts +142 -0
  180. package/dist/transport-stdio/transport.js +743 -0
  181. package/dist/transport-stdio/write-queue.d.ts +48 -0
  182. package/dist/transport-stdio/write-queue.js +147 -0
  183. package/package.json +134 -4
@@ -0,0 +1,388 @@
1
+ import { createHash, createPrivateKey, sign as cryptoSign } from 'node:crypto';
2
+ import { getDocument, object, strings } from './discovery.js';
3
+ import { AuthError, basicAuthorization, cancelled, canonicalResource, fail, parseBearerChallenges, secureUrl, withAbort } from './protocol.js';
4
+ import { SafeFetch } from './safe-fetch.js';
5
+ const JWT_BEARER = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';
6
+ const SKEW_MS = 10_000;
7
+ const DEFAULT_TTL_S = 300;
8
+ const ASSERTION_TTL_S = 60;
9
+ const textEncoder = new TextEncoder();
10
+ const ALLOWED_SIGNING_ALGS = new Set(['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512', 'EdDSA']);
11
+ const RSA_HASH_FOR_ALG = {
12
+ RS256: { web: 'SHA-256', node: 'sha256' },
13
+ RS384: { web: 'SHA-384', node: 'sha384' },
14
+ RS512: { web: 'SHA-512', node: 'sha512' },
15
+ };
16
+ const EC_SPEC_FOR_ALG = {
17
+ ES256: { curve: 'P-256', web: 'SHA-256', node: 'sha256' },
18
+ ES384: { curve: 'P-384', web: 'SHA-384', node: 'sha384' },
19
+ ES512: { curve: 'P-521', web: 'SHA-512', node: 'sha512' },
20
+ };
21
+ /** Sign with a non-extractable WebCrypto private key. ECDSA output is the raw r||s form JWS requires. */
22
+ export function createWebCryptoAssertionSigner(alg, privateKey, kid) {
23
+ if (privateKey.type !== 'private')
24
+ throw new Error('a private CryptoKey is required');
25
+ if (!ALLOWED_SIGNING_ALGS.has(alg))
26
+ throw new AuthError('auth-unavailable', 'unsupported-signing-alg');
27
+ const keyAlg = privateKey.algorithm;
28
+ let params;
29
+ if (alg === 'RS256' || alg === 'RS384' || alg === 'RS512') {
30
+ const spec = RSA_HASH_FOR_ALG[alg];
31
+ if (keyAlg.name !== 'RSASSA-PKCS1-v1_5' || keyAlg.hash?.name !== spec.web) {
32
+ throw new AuthError('auth-unavailable', 'signing-alg-mismatch');
33
+ }
34
+ params = { name: 'RSASSA-PKCS1-v1_5' };
35
+ }
36
+ else if (alg === 'ES256' || alg === 'ES384' || alg === 'ES512') {
37
+ const spec = EC_SPEC_FOR_ALG[alg];
38
+ if (keyAlg.name !== 'ECDSA' || keyAlg.namedCurve !== spec.curve) {
39
+ throw new AuthError('auth-unavailable', 'signing-alg-mismatch');
40
+ }
41
+ params = { name: 'ECDSA', hash: spec.web };
42
+ }
43
+ else {
44
+ if (keyAlg.name !== 'Ed25519' && keyAlg.name !== 'Ed448') {
45
+ throw new AuthError('auth-unavailable', 'signing-alg-mismatch');
46
+ }
47
+ params = { name: keyAlg.name };
48
+ }
49
+ return {
50
+ alg,
51
+ ...(kid !== undefined ? { kid } : {}),
52
+ async sign(input) {
53
+ return new Uint8Array(await crypto.subtle.sign(params, privateKey, input));
54
+ },
55
+ };
56
+ }
57
+ /** Sign with a PEM-encoded private key (PKCS#8, PKCS#1 RSA, or SEC1 EC) via Node's `node:crypto`. */
58
+ export function createPemAssertionSigner(privateKeyPem, options) {
59
+ if (options?.alg !== undefined && !ALLOWED_SIGNING_ALGS.has(options.alg)) {
60
+ throw new AuthError('auth-unavailable', 'unsupported-signing-alg');
61
+ }
62
+ if (typeof privateKeyPem !== 'string' || privateKeyPem.trim() === '') {
63
+ throw new AuthError('auth-unavailable', 'invalid-private-key');
64
+ }
65
+ let key;
66
+ try {
67
+ key = createPrivateKey(privateKeyPem);
68
+ }
69
+ catch {
70
+ // Redact OpenSSL diagnostics and PEM bytes from errors.
71
+ throw new AuthError('auth-unavailable', 'invalid-private-key');
72
+ }
73
+ let resolvedAlg;
74
+ const keyType = key.asymmetricKeyType;
75
+ if (keyType === 'rsa') {
76
+ resolvedAlg = options?.alg ?? 'RS256';
77
+ if (resolvedAlg !== 'RS256' && resolvedAlg !== 'RS384' && resolvedAlg !== 'RS512') {
78
+ throw new AuthError('auth-unavailable', 'signing-alg-mismatch');
79
+ }
80
+ }
81
+ else if (keyType === 'ec') {
82
+ const curve = key.asymmetricKeyDetails?.namedCurve;
83
+ const inferred = curve === 'prime256v1' ? 'ES256' : curve === 'secp384r1' ? 'ES384' : curve === 'secp521r1' ? 'ES512' : undefined;
84
+ if (!inferred)
85
+ throw new AuthError('auth-unavailable', 'invalid-private-key');
86
+ if (options?.alg !== undefined && options.alg !== inferred) {
87
+ throw new AuthError('auth-unavailable', 'signing-alg-mismatch');
88
+ }
89
+ resolvedAlg = inferred;
90
+ }
91
+ else if (keyType === 'ed25519' || keyType === 'ed448') {
92
+ if (options?.alg !== undefined && options.alg !== 'EdDSA') {
93
+ throw new AuthError('auth-unavailable', 'signing-alg-mismatch');
94
+ }
95
+ resolvedAlg = 'EdDSA';
96
+ }
97
+ else {
98
+ throw new AuthError('auth-unavailable', 'invalid-private-key');
99
+ }
100
+ return {
101
+ alg: resolvedAlg,
102
+ ...(options?.kid !== undefined ? { kid: options.kid } : {}),
103
+ sign(input) {
104
+ if (resolvedAlg === 'EdDSA') {
105
+ return new Uint8Array(cryptoSign(null, input, key));
106
+ }
107
+ if (resolvedAlg === 'ES256' || resolvedAlg === 'ES384' || resolvedAlg === 'ES512') {
108
+ return new Uint8Array(cryptoSign(EC_SPEC_FOR_ALG[resolvedAlg].node, input, { key, dsaEncoding: 'ieee-p1363' }));
109
+ }
110
+ return new Uint8Array(cryptoSign(RSA_HASH_FOR_ALG[resolvedAlg].node, input, key));
111
+ },
112
+ };
113
+ }
114
+ export function isConfigured(c) {
115
+ const hasPem = typeof c.privateKeyPem === 'string' && c.privateKeyPem.trim() !== '';
116
+ const hasSecret = (typeof c.secret === 'string' && c.secret !== '') || (!!c.credentials && !!c.credentialKey);
117
+ return !!c.resource && !!c.clientId && (hasSecret || !!c.signer || hasPem);
118
+ }
119
+ function secureNoHash(input, dev) {
120
+ if (typeof input !== 'string')
121
+ return fail('invalid-url');
122
+ const url = secureUrl(input, dev);
123
+ if (url.hash)
124
+ fail('invalid-url');
125
+ return url;
126
+ }
127
+ function validateIssuerUrl(input, dev) {
128
+ const url = secureNoHash(input, dev);
129
+ if (url.search || /[?#]/u.test(input))
130
+ fail('as-issuer-invalid');
131
+ return url;
132
+ }
133
+ async function signAssertion(signer, claims) {
134
+ const b64 = (bytes) => Buffer.from(bytes).toString('base64url');
135
+ const iat = Math.floor(claims.nowMs / 1000);
136
+ const header = { alg: signer.alg, typ: 'JWT', ...(signer.kid !== undefined ? { kid: signer.kid } : {}) };
137
+ const payload = { iss: claims.clientId, sub: claims.clientId, aud: claims.audience, iat, exp: iat + claims.ttlSeconds, jti: claims.jti };
138
+ const input = `${b64(textEncoder.encode(JSON.stringify(header)))}.${b64(textEncoder.encode(JSON.stringify(payload)))}`;
139
+ return `${input}.${b64(await signer.sign(textEncoder.encode(input)))}`;
140
+ }
141
+ /** OAuth 2.0 `client_credentials` provider supporting client secrets and RFC 7523 `private_key_jwt` assertions. */
142
+ export class ClientCredentialsAuth {
143
+ config;
144
+ stepUpLimit = 0;
145
+ fetcher;
146
+ resource;
147
+ dev;
148
+ signer;
149
+ pinned;
150
+ token;
151
+ inflight;
152
+ constructor(config) {
153
+ this.config = config;
154
+ if (!isConfigured(config))
155
+ throw new AuthError('auth-unavailable', 'not-configured');
156
+ if (config.signer && config.privateKeyPem !== undefined) {
157
+ throw new AuthError('auth-unavailable', 'invalid-config');
158
+ }
159
+ this.dev = config.allowInsecureDev === true;
160
+ secureNoHash(config.resource, this.dev);
161
+ this.resource = canonicalResource(config.resource);
162
+ this.fetcher = config.fetch ?? new SafeFetch({ allowInsecureDev: this.dev });
163
+ this.pinned = config.expectedIssuer;
164
+ if (this.pinned !== undefined)
165
+ validateIssuerUrl(this.pinned, this.dev);
166
+ if (config.authServerMetadataUrl !== undefined)
167
+ secureNoHash(config.authServerMetadataUrl, this.dev);
168
+ if (config.tokenEndpoint !== undefined)
169
+ secureNoHash(config.tokenEndpoint, this.dev);
170
+ if (config.privateKeyPem !== undefined) {
171
+ this.signer = createPemAssertionSigner(config.privateKeyPem, {
172
+ ...(config.alg !== undefined ? { alg: config.alg } : {}),
173
+ ...(config.kid !== undefined ? { kid: config.kid } : {}),
174
+ });
175
+ }
176
+ else {
177
+ this.signer = config.signer;
178
+ }
179
+ if (config.tokenEndpoint !== undefined && config.authServerMetadataUrl === undefined && this.signer && this.pinned === undefined) {
180
+ throw new AuthError('auth-unavailable', 'expected-issuer-required');
181
+ }
182
+ }
183
+ contextId() {
184
+ const digest = createHash('sha256').update(`${this.resource}\n${this.config.clientId}\n${this.pinned ?? ''}`).digest('base64url');
185
+ return `cc:${digest.slice(0, 22)}`;
186
+ }
187
+ async headerFor(url, _operation, context) {
188
+ let target;
189
+ try {
190
+ target = canonicalResource(url);
191
+ }
192
+ catch {
193
+ return undefined;
194
+ }
195
+ if (target !== this.resource)
196
+ return undefined;
197
+ const token = await this.current(context?.signal);
198
+ return { authorization: `Bearer ${token.value}`, contextId: this.contextId(), credentialVersion: token.version };
199
+ }
200
+ async onChallenge(challenge, signal, _context) {
201
+ if (challenge.status === 403) {
202
+ const insufficient = parseBearerChallenges(challenge.wwwAuthenticate ?? '').some((c) => c.error === 'insufficient_scope');
203
+ // No interactive step-up for a machine credential: abort instead of retrying.
204
+ if (insufficient)
205
+ throw new AuthError('auth-failure', 'insufficient-scope');
206
+ return false;
207
+ }
208
+ if (this.token && challenge.credentialVersion !== null && challenge.credentialVersion !== undefined
209
+ && challenge.credentialVersion !== this.token.version)
210
+ return true;
211
+ if (this.token) {
212
+ this.token = undefined;
213
+ this.diag('token-invalidated');
214
+ }
215
+ await this.current(signal);
216
+ return true;
217
+ }
218
+ current(signal) {
219
+ const t = this.token;
220
+ if (t && this.now() < t.expiresAt - SKEW_MS)
221
+ return Promise.resolve(t);
222
+ this.inflight ??= this.acquire().then((fresh) => { this.token = fresh; this.inflight = undefined; return fresh; }, (error) => { this.inflight = undefined; throw error; });
223
+ return signal ? withAbort(this.inflight, signal, cancelled) : this.inflight;
224
+ }
225
+ now() { return this.config.clock?.now() ?? Date.now(); }
226
+ diag(event, detail) {
227
+ try {
228
+ this.config.onDiagnostic?.({ event, ...(detail !== undefined ? { detail } : {}) });
229
+ }
230
+ catch { /* host hook failure is not ours */ }
231
+ }
232
+ async acquire() {
233
+ try {
234
+ const signal = AbortSignal.timeout(30_000);
235
+ const as = await this.discover(signal);
236
+ const token = await this.requestToken(as, signal);
237
+ this.diag('token-acquired', new URL(as.issuer).host);
238
+ return { ...token, version: {} };
239
+ }
240
+ catch (error) {
241
+ const out = error instanceof AuthError ? error : new AuthError('auth-failure', 'token-request-failed');
242
+ this.diag('token-failed', out.reason);
243
+ throw out;
244
+ }
245
+ }
246
+ /** PRM then AS metadata (or explicit endpoint/metadata overrides). Never reads or calls a registration endpoint. */
247
+ async discover(signal) {
248
+ if (this.config.tokenEndpoint !== undefined && this.config.authServerMetadataUrl === undefined) {
249
+ const endpoint = secureNoHash(this.config.tokenEndpoint, this.dev);
250
+ return {
251
+ issuer: this.pinned ?? endpoint.origin,
252
+ tokenEndpoint: endpoint.href,
253
+ methods: [],
254
+ algs: [],
255
+ };
256
+ }
257
+ if (this.config.authServerMetadataUrl !== undefined) {
258
+ const metaUrl = secureNoHash(this.config.authServerMetadataUrl, this.dev).href;
259
+ const doc = await getDocument(this.fetcher, metaUrl, signal);
260
+ if (!doc)
261
+ return fail('as-metadata-missing');
262
+ const rawIssuer = doc['issuer'];
263
+ if (typeof rawIssuer !== 'string')
264
+ return fail('as-issuer-invalid');
265
+ validateIssuerUrl(rawIssuer, this.dev);
266
+ if (this.pinned !== undefined && rawIssuer !== this.pinned)
267
+ fail('as-issuer-mismatch');
268
+ this.pinned = rawIssuer;
269
+ const tokenEndpoint = secureNoHash(this.config.tokenEndpoint ?? doc['token_endpoint'], this.dev).href;
270
+ return {
271
+ issuer: rawIssuer,
272
+ tokenEndpoint,
273
+ methods: strings(doc['token_endpoint_auth_methods_supported']),
274
+ algs: strings(doc['token_endpoint_auth_signing_alg_values_supported']),
275
+ };
276
+ }
277
+ const url = secureNoHash(this.resource, this.dev);
278
+ const root = `${url.origin}/.well-known/oauth-protected-resource`;
279
+ const candidates = [...new Set([`${root}${url.pathname === '/' ? '' : url.pathname}${url.search}`, root])];
280
+ let prm;
281
+ for (const candidate of candidates) {
282
+ const doc = await getDocument(this.fetcher, candidate, signal);
283
+ if (!doc)
284
+ continue;
285
+ if (doc['resource'] !== (candidate === root && candidates.length > 1 ? url.origin : this.resource))
286
+ fail('prm-resource-mismatch');
287
+ prm = doc;
288
+ break;
289
+ }
290
+ const issuers = prm ? [...new Set(strings(prm['authorization_servers']))] : [];
291
+ if (!issuers.length)
292
+ fail('prm-invalid');
293
+ // Pin the issuer so credentials only ever go to the validated AS.
294
+ const issuer = this.pinned ?? issuers[0];
295
+ if (!issuers.includes(issuer))
296
+ fail('issuer-mismatch');
297
+ this.pinned = issuer;
298
+ return await this.metadata(issuer, signal);
299
+ }
300
+ async metadata(issuer, signal) {
301
+ const url = validateIssuerUrl(issuer, this.dev);
302
+ const path = url.pathname === '/' ? '' : url.pathname.replace(/\/$/u, '');
303
+ const urls = [`${url.origin}/.well-known/oauth-authorization-server${path}`, `${url.origin}/.well-known/openid-configuration${path}`];
304
+ if (path)
305
+ urls.push(`${url.origin}${path}/.well-known/openid-configuration`);
306
+ for (const candidate of urls) {
307
+ const doc = await getDocument(this.fetcher, candidate, signal);
308
+ if (!doc)
309
+ continue;
310
+ if (doc['issuer'] !== issuer)
311
+ fail('as-issuer-mismatch');
312
+ return {
313
+ issuer,
314
+ tokenEndpoint: secureNoHash(doc['token_endpoint'], this.dev).href,
315
+ methods: strings(doc['token_endpoint_auth_methods_supported']),
316
+ algs: strings(doc['token_endpoint_auth_signing_alg_values_supported']),
317
+ };
318
+ }
319
+ return fail('as-metadata-missing');
320
+ }
321
+ async secretValue() {
322
+ const { secret, credentials, credentialKey } = this.config;
323
+ const value = secret ?? (credentials && credentialKey !== undefined ? await credentials.get(credentialKey) : undefined);
324
+ if (!value)
325
+ throw new AuthError('auth-unavailable', 'credentials-missing');
326
+ return value;
327
+ }
328
+ async requestToken(as, signal) {
329
+ const form = new URLSearchParams({ grant_type: 'client_credentials', resource: this.resource });
330
+ if (this.config.scopes?.length)
331
+ form.set('scope', this.config.scopes.join(' '));
332
+ const headers = { 'content-type': 'application/x-www-form-urlencoded' };
333
+ const { clientId } = this.config;
334
+ const signer = this.signer;
335
+ if (signer) {
336
+ if (as.methods.length && !as.methods.includes('private_key_jwt'))
337
+ fail('auth-method-unsupported');
338
+ if (as.algs.length && !as.algs.includes(signer.alg))
339
+ fail('signing-alg-unsupported');
340
+ const random = this.config.random?.bytes(16) ?? crypto.getRandomValues(new Uint8Array(16));
341
+ form.set('client_assertion_type', JWT_BEARER);
342
+ form.set('client_assertion', await signAssertion(signer, {
343
+ clientId: clientId, audience: as.issuer, nowMs: this.now(), ttlSeconds: ASSERTION_TTL_S, jti: Buffer.from(random).toString('hex'),
344
+ }));
345
+ }
346
+ else {
347
+ const secret = await this.secretValue();
348
+ const methods = as.methods.length ? as.methods : ['client_secret_basic'];
349
+ if (methods.includes('client_secret_basic')) {
350
+ headers['authorization'] = basicAuthorization(clientId, secret);
351
+ }
352
+ else if (methods.includes('client_secret_post')) {
353
+ form.set('client_id', clientId);
354
+ form.set('client_secret', secret);
355
+ }
356
+ else
357
+ fail('auth-method-unsupported');
358
+ }
359
+ let res;
360
+ try {
361
+ res = await this.fetcher.fetch(as.tokenEndpoint, { method: 'POST', headers, body: form.toString(), credentials: 'omit', redirect: 'manual', signal });
362
+ }
363
+ catch (error) {
364
+ if (error instanceof AuthError)
365
+ throw error;
366
+ return fail('token-request-failed');
367
+ }
368
+ if (!res.ok) {
369
+ await res.body?.cancel();
370
+ return fail('token-request-rejected');
371
+ }
372
+ let body;
373
+ try {
374
+ body = object(await res.json());
375
+ }
376
+ catch {
377
+ return fail('invalid-token-response');
378
+ }
379
+ const value = body['access_token'];
380
+ if (typeof value !== 'string' || !/^[A-Za-z\d._~+/-]+=*$/u.test(value))
381
+ return fail('invalid-token-response');
382
+ if (typeof body['token_type'] !== 'string' || body['token_type'].toLowerCase() !== 'bearer')
383
+ return fail('invalid-token-response');
384
+ const ttl = typeof body['expires_in'] === 'number' && Number.isFinite(body['expires_in']) && body['expires_in'] > 0
385
+ ? body['expires_in'] : DEFAULT_TTL_S;
386
+ return { value, expiresAt: this.now() + ttl * 1000 };
387
+ }
388
+ }
@@ -0,0 +1,28 @@
1
+ import type { FetchPort } from '../core/index.js';
2
+ export type JsonObject = Record<string, unknown>;
3
+ export declare const object: (value: unknown) => JsonObject;
4
+ export declare const strings: (value: unknown) => string[];
5
+ export interface Metadata {
6
+ readonly issuer: string;
7
+ readonly authorizationEndpoint: URL;
8
+ readonly tokenEndpoint: URL;
9
+ readonly cimd: boolean;
10
+ readonly responseIssuer: boolean;
11
+ readonly scopes: readonly string[];
12
+ readonly clientAuthMethods: readonly string[];
13
+ readonly registrationEndpoint?: URL;
14
+ }
15
+ export interface DiscoveryOptions {
16
+ readonly allowInsecureDev?: boolean;
17
+ readonly onDiagnostic?: (message: string) => void;
18
+ readonly chooseAuthorizationServer?: (candidates: readonly string[]) => string | Promise<string>;
19
+ /** Skip PRM/issuer discovery: fetch this AS metadata document and trust it as configured. */
20
+ readonly authServerMetadataUrl?: string;
21
+ }
22
+ export declare function getDocument(fetcher: FetchPort, url: string, signal: AbortSignal): Promise<JsonObject | undefined>;
23
+ export declare function discover(fetcher: FetchPort, resource: string, requestUrl: string, location: string | undefined, options: DiscoveryOptions, signal: AbortSignal): Promise<{
24
+ metadata: Metadata;
25
+ scopes: string[];
26
+ resource: string;
27
+ }>;
28
+ export declare function discoverIssuer(fetcher: FetchPort, issuer: string, options: DiscoveryOptions, signal: AbortSignal): Promise<Metadata>;
@@ -0,0 +1,125 @@
1
+ import { AuthError, fail, secureUrl } from './protocol.js';
2
+ export const object = (value) => {
3
+ if (!value || typeof value !== 'object' || Array.isArray(value))
4
+ fail('invalid-document');
5
+ return value;
6
+ };
7
+ export const strings = (value) => Array.isArray(value) && value.every((x) => typeof x === 'string') ? value : [];
8
+ export async function getDocument(fetcher, url, signal) {
9
+ let response;
10
+ try {
11
+ response = await fetcher.fetch(url, { method: 'GET', credentials: 'omit', redirect: 'manual', signal });
12
+ }
13
+ catch (error) {
14
+ if (error instanceof AuthError)
15
+ throw error;
16
+ return fail('discovery-fetch');
17
+ }
18
+ if (response.status === 404 || response.status === 410) {
19
+ await response.body?.cancel();
20
+ return undefined;
21
+ }
22
+ if (!response.ok) {
23
+ await response.body?.cancel();
24
+ fail('discovery-fetch');
25
+ }
26
+ try {
27
+ return object(await response.json());
28
+ }
29
+ catch {
30
+ return fail('invalid-document');
31
+ }
32
+ }
33
+ export async function discover(fetcher, resource, requestUrl, location, options, signal) {
34
+ const url = secureUrl(resource, options.allowInsecureDev);
35
+ if (options.authServerMetadataUrl !== undefined) {
36
+ const metadataUrl = secureUrl(options.authServerMetadataUrl, options.allowInsecureDev);
37
+ const doc = await getDocument(fetcher, metadataUrl.href, signal);
38
+ if (!doc)
39
+ fail('as-metadata-missing');
40
+ const issuer = doc['issuer'];
41
+ if (typeof issuer !== 'string' || !issuer)
42
+ fail('as-issuer-invalid');
43
+ return { resource: url.href, metadata: await discoverIssuer(fetcher, issuer, options, signal), scopes: [] };
44
+ }
45
+ const root = `${url.origin}/.well-known/oauth-protected-resource`;
46
+ const locations = location !== undefined ? [secureUrl(location, options.allowInsecureDev).href] :
47
+ [...new Set([`${root}${url.pathname === '/' ? '' : url.pathname}${url.search}`, root])];
48
+ let prm;
49
+ for (const candidate of locations) {
50
+ const doc = await getDocument(fetcher, candidate, signal);
51
+ if (doc === undefined)
52
+ continue;
53
+ // Root fallback is the metadata for the origin, not for the nested endpoint.
54
+ const expected = location !== undefined ? requestUrl : candidate === root && locations.length > 1 ? url.origin : resource;
55
+ if (doc['resource'] !== expected)
56
+ fail('prm-resource-mismatch');
57
+ prm = { ...doc, resource: expected };
58
+ break;
59
+ }
60
+ const issuers = [...new Set(strings(prm?.['authorization_servers']))];
61
+ if (!prm || !issuers.length)
62
+ fail('prm-invalid');
63
+ const selected = await options.chooseAuthorizationServer?.(Object.freeze([...issuers]));
64
+ if (selected !== undefined && !issuers.includes(selected))
65
+ fail('as-selection-invalid');
66
+ let lastError;
67
+ for (const issuer of selected === undefined ? issuers : [selected]) {
68
+ try {
69
+ return { resource: prm.resource, metadata: await discoverIssuer(fetcher, issuer, options, signal), scopes: strings(prm['scopes_supported']) };
70
+ }
71
+ catch (error) {
72
+ if (!(error instanceof AuthError))
73
+ throw error;
74
+ lastError = error;
75
+ }
76
+ }
77
+ throw lastError ?? new AuthError('auth-failure', 'as-metadata-missing');
78
+ }
79
+ export async function discoverIssuer(fetcher, issuer, options, signal) {
80
+ const url = secureUrl(issuer, options.allowInsecureDev);
81
+ if (url.search || url.hash || /[?#]/u.test(issuer))
82
+ fail('as-issuer-invalid');
83
+ const path = url.pathname === '/' ? '' : url.pathname.replace(/\/$/u, '');
84
+ const candidates = options.authServerMetadataUrl !== undefined
85
+ ? [secureUrl(options.authServerMetadataUrl, options.allowInsecureDev).href]
86
+ : [`${url.origin}/.well-known/oauth-authorization-server${path}`, `${url.origin}/.well-known/openid-configuration${path}`];
87
+ if (!options.authServerMetadataUrl && path)
88
+ candidates.push(`${url.origin}${path}/.well-known/openid-configuration`);
89
+ for (const candidate of candidates) {
90
+ const doc = await getDocument(fetcher, candidate, signal);
91
+ if (!doc)
92
+ continue;
93
+ if (doc['issuer'] !== issuer)
94
+ fail('as-issuer-mismatch');
95
+ if (!strings(doc['code_challenge_methods_supported']).includes('S256'))
96
+ fail('pkce-s256-required');
97
+ const authorizationEndpoint = secureUrl(doc['authorization_endpoint'], options.allowInsecureDev);
98
+ const tokenEndpoint = secureUrl(doc['token_endpoint'], options.allowInsecureDev);
99
+ if (authorizationEndpoint.hash || tokenEndpoint.hash)
100
+ fail('invalid-url');
101
+ let registrationEndpoint;
102
+ if (doc['registration_endpoint'] !== undefined) {
103
+ try {
104
+ if (typeof doc['registration_endpoint'] !== 'string')
105
+ fail('invalid-url');
106
+ registrationEndpoint = secureUrl(doc['registration_endpoint'], options.allowInsecureDev);
107
+ if (registrationEndpoint.hash)
108
+ fail('invalid-url');
109
+ }
110
+ catch (error) {
111
+ if (!(error instanceof AuthError))
112
+ throw error;
113
+ registrationEndpoint = undefined;
114
+ options.onDiagnostic?.(`ignoring invalid registration_endpoint: ${error.message}`);
115
+ }
116
+ }
117
+ return { issuer, authorizationEndpoint, tokenEndpoint, ...(registrationEndpoint ? { registrationEndpoint } : {}),
118
+ cimd: doc['client_id_metadata_document_supported'] === true,
119
+ responseIssuer: doc['authorization_response_iss_parameter_supported'] === true,
120
+ scopes: strings(doc['scopes_supported']),
121
+ clientAuthMethods: strings(doc['token_endpoint_auth_methods_supported']),
122
+ };
123
+ }
124
+ return fail('as-metadata-missing');
125
+ }
@@ -0,0 +1,9 @@
1
+ export { AuthError, canonicalResource, parseBearerChallenges, pkceChallenge } from './protocol.js';
2
+ export type { BearerChallenge } from './protocol.js';
3
+ export { SafeFetch } from './safe-fetch.js';
4
+ export type { SafeFetchOptions } from './safe-fetch.js';
5
+ export { ConfiguredBearer, OAuthAuthorization, MemoryCredentialStore } from './provider.js';
6
+ export type { ConfiguredBearerOptions, OAuthOptions, AuthorizationConsent, AuthorizationPrompt, RedirectPort, ClientRegistration } from './provider.js';
7
+ export { ClientCredentialsAuth, createPemAssertionSigner, createWebCryptoAssertionSigner, isConfigured } from './client-credentials.js';
8
+ export type { AssertionSigner, AssertionSigningAlgorithm, ClientCredentialsConfig, ClientCredentialsDiagnostic } from './client-credentials.js';
9
+ export { openSystemBrowser, startLoopbackRedirect } from './node-ports.js';
@@ -0,0 +1,5 @@
1
+ export { AuthError, canonicalResource, parseBearerChallenges, pkceChallenge } from './protocol.js';
2
+ export { SafeFetch } from './safe-fetch.js';
3
+ export { ConfiguredBearer, OAuthAuthorization, MemoryCredentialStore } from './provider.js';
4
+ export { ClientCredentialsAuth, createPemAssertionSigner, createWebCryptoAssertionSigner, isConfigured } from './client-credentials.js';
5
+ export { openSystemBrowser, startLoopbackRedirect } from './node-ports.js';
@@ -0,0 +1,8 @@
1
+ import type { RedirectPort } from './provider.js';
2
+ /** Launch a fixed program with an opaque URL argument; never use a shell. */
3
+ export declare function openSystemBrowser(input: string, signal: AbortSignal): Promise<void>;
4
+ /** Bind before registration so the host can register the exact callback URI. Single use. */
5
+ export declare function startLoopbackRedirect(path?: string): Promise<RedirectPort & {
6
+ readonly redirectUri: string;
7
+ close(): void;
8
+ }>;
@@ -0,0 +1,67 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createServer } from 'node:http';
3
+ import { AuthError, cancelled, fail, secureUrl, withAbort } from './protocol.js';
4
+ /** Launch a fixed program with an opaque URL argument; never use a shell. */
5
+ export async function openSystemBrowser(input, signal) {
6
+ const url = secureUrl(input);
7
+ signal.throwIfAborted();
8
+ const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'rundll32.exe' : 'xdg-open';
9
+ const args = process.platform === 'win32' ? ['url.dll,FileProtocolHandler', url.href] : [url.href];
10
+ await new Promise((resolve, reject) => {
11
+ const child = spawn(command, args, { shell: false, stdio: 'ignore', detached: true });
12
+ child.once('error', () => reject(new AuthError('auth-unavailable', 'browser')));
13
+ child.once('spawn', () => { child.unref(); resolve(); });
14
+ });
15
+ }
16
+ /** Bind before registration so the host can register the exact callback URI. Single use. */
17
+ export async function startLoopbackRedirect(path = '/callback') {
18
+ if (!/^\/[a-z0-9/_-]+$/iu.test(path))
19
+ fail('invalid-redirect-uri');
20
+ let pending;
21
+ let used = false;
22
+ let redirectUri;
23
+ const server = createServer((request, response) => {
24
+ const target = request.url ?? '';
25
+ if (request.method !== 'GET' || !target.startsWith(`${path}?`) || !pending || request.headers.host !== new URL(redirectUri).host) {
26
+ response.writeHead(404, { Connection: 'close' }).end();
27
+ return;
28
+ }
29
+ const resolve = pending.resolve;
30
+ pending = undefined;
31
+ response.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store',
32
+ 'Referrer-Policy': 'no-referrer', Connection: 'close' }).end('Authorization response received. You can close this tab.');
33
+ resolve(new URLSearchParams(target.slice(path.length + 1)));
34
+ server.close();
35
+ });
36
+ server.requestTimeout = 10_000;
37
+ await new Promise((resolve, reject) => {
38
+ const error = () => reject(new AuthError('auth-unavailable', 'redirect'));
39
+ server.once('error', error);
40
+ server.listen(0, '127.0.0.1', () => { server.removeListener('error', error); resolve(); });
41
+ });
42
+ const address = server.address();
43
+ if (!address || typeof address === 'string') {
44
+ server.close();
45
+ return fail('redirect-unavailable');
46
+ }
47
+ redirectUri = `http://127.0.0.1:${address.port}${path}`;
48
+ const close = () => {
49
+ used = true;
50
+ pending?.reject(new AuthError('auth-failure', 'cancelled'));
51
+ pending = undefined;
52
+ server.close();
53
+ server.closeAllConnections();
54
+ };
55
+ return { redirectUri, close, async waitForCallback(options) {
56
+ if (options.redirectUri !== redirectUri || used)
57
+ fail('invalid-redirect-uri');
58
+ used = true;
59
+ const work = new Promise((resolve, reject) => { pending = { resolve, reject }; });
60
+ try {
61
+ return await withAbort(work, options.signal, cancelled);
62
+ }
63
+ finally {
64
+ close();
65
+ }
66
+ } };
67
+ }
@@ -0,0 +1,12 @@
1
+ import { AuthError } from '../core/index.js';
2
+ export { AuthError, parseBearerChallenges, withAbort, type BearerChallenge } from '../core/index.js';
3
+ export declare function fail(reason: string): never;
4
+ export declare const cancelled: () => AuthError;
5
+ export declare const hash: (input: string) => string;
6
+ export declare const pkceChallenge: typeof hash;
7
+ export declare const isLoopback: (host: string) => boolean;
8
+ export declare function secureUrl(input: string, dev?: boolean): URL;
9
+ export declare function canonicalResource(input: string, preserveTrailingSlash?: boolean): string;
10
+ export declare function bearerValue(value: unknown): string;
11
+ /** RFC 6749 §2.3.1 HTTP Basic credential header with form-urlencoded client id and secret. */
12
+ export declare function basicAuthorization(clientId: string, clientSecret: string): string;