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
package/dist/server.js CHANGED
@@ -11,21 +11,42 @@ const bundledKrl_1 = require("./bundledKrl");
11
11
  const pico_engine_core_1 = require("pico-engine-core");
12
12
  const auth_1 = require("./auth");
13
13
  const oauth_1 = require("./oauth");
14
+ const cimd_1 = require("./oauth/cimd");
15
+ const discovery_1 = require("./oauth/discovery");
14
16
  const provisionRoot_1 = require("./provisionRoot");
15
17
  const pico_engine_core_2 = require("pico-engine-core");
16
18
  const xmluiRuntime_1 = require("./xmluiRuntime");
17
19
  const webvhRoutes_1 = require("./identity/webvhRoutes");
18
20
  const didcommIngressRoutes_1 = require("./identity/didcommIngressRoutes");
19
21
  const engineConfig_1 = require("./engineConfig");
22
+ const internalAccess_1 = require("./internalAccess");
20
23
  const logging_1 = require("./logging");
21
24
  const stageKrl_1 = require("./stageKrl");
22
25
  const engineVersion = require("../package.json").version;
23
- function localhostChannelBypassEnabled() {
24
- return (0, engineConfig_1.getEngineRuntimeSettings)().allowLocalhostChannelBypass;
25
- }
26
26
  function mergeGetPost(req) {
27
- // give preference to post body params
28
- return _.assign({}, req.query, req.body, { _headers: req.headers });
27
+ // give preference to post body params. Credential headers never reach KRL.
28
+ return _.assign({}, req.query, req.body, { _headers: (0, internalAccess_1.headersForKrl)(req.headers) });
29
+ }
30
+ function withRequestCookies(req, target) {
31
+ (0, pico_engine_core_2.attachRequestCookies)(target, req.headers.cookie);
32
+ return target;
33
+ }
34
+ /** Buffer captured while parsing, only for a channel that keeps the raw body. */
35
+ const RAW_BODY_BUF = Symbol("pico.rawBodyBuf");
36
+ function eciFromEventPath(url) {
37
+ if (!url) {
38
+ return null;
39
+ }
40
+ const pathOnly = url.split("?")[0];
41
+ const sky = pathOnly.match(/^\/sky\/event\/([^/]+)\//);
42
+ if (sky) {
43
+ return decodeURIComponent(sky[1]);
44
+ }
45
+ const internal = pathOnly.match(/^\/c\/([^/]+)\/event(?:\/|$)/);
46
+ if (internal) {
47
+ return decodeURIComponent(internal[1]);
48
+ }
49
+ return null;
29
50
  }
30
51
  function parseCookies(req) {
31
52
  const header = req.headers.cookie;
@@ -46,27 +67,19 @@ function parseCookies(req) {
46
67
  }
47
68
  return out;
48
69
  }
49
- function isLocalhostAddress(addr) {
50
- if (!addr) {
51
- return false;
52
- }
53
- const normalized = addr.replace(/^::ffff:/, "");
54
- return normalized === "127.0.0.1" || normalized === "::1";
55
- }
56
- function isLocalhostRequest(req) {
57
- var _a;
58
- if (isLocalhostAddress(req.ip)) {
59
- return true;
60
- }
61
- if (isLocalhostAddress((_a = req.socket) === null || _a === void 0 ? void 0 : _a.remoteAddress)) {
62
- return true;
63
- }
64
- const host = req.headers.host || "";
65
- return host.startsWith("localhost:") || host.startsWith("127.0.0.1:");
66
- }
67
- function server(core, uiECI, auth, oauth, identity) {
70
+ function server(core, uiECI, auth, oauth, identity, internalToken = "") {
68
71
  const pf = core.picoFramework;
69
72
  const app = express();
73
+ // Captured per engine. A later startEngine() in this process must not
74
+ // change an engine that is already listening.
75
+ const localhostBypass = (0, engineConfig_1.getEngineRuntimeSettings)().allowLocalhostChannelBypass;
76
+ function allowInternal(req) {
77
+ const presented = req.headers["x-pico-internal"];
78
+ if ((0, internalAccess_1.internalTokenAccepted)(presented, internalToken)) {
79
+ return true;
80
+ }
81
+ return localhostBypass && (0, internalAccess_1.isDirectLoopbackRequest)(req);
82
+ }
70
83
  function cookies() {
71
84
  return auth
72
85
  ? (0, auth_1.authCookieNames)(auth.rp().origin)
@@ -118,6 +131,34 @@ function server(core, uiECI, auth, oauth, identity) {
118
131
  if (identity) {
119
132
  (0, webvhRoutes_1.registerWebvhRoutes)(app, identity);
120
133
  }
134
+ function channelKeepsRawBody(eci) {
135
+ try {
136
+ return pf.lookupChannel(eci).rawBody === true;
137
+ }
138
+ catch (_a) {
139
+ return false;
140
+ }
141
+ }
142
+ // Hold the raw bytes only when this channel opted in. Other requests drop
143
+ // them with the parser.
144
+ function rememberRawBody(req, _res, buf) {
145
+ const eci = eciFromEventPath(req.url);
146
+ if (!eci || !channelKeepsRawBody(eci)) {
147
+ return;
148
+ }
149
+ Object.defineProperty(req, RAW_BODY_BUF, {
150
+ value: Buffer.from(buf),
151
+ enumerable: false,
152
+ configurable: true,
153
+ });
154
+ }
155
+ function withRawBody(req, eci, target) {
156
+ const buf = req[RAW_BODY_BUF];
157
+ if (Buffer.isBuffer(buf) && channelKeepsRawBody(eci)) {
158
+ (0, pico_engine_core_2.attachRawBody)(target, buf.toString("utf8"));
159
+ }
160
+ return target;
161
+ }
121
162
  app.use(bodyParser.json({
122
163
  type: [
123
164
  "application/json",
@@ -125,11 +166,13 @@ function server(core, uiECI, auth, oauth, identity) {
125
166
  "application/ssi-agent-wire",
126
167
  "application/didcomm-encrypted+json",
127
168
  ],
169
+ verify: rememberRawBody,
128
170
  }));
129
171
  app.use(bodyParser.urlencoded({
130
172
  limit: "512mb",
131
173
  type: "application/x-www-form-urlencoded",
132
174
  extended: false,
175
+ verify: rememberRawBody,
133
176
  }));
134
177
  if (identity) {
135
178
  (0, didcommIngressRoutes_1.registerDidcommIngressRoutes)(app, identity);
@@ -178,13 +221,25 @@ function server(core, uiECI, auth, oauth, identity) {
178
221
  })
179
222
  .catch(next);
180
223
  }
181
- /** `/c/*` is internal: passkey session, or localhost for in-engine HTTP loops. */
224
+ /**
225
+ * `/c/*` is internal. Accept the startup internal token, a passkey session
226
+ * for this mesh, or (only when the operator opted in) a direct loopback
227
+ * connection. The Host header is not a credential.
228
+ */
182
229
  function requireChannelSession(req, res, next) {
183
230
  if (!auth) {
184
231
  next();
185
232
  return;
186
233
  }
187
- if (localhostChannelBypassEnabled() && isLocalhostRequest(req)) {
234
+ if (allowInternal(req)) {
235
+ next();
236
+ return;
237
+ }
238
+ requireAuthSession(req, res, next);
239
+ }
240
+ /** Session, internal token, or an opted-in direct loopback connection. */
241
+ function requireSessionOrInternal(req, res, next) {
242
+ if (allowInternal(req)) {
188
243
  next();
189
244
  return;
190
245
  }
@@ -302,7 +357,7 @@ function server(core, uiECI, auth, oauth, identity) {
302
357
  next(err);
303
358
  }
304
359
  });
305
- app.get("/api/try-it", function (req, res, next) {
360
+ app.get("/api/try-it", requireSessionOrInternal, function (req, res, next) {
306
361
  try {
307
362
  let baseUrl = core.base_url;
308
363
  if (!baseUrl) {
@@ -351,6 +406,9 @@ function server(core, uiECI, auth, oauth, identity) {
351
406
  res.type("text/plain").send(data);
352
407
  });
353
408
  });
409
+ // Pre-login bootstrap. Version, hasRoots, allowSelfSignup, and showTryItMenu
410
+ // are public. The ui ECI is added only when the passkey cookie is valid.
411
+ // This route does not use the localhost bypass (1.10 §1 review).
354
412
  app.get("/api/ui-context", function (req, res, next) {
355
413
  const hasRoots = pf.rootPicos().length > 0;
356
414
  const base = {
@@ -427,11 +485,15 @@ function server(core, uiECI, auth, oauth, identity) {
427
485
  unsubscribe();
428
486
  });
429
487
  });
430
- /** Localhost-only context for dev MCP (stdio) and other local tooling. */
488
+ /**
489
+ * Dev MCP context: root UI ECI and log paths. Internal token, or an opted-in
490
+ * direct loopback connection. A browser session is not enough; this returns
491
+ * the data directory.
492
+ */
431
493
  app.get("/api/dev/local", function (req, res) {
432
494
  var _a;
433
- if (!localhostChannelBypassEnabled() || !isLocalhostRequest(req)) {
434
- res.status(403).json({ error: "localhost only" });
495
+ if (!allowInternal(req)) {
496
+ res.status(403).json({ error: "internal only" });
435
497
  return;
436
498
  }
437
499
  const roots = pf.rootPicos();
@@ -488,13 +550,13 @@ function server(core, uiECI, auth, oauth, identity) {
488
550
  });
489
551
  app.all("/c/:eci/event/:domain/:name", requireChannelSession, function (req, res, next) {
490
552
  core
491
- .event({
553
+ .event(withRawBody(req, req.params.eci, withRequestCookies(req, {
492
554
  eci: req.params.eci,
493
555
  domain: req.params.domain,
494
556
  name: req.params.name,
495
557
  data: { attrs: mergeGetPost(req) },
496
558
  time: 0, // TODO remove this typescript requirement
497
- })
559
+ })))
498
560
  .then((eid) => {
499
561
  res.json(eid);
500
562
  })
@@ -502,13 +564,13 @@ function server(core, uiECI, auth, oauth, identity) {
502
564
  });
503
565
  app.all("/c/:eci/event-wait/:domain/:name", requireChannelSession, function (req, res, next) {
504
566
  core
505
- .eventWait({
567
+ .eventWait(withRawBody(req, req.params.eci, withRequestCookies(req, {
506
568
  eci: req.params.eci,
507
569
  domain: req.params.domain,
508
570
  name: req.params.name,
509
571
  data: { attrs: mergeGetPost(req) },
510
572
  time: 0, // TODO remove this typescript requirement
511
- })
573
+ })))
512
574
  .then((data) => {
513
575
  res.json(data);
514
576
  })
@@ -520,13 +582,13 @@ function server(core, uiECI, auth, oauth, identity) {
520
582
  attrs.__eid = req.params.eid;
521
583
  }
522
584
  core
523
- .eventWait({
585
+ .eventWait(withRawBody(req, req.params.eci, withRequestCookies(req, {
524
586
  eci: req.params.eci,
525
587
  domain: req.params.domain,
526
588
  name: req.params["type"],
527
589
  data: { attrs },
528
590
  time: 0, // TODO remove this typescript requirement
529
- })
591
+ })))
530
592
  .then((data) => {
531
593
  if (data.directives) {
532
594
  var _res = _.filter(data.directives, { name: "_cookie" });
@@ -553,18 +615,18 @@ function server(core, uiECI, auth, oauth, identity) {
553
615
  app.all("/c/:eci/event/:domain/:name/query/:rid/:qname", requireChannelSession, function (req, res, next) {
554
616
  const attrs = mergeGetPost(req);
555
617
  core
556
- .eventQuery({
618
+ .eventQuery(withRawBody(req, req.params.eci, withRequestCookies(req, {
557
619
  eci: req.params.eci,
558
620
  domain: req.params.domain,
559
621
  name: req.params.name,
560
622
  data: { attrs },
561
623
  time: 0, // TODO remove this typescript requirement
562
- }, {
624
+ })), withRequestCookies(req, {
563
625
  eci: req.params.eci,
564
626
  rid: req.params.rid,
565
627
  name: req.params.qname,
566
628
  args: attrs,
567
- })
629
+ }))
568
630
  .then((data) => {
569
631
  res.json(data);
570
632
  })
@@ -573,12 +635,12 @@ function server(core, uiECI, auth, oauth, identity) {
573
635
  function handleSkyQuery(req, res, next) {
574
636
  const funcPart = req.params["function"].split(".");
575
637
  core
576
- .query({
638
+ .query(withRequestCookies(req, {
577
639
  eci: req.params.eci,
578
640
  rid: req.params.rid,
579
641
  name: funcPart[0],
580
642
  args: mergeGetPost(req),
581
- })
643
+ }))
582
644
  .then((data) => {
583
645
  if (funcPart[1] === "html") {
584
646
  res.header("Content-Type", "text/html");
@@ -597,12 +659,12 @@ function server(core, uiECI, auth, oauth, identity) {
597
659
  app.all("/c/:eci/query/:rid/:name", requireChannelSession, function (req, res, next) {
598
660
  const funcPart = req.params.name.split(".");
599
661
  core
600
- .query({
662
+ .query(withRequestCookies(req, {
601
663
  eci: req.params.eci,
602
664
  rid: req.params.rid,
603
665
  name: funcPart[0],
604
666
  args: mergeGetPost(req),
605
- })
667
+ }))
606
668
  .then((data) => {
607
669
  if (funcPart[1] === "html") {
608
670
  res.header("Content-Type", "text/html");
@@ -717,10 +779,64 @@ function server(core, uiECI, auth, oauth, identity) {
717
779
  app.all("/sky/query/:eci/:rid/:function", requireSkyBearerIfOAuth, handleSkyQuery);
718
780
  // Legacy alias; prefer /sky/query/ per Sky Query API docs.
719
781
  app.all("/sky/cloud/:eci/:rid/:function", requireSkyBearerIfOAuth, handleSkyQuery);
782
+ // MCP authorization discovery (RFC 8414, RFC 9728). Unauthenticated.
783
+ function discoveryOrigin(req) {
784
+ return (0, discovery_1.canonicalBaseUrl)(core.base_url, req);
785
+ }
786
+ function knownChannel(eci) {
787
+ try {
788
+ pf.lookupChannel(eci);
789
+ return true;
790
+ }
791
+ catch (_e) {
792
+ return false;
793
+ }
794
+ }
795
+ app.get("/.well-known/oauth-authorization-server", function (req, res) {
796
+ res.json((0, discovery_1.authorizationServerMetadata)(discoveryOrigin(req)));
797
+ });
798
+ // Claude inserts the MCP path into this well-known URL. A 404 there makes
799
+ // it skip the root document and report that client registration is missing.
800
+ function pathAuthorizationServer(req, res) {
801
+ if (!knownChannel(req.params.eci)) {
802
+ res.status(404).json({ error: "Unknown channel ECI" });
803
+ return;
804
+ }
805
+ res.json((0, discovery_1.authorizationServerMetadata)(discoveryOrigin(req)));
806
+ }
807
+ app.get("/.well-known/oauth-authorization-server/mcp/mesh/:eci", function (req, res) {
808
+ pathAuthorizationServer(req, res);
809
+ });
810
+ app.get("/.well-known/oauth-authorization-server/mcp/:eci", function (req, res) {
811
+ pathAuthorizationServer(req, res);
812
+ });
813
+ app.get("/.well-known/openid-configuration", function (req, res) {
814
+ res.json((0, discovery_1.authorizationServerMetadata)(discoveryOrigin(req)));
815
+ });
816
+ app.get("/.well-known/openid-configuration/mcp/mesh/:eci", function (req, res) {
817
+ pathAuthorizationServer(req, res);
818
+ });
819
+ app.get("/.well-known/openid-configuration/mcp/:eci", function (req, res) {
820
+ pathAuthorizationServer(req, res);
821
+ });
822
+ app.get("/.well-known/oauth-protected-resource/mcp/mesh/:eci", function (req, res) {
823
+ if (!knownChannel(req.params.eci)) {
824
+ res.status(404).json({ error: "Unknown channel ECI" });
825
+ return;
826
+ }
827
+ res.json((0, discovery_1.protectedResourceMetadata)(discoveryOrigin(req), req.params.eci, "mesh"));
828
+ });
829
+ app.get("/.well-known/oauth-protected-resource/mcp/:eci", function (req, res) {
830
+ if (!knownChannel(req.params.eci)) {
831
+ res.status(404).json({ error: "Unknown channel ECI" });
832
+ return;
833
+ }
834
+ res.json((0, discovery_1.protectedResourceMetadata)(discoveryOrigin(req), req.params.eci, "channel"));
835
+ });
720
836
  // Mesh MCP (Streamable HTTP, OAuth bearer scoped to :eci)
721
837
  // eslint-disable-next-line @typescript-eslint/no-require-imports
722
838
  const { registerMeshMcpRoutes } = require("../mcp/meshHttp.js");
723
- registerMeshMcpRoutes(app, core, oauth);
839
+ registerMeshMcpRoutes(app, core, oauth, (eci, error, req, surface, scope) => (0, discovery_1.bearerChallengeHeader)((0, discovery_1.protectedResourceMetadataUrl)(discoveryOrigin(req), eci, surface), scope || discovery_1.MCP_CHANNEL_SCOPE, error));
724
840
  app.use(function (err, req, res, next) {
725
841
  var _a, _b, _c;
726
842
  if (err instanceof auth_1.AuthError) {
@@ -998,9 +1114,9 @@ function registerOAuthRoutes(app, oauth, auth, requireAuthSession, parseCookiesF
998
1114
  next(err);
999
1115
  return;
1000
1116
  }
1001
- oauth
1117
+ const showConsent = () => oauth
1002
1118
  .getAppForAuthorize(params)
1003
- .then(async (appRecord) => {
1119
+ .then(async (resolved) => {
1004
1120
  if (!auth) {
1005
1121
  res.status(503).send("Authentication is not configured");
1006
1122
  return;
@@ -1012,13 +1128,46 @@ function registerOAuthRoutes(app, oauth, auth, requireAuthSession, parseCookiesF
1012
1128
  res.redirect("/?oauth_return=" + encodeURIComponent(returnPath));
1013
1129
  return;
1014
1130
  }
1015
- if (session.rootPicoId !== appRecord.rootPicoId) {
1131
+ if (resolved.cimd) {
1132
+ if (!oauth.meshOAuthEnabled(session.rootPicoId)) {
1133
+ res.status(400).send("Install io.picolabs.oauth on the root pico first");
1134
+ return;
1135
+ }
1136
+ if (params.resource !== undefined) {
1137
+ params.resource = oauth.bindAuthorizeResource(params.resource, session.rootPicoId);
1138
+ }
1139
+ }
1140
+ else if (session.rootPicoId !== resolved.app.rootPicoId) {
1016
1141
  res.status(403).send("Signed in to a different mesh");
1017
1142
  return;
1018
1143
  }
1019
- res.type("html").send((0, oauth_1.renderConsentHtml)(appRecord, params));
1144
+ const account = await auth.getAccount(session.accountId);
1145
+ const meshName = ((account === null || account === void 0 ? void 0 : account.displayName) || "").trim() || "this mesh";
1146
+ res.type("html").send((0, oauth_1.renderConsentHtml)(resolved.app, params, Object.assign(Object.assign({}, resolved.consent), { meshName })));
1020
1147
  })
1021
1148
  .catch(next);
1149
+ // A metadata URL is fetched from here. Require a session first so an
1150
+ // anonymous request cannot make the engine request an arbitrary URL.
1151
+ if ((0, cimd_1.isClientMetadataUrl)(params.client_id)) {
1152
+ if (!auth) {
1153
+ res.status(503).send("Authentication is not configured");
1154
+ return;
1155
+ }
1156
+ const token = parseCookiesFn(req)[cookies().session] || "";
1157
+ auth
1158
+ .getSession(token)
1159
+ .then((session) => {
1160
+ if (!session) {
1161
+ const returnPath = req.originalUrl || "/oauth/authorize";
1162
+ res.redirect("/?oauth_return=" + encodeURIComponent(returnPath));
1163
+ return;
1164
+ }
1165
+ showConsent();
1166
+ })
1167
+ .catch(next);
1168
+ return;
1169
+ }
1170
+ showConsent();
1022
1171
  });
1023
1172
  app.post("/oauth/approve", function (req, res, next) {
1024
1173
  if (!auth) {
@@ -55,7 +55,7 @@ async function rulesetFromParent(parent, rid, rsRegistry) {
55
55
  return { rs: loaded.ruleset, config };
56
56
  }
57
57
  /** Same bootstrap as wrangler bootstrapNewChild, without blocking the parent's event queue. */
58
- async function bootstrapImportChildSync(pf, parent, name, rsRegistry, options) {
58
+ async function bootstrapImportChildSync(pf, parent, name, rsRegistry, options, onPicoCreated) {
59
59
  const ui = await rulesetFromParent(parent, ENGINE_UI_RID, rsRegistry);
60
60
  const wrangler = await rulesetFromParent(parent, WRANGLER_RID, rsRegistry);
61
61
  const familyEci = await parent.newPico({
@@ -65,6 +65,9 @@ async function bootstrapImportChildSync(pf, parent, name, rsRegistry, options) {
65
65
  if (!child) {
66
66
  throw new Error(`Failed to resolve child for family ECI ${familyEci}`);
67
67
  }
68
+ if (onPicoCreated) {
69
+ await onPicoCreated(child.id, { isRoot: false, parentPicoId: parent.id });
70
+ }
68
71
  const parentUi = parent.toReadOnly().channels.find((c) => [...c.tags].sort().join(",") === "engine,ui");
69
72
  await pf.eventWait({
70
73
  eci: familyEci,
@@ -144,9 +147,9 @@ async function waitForWranglerBootstrapRulesets(pf, parentPicoId, familyEci, chi
144
147
  throw new Error(`Import child wrangler bootstrap missing rulesets: ${missing.join(", ")}`);
145
148
  }
146
149
  /** Create an import child through wrangler (sync bootstrap when parent queue is busy). */
147
- async function createImportChildViaWrangler(pf, parent, name, rsRegistry, options) {
150
+ async function createImportChildViaWrangler(pf, parent, name, rsRegistry, options, onPicoCreated) {
148
151
  if (parentIsHandlingEvent(parent)) {
149
- return bootstrapImportChildSync(pf, parent, name, rsRegistry, options);
152
+ return bootstrapImportChildSync(pf, parent, name, rsRegistry, options, onPicoCreated);
150
153
  }
151
154
  const newChildRequest = {
152
155
  domain: "wrangler",
@@ -173,8 +176,8 @@ async function createImportChildViaWrangler(pf, parent, name, rsRegistry, option
173
176
  return { familyEci, child };
174
177
  }
175
178
  /** Wrangler-backed child creation wired into ctx subtree import. */
176
- function wranglerSubtreeImportServices(rsRegistry) {
179
+ function wranglerSubtreeImportServices(rsRegistry, onPicoCreated) {
177
180
  return {
178
- createImportChild: (pf, parent, name, opts) => createImportChildViaWrangler(pf, parent, name, rsRegistry, opts),
181
+ createImportChild: (pf, parent, name, opts) => createImportChildViaWrangler(pf, parent, name, rsRegistry, opts, onPicoCreated),
179
182
  };
180
183
  }
@@ -39,6 +39,7 @@ exports.UI_CHANNEL_EVENT_POLICY = {
39
39
  { domain: "wrangler", name: "new_child_created" },
40
40
  { domain: "wrangler", name: "install_ruleset_request" },
41
41
  { domain: "wrangler", name: "new_channel_request" },
42
+ { domain: "pds", name: "add_settings" },
42
43
  ],
43
44
  deny: [],
44
45
  };
@@ -63,6 +64,7 @@ exports.UI_CHANNEL_QUERY_POLICY = {
63
64
  { rid: "io.picolabs.subscription", name: "wellKnown_Rx" },
64
65
  { rid: "io.picolabs.wrangler", name: "myDid" },
65
66
  { rid: "io.picolabs.wrangler", name: "publicIntro" },
67
+ { rid: "io.picolabs.pds", name: "settings" },
66
68
  ],
67
69
  deny: [],
68
70
  };