@mfdaves/okf-mcp 0.9.1 → 0.13.0-rc.1
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.
- package/CHANGELOG.md +100 -0
- package/README.md +452 -26
- package/bin/okf-mcp.js +6 -1
- package/okf/okf-mcp/distribution/reference-bundle.md +10 -3
- package/okf/okf-mcp/index.md +2 -1
- package/okf/okf-mcp/interfaces/http-authoring-api.md +11 -2
- package/okf/okf-mcp/interfaces/mcp-http.md +64 -0
- package/okf/okf-mcp/interfaces/mcp-tools.md +25 -6
- package/okf/okf-mcp/overview/okf-mcp.md +16 -6
- package/okf/okf-mcp/policies/authoring-safety.md +28 -5
- package/okf/okf-mcp/runtime/indexer.md +14 -1
- package/okf/okf-mcp/runtime/mcp-server.md +16 -8
- package/okf/okf-mcp/specs/producer-api.md +16 -2
- package/package.json +17 -5
- package/server.json +38 -2
- package/src/assets.js +165 -73
- package/src/authoring/candidates.js +434 -0
- package/src/authoring/git-preflight.js +225 -0
- package/src/authoring/git-publish.js +783 -0
- package/src/authoring/live.js +757 -0
- package/src/authoring/paths.js +112 -0
- package/src/authoring/policy-hook.js +221 -0
- package/src/authoring/proposal-policy.js +159 -0
- package/src/authoring/receipts.js +373 -0
- package/src/authoring/render.js +38 -0
- package/src/authoring/shared.js +75 -0
- package/src/authoring/staging.js +216 -0
- package/src/authoring.js +386 -287
- package/src/cache/files.js +147 -0
- package/src/cache/lock.js +201 -0
- package/src/cache/paths.js +197 -0
- package/src/cache/store.js +703 -0
- package/src/catalog-text.js +19 -0
- package/src/cli/commands.js +448 -0
- package/src/cli/http-options.js +193 -0
- package/src/cli/options.js +554 -0
- package/src/cli/usage.js +96 -0
- package/src/cli.js +18 -932
- package/src/computation.js +99 -61
- package/src/context/assemble.js +567 -0
- package/src/context/cli-options.js +88 -0
- package/src/context/score.js +234 -0
- package/src/context/sections.js +274 -0
- package/src/embed/interface.js +160 -0
- package/src/embed/openai.js +715 -0
- package/src/embed/prepare.js +182 -0
- package/src/embed/units.js +96 -0
- package/src/error-details.js +53 -0
- package/src/git-source.js +112 -52
- package/src/graph.js +95 -37
- package/src/http-server.js +36 -17
- package/src/index.js +15 -0
- package/src/indexer/assemble.js +566 -0
- package/src/indexer/build.js +290 -0
- package/src/indexer/cache.js +81 -0
- package/src/indexer/edges.js +430 -0
- package/src/indexer/index.js +44 -0
- package/src/indexer/paths.js +178 -0
- package/src/indexer/resolve.js +282 -0
- package/src/indexer/update.js +720 -0
- package/src/indexer.js +3 -1068
- package/src/live-authoring.js +4 -2329
- package/src/markdown.js +21 -16
- package/src/mcp/auth.js +409 -0
- package/src/mcp/http.js +317 -0
- package/src/mcp/principal.js +59 -0
- package/src/mcp/registry.js +356 -0
- package/src/mcp/resources.js +45 -0
- package/src/mcp/server.js +567 -0
- package/src/mcp/tools/catalog.js +247 -0
- package/src/mcp/tools/computation.js +83 -0
- package/src/mcp/tools/context.js +133 -0
- package/src/mcp/tools/graph.js +167 -0
- package/src/mcp/tools/live-authoring.js +316 -0
- package/src/mcp/tools/migration.js +86 -0
- package/src/mcp/tools/producers.js +79 -0
- package/src/mcp/tools/proposals.js +225 -0
- package/src/mcp/tools/provenance.js +87 -0
- package/src/mcp/tools/remote.js +79 -0
- package/src/mcp/tools/search.js +242 -0
- package/src/mcp-server.js +3 -1611
- package/src/migration.js +431 -253
- package/src/parser.js +245 -130
- package/src/plugins.js +71 -48
- package/src/policy/write-policy.js +713 -0
- package/src/producer-publisher.js +202 -78
- package/src/producers.js +311 -103
- package/src/project.js +346 -93
- package/src/remote.js +96 -61
- package/src/search/cli-options.js +107 -0
- package/src/search/confidence.js +61 -0
- package/src/search/dense.js +304 -0
- package/src/search/embedding-cli.js +57 -0
- package/src/search/embedding-config.js +217 -0
- package/src/search/fusion.js +249 -0
- package/src/search/hybrid.js +526 -0
- package/src/search/languages.js +200 -0
- package/src/search/lexical.js +695 -0
- package/src/search/query.js +620 -0
- package/src/search/stem/among.js +43 -0
- package/src/search/stem/base-stemmer.js +311 -0
- package/src/search/stem/en-regions.js +456 -0
- package/src/search/stem/en-suffixes.js +664 -0
- package/src/search/stem/en-tables.js +176 -0
- package/src/search/stem/en.js +238 -0
- package/src/search/stem/it-regions.js +459 -0
- package/src/search/stem/it-suffixes.js +471 -0
- package/src/search/stem/it-tables.js +257 -0
- package/src/search/stem/it.js +155 -0
- package/src/search-index.js +2 -81
- package/src/search.js +2 -252
- package/src/store.js +134 -81
- package/src/tool-packs.js +346 -0
- package/src/v02.js +301 -105
- package/src/validation.js +24 -20
package/src/markdown.js
CHANGED
|
@@ -22,11 +22,11 @@ function isDocumentChild(node) {
|
|
|
22
22
|
|
|
23
23
|
function isTopLevelItem(node) {
|
|
24
24
|
return Boolean(
|
|
25
|
-
node
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
25
|
+
node &&
|
|
26
|
+
node.parent &&
|
|
27
|
+
node.parent.type === "list" &&
|
|
28
|
+
node.parent.parent &&
|
|
29
|
+
node.parent.parent.type === "document",
|
|
30
30
|
);
|
|
31
31
|
}
|
|
32
32
|
|
|
@@ -63,9 +63,11 @@ function markdownStructure(body) {
|
|
|
63
63
|
const fenceLength = Number(node._fenceLength || 0);
|
|
64
64
|
const closingLine = lines[node.sourcepos[1][0] - 1] || "";
|
|
65
65
|
const closed = Boolean(
|
|
66
|
-
node._isFenced
|
|
67
|
-
|
|
68
|
-
|
|
66
|
+
node._isFenced &&
|
|
67
|
+
fenceCharacter &&
|
|
68
|
+
new RegExp(`^ {0,3}${fenceCharacter === "`" ? "`" : "~"}{${fenceLength},}\\s*$`).test(
|
|
69
|
+
closingLine,
|
|
70
|
+
),
|
|
69
71
|
);
|
|
70
72
|
codeBlocks.push({
|
|
71
73
|
node,
|
|
@@ -73,7 +75,10 @@ function markdownStructure(body) {
|
|
|
73
75
|
endLine: node.sourcepos[1][0],
|
|
74
76
|
fenced: Boolean(node._isFenced),
|
|
75
77
|
closed,
|
|
76
|
-
language:
|
|
78
|
+
language:
|
|
79
|
+
String(node.info || "")
|
|
80
|
+
.trim()
|
|
81
|
+
.split(/\s+/)[0] || "",
|
|
77
82
|
content: String(node.literal || "").replace(/\n$/, ""),
|
|
78
83
|
});
|
|
79
84
|
}
|
|
@@ -89,9 +94,9 @@ function markdownStructure(body) {
|
|
|
89
94
|
}
|
|
90
95
|
|
|
91
96
|
function sectionEndLine(structure, heading) {
|
|
92
|
-
const next = structure.headings.find(
|
|
93
|
-
entry.startLine > heading.startLine && entry.level <= heading.level
|
|
94
|
-
)
|
|
97
|
+
const next = structure.headings.find(
|
|
98
|
+
(entry) => entry.startLine > heading.startLine && entry.level <= heading.level,
|
|
99
|
+
);
|
|
95
100
|
return next ? next.startLine : Number.POSITIVE_INFINITY;
|
|
96
101
|
}
|
|
97
102
|
|
|
@@ -99,10 +104,10 @@ function sectionNodes(heading, options) {
|
|
|
99
104
|
const nodes = [];
|
|
100
105
|
let current = heading && heading.node ? heading.node.next : null;
|
|
101
106
|
while (current) {
|
|
102
|
-
if (
|
|
103
|
-
|
|
104
|
-
|| current.level <= heading.level
|
|
105
|
-
)
|
|
107
|
+
if (
|
|
108
|
+
current.type === "heading" &&
|
|
109
|
+
((options && options.stopAtAnyHeading) || current.level <= heading.level)
|
|
110
|
+
) {
|
|
106
111
|
break;
|
|
107
112
|
}
|
|
108
113
|
nodes.push(current);
|
package/src/mcp/auth.js
ADDED
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
// Bearer authentication for MCP over HTTP (plan I-2a). okf-mcp is a resource
|
|
4
|
+
// server only: it checks opaque tokens and never issues them.
|
|
5
|
+
//
|
|
6
|
+
// - `tokens:<file>`: a YAML list of { sha256, subject, actor, scopes } where
|
|
7
|
+
// sha256 is the hex SHA-256 of a bearer token; tokens themselves are never
|
|
8
|
+
// stored.
|
|
9
|
+
// - `introspect:<url>`: RFC 7662 introspection against an external
|
|
10
|
+
// authorization server, with HTTP Basic client credentials taken from
|
|
11
|
+
// OKF_INTROSPECTION_CLIENT_ID / OKF_INTROSPECTION_CLIENT_SECRET only. A
|
|
12
|
+
// token is accepted when `active` is true, `aud` equals the public MCP URL,
|
|
13
|
+
// `exp` is in the future and `scope` holds okf.read; the actor is
|
|
14
|
+
// human:<username>. Accepted answers are cached by token hash until the
|
|
15
|
+
// earlier of `exp` and 60 s, so a revoked token can live that long here;
|
|
16
|
+
// refused ones for 30 s. At most 8 introspections run at once.
|
|
17
|
+
//
|
|
18
|
+
// Token values never reach an error, a log line or a response, and the
|
|
19
|
+
// caches keep only their hash; the verified token goes on only to tool-pack
|
|
20
|
+
// handlers, as ctx.subjectToken (src/tool-packs.js).
|
|
21
|
+
|
|
22
|
+
const crypto = require("node:crypto");
|
|
23
|
+
const fs = require("node:fs");
|
|
24
|
+
const path = require("node:path");
|
|
25
|
+
const yaml = require("js-yaml");
|
|
26
|
+
const {
|
|
27
|
+
OAuthError,
|
|
28
|
+
OAuthErrorCode,
|
|
29
|
+
buildOAuthProtectedResourceMetadata,
|
|
30
|
+
getOAuthProtectedResourceMetadataUrl,
|
|
31
|
+
verifyBearerToken,
|
|
32
|
+
} = require("@modelcontextprotocol/server");
|
|
33
|
+
|
|
34
|
+
const { authorEmail, authorName } = require("../authoring/candidates");
|
|
35
|
+
const { validActor } = require("../v02");
|
|
36
|
+
const { KNOWN_SCOPES, READ_SCOPE, SCOPE_NAME } = require("./principal");
|
|
37
|
+
|
|
38
|
+
// A scope a principal may carry: okf.read, okf.write, or any well-formed
|
|
39
|
+
// scope outside okf.* (such as odoo.read, which tool-pack tools declare).
|
|
40
|
+
function grantableScope(scope) {
|
|
41
|
+
return (
|
|
42
|
+
typeof scope === "string" &&
|
|
43
|
+
SCOPE_NAME.test(scope) &&
|
|
44
|
+
(KNOWN_SCOPES.includes(scope) || !scope.startsWith("okf."))
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
const CACHE_TTL_MS = 60 * 1000;
|
|
48
|
+
const NEGATIVE_CACHE_TTL_MS = 30 * 1000;
|
|
49
|
+
const CACHE_LIMIT = 1000;
|
|
50
|
+
const MAX_CONCURRENT_INTROSPECTIONS = 8;
|
|
51
|
+
const INTROSPECTION_TIMEOUT_MS = 5000;
|
|
52
|
+
const MAX_TOKEN_FILE_BYTES = 1024 * 1024;
|
|
53
|
+
|
|
54
|
+
class IntrospectionUnavailableError extends Error {}
|
|
55
|
+
|
|
56
|
+
function tokenHash(token) {
|
|
57
|
+
return crypto.createHash("sha256").update(token, "utf8").digest("hex");
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function invalidToken() {
|
|
61
|
+
return new OAuthError(OAuthErrorCode.InvalidToken, "The access token is not valid.");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// AuthInfo for verifyBearerToken: scopes and expiry are checked there; the
|
|
65
|
+
// principal rides in `extra`, and `token` stays empty.
|
|
66
|
+
function authInfoFor(principal, expiresAt, clientId) {
|
|
67
|
+
return {
|
|
68
|
+
token: "",
|
|
69
|
+
clientId: clientId || principal.subject,
|
|
70
|
+
scopes: [...principal.scopes],
|
|
71
|
+
expiresAt,
|
|
72
|
+
extra: { principal },
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function readTokenFile(file) {
|
|
77
|
+
const resolved = path.resolve(file);
|
|
78
|
+
const stat = fs.lstatSync(resolved);
|
|
79
|
+
if (stat.isSymbolicLink() || !stat.isFile() || stat.size > MAX_TOKEN_FILE_BYTES) {
|
|
80
|
+
throw new Error("The token file must be a regular file of at most 1 MiB.");
|
|
81
|
+
}
|
|
82
|
+
const descriptor = fs.openSync(resolved, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
|
|
83
|
+
try {
|
|
84
|
+
return fs.readFileSync(descriptor, "utf8");
|
|
85
|
+
} finally {
|
|
86
|
+
fs.closeSync(descriptor);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// The token file as a Map from token hash to principal. Errors name the
|
|
91
|
+
// entry and field, never a value.
|
|
92
|
+
function loadTokenFile(file) {
|
|
93
|
+
let document;
|
|
94
|
+
try {
|
|
95
|
+
document = yaml.load(readTokenFile(file));
|
|
96
|
+
} catch (error) {
|
|
97
|
+
throw new Error(`Invalid token file: ${error.code === "ENOENT" ? "not found" : error.message}`);
|
|
98
|
+
}
|
|
99
|
+
const entries = document?.tokens;
|
|
100
|
+
if (!Array.isArray(entries) || Object.keys(document).length !== 1) {
|
|
101
|
+
throw new Error("Invalid token file: expected one `tokens` list.");
|
|
102
|
+
}
|
|
103
|
+
const principals = new Map();
|
|
104
|
+
entries.forEach((entry, index) => {
|
|
105
|
+
const fail = (field, message) => {
|
|
106
|
+
throw new Error(`Invalid token file: tokens[${index}]${field} ${message}`);
|
|
107
|
+
};
|
|
108
|
+
const keys = entry && typeof entry === "object" ? Object.keys(entry) : [];
|
|
109
|
+
const unknown = keys.find((key) => !["sha256", "subject", "actor", "scopes"].includes(key));
|
|
110
|
+
if (!keys.length || unknown) fail(unknown ? `.${unknown}` : "", "is not a known field.");
|
|
111
|
+
if (!/^[0-9a-f]{64}$/i.test(String(entry.sha256 || ""))) {
|
|
112
|
+
fail(".sha256", "must be 64 hex characters.");
|
|
113
|
+
}
|
|
114
|
+
if (typeof entry.subject !== "string" || !entry.subject.trim()) {
|
|
115
|
+
fail(".subject", "must be a non-empty string.");
|
|
116
|
+
}
|
|
117
|
+
if (!validActor(entry.actor))
|
|
118
|
+
fail(".actor", "must be human:<id>, process:<id> or provider/model.");
|
|
119
|
+
const scopes = Array.isArray(entry.scopes) ? entry.scopes : [];
|
|
120
|
+
if (!scopes.length || !scopes.every(grantableScope)) {
|
|
121
|
+
fail(".scopes", `must list ${KNOWN_SCOPES.join(", ")} or well-formed scopes outside okf.*.`);
|
|
122
|
+
}
|
|
123
|
+
const hash = entry.sha256.toLowerCase();
|
|
124
|
+
if (principals.has(hash)) fail(".sha256", "repeats an earlier entry.");
|
|
125
|
+
principals.set(hash, {
|
|
126
|
+
subject: entry.subject,
|
|
127
|
+
actor: entry.actor,
|
|
128
|
+
scopes: new Set(scopes),
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
return principals;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function tokenFileVerifier(file) {
|
|
135
|
+
const principals = loadTokenFile(file);
|
|
136
|
+
return {
|
|
137
|
+
async verifyAccessToken(token) {
|
|
138
|
+
const principal = principals.get(tokenHash(token));
|
|
139
|
+
if (!principal) throw invalidToken();
|
|
140
|
+
// Listed tokens do not expire; the bearer check wants an expiry.
|
|
141
|
+
return authInfoFor(principal, Math.floor(Date.now() / 1000) + 3600);
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// `aud` against the public MCP URL, verbatim except for one trailing slash
|
|
147
|
+
// on either side.
|
|
148
|
+
function sameAudience(aud, audience) {
|
|
149
|
+
const trim = (value) => (value.endsWith("/") ? value.slice(0, -1) : value);
|
|
150
|
+
return typeof aud === "string" && trim(aud) === trim(audience);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// The principal an introspection answer grants, or null when the token is
|
|
154
|
+
// not accepted (shared contract, plan I-2a). `name` and `email` are each
|
|
155
|
+
// optional and cleaned (authorName, authorEmail); one that is absent or
|
|
156
|
+
// unusable leaves that git author field to the configured identity.
|
|
157
|
+
function introspectionPrincipal(answer, audience, nowSeconds) {
|
|
158
|
+
if (answer?.active !== true || !sameAudience(answer.aud, audience)) return null;
|
|
159
|
+
if (typeof answer.exp !== "number" || !(answer.exp > nowSeconds)) return null;
|
|
160
|
+
const scopes = typeof answer.scope === "string" ? answer.scope.split(" ") : [];
|
|
161
|
+
const actor = humanActor(answer.username);
|
|
162
|
+
const subject = typeof answer.sub === "number" ? String(answer.sub) : answer.sub;
|
|
163
|
+
if (!actor || typeof subject !== "string" || !subject) return null;
|
|
164
|
+
const principal = {
|
|
165
|
+
subject,
|
|
166
|
+
actor,
|
|
167
|
+
scopes: new Set(scopes.filter(grantableScope).slice(0, 64)),
|
|
168
|
+
};
|
|
169
|
+
const name = authorName(answer.name);
|
|
170
|
+
const email = authorEmail(answer.email);
|
|
171
|
+
if (name) principal.name = name;
|
|
172
|
+
if (email) principal.email = email;
|
|
173
|
+
return { principal, exp: answer.exp, clientId: answer.client_id };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// The actor of an introspected user: human:<username> with every character
|
|
177
|
+
// outside [A-Za-z0-9._@+-] mapped to "-", so a username can never carry a
|
|
178
|
+
// "/" (the provider/model actor form) or anything a policy pattern treats
|
|
179
|
+
// specially. Null for an empty username.
|
|
180
|
+
function humanActor(username) {
|
|
181
|
+
if (typeof username !== "string" || !username) return null;
|
|
182
|
+
return `human:${username.replace(/[^A-Za-z0-9._@+-]/g, "-")}`;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// HTTP Basic credentials per RFC 6749 section 2.3.1: id and secret are
|
|
186
|
+
// form-urlencoded before they are joined and base64-encoded.
|
|
187
|
+
function basicCredentials(clientId, clientSecret) {
|
|
188
|
+
const encode = (value) => new URLSearchParams([["", value]]).toString().slice(1);
|
|
189
|
+
return Buffer.from(`${encode(clientId)}:${encode(clientSecret)}`).toString("base64");
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// A bounded least-recently-used map of token hash to { result, until }.
|
|
193
|
+
function lruCache(limit, now) {
|
|
194
|
+
const entries = new Map();
|
|
195
|
+
return {
|
|
196
|
+
get(key) {
|
|
197
|
+
const entry = entries.get(key);
|
|
198
|
+
if (!entry) return undefined;
|
|
199
|
+
entries.delete(key);
|
|
200
|
+
if (entry.until <= now()) return undefined;
|
|
201
|
+
entries.set(key, entry);
|
|
202
|
+
return entry;
|
|
203
|
+
},
|
|
204
|
+
set(key, entry) {
|
|
205
|
+
entries.delete(key);
|
|
206
|
+
if (entries.size >= limit) entries.delete(entries.keys().next().value);
|
|
207
|
+
entries.set(key, entry);
|
|
208
|
+
},
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Answers are cached by token hash in two bounded LRU caches: accepted ones
|
|
213
|
+
// until the earlier of exp and 60 s, refused ones (inactive, wrong audience,
|
|
214
|
+
// expired) for 30 s. Concurrent lookups of one token share one upstream
|
|
215
|
+
// call, and at most `maxConcurrent` upstream calls run at once; a lookup
|
|
216
|
+
// beyond that is answered as unavailable (503) instead of queued.
|
|
217
|
+
function introspectionVerifier(options) {
|
|
218
|
+
const { url, audience, clientId, clientSecret } = options;
|
|
219
|
+
const fetchImpl = options.fetch || globalThis.fetch;
|
|
220
|
+
const now = options.now || Date.now;
|
|
221
|
+
const limit = options.cacheLimit || CACHE_LIMIT;
|
|
222
|
+
const maxConcurrent = options.maxConcurrent || MAX_CONCURRENT_INTROSPECTIONS;
|
|
223
|
+
const accepted = lruCache(limit, now);
|
|
224
|
+
const refused = lruCache(limit, now);
|
|
225
|
+
const pending = new Map();
|
|
226
|
+
let inFlight = 0;
|
|
227
|
+
|
|
228
|
+
async function introspect(token) {
|
|
229
|
+
let response;
|
|
230
|
+
try {
|
|
231
|
+
response = await fetchImpl(url, {
|
|
232
|
+
method: "POST",
|
|
233
|
+
headers: {
|
|
234
|
+
authorization: `Basic ${basicCredentials(clientId, clientSecret)}`,
|
|
235
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
236
|
+
accept: "application/json",
|
|
237
|
+
},
|
|
238
|
+
body: new URLSearchParams({ token }).toString(),
|
|
239
|
+
redirect: "error",
|
|
240
|
+
signal: AbortSignal.timeout(INTROSPECTION_TIMEOUT_MS),
|
|
241
|
+
});
|
|
242
|
+
} catch {
|
|
243
|
+
throw new IntrospectionUnavailableError("introspection unreachable");
|
|
244
|
+
}
|
|
245
|
+
if (response.status !== 200) {
|
|
246
|
+
await response.body?.cancel();
|
|
247
|
+
throw new IntrospectionUnavailableError("introspection refused");
|
|
248
|
+
}
|
|
249
|
+
try {
|
|
250
|
+
return await response.json();
|
|
251
|
+
} catch {
|
|
252
|
+
throw new IntrospectionUnavailableError("introspection answer unreadable");
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async function lookup(hash, token) {
|
|
257
|
+
inFlight += 1;
|
|
258
|
+
try {
|
|
259
|
+
const answer = await introspect(token);
|
|
260
|
+
const result = introspectionPrincipal(answer, audience, now() / 1000);
|
|
261
|
+
if (result) {
|
|
262
|
+
accepted.set(hash, { result, until: Math.min(now() + CACHE_TTL_MS, result.exp * 1000) });
|
|
263
|
+
} else {
|
|
264
|
+
refused.set(hash, { result: null, until: now() + NEGATIVE_CACHE_TTL_MS });
|
|
265
|
+
}
|
|
266
|
+
return result;
|
|
267
|
+
} finally {
|
|
268
|
+
inFlight -= 1;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
return {
|
|
273
|
+
async verifyAccessToken(token) {
|
|
274
|
+
const hash = tokenHash(token);
|
|
275
|
+
const cached = accepted.get(hash) || refused.get(hash);
|
|
276
|
+
let result;
|
|
277
|
+
if (cached) {
|
|
278
|
+
result = cached.result;
|
|
279
|
+
} else {
|
|
280
|
+
if (!pending.has(hash)) {
|
|
281
|
+
if (inFlight >= maxConcurrent) {
|
|
282
|
+
throw new IntrospectionUnavailableError("too many introspections in flight");
|
|
283
|
+
}
|
|
284
|
+
pending.set(
|
|
285
|
+
hash,
|
|
286
|
+
lookup(hash, token).finally(() => pending.delete(hash)),
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
result = await pending.get(hash);
|
|
290
|
+
}
|
|
291
|
+
if (!result) throw invalidToken();
|
|
292
|
+
return authInfoFor(result.principal, result.exp, result.clientId);
|
|
293
|
+
},
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// The authentication of one HTTP server: { authenticate(request) →
|
|
298
|
+
// { principal, subjectToken } or a ready Response, routes(request) → the protected-resource
|
|
299
|
+
// metadata document or undefined }.
|
|
300
|
+
function createHttpAuth(auth, options) {
|
|
301
|
+
const config = options || {};
|
|
302
|
+
const env = config.env || process.env;
|
|
303
|
+
// The scopes to advertise: okf.read, okf.write and the tool packs' (see
|
|
304
|
+
// advertisedScopes in src/tool-packs.js).
|
|
305
|
+
const scopes = config.scopes || [...KNOWN_SCOPES];
|
|
306
|
+
let verifier;
|
|
307
|
+
let resourceMetadataUrl;
|
|
308
|
+
let metadata = null;
|
|
309
|
+
if (auth.mode === "tokens") {
|
|
310
|
+
verifier = tokenFileVerifier(auth.file);
|
|
311
|
+
} else {
|
|
312
|
+
const clientId = env.OKF_INTROSPECTION_CLIENT_ID;
|
|
313
|
+
const clientSecret = env.OKF_INTROSPECTION_CLIENT_SECRET;
|
|
314
|
+
if (!clientId || !clientSecret) {
|
|
315
|
+
throw new Error(
|
|
316
|
+
"--auth introspect needs OKF_INTROSPECTION_CLIENT_ID and OKF_INTROSPECTION_CLIENT_SECRET in the environment.",
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
const resource = new URL(config.publicUrl);
|
|
320
|
+
metadata = buildOAuthProtectedResourceMetadata({
|
|
321
|
+
oauthMetadata: { issuer: auth.issuer },
|
|
322
|
+
resourceServerUrl: resource,
|
|
323
|
+
scopesSupported: scopes,
|
|
324
|
+
});
|
|
325
|
+
resourceMetadataUrl = getOAuthProtectedResourceMetadataUrl(resource);
|
|
326
|
+
verifier = introspectionVerifier({
|
|
327
|
+
url: auth.url,
|
|
328
|
+
audience: resource.href,
|
|
329
|
+
clientId,
|
|
330
|
+
clientSecret,
|
|
331
|
+
fetch: config.fetch,
|
|
332
|
+
now: config.now,
|
|
333
|
+
cacheLimit: config.cacheLimit,
|
|
334
|
+
maxConcurrent: config.maxConcurrent,
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
const bearer = { verifier, requiredScopes: [READ_SCOPE], resourceMetadataUrl };
|
|
338
|
+
// The WWW-Authenticate challenge (RFC 6750 section 3). It names every scope
|
|
339
|
+
// the server offers, so a client signing in asks for all of them and the
|
|
340
|
+
// authorization server narrows them to the user's rights; error is set only
|
|
341
|
+
// when a Bearer token was presented (section 3.1), and a token lacking
|
|
342
|
+
// okf.read is told that it needs okf.read.
|
|
343
|
+
const challenge = (status, error, required) => {
|
|
344
|
+
const header = ['Bearer realm="okf-mcp"']
|
|
345
|
+
.concat(error ? [`error="${error}"`] : [])
|
|
346
|
+
.concat([`scope="${required.join(" ")}"`])
|
|
347
|
+
.concat(resourceMetadataUrl ? [`resource_metadata="${resourceMetadataUrl}"`] : [])
|
|
348
|
+
.join(", ");
|
|
349
|
+
return Response.json(
|
|
350
|
+
{ error: error || "unauthorized" },
|
|
351
|
+
{ status, headers: { "www-authenticate": header } },
|
|
352
|
+
);
|
|
353
|
+
};
|
|
354
|
+
const metadataPaths = metadata
|
|
355
|
+
? new Set([new URL(resourceMetadataUrl).pathname, "/.well-known/oauth-protected-resource"])
|
|
356
|
+
: new Set();
|
|
357
|
+
|
|
358
|
+
return {
|
|
359
|
+
async authenticate(request) {
|
|
360
|
+
const [header] = (request.headers.get("authorization") || "").split(",");
|
|
361
|
+
// No credentials: no Authorization header, or none with a Bearer token.
|
|
362
|
+
if (!/^\s*bearer\s+\S/i.test(header)) return challenge(401, null, scopes);
|
|
363
|
+
try {
|
|
364
|
+
const verified = await verifyBearerToken(header.trim(), bearer);
|
|
365
|
+
// The token itself travels on only as a tool pack's subjectToken.
|
|
366
|
+
return {
|
|
367
|
+
principal: verified.extra.principal,
|
|
368
|
+
subjectToken: header.trim().split(/\s+/)[1],
|
|
369
|
+
};
|
|
370
|
+
} catch (error) {
|
|
371
|
+
if (error instanceof IntrospectionUnavailableError) {
|
|
372
|
+
return Response.json(
|
|
373
|
+
{ error: "temporarily_unavailable" },
|
|
374
|
+
{ status: 503, headers: { "retry-after": "5" } },
|
|
375
|
+
);
|
|
376
|
+
}
|
|
377
|
+
if (error?.code === OAuthErrorCode.InsufficientScope) {
|
|
378
|
+
return challenge(403, "insufficient_scope", [READ_SCOPE]);
|
|
379
|
+
}
|
|
380
|
+
if (error?.code === OAuthErrorCode.InvalidToken) {
|
|
381
|
+
return challenge(401, "invalid_token", scopes);
|
|
382
|
+
}
|
|
383
|
+
return Response.json({ error: "server_error" }, { status: 500 });
|
|
384
|
+
}
|
|
385
|
+
},
|
|
386
|
+
routes(request) {
|
|
387
|
+
if (!metadataPaths.has(new URL(request.url).pathname)) return undefined;
|
|
388
|
+
if (request.method !== "GET" && request.method !== "HEAD") {
|
|
389
|
+
return Response.json(
|
|
390
|
+
{ error: "method_not_allowed" },
|
|
391
|
+
{ status: 405, headers: { allow: "GET, HEAD" } },
|
|
392
|
+
);
|
|
393
|
+
}
|
|
394
|
+
// CORS for browser origins is added by the HTTP handler, as for the
|
|
395
|
+
// MCP endpoint.
|
|
396
|
+
return Response.json(metadata);
|
|
397
|
+
},
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
module.exports = {
|
|
402
|
+
createHttpAuth,
|
|
403
|
+
/** @internal Exposed for the contract tests. */
|
|
404
|
+
introspectionPrincipal,
|
|
405
|
+
/** @internal */
|
|
406
|
+
loadTokenFile,
|
|
407
|
+
/** @internal */
|
|
408
|
+
tokenHash,
|
|
409
|
+
};
|