pico-engine 1.9.5 → 1.10.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 (126) hide show
  1. package/README.md +11 -5
  2. package/demos/bootstrap/com.example.visitors.bootstrap.krl +9 -5
  3. package/demos/child_tasks/com.example.task_runner.bootstrap.krl +10 -7
  4. package/demos/echo/com.example.echo.bootstrap.krl +10 -7
  5. package/demos/guard_rules/com.example.archive.bootstrap.krl +10 -7
  6. package/demos/json_query/README.md +11 -0
  7. package/demos/json_query/com.example.json_query.bootstrap.krl +84 -0
  8. package/demos/json_query/com.example.json_query.krl +162 -0
  9. package/demos/json_query/try-it.md +5 -0
  10. package/demos/kblog/com.example.kblog.bootstrap.krl +10 -7
  11. package/demos/layered_rulesets/com.example.invitations.bootstrap.krl +10 -7
  12. package/demos/score_tracker/com.example.score_tracker.bootstrap.krl +10 -7
  13. package/demos/secrets/com.example.notifier.bootstrap.krl +10 -7
  14. package/demos/try-it-order.json +1 -1
  15. package/demos/two_picos/com.example.two_picos.bootstrap.krl +5 -2
  16. package/demos/xmlui/com.example.thermostat.bootstrap.krl +10 -7
  17. package/dist/cli.js +5 -1
  18. package/dist/engineConfig.js +1 -1
  19. package/dist/identity/portableMove.js +5 -1
  20. package/dist/index.js +44 -12
  21. package/dist/internalAccess.js +110 -0
  22. package/dist/oauth/OAuthService.js +172 -10
  23. package/dist/oauth/acg.js +194 -24
  24. package/dist/oauth/cimd.js +381 -0
  25. package/dist/oauth/discovery.js +175 -0
  26. package/dist/runMcp.js +1 -1
  27. package/dist/server.js +197 -48
  28. package/dist/subtreeWrangler.js +8 -5
  29. package/dist/uiChannelPolicies.js +2 -0
  30. package/krl/io.picolabs.pds.krl +109 -21
  31. package/krl/io.picolabs.pico-engine-ui.krl +13 -7
  32. package/krl/io.picolabs.wrangler.krl +21 -9
  33. package/mcp/devResources.js +52 -0
  34. package/mcp/devTools.js +40 -9
  35. package/mcp/docs/CLAUDE.md +3 -2
  36. package/mcp/docs/cookbook/README.md +23 -0
  37. package/mcp/docs/cookbook/bootstrap/README.md +23 -0
  38. package/mcp/docs/cookbook/bootstrap/instructions.md +75 -0
  39. package/mcp/docs/cookbook/child_tasks/README.md +20 -0
  40. package/mcp/docs/cookbook/child_tasks/instructions.md +60 -0
  41. package/mcp/docs/cookbook/collection/README.md +21 -0
  42. package/mcp/docs/cookbook/collection/instructions.md +93 -0
  43. package/mcp/docs/cookbook/echo/README.md +19 -0
  44. package/mcp/docs/cookbook/echo/instructions.md +59 -0
  45. package/mcp/docs/cookbook/guard_rules/README.md +22 -0
  46. package/mcp/docs/cookbook/guard_rules/instructions.md +73 -0
  47. package/mcp/docs/cookbook/json_query/README.md +26 -0
  48. package/mcp/docs/cookbook/json_query/instructions.md +64 -0
  49. package/mcp/docs/cookbook/kblog/README.md +60 -0
  50. package/mcp/docs/cookbook/kblog/instructions.md +102 -0
  51. package/mcp/docs/cookbook/layered_rulesets/README.md +24 -0
  52. package/mcp/docs/cookbook/layered_rulesets/instructions.md +87 -0
  53. package/mcp/docs/cookbook/moving_picos/README.md +44 -0
  54. package/mcp/docs/cookbook/moving_picos/instructions.md +150 -0
  55. package/mcp/docs/cookbook/score_tracker/README.md +19 -0
  56. package/mcp/docs/cookbook/score_tracker/instructions.md +73 -0
  57. package/mcp/docs/cookbook/secrets/README.md +25 -0
  58. package/mcp/docs/cookbook/secrets/instructions.md +98 -0
  59. package/mcp/docs/cookbook/two_picos/README.md +20 -0
  60. package/mcp/docs/cookbook/two_picos/instructions.md +88 -0
  61. package/mcp/docs/cookbook/xmlui/README.md +23 -0
  62. package/mcp/docs/cookbook/xmlui/instructions.md +84 -0
  63. package/mcp/docs/developing/README.md +28 -0
  64. package/mcp/docs/developing/accepting-relationship-requests.md +65 -0
  65. package/mcp/docs/developing/arrays-and-maps.md +77 -0
  66. package/mcp/docs/developing/converting-time-formats.md +28 -0
  67. package/mcp/docs/developing/cookies-and-redirects.md +81 -0
  68. package/mcp/docs/developing/decoding-form-data.md +67 -0
  69. package/mcp/docs/developing/engine-log-files.md +34 -0
  70. package/mcp/docs/developing/event-loop.md +77 -0
  71. package/mcp/docs/developing/events-from-email.md +80 -0
  72. package/mcp/docs/developing/initializing-entity-variables.md +83 -0
  73. package/mcp/docs/developing/mcp-ai-tools.md +98 -0
  74. package/mcp/docs/developing/misconceptions.md +467 -0
  75. package/mcp/docs/developing/names-and-scope.md +44 -0
  76. package/mcp/docs/developing/postman.md +159 -0
  77. package/mcp/docs/developing/querying-another-pico.md +47 -0
  78. package/mcp/docs/developing/singleton-picos.md +36 -0
  79. package/mcp/docs/developing/tabular-data.md +67 -0
  80. package/mcp/docs/developing/tips.md +251 -0
  81. package/mcp/docs/developing/webhook-signatures.md +56 -0
  82. package/mcp/docs/developing/workflow.md +106 -0
  83. package/mcp/docs/exp/README.md +46 -0
  84. package/mcp/docs/exp/event.md +110 -0
  85. package/mcp/docs/exp/query.md +94 -0
  86. package/mcp/docs/lessons/README.md +59 -0
  87. package/mcp/docs/lessons/events-and-queries.md +247 -0
  88. package/mcp/docs/lessons/gossip.md +28 -0
  89. package/mcp/docs/lessons/modules-and-apis.md +270 -0
  90. package/mcp/docs/lessons/pico-based-systems.md +470 -0
  91. package/mcp/docs/lessons/pico-state.md +267 -0
  92. package/mcp/docs/lessons/pico-views.md +290 -0
  93. package/mcp/docs/lessons/quickstart.md +157 -0
  94. package/mcp/docs/lessons/relationships.md +530 -0
  95. package/mcp/docs/lessons/scatter-gather.md +362 -0
  96. package/mcp/docs/pico-engine.md +7 -5
  97. package/mcp/docs/pico-overview.md +3 -3
  98. package/mcp/docs/wrangler/README.md +47 -0
  99. package/mcp/docs/wrangler/channels.md +235 -0
  100. package/mcp/docs/wrangler/oauth.md +56 -0
  101. package/mcp/docs/wrangler/pds.md +423 -0
  102. package/mcp/docs/wrangler/portable-subtree.md +44 -0
  103. package/mcp/docs/wrangler/relationships.md +297 -0
  104. package/mcp/docs/wrangler/wrangler.md +253 -0
  105. package/mcp/docs/wrangler/xmlui.md +60 -0
  106. package/mcp/engineClient.js +57 -5
  107. package/mcp/mcpScopes.js +118 -0
  108. package/mcp/meshHttp.js +151 -45
  109. package/mcp/runStdio.js +2 -0
  110. package/mcp/subtreeTools.js +184 -0
  111. package/mcp/tryItTools.js +202 -0
  112. package/package.json +14 -8
  113. package/public/pico-engine-ui.js +26 -26
  114. package/src/cli.ts +6 -2
  115. package/src/engineConfig.ts +5 -2
  116. package/src/identity/portableMove.ts +6 -1
  117. package/src/index.ts +469 -430
  118. package/src/internalAccess.ts +127 -0
  119. package/src/oauth/OAuthService.ts +243 -11
  120. package/src/oauth/acg.ts +289 -25
  121. package/src/oauth/cimd.ts +508 -0
  122. package/src/oauth/discovery.ts +233 -0
  123. package/src/runMcp.ts +3 -1
  124. package/src/server.ts +252 -52
  125. package/src/subtreeWrangler.ts +17 -5
  126. package/src/uiChannelPolicies.ts +2 -0
@@ -0,0 +1,381 @@
1
+ "use strict";
2
+ /**
3
+ * Client ID Metadata Documents (1.10 §2 A4).
4
+ *
5
+ * A client_id that is an https URL is fetched and checked. The document's
6
+ * client_id must equal that URL, and its redirect_uris must contain the
7
+ * request's redirect_uri exactly. Pre-registered app_ clients never come
8
+ * through here.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.CIMD_CACHE_CEILING_MS = exports.CIMD_TIMEOUT_MS = exports.CIMD_MAX_BYTES = void 0;
12
+ exports.isClientMetadataUrl = isClientMetadataUrl;
13
+ exports.rejectsAsMetadataUrl = rejectsAsMetadataUrl;
14
+ exports.isPrivateAddress = isPrivateAddress;
15
+ exports.safeDisplayUrl = safeDisplayUrl;
16
+ exports.cacheTtlMs = cacheTtlMs;
17
+ exports.parseClientMetadata = parseClientMetadata;
18
+ exports.loadClientMetadata = loadClientMetadata;
19
+ exports.assertPublicMetadataUrl = assertPublicMetadataUrl;
20
+ const dns = require("dns");
21
+ const https = require("https");
22
+ const net = require("net");
23
+ const errors_1 = require("./errors");
24
+ exports.CIMD_MAX_BYTES = 5 * 1024;
25
+ exports.CIMD_TIMEOUT_MS = 5000;
26
+ exports.CIMD_CACHE_CEILING_MS = 60 * 60 * 1000;
27
+ const MAX_REDIRECTS = 5;
28
+ const blocked = new net.BlockList();
29
+ blocked.addSubnet("0.0.0.0", 8, "ipv4");
30
+ blocked.addSubnet("10.0.0.0", 8, "ipv4");
31
+ blocked.addSubnet("100.64.0.0", 10, "ipv4");
32
+ blocked.addSubnet("127.0.0.0", 8, "ipv4");
33
+ blocked.addSubnet("169.254.0.0", 16, "ipv4");
34
+ blocked.addSubnet("172.16.0.0", 12, "ipv4");
35
+ blocked.addSubnet("192.0.0.0", 24, "ipv4");
36
+ blocked.addSubnet("192.0.2.0", 24, "ipv4");
37
+ blocked.addSubnet("192.168.0.0", 16, "ipv4");
38
+ blocked.addSubnet("198.18.0.0", 15, "ipv4");
39
+ blocked.addSubnet("198.51.100.0", 24, "ipv4");
40
+ blocked.addSubnet("203.0.113.0", 24, "ipv4");
41
+ blocked.addSubnet("224.0.0.0", 4, "ipv4");
42
+ blocked.addSubnet("240.0.0.0", 4, "ipv4");
43
+ blocked.addSubnet("::", 128, "ipv6");
44
+ blocked.addSubnet("::1", 128, "ipv6");
45
+ blocked.addSubnet("fc00::", 7, "ipv6");
46
+ blocked.addSubnet("fe80::", 10, "ipv6");
47
+ blocked.addSubnet("ff00::", 8, "ipv6");
48
+ blocked.addSubnet("2001:db8::", 32, "ipv6");
49
+ const defaultCache = new Map();
50
+ function isClientMetadataUrl(value) {
51
+ let url;
52
+ try {
53
+ url = new URL(value);
54
+ }
55
+ catch (_a) {
56
+ return false;
57
+ }
58
+ return (url.protocol === "https:" &&
59
+ !url.username &&
60
+ !url.password &&
61
+ url.hash === "" &&
62
+ url.hostname.length > 0);
63
+ }
64
+ /** An http(s) client_id that is not a usable metadata URL. */
65
+ function rejectsAsMetadataUrl(value) {
66
+ return /^https?:\/\//i.test(value) && !isClientMetadataUrl(value);
67
+ }
68
+ function isPrivateAddress(address) {
69
+ let ip = address.trim().toLowerCase().replace(/^\[|\]$/g, "").split("%")[0];
70
+ if (ip.startsWith("::ffff:")) {
71
+ const rest = ip.slice("::ffff:".length);
72
+ if (net.isIP(rest) === 4) {
73
+ return isPrivateAddress(rest);
74
+ }
75
+ const mapped = /^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(rest);
76
+ if (mapped) {
77
+ const hi = parseInt(mapped[1], 16);
78
+ const lo = parseInt(mapped[2], 16);
79
+ ip = `${(hi >> 8) & 255}.${hi & 255}.${(lo >> 8) & 255}.${lo & 255}`;
80
+ }
81
+ }
82
+ const kind = net.isIP(ip);
83
+ if (kind === 4) {
84
+ return blocked.check(ip, "ipv4");
85
+ }
86
+ if (kind === 6) {
87
+ return blocked.check(ip, "ipv6");
88
+ }
89
+ return true;
90
+ }
91
+ /** https URL safe to put on the approval page (the browser will fetch it). */
92
+ function safeDisplayUrl(value) {
93
+ if (typeof value !== "string" || !value.trim()) {
94
+ return undefined;
95
+ }
96
+ let url;
97
+ try {
98
+ url = new URL(value.trim());
99
+ }
100
+ catch (_a) {
101
+ return undefined;
102
+ }
103
+ if (url.protocol !== "https:" || url.username || url.password) {
104
+ return undefined;
105
+ }
106
+ if (isBlockedHostname(url.hostname)) {
107
+ return undefined;
108
+ }
109
+ if (net.isIP(url.hostname) && isPrivateAddress(url.hostname)) {
110
+ return undefined;
111
+ }
112
+ return value.trim();
113
+ }
114
+ function cacheTtlMs(headers, now) {
115
+ const cc = headerValue(headers, "cache-control").toLowerCase();
116
+ const expires = headerValue(headers, "expires");
117
+ if (!cc && !expires) {
118
+ return null;
119
+ }
120
+ if (/\bno-store\b/.test(cc) || /\bno-cache\b/.test(cc)) {
121
+ return null;
122
+ }
123
+ const maxAge = /\bmax-age=(\d+)/.exec(cc);
124
+ if (maxAge) {
125
+ const ms = Number(maxAge[1]) * 1000;
126
+ if (ms <= 0) {
127
+ return null;
128
+ }
129
+ return Math.min(ms, exports.CIMD_CACHE_CEILING_MS);
130
+ }
131
+ if (expires) {
132
+ const at = Date.parse(expires);
133
+ if (!Number.isNaN(at) && at > now) {
134
+ return Math.min(at - now, exports.CIMD_CACHE_CEILING_MS);
135
+ }
136
+ }
137
+ return null;
138
+ }
139
+ function parseClientMetadata(requestedUrl, body) {
140
+ if (body.length > exports.CIMD_MAX_BYTES) {
141
+ throw new errors_1.OAuthError("Client metadata document is too large", "invalid_client", 401);
142
+ }
143
+ let text = body.toString("utf8");
144
+ if (text.charCodeAt(0) === 0xfeff) {
145
+ text = text.slice(1);
146
+ }
147
+ let json;
148
+ try {
149
+ json = JSON.parse(text);
150
+ }
151
+ catch (_a) {
152
+ throw new errors_1.OAuthError("Client metadata document is not JSON", "invalid_client", 401);
153
+ }
154
+ if (!json || typeof json !== "object" || Array.isArray(json)) {
155
+ throw new errors_1.OAuthError("Client metadata document is not an object", "invalid_client", 401);
156
+ }
157
+ const doc = json;
158
+ if (doc.client_id !== requestedUrl) {
159
+ throw new errors_1.OAuthError("client_id in the metadata document does not match the URL", "invalid_client", 401);
160
+ }
161
+ if (!Array.isArray(doc.redirect_uris) ||
162
+ doc.redirect_uris.some((uri) => typeof uri !== "string")) {
163
+ throw new errors_1.OAuthError("Client metadata document is missing redirect_uris", "invalid_client", 401);
164
+ }
165
+ const redirectUris = doc.redirect_uris.map((uri) => uri.trim()).filter(Boolean);
166
+ if (typeof doc.token_endpoint_auth_method === "string" &&
167
+ doc.token_endpoint_auth_method !== "none") {
168
+ throw new errors_1.OAuthError("Client metadata document must use token_endpoint_auth_method none", "invalid_client", 401);
169
+ }
170
+ if (Array.isArray(doc.grant_types) &&
171
+ !doc.grant_types.includes("authorization_code")) {
172
+ throw new errors_1.OAuthError("Client metadata document does not allow authorization_code", "invalid_client", 401);
173
+ }
174
+ const host = new URL(requestedUrl).host;
175
+ return {
176
+ clientId: requestedUrl,
177
+ clientName: cleanName(typeof doc.client_name === "string" ? doc.client_name : "", host),
178
+ redirectUris,
179
+ clientUri: safeDisplayUrl(doc.client_uri),
180
+ logoUri: safeDisplayUrl(doc.logo_uri),
181
+ };
182
+ }
183
+ async function loadClientMetadata(clientIdUrl, deps = {}) {
184
+ const now = (deps.now || Date.now)();
185
+ const cache = deps.cache || defaultCache;
186
+ const hit = cache.get(clientIdUrl);
187
+ if (hit && hit.expiresAt > now) {
188
+ return hit.doc;
189
+ }
190
+ let response;
191
+ try {
192
+ const signal = AbortSignal.timeout(exports.CIMD_TIMEOUT_MS);
193
+ response = await fetchDocument(clientIdUrl, deps, signal);
194
+ }
195
+ catch (err) {
196
+ throw asOAuthError(err);
197
+ }
198
+ const doc = parseClientMetadata(clientIdUrl, response.body);
199
+ const ttl = cacheTtlMs(response.headers, now);
200
+ if (ttl && ttl > 0) {
201
+ cache.set(clientIdUrl, { doc, expiresAt: now + ttl });
202
+ }
203
+ else {
204
+ cache.delete(clientIdUrl);
205
+ }
206
+ return doc;
207
+ }
208
+ async function fetchDocument(startUrl, deps, signal) {
209
+ let current = startUrl;
210
+ const seen = new Set();
211
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
212
+ if (seen.has(current)) {
213
+ throw new errors_1.OAuthError("Client metadata URL redirected too many times", "invalid_client", 401);
214
+ }
215
+ seen.add(current);
216
+ await assertPublicMetadataUrl(current, deps.lookup);
217
+ const response = await (deps.request || defaultRequest)(current, signal);
218
+ if ([301, 302, 303, 307, 308].includes(response.status)) {
219
+ const location = headerValue(response.headers, "location");
220
+ if (!location) {
221
+ throw new errors_1.OAuthError("Client metadata could not be fetched", "invalid_client", 401);
222
+ }
223
+ current = new URL(location, current).toString();
224
+ continue;
225
+ }
226
+ if (response.status !== 200) {
227
+ throw new errors_1.OAuthError("Client metadata could not be fetched", "invalid_client", 401);
228
+ }
229
+ const declared = Number(headerValue(response.headers, "content-length") || "0");
230
+ if ((declared > 0 && declared > exports.CIMD_MAX_BYTES) ||
231
+ response.body.length > exports.CIMD_MAX_BYTES) {
232
+ throw new errors_1.OAuthError("Client metadata document is too large", "invalid_client", 401);
233
+ }
234
+ return { headers: response.headers, body: response.body };
235
+ }
236
+ throw new errors_1.OAuthError("Client metadata URL redirected too many times", "invalid_client", 401);
237
+ }
238
+ async function assertPublicMetadataUrl(raw, lookup = defaultLookup) {
239
+ let url;
240
+ try {
241
+ url = new URL(raw);
242
+ }
243
+ catch (_a) {
244
+ throw new errors_1.OAuthError("Invalid client metadata URL", "invalid_client", 401);
245
+ }
246
+ if (url.protocol !== "https:" || url.username || url.password || url.hash) {
247
+ throw new errors_1.OAuthError("client_id must be an https URL without a fragment or userinfo", "invalid_client", 401);
248
+ }
249
+ const hostname = url.hostname.replace(/\.$/, "");
250
+ if (isBlockedHostname(hostname)) {
251
+ throw new errors_1.OAuthError("Client metadata URL resolves to a private address", "invalid_client", 401);
252
+ }
253
+ if (net.isIP(hostname)) {
254
+ if (isPrivateAddress(hostname)) {
255
+ throw new errors_1.OAuthError("Client metadata URL resolves to a private address", "invalid_client", 401);
256
+ }
257
+ return;
258
+ }
259
+ let addresses;
260
+ try {
261
+ addresses = await lookup(hostname);
262
+ }
263
+ catch (_b) {
264
+ throw new errors_1.OAuthError("Client metadata URL could not be resolved", "invalid_client", 401);
265
+ }
266
+ if (!addresses.length || addresses.some((address) => isPrivateAddress(address))) {
267
+ throw new errors_1.OAuthError("Client metadata URL resolves to a private address", "invalid_client", 401);
268
+ }
269
+ }
270
+ function isBlockedHostname(hostname) {
271
+ const host = hostname.toLowerCase().replace(/\.$/, "");
272
+ if (!host ||
273
+ host === "localhost" ||
274
+ host.endsWith(".localhost") ||
275
+ host.endsWith(".local") ||
276
+ host.endsWith(".internal")) {
277
+ return true;
278
+ }
279
+ if (!host.includes(".")) {
280
+ return true;
281
+ }
282
+ if (/^\d+$/.test(host) || /^0x[0-9a-f]+$/i.test(host)) {
283
+ return true;
284
+ }
285
+ return false;
286
+ }
287
+ async function defaultLookup(hostname) {
288
+ const records = await dns.promises.lookup(hostname, { all: true, verbatim: true });
289
+ return records.map((record) => record.address);
290
+ }
291
+ function defaultRequest(url, signal) {
292
+ return new Promise((resolve, reject) => {
293
+ if (signal.aborted) {
294
+ reject(Object.assign(new Error("timeout"), { name: "TimeoutError" }));
295
+ return;
296
+ }
297
+ const req = https.request(url, {
298
+ method: "GET",
299
+ headers: { Accept: "application/json", "User-Agent": "pico-engine" },
300
+ lookup: publicLookup,
301
+ }, (res) => {
302
+ const chunks = [];
303
+ let size = 0;
304
+ res.on("data", (chunk) => {
305
+ size += chunk.length;
306
+ if (size > exports.CIMD_MAX_BYTES) {
307
+ res.destroy();
308
+ reject(new errors_1.OAuthError("Client metadata document is too large", "invalid_client", 401));
309
+ return;
310
+ }
311
+ chunks.push(chunk);
312
+ });
313
+ res.on("end", () => {
314
+ resolve({
315
+ status: res.statusCode || 0,
316
+ headers: res.headers,
317
+ body: Buffer.concat(chunks),
318
+ });
319
+ });
320
+ res.on("error", reject);
321
+ });
322
+ const abort = () => {
323
+ req.destroy(Object.assign(new Error("timeout"), { name: "TimeoutError" }));
324
+ };
325
+ signal.addEventListener("abort", abort, { once: true });
326
+ req.setTimeout(exports.CIMD_TIMEOUT_MS, abort);
327
+ req.on("error", reject);
328
+ req.end();
329
+ });
330
+ }
331
+ function publicLookup(hostname, options, callback) {
332
+ let opts = options;
333
+ let cb = callback;
334
+ if (typeof options === "function") {
335
+ cb = options;
336
+ opts = {};
337
+ }
338
+ dns.lookup(hostname, { all: true, verbatim: true }, (err, addresses) => {
339
+ if (err || !addresses.length || addresses.some((item) => isPrivateAddress(item.address))) {
340
+ const error = err ||
341
+ Object.assign(new Error("Client metadata URL resolves to a private address"), {
342
+ code: "EPERM",
343
+ });
344
+ cb(error, opts.all ? [] : "", 0);
345
+ return;
346
+ }
347
+ if (opts.all) {
348
+ cb(null, addresses.map((item) => ({ address: item.address, family: item.family })));
349
+ return;
350
+ }
351
+ cb(null, addresses[0].address, addresses[0].family);
352
+ });
353
+ }
354
+ function headerValue(headers, name) {
355
+ const wanted = name.toLowerCase();
356
+ for (const [key, value] of Object.entries(headers)) {
357
+ if (key.toLowerCase() !== wanted || value === undefined) {
358
+ continue;
359
+ }
360
+ return Array.isArray(value) ? value.join(", ") : value;
361
+ }
362
+ return "";
363
+ }
364
+ function cleanName(name, fallback) {
365
+ const cleaned = name.replace(/[\u0000-\u001f\u007f]/g, "").trim().slice(0, 200);
366
+ return cleaned || fallback;
367
+ }
368
+ function asOAuthError(err) {
369
+ if (err instanceof errors_1.OAuthError) {
370
+ return err;
371
+ }
372
+ const name = err instanceof Error ? err.name : "";
373
+ const message = err instanceof Error ? err.message : "";
374
+ if (message.includes("private address")) {
375
+ return new errors_1.OAuthError("Client metadata URL resolves to a private address", "invalid_client", 401);
376
+ }
377
+ if (name === "AbortError" || name === "TimeoutError" || message === "timeout") {
378
+ return new errors_1.OAuthError("Client metadata request timed out", "invalid_client", 401);
379
+ }
380
+ return new errors_1.OAuthError("Client metadata could not be fetched", "invalid_client", 401);
381
+ }
@@ -0,0 +1,175 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GRANT_TYPES_SUPPORTED = exports.MCP_CHANNEL_SCOPE = exports.MCP_SCOPES = void 0;
4
+ exports.parseScopeList = parseScopeList;
5
+ exports.assertMcpScopes = assertMcpScopes;
6
+ exports.scopeIncludes = scopeIncludes;
7
+ exports.canonicalBaseUrl = canonicalBaseUrl;
8
+ exports.authorizationServerMetadata = authorizationServerMetadata;
9
+ exports.skyResourceUrl = skyResourceUrl;
10
+ exports.mcpResourceUrl = mcpResourceUrl;
11
+ exports.protectedResourceMetadataUrl = protectedResourceMetadataUrl;
12
+ exports.protectedResourceMetadata = protectedResourceMetadata;
13
+ exports.bearerChallengeHeader = bearerChallengeHeader;
14
+ exports.classifyResource = classifyResource;
15
+ exports.canonicalResourceUrl = canonicalResourceUrl;
16
+ const errors_1 = require("./errors");
17
+ /**
18
+ * MCP authorization discovery (1.10 §2).
19
+ *
20
+ * RFC 9728 protected-resource metadata, RFC 8414 authorization-server
21
+ * metadata, and the RFC 6750 challenge on `/mcp/:eci`. Scope names are the
22
+ * ones enforced on `/mcp/{eci}` and `/mcp/mesh/{eci}`.
23
+ */
24
+ exports.MCP_SCOPES = ["mesh:read", "mesh:act", "mesh:admin"];
25
+ /** Scopes a channel MCP client holds when it does not ask for a narrower set. */
26
+ exports.MCP_CHANNEL_SCOPE = "mesh:read mesh:act";
27
+ function parseScopeList(scope) {
28
+ return [...new Set(String(scope || "").split(/\s+/).filter(Boolean))];
29
+ }
30
+ /** Every name must be an advertised MCP scope. */
31
+ function assertMcpScopes(scope) {
32
+ const names = parseScopeList(scope);
33
+ if (names.length === 0) {
34
+ throw new errors_1.OAuthError("Missing scope", "invalid_scope", 400);
35
+ }
36
+ for (const name of names) {
37
+ if (!exports.MCP_SCOPES.includes(name)) {
38
+ throw new errors_1.OAuthError(`Unknown scope: ${name}`, "invalid_scope", 400);
39
+ }
40
+ }
41
+ return names.join(" ");
42
+ }
43
+ function scopeIncludes(scope, required) {
44
+ return parseScopeList(scope).includes(required);
45
+ }
46
+ exports.GRANT_TYPES_SUPPORTED = [
47
+ "authorization_code",
48
+ "refresh_token",
49
+ "client_credentials",
50
+ ];
51
+ /** Configured public origin, else the request's own origin. No trailing slash. */
52
+ function canonicalBaseUrl(configured, req) {
53
+ const fromConfig = configured && configured.trim();
54
+ const raw = fromConfig ||
55
+ (req && req.protocol
56
+ ? `${req.protocol}://${(req.get && req.get("host")) || "localhost"}`
57
+ : "");
58
+ return raw.replace(/\/$/, "");
59
+ }
60
+ function authorizationServerMetadata(baseUrl, issuerUrl) {
61
+ const origin = canonicalBaseUrl(baseUrl);
62
+ const issuer = canonicalBaseUrl(issuerUrl || origin);
63
+ return {
64
+ issuer,
65
+ authorization_endpoint: `${origin}/oauth/authorize`,
66
+ token_endpoint: `${origin}/oauth/token`,
67
+ response_types_supported: ["code"],
68
+ grant_types_supported: [...exports.GRANT_TYPES_SUPPORTED],
69
+ code_challenge_methods_supported: ["S256"],
70
+ scopes_supported: [...exports.MCP_SCOPES],
71
+ token_endpoint_auth_methods_supported: ["none", "client_secret_post"],
72
+ client_id_metadata_document_supported: true,
73
+ };
74
+ }
75
+ function eciPath(eci) {
76
+ return encodeURIComponent(eci);
77
+ }
78
+ /** Audience for Sky routes. A token for an MCP URL is not a Sky token. */
79
+ function skyResourceUrl(baseUrl) {
80
+ return `${canonicalBaseUrl(baseUrl)}/sky`;
81
+ }
82
+ /** The MCP URL recorded on a token issued for that endpoint. */
83
+ function mcpResourceUrl(baseUrl, eci, surface) {
84
+ const origin = canonicalBaseUrl(baseUrl);
85
+ const id = eciPath(eci);
86
+ return surface === "mesh" ? `${origin}/mcp/mesh/${id}` : `${origin}/mcp/${id}`;
87
+ }
88
+ /** RFC 9728: insert `/.well-known/oauth-protected-resource` before the resource path. */
89
+ function protectedResourceMetadataUrl(baseUrl, eci, surface) {
90
+ const origin = canonicalBaseUrl(baseUrl);
91
+ const id = eciPath(eci);
92
+ return surface === "mesh"
93
+ ? `${origin}/.well-known/oauth-protected-resource/mcp/mesh/${id}`
94
+ : `${origin}/.well-known/oauth-protected-resource/mcp/${id}`;
95
+ }
96
+ function protectedResourceMetadata(baseUrl, eci, surface) {
97
+ return {
98
+ resource: mcpResourceUrl(baseUrl, eci, surface),
99
+ authorization_servers: [canonicalBaseUrl(baseUrl)],
100
+ scopes_supported: [...exports.MCP_SCOPES],
101
+ bearer_methods_supported: ["header"],
102
+ };
103
+ }
104
+ function quoteAuthParam(value) {
105
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
106
+ }
107
+ /**
108
+ * `WWW-Authenticate` for a missing or rejected bearer token.
109
+ * `error` is set only when a token was presented and refused (RFC 6750).
110
+ */
111
+ function bearerChallengeHeader(resourceMetadataUrl, scope, error) {
112
+ const parts = [
113
+ `resource_metadata=${quoteAuthParam(resourceMetadataUrl)}`,
114
+ `scope=${quoteAuthParam(scope)}`,
115
+ ];
116
+ if (error) {
117
+ parts.push(`error=${quoteAuthParam(error)}`);
118
+ }
119
+ return `Bearer ${parts.join(", ")}`;
120
+ }
121
+ /**
122
+ * RFC 8707 resource indicator. The absolute URI must be this engine's Sky
123
+ * audience or one of its MCP URLs, with no query, fragment, or userinfo.
124
+ */
125
+ function classifyResource(baseUrl, resource) {
126
+ const origin = canonicalBaseUrl(baseUrl);
127
+ if (!origin) {
128
+ throw new errors_1.OAuthError("Engine base URL is not configured", "invalid_target", 400);
129
+ }
130
+ let url;
131
+ try {
132
+ url = new URL(resource);
133
+ }
134
+ catch (_a) {
135
+ throw new errors_1.OAuthError("Invalid resource", "invalid_target", 400);
136
+ }
137
+ if (url.origin !== origin ||
138
+ url.search ||
139
+ url.hash ||
140
+ url.username ||
141
+ url.password) {
142
+ throw new errors_1.OAuthError("Invalid resource", "invalid_target", 400);
143
+ }
144
+ if (url.pathname === "/sky") {
145
+ return { kind: "sky" };
146
+ }
147
+ const mesh = /^\/mcp\/mesh\/([^/]+)$/.exec(url.pathname);
148
+ if (mesh) {
149
+ return { kind: "mcp", surface: "mesh", eci: decodeResourceEci(mesh[1]) };
150
+ }
151
+ const channel = /^\/mcp\/([^/]+)$/.exec(url.pathname);
152
+ if (channel) {
153
+ return { kind: "mcp", surface: "channel", eci: decodeResourceEci(channel[1]) };
154
+ }
155
+ throw new errors_1.OAuthError("Invalid resource", "invalid_target", 400);
156
+ }
157
+ function canonicalResourceUrl(baseUrl, target) {
158
+ if (target.kind === "sky") {
159
+ return skyResourceUrl(baseUrl);
160
+ }
161
+ return mcpResourceUrl(baseUrl, target.eci, target.surface);
162
+ }
163
+ function decodeResourceEci(segment) {
164
+ let eci;
165
+ try {
166
+ eci = decodeURIComponent(segment);
167
+ }
168
+ catch (_a) {
169
+ throw new errors_1.OAuthError("Invalid resource", "invalid_target", 400);
170
+ }
171
+ if (!eci) {
172
+ throw new errors_1.OAuthError("Invalid resource", "invalid_target", 400);
173
+ }
174
+ return eci;
175
+ }
package/dist/runMcp.js CHANGED
@@ -18,7 +18,7 @@ async function runMcpCli(argv) {
18
18
  console.error("Usage: pico-engine mcp --stdio");
19
19
  console.error("");
20
20
  console.error("Connects to a running local engine (PICO_ENGINE_BASE_URL).");
21
- console.error("Requires localhost /c access or PICO_ENGINE_UI_ECI.");
21
+ console.error("Reads $PICO_ENGINE_HOME/internal-token (written when the engine starts) or uses PICO_ENGINE_UI_ECI.");
22
22
  process.exit(1);
23
23
  }
24
24
  // JS (not tsc): avoids pulling MCP SDK types into the main compile.