@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,39 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { AuthError } from '../core/index.js';
3
+ export { AuthError, parseBearerChallenges, withAbort } from '../core/index.js';
4
+ export function fail(reason) { throw new AuthError('auth-failure', reason); }
5
+ export const cancelled = () => new AuthError('auth-failure', 'cancelled');
6
+ export const hash = (input) => createHash('sha256').update(input).digest('base64url');
7
+ export const pkceChallenge = hash;
8
+ export const isLoopback = (host) => ['localhost', '127.0.0.1', '[::1]'].includes(host);
9
+ export function secureUrl(input, dev = false) {
10
+ if (typeof input !== 'string' || !/^https?:\/\//iu.test(input) || /[\s\\<>"'`|{}^]/u.test(input))
11
+ fail('invalid-url');
12
+ let url;
13
+ try {
14
+ url = new URL(input);
15
+ }
16
+ catch {
17
+ return fail('invalid-url');
18
+ }
19
+ if (url.username || url.password || (url.protocol !== 'https:' &&
20
+ !(dev && url.protocol === 'http:' && isLoopback(url.hostname))))
21
+ fail('invalid-url');
22
+ return url;
23
+ }
24
+ export function canonicalResource(input, preserveTrailingSlash = false) {
25
+ const url = secureUrl(input, true);
26
+ url.hash = '';
27
+ const path = preserveTrailingSlash ? url.pathname : url.pathname.replace(/\/$/u, '');
28
+ return `${url.origin}${path}${url.search}`;
29
+ }
30
+ export function bearerValue(value) {
31
+ if (typeof value !== 'string' || !/^[A-Za-z\d._~+/\-]+=*$/u.test(value))
32
+ fail('invalid-token');
33
+ return value;
34
+ }
35
+ /** RFC 6749 §2.3.1 HTTP Basic credential header with form-urlencoded client id and secret. */
36
+ export function basicAuthorization(clientId, clientSecret) {
37
+ const encode = (value) => new URLSearchParams({ x: value }).toString().slice(2);
38
+ return `Basic ${Buffer.from(`${encode(clientId)}:${encode(clientSecret)}`).toString('base64')}`;
39
+ }
@@ -0,0 +1,114 @@
1
+ import type { AuthChallenge, AuthHeaderResult, AuthProvider, AuthRequestContext, CredentialStore, FetchPort, RandomPort } from '../core/index.js';
2
+ import { type DiscoveryOptions } from './discovery.js';
3
+ export declare class MemoryCredentialStore implements CredentialStore {
4
+ #private;
5
+ get(key: string): Promise<string | undefined>;
6
+ set(key: string, value: string): Promise<void>;
7
+ delete(key: string): Promise<void>;
8
+ }
9
+ interface ResourceOptions {
10
+ readonly resource: string;
11
+ readonly preserveTrailingSlash?: boolean;
12
+ }
13
+ export interface ConfiguredBearerOptions extends ResourceOptions {
14
+ readonly token: string | (() => Promise<string>);
15
+ readonly refresh?: () => Promise<void>;
16
+ readonly allowInsecureDev?: boolean;
17
+ }
18
+ export declare class ConfiguredBearer implements AuthProvider {
19
+ #private;
20
+ constructor(options: ConfiguredBearerOptions);
21
+ contextId(): string;
22
+ headerFor(url: string): Promise<AuthHeaderResult | undefined>;
23
+ onChallenge(challenge: AuthChallenge, signal: AbortSignal): Promise<boolean>;
24
+ }
25
+ export interface ClientRegistration {
26
+ readonly clientId: string;
27
+ readonly clientSecret?: string;
28
+ readonly clientSecretExpiresAt?: number;
29
+ readonly authMethod?: 'none' | 'client_secret_basic' | 'client_secret_post';
30
+ readonly redirectUris: readonly string[];
31
+ }
32
+ export type AuthorizationPrompt = {
33
+ readonly kind: 'client-info';
34
+ readonly serverLabel: string;
35
+ readonly issuer: string;
36
+ readonly redirectUri: string;
37
+ } | {
38
+ readonly kind: 'authorize';
39
+ readonly serverLabel: string;
40
+ readonly issuerHost: string;
41
+ readonly resource: string;
42
+ readonly scopes: readonly string[];
43
+ readonly redirectHost: string;
44
+ readonly localhostWarning: boolean;
45
+ };
46
+ export interface AuthorizationConsent {
47
+ request(prompt: AuthorizationPrompt, signal: AbortSignal): Promise<{
48
+ readonly decision: 'accept';
49
+ readonly registration?: ClientRegistration;
50
+ } | {
51
+ readonly decision: 'decline' | 'cancel';
52
+ }>;
53
+ }
54
+ export interface RedirectPort {
55
+ waitForCallback(options: {
56
+ readonly redirectUri: string;
57
+ readonly state: string;
58
+ readonly signal: AbortSignal;
59
+ }): Promise<URLSearchParams>;
60
+ }
61
+ export interface OAuthOptions extends ResourceOptions, DiscoveryOptions {
62
+ readonly serverLabel?: string;
63
+ readonly redirectUri: string;
64
+ readonly registrations?: Readonly<Record<string, ClientRegistration>>;
65
+ readonly cimd?: {
66
+ readonly clientIdUrl: string;
67
+ readonly redirectUris: readonly string[];
68
+ readonly selfCheck?: boolean;
69
+ };
70
+ readonly dynamicRegistration?: {
71
+ readonly clientName: string;
72
+ readonly softwareId?: string;
73
+ };
74
+ readonly consent?: AuthorizationConsent;
75
+ readonly browser?: {
76
+ open(url: string, signal: AbortSignal): Promise<void>;
77
+ };
78
+ readonly redirect?: RedirectPort;
79
+ readonly credentials?: CredentialStore;
80
+ readonly fetch?: FetchPort;
81
+ readonly random?: RandomPort;
82
+ readonly clock?: {
83
+ now(): number;
84
+ };
85
+ readonly skewMs?: number;
86
+ readonly flowTimeoutMs?: number;
87
+ readonly stepUpLimit?: number;
88
+ readonly offlineAccess?: boolean;
89
+ /** Space-separated scopes requested when the server does not advertise required scopes. */
90
+ readonly scope?: string;
91
+ readonly onDiagnostic?: (message: string) => void;
92
+ }
93
+ export declare class OAuthAuthorization implements AuthProvider {
94
+ #private;
95
+ readonly stepUpLimit: number;
96
+ constructor(options: OAuthOptions);
97
+ contextId(): string;
98
+ headerFor(url: string, _operation?: string, context?: AuthRequestContext): Promise<AuthHeaderResult | undefined>;
99
+ onChallenge(challenge: AuthChallenge, signal: AbortSignal, context?: AuthRequestContext): Promise<boolean>;
100
+ private now;
101
+ private diagnostic;
102
+ private start;
103
+ private challenge;
104
+ private refreshKey;
105
+ private validateRegistration;
106
+ private registration;
107
+ private register;
108
+ private consent;
109
+ private renew;
110
+ private nonce;
111
+ private interactive;
112
+ private token;
113
+ }
114
+ export {};
@@ -0,0 +1,407 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { discover, getDocument, object, strings } from './discovery.js';
3
+ import { AuthError, basicAuthorization, bearerValue, cancelled, canonicalResource, fail, hash, isLoopback, parseBearerChallenges, pkceChallenge, secureUrl, withAbort } from './protocol.js';
4
+ import { SafeFetch } from './safe-fetch.js';
5
+ export class MemoryCredentialStore {
6
+ #values = new Map();
7
+ async get(key) { return this.#values.get(key); }
8
+ async set(key, value) { this.#values.set(key, value); }
9
+ async delete(key) { this.#values.delete(key); }
10
+ }
11
+ function matches(options, resource, candidate) {
12
+ try {
13
+ return canonicalResource(candidate, options.preserveTrailingSlash) === resource && !new URL(candidate).hash;
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
19
+ export class ConfiguredBearer {
20
+ #resource;
21
+ #context = 'anonymous';
22
+ #credentialVersion = {};
23
+ #pending;
24
+ #options;
25
+ constructor(options) {
26
+ this.#options = options;
27
+ secureUrl(options.resource, options.allowInsecureDev);
28
+ this.#resource = canonicalResource(options.resource, options.preserveTrailingSlash);
29
+ }
30
+ contextId() { return this.#context; }
31
+ async headerFor(url) {
32
+ if (!matches(this.#options, this.#resource, url))
33
+ return undefined;
34
+ try {
35
+ const token = bearerValue(typeof this.#options.token === 'string' ? this.#options.token : await this.#options.token());
36
+ const context = hash(JSON.stringify([this.#resource, 'bearer', hash(token)]));
37
+ if (context !== this.#context)
38
+ this.#credentialVersion = {};
39
+ this.#context = context;
40
+ return { authorization: `Bearer ${token}`, contextId: context, credentialVersion: this.#credentialVersion };
41
+ }
42
+ catch {
43
+ return fail('configured-bearer-unavailable');
44
+ }
45
+ }
46
+ async onChallenge(challenge, signal) {
47
+ if (challenge.status !== 401 || !this.#options.refresh || signal.aborted ||
48
+ (challenge.resource !== undefined && !matches(this.#options, this.#resource, challenge.resource)))
49
+ return false;
50
+ if (challenge.credentialVersion && challenge.credentialVersion !== this.#credentialVersion)
51
+ return true;
52
+ this.#pending ??= Promise.resolve().then(this.#options.refresh).then(() => {
53
+ this.#credentialVersion = {};
54
+ return true;
55
+ }, () => false).finally(() => { this.#pending = undefined; });
56
+ return withAbort(this.#pending, signal, cancelled);
57
+ }
58
+ }
59
+ const scopesOf = (scope) => scope?.split(/ +/u).filter((value) => /^[\x21\x23-\x5b\x5d-\x7e]+$/u.test(value)) ?? [];
60
+ export class OAuthAuthorization {
61
+ #resource;
62
+ #redirect;
63
+ #fetch;
64
+ #store;
65
+ #stepUps = new Map();
66
+ stepUpLimit;
67
+ #grant;
68
+ #resourceMetadataHint;
69
+ #pending;
70
+ #options;
71
+ constructor(options) {
72
+ this.#options = options;
73
+ this.stepUpLimit = options.stepUpLimit ?? 3;
74
+ if (!Number.isSafeInteger(this.stepUpLimit) || this.stepUpLimit < 0)
75
+ fail('invalid-step-up-limit');
76
+ secureUrl(options.resource, options.allowInsecureDev);
77
+ this.#resource = canonicalResource(options.resource, options.preserveTrailingSlash);
78
+ this.#redirect = secureUrl(options.redirectUri, options.allowInsecureDev);
79
+ if (this.#redirect.hash || [...this.#redirect.searchParams.keys()].some((key) => ['code', 'error', 'iss', 'state'].includes(key)))
80
+ fail('invalid-redirect-uri');
81
+ this.#fetch = options.fetch ?? new SafeFetch({ allowInsecureDev: options.allowInsecureDev ?? false });
82
+ this.#store = options.credentials ?? new MemoryCredentialStore();
83
+ }
84
+ contextId() { return this.#grant?.context ?? 'anonymous'; }
85
+ async headerFor(url, _operation, context) {
86
+ if (!matches(this.#options, this.#resource, url))
87
+ return undefined;
88
+ context?.signal.throwIfAborted();
89
+ const grant = this.#grant;
90
+ const work = this.#pending?.work ?? (grant && grant.expires - (this.#options.skewMs ?? 30_000) <= this.now()
91
+ ? this.start(undefined, signal => this.renew(grant, grant.scopes, signal, context)) : undefined);
92
+ if (work)
93
+ await (context ? withAbort(work, context.signal, cancelled) : work);
94
+ return this.#grant && { authorization: `Bearer ${this.#grant.token}`, contextId: this.#grant.context, credentialVersion: this.#grant.version };
95
+ }
96
+ async onChallenge(challenge, signal, context) {
97
+ if (signal.aborted)
98
+ fail('cancelled');
99
+ if (challenge.resource !== undefined && !matches(this.#options, this.#resource, challenge.resource))
100
+ return false;
101
+ const parsed = parseBearerChallenges(challenge.wwwAuthenticate ?? '');
102
+ const bearer = challenge.status === 403 ? parsed.find(x => x.error === 'insufficient_scope') :
103
+ parsed.find(x => x.resource_metadata !== undefined) ?? parsed[0];
104
+ if (challenge.status === 403 && !bearer)
105
+ return false;
106
+ if (challenge.status === 401 && !this.#pending && this.#grant && challenge.credentialVersion !== undefined &&
107
+ challenge.credentialVersion !== this.#grant.version &&
108
+ (bearer?.resource_metadata === undefined || bearer.resource_metadata === this.#resourceMetadataHint))
109
+ return true;
110
+ if (challenge.status === 401 && !bearer && /^\s*Basic(?:\s|$)/iu.test(challenge.wwwAuthenticate ?? ''))
111
+ fail('unsupported-scheme');
112
+ const operation = challenge.operation ?? '';
113
+ const scopeKey = challenge.status === 403 ? JSON.stringify([operation, bearer?.scope, bearer?.resource_metadata]) : undefined;
114
+ while (this.#pending) {
115
+ const pending = this.#pending;
116
+ await withAbort(pending.work, signal, cancelled);
117
+ if (pending.scopeKey === scopeKey)
118
+ return true;
119
+ if (scopeKey === undefined)
120
+ return true;
121
+ if (signal.aborted)
122
+ fail('cancelled');
123
+ }
124
+ if (scopeKey !== undefined) {
125
+ const used = this.#stepUps.get(operation) ?? 0;
126
+ if (used >= this.stepUpLimit)
127
+ fail('insufficient-scope');
128
+ this.#stepUps.set(operation, used + 1);
129
+ }
130
+ await withAbort(this.start(scopeKey, flowSignal => this.challenge(challenge, bearer, flowSignal, context)), signal, cancelled);
131
+ return true;
132
+ }
133
+ now() { return this.#options.clock?.now() ?? Date.now(); }
134
+ diagnostic(message) { this.#options.onDiagnostic?.(message); }
135
+ start(scopeKey, run) {
136
+ const signal = AbortSignal.timeout(this.#options.flowTimeoutMs ?? 120_000);
137
+ const work = Promise.resolve().then(() => withAbort(run(signal), signal, cancelled)).catch((error) => {
138
+ if (error instanceof AuthError)
139
+ throw error;
140
+ return fail('flow-failed');
141
+ }).finally(() => { this.#pending = undefined; });
142
+ this.#pending = { ...(scopeKey === undefined ? {} : { scopeKey }), work };
143
+ return work;
144
+ }
145
+ async challenge(challenge, bearer, signal, context) {
146
+ const previous = this.#grant;
147
+ const step = challenge.status === 403;
148
+ if (!step)
149
+ this.#grant = undefined;
150
+ const { metadata, scopes, resource } = await discover(this.#fetch, this.#resource, challenge.resource ?? new URL(this.#options.resource).href, bearer?.resource_metadata, this.#options, signal);
151
+ const sameBinding = previous?.metadata.issuer === metadata.issuer && previous.resource === resource;
152
+ if (previous && !sameBinding)
153
+ this.#grant = undefined;
154
+ const selected = [...new Set([...(step && sameBinding ? previous.scopes : []),
155
+ ...(bearer?.scope !== undefined ? scopesOf(bearer.scope) : step && sameBinding ? [] : scopes.flatMap(scopesOf)),
156
+ ...scopesOf(this.#options.scope),
157
+ ])].filter(scope => scope !== 'offline_access');
158
+ if (this.#options.offlineAccess && metadata.scopes.includes('offline_access'))
159
+ selected.push('offline_access');
160
+ const session = { metadata, resource, registration: await this.registration(metadata, signal, context, selected) };
161
+ if (!step && (!previous || sameBinding)) {
162
+ await this.renew(session, selected, signal, context, sameBinding ? previous : undefined);
163
+ }
164
+ else {
165
+ await this.interactive(session, selected, signal, context);
166
+ }
167
+ this.#resourceMetadataHint = bearer?.resource_metadata;
168
+ }
169
+ refreshKey(session) {
170
+ const key = ['refresh', this.#resource, session.metadata.issuer, session.registration.clientId];
171
+ // Preserve existing keys for grants whose audience is the configured endpoint.
172
+ if (session.resource !== this.#resource)
173
+ key.push(session.resource);
174
+ return JSON.stringify(key);
175
+ }
176
+ validateRegistration(reg) {
177
+ if (!reg || typeof reg.clientId !== 'string' || !reg.clientId || !strings(reg.redirectUris).includes(this.#options.redirectUri) ||
178
+ (reg.clientSecret !== undefined && typeof reg.clientSecret !== 'string'))
179
+ fail('invalid-client-registration');
180
+ return { clientId: reg.clientId, redirectUris: [...reg.redirectUris], ...(reg.clientSecret !== undefined ? { clientSecret: reg.clientSecret } : {}),
181
+ ...(reg.clientSecretExpiresAt !== undefined ? { clientSecretExpiresAt: reg.clientSecretExpiresAt } : {}),
182
+ ...(reg.authMethod !== undefined ? { authMethod: reg.authMethod } : {}) };
183
+ }
184
+ async registration(metadata, signal, context, scopes = []) {
185
+ const registrations = this.#options.registrations;
186
+ const preset = registrations && Object.hasOwn(registrations, metadata.issuer) ? registrations[metadata.issuer] : undefined;
187
+ if (preset)
188
+ return this.validateRegistration(preset);
189
+ const cimd = this.#options.cimd;
190
+ if (metadata.cimd && cimd) {
191
+ const id = secureUrl(cimd.clientIdUrl);
192
+ if (id.pathname === '/' || /[?#]/u.test(cimd.clientIdUrl))
193
+ fail('cimd-client-id-invalid');
194
+ if (cimd.selfCheck) {
195
+ const doc = await getDocument(this.#fetch, id.href, signal);
196
+ if (doc?.['client_id'] !== cimd.clientIdUrl || typeof doc['client_name'] !== 'string' || !doc['client_name'] ||
197
+ !strings(doc['redirect_uris']).includes(this.#options.redirectUri))
198
+ fail('cimd-document-invalid');
199
+ if (!strings(doc['grant_types']).includes('refresh_token'))
200
+ this.diagnostic('CIMD does not list the refresh_token grant');
201
+ }
202
+ return this.validateRegistration({ clientId: cimd.clientIdUrl, redirectUris: cimd.redirectUris });
203
+ }
204
+ if (registrations && Object.keys(registrations).length)
205
+ fail('client-issuer-mismatch');
206
+ const key = JSON.stringify(['registration', this.#resource, metadata.issuer, null]);
207
+ const cached = await this.#store.get(key);
208
+ if (cached) {
209
+ const reg = this.validateRegistration(JSON.parse(cached));
210
+ if (!reg.clientSecretExpiresAt || reg.clientSecretExpiresAt * 1000 > this.now())
211
+ return reg;
212
+ }
213
+ if (this.#options.dynamicRegistration && metadata.registrationEndpoint) {
214
+ const registration = await this.register(metadata, metadata.registrationEndpoint, this.#options.dynamicRegistration, scopes, signal);
215
+ signal.throwIfAborted();
216
+ await this.#store.set(key, JSON.stringify(registration));
217
+ return registration;
218
+ }
219
+ if (!this.#options.consent && !context?.consent)
220
+ fail('no-registration-mechanism');
221
+ const result = await this.consent({ kind: 'client-info', serverLabel: this.#options.serverLabel ?? context?.serverLabel ?? this.#resource,
222
+ issuer: metadata.issuer, redirectUri: this.#options.redirectUri }, signal, context);
223
+ if (!result.registration)
224
+ fail('no-registration-mechanism');
225
+ const registration = this.validateRegistration(result.registration);
226
+ signal.throwIfAborted();
227
+ await this.#store.set(key, JSON.stringify(registration));
228
+ return registration;
229
+ }
230
+ // RFC 7591 dynamic client registration. Never logs or echoes the secret.
231
+ async register(metadata, endpoint, dcr, scopes, signal) {
232
+ const supported = metadata.clientAuthMethods;
233
+ const method = ['none', 'client_secret_basic', 'client_secret_post'].find(m => supported.includes(m)) ?? 'client_secret_basic';
234
+ const body = { client_name: dcr.clientName, redirect_uris: [this.#options.redirectUri],
235
+ grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: method,
236
+ application_type: this.#redirect.protocol === 'http:' && isLoopback(this.#redirect.hostname) ? 'native' : 'web',
237
+ ...(dcr.softwareId !== undefined ? { software_id: dcr.softwareId } : {}), ...(scopes.length ? { scope: scopes.join(' ') } : {}) };
238
+ signal.throwIfAborted();
239
+ let response;
240
+ try {
241
+ response = await this.#fetch.fetch(endpoint.href, { method: 'POST', body: JSON.stringify(body),
242
+ headers: new Headers({ 'Content-Type': 'application/json', Accept: 'application/json' }), credentials: 'omit', redirect: 'error', signal });
243
+ }
244
+ catch {
245
+ return fail('registration-failed');
246
+ }
247
+ let doc;
248
+ try {
249
+ doc = object(await response.json());
250
+ }
251
+ catch {
252
+ return fail('registration-failed');
253
+ }
254
+ if (response.status !== 201 && response.status !== 200)
255
+ return fail('registration-failed');
256
+ const { client_id: clientId, client_secret: secret, client_secret_expires_at: expires, token_endpoint_auth_method: returned } = doc;
257
+ if (typeof clientId !== 'string' || !clientId || (secret !== undefined && typeof secret !== 'string') ||
258
+ (expires !== undefined && (typeof expires !== 'number' || !Number.isFinite(expires))))
259
+ return fail('registration-failed');
260
+ const authMethod = returned ?? method;
261
+ if (authMethod !== 'none' && authMethod !== 'client_secret_basic' && authMethod !== 'client_secret_post')
262
+ return fail('registration-failed');
263
+ if (authMethod !== 'none' && !secret)
264
+ return fail('registration-failed');
265
+ return { clientId, redirectUris: [this.#options.redirectUri], authMethod,
266
+ ...(secret ? { clientSecret: secret } : {}), ...(expires ? { clientSecretExpiresAt: expires } : {}) };
267
+ }
268
+ async consent(prompt, signal, context) {
269
+ signal.throwIfAborted();
270
+ if (this.#options.consent) {
271
+ const result = await this.#options.consent.request(prompt, signal);
272
+ if (result.decision !== 'accept')
273
+ fail(result.decision === 'decline' ? 'declined' : 'cancelled');
274
+ signal.throwIfAborted();
275
+ return result;
276
+ }
277
+ if (!context?.consent)
278
+ throw new AuthError('auth-unavailable', prompt.kind);
279
+ const result = await context.consent.request(prompt, signal);
280
+ if (result.decision !== 'accept')
281
+ fail(result.decision === 'decline' ? 'declined' : 'cancelled');
282
+ signal.throwIfAborted();
283
+ if (prompt.kind === 'client-info' && result.content) {
284
+ return { registration: this.validateRegistration(result.content) };
285
+ }
286
+ return { registration: undefined };
287
+ }
288
+ async renew(session, scopes, signal, context, previous = this.#grant) {
289
+ const refresh = await this.#store.get(this.refreshKey(session));
290
+ if (refresh) {
291
+ const form = new URLSearchParams({ grant_type: 'refresh_token', refresh_token: refresh });
292
+ if (await this.token(session, form, previous?.scopes ?? scopes, signal, refresh, previous))
293
+ return;
294
+ await this.#store.delete(this.refreshKey(session));
295
+ this.#grant = undefined;
296
+ }
297
+ await this.interactive(session, scopes, signal, context);
298
+ }
299
+ nonce(size) {
300
+ const bytes = this.#options.random ? this.#options.random.bytes(size) : randomBytes(size);
301
+ if (bytes.length !== size)
302
+ fail('invalid-random-source');
303
+ return Buffer.from(bytes).toString('base64url');
304
+ }
305
+ async interactive(session, scopes, signal, context) {
306
+ const { metadata, registration } = session;
307
+ const { browser, redirect, redirectUri } = this.#options;
308
+ if (!browser || !redirect)
309
+ throw new AuthError('auth-unavailable', 'authorize');
310
+ await this.consent({ kind: 'authorize', serverLabel: this.#options.serverLabel ?? context?.serverLabel ?? this.#resource,
311
+ issuerHost: new URL(metadata.issuer).hostname, resource: session.resource, scopes: Object.freeze([...scopes]),
312
+ redirectHost: this.#redirect.hostname, localhostWarning: isLoopback(this.#redirect.hostname) }, signal, context);
313
+ const verifier = this.nonce(32), state = this.nonce(24);
314
+ const url = new URL(metadata.authorizationEndpoint);
315
+ const parameters = { response_type: 'code', client_id: registration.clientId, redirect_uri: redirectUri,
316
+ code_challenge: pkceChallenge(verifier), code_challenge_method: 'S256', state, resource: session.resource };
317
+ for (const [key, value] of Object.entries(parameters))
318
+ url.searchParams.set(key, value);
319
+ url.searchParams.delete('scope');
320
+ if (scopes.length)
321
+ url.searchParams.set('scope', scopes.join(' '));
322
+ const callbackController = new AbortController();
323
+ const callbackSignal = AbortSignal.any([signal, callbackController.signal]);
324
+ try {
325
+ const callback = redirect.waitForCallback({ redirectUri, state, signal: callbackSignal });
326
+ // Listen before opening the browser; avoid an unhandled rejection if either port fails.
327
+ const [, params] = await Promise.all([Promise.resolve().then(() => browser.open(url.href, callbackSignal)), callback]);
328
+ if (params.getAll('state').length !== 1 || params.get('state') !== state)
329
+ fail('state-mismatch');
330
+ const iss = params.getAll('iss');
331
+ if (iss.length > 1 || (iss.length === 0 ? metadata.responseIssuer : iss[0] !== metadata.issuer))
332
+ fail('issuer-mismatch');
333
+ if (params.has('error'))
334
+ fail('authorization-rejected');
335
+ const code = params.get('code');
336
+ if (!code || params.getAll('code').length !== 1)
337
+ fail('invalid-code');
338
+ await this.token(session, new URLSearchParams({ grant_type: 'authorization_code', code, code_verifier: verifier, redirect_uri: redirectUri }), scopes, signal);
339
+ }
340
+ finally {
341
+ callbackController.abort();
342
+ }
343
+ }
344
+ async token(session, form, scopes, signal, refresh, previous) {
345
+ const { metadata, registration } = session;
346
+ form.set('client_id', registration.clientId);
347
+ form.set('resource', session.resource);
348
+ const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' });
349
+ const setBasicAuth = () => headers.set('Authorization', basicAuthorization(registration.clientId, registration.clientSecret));
350
+ if (registration.authMethod === 'client_secret_basic')
351
+ setBasicAuth();
352
+ else if (registration.authMethod === 'client_secret_post')
353
+ form.set('client_secret', registration.clientSecret);
354
+ else if (registration.authMethod === 'none') { /* public client */ }
355
+ else if (registration.clientSecret !== undefined) {
356
+ if (!metadata.clientAuthMethods.length || metadata.clientAuthMethods.includes('client_secret_basic')) {
357
+ setBasicAuth();
358
+ }
359
+ else if (metadata.clientAuthMethods.includes('client_secret_post')) {
360
+ form.set('client_secret', registration.clientSecret);
361
+ }
362
+ else
363
+ fail('client-auth-method-unsupported');
364
+ }
365
+ signal.throwIfAborted();
366
+ let response;
367
+ try {
368
+ response = await this.#fetch.fetch(metadata.tokenEndpoint.href, { method: 'POST', body: form.toString(), headers,
369
+ credentials: 'omit', redirect: 'error', signal });
370
+ }
371
+ catch {
372
+ return fail('token-endpoint-unavailable');
373
+ }
374
+ let doc;
375
+ try {
376
+ doc = object(await response.json());
377
+ }
378
+ catch {
379
+ return fail('token-response-invalid');
380
+ }
381
+ if (!response.ok) {
382
+ if (refresh && response.status === 400 && doc['error'] === 'invalid_grant')
383
+ return false;
384
+ return fail('token-request-rejected');
385
+ }
386
+ if (typeof doc['token_type'] !== 'string' || doc['token_type'].toLowerCase() !== 'bearer')
387
+ fail('invalid-token-type');
388
+ const token = bearerValue(doc['access_token']);
389
+ const lifetime = doc['expires_in'];
390
+ if (lifetime !== undefined && (typeof lifetime !== 'number' || !Number.isFinite(lifetime) || lifetime <= 0 || lifetime > Number.MAX_SAFE_INTEGER / 1000))
391
+ fail('invalid-token-expiry');
392
+ const issuedRefresh = doc['refresh_token'];
393
+ if (issuedRefresh !== undefined && (typeof issuedRefresh !== 'string' || !issuedRefresh))
394
+ fail('invalid-refresh-token');
395
+ const key = this.refreshKey(session);
396
+ signal.throwIfAborted();
397
+ if (issuedRefresh !== undefined)
398
+ await this.#store.set(key, issuedRefresh);
399
+ else if (!refresh)
400
+ await this.#store.delete(key);
401
+ signal.throwIfAborted();
402
+ const context = refresh && previous?.metadata.issuer === metadata.issuer && previous.registration.clientId === registration.clientId ? previous.context : randomBytes(18).toString('base64url');
403
+ this.#grant = { ...session, token, context, version: {}, expires: lifetime === undefined ? Infinity : this.now() + lifetime * 1000,
404
+ scopes: [...new Set([...scopes, ...scopesOf(typeof doc['scope'] === 'string' ? doc['scope'] : undefined)])] };
405
+ return true;
406
+ }
407
+ }
@@ -0,0 +1,14 @@
1
+ import type { FetchPort } from '../core/index.js';
2
+ export interface SafeFetchOptions {
3
+ readonly allowInsecureDev?: boolean;
4
+ /** Explicit host policy for an otherwise blocked resolved address. */
5
+ readonly allowAddress?: (hostname: string, ip: string) => boolean;
6
+ readonly timeoutMs?: number;
7
+ readonly maxBytes?: number;
8
+ }
9
+ export declare class SafeFetch implements FetchPort {
10
+ private readonly options;
11
+ constructor(options?: SafeFetchOptions);
12
+ fetch(input: string, init?: RequestInit): Promise<Response>;
13
+ private send;
14
+ }