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/src/server.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import * as bodyParser from "body-parser";
2
2
  import * as express from "express";
3
3
  import { Express, Request, Response } from "express";
4
+ import { IncomingMessage, ServerResponse } from "http";
4
5
  import * as fs from "fs";
5
6
  import helmet from "helmet";
6
7
  import * as _ from "lodash";
@@ -27,8 +28,17 @@ import {
27
28
  renderConsentHtml,
28
29
  rootHasOAuthMeshRuleset,
29
30
  } from "./oauth";
31
+ import { isClientMetadataUrl } from "./oauth/cimd";
32
+ import {
33
+ MCP_CHANNEL_SCOPE,
34
+ authorizationServerMetadata,
35
+ bearerChallengeHeader,
36
+ canonicalBaseUrl,
37
+ protectedResourceMetadata,
38
+ protectedResourceMetadataUrl,
39
+ } from "./oauth/discovery";
30
40
  import { uiECIForRoot } from "./provisionRoot";
31
- import { channelSchemaForEci } from "pico-engine-core";
41
+ import { attachRawBody, attachRequestCookies, channelSchemaForEci } from "pico-engine-core";
32
42
  import {
33
43
  contentTypeForUiPath,
34
44
  isXmluiCodeBehindPath,
@@ -42,6 +52,11 @@ import { registerWebvhRoutes } from "./identity/webvhRoutes";
42
52
  import { registerDidcommIngressRoutes } from "./identity/didcommIngressRoutes";
43
53
 
44
54
  import { getEngineRuntimeSettings } from "./engineConfig";
55
+ import {
56
+ headersForKrl,
57
+ internalTokenAccepted,
58
+ isDirectLoopbackRequest,
59
+ } from "./internalAccess";
45
60
  import {
46
61
  picoLogEntries,
47
62
  resolveEngineLogFilePath,
@@ -52,13 +67,33 @@ import { stageKrlContent } from "./stageKrl";
52
67
 
53
68
  const engineVersion = require("../package.json").version;
54
69
 
55
- function localhostChannelBypassEnabled(): boolean {
56
- return getEngineRuntimeSettings().allowLocalhostChannelBypass;
70
+ function mergeGetPost(req: Request) {
71
+ // give preference to post body params. Credential headers never reach KRL.
72
+ return _.assign({}, req.query, req.body, { _headers: headersForKrl(req.headers) });
73
+ }
74
+
75
+ function withRequestCookies<T extends object>(req: Request, target: T): T {
76
+ attachRequestCookies(target, req.headers.cookie);
77
+ return target;
57
78
  }
58
79
 
59
- function mergeGetPost(req: Request) {
60
- // give preference to post body params
61
- return _.assign({}, req.query, req.body, { _headers: req.headers });
80
+ /** Buffer captured while parsing, only for a channel that keeps the raw body. */
81
+ const RAW_BODY_BUF = Symbol("pico.rawBodyBuf");
82
+
83
+ function eciFromEventPath(url: string | undefined): string | null {
84
+ if (!url) {
85
+ return null;
86
+ }
87
+ const pathOnly = url.split("?")[0];
88
+ const sky = pathOnly.match(/^\/sky\/event\/([^/]+)\//);
89
+ if (sky) {
90
+ return decodeURIComponent(sky[1]);
91
+ }
92
+ const internal = pathOnly.match(/^\/c\/([^/]+)\/event(?:\/|$)/);
93
+ if (internal) {
94
+ return decodeURIComponent(internal[1]);
95
+ }
96
+ return null;
62
97
  }
63
98
 
64
99
  function parseCookies(req: Request): { [name: string]: string } {
@@ -81,34 +116,27 @@ function parseCookies(req: Request): { [name: string]: string } {
81
116
  return out;
82
117
  }
83
118
 
84
- function isLocalhostAddress(addr: string | undefined): boolean {
85
- if (!addr) {
86
- return false;
87
- }
88
- const normalized = addr.replace(/^::ffff:/, "");
89
- return normalized === "127.0.0.1" || normalized === "::1";
90
- }
91
-
92
- function isLocalhostRequest(req: Request): boolean {
93
- if (isLocalhostAddress(req.ip)) {
94
- return true;
95
- }
96
- if (isLocalhostAddress(req.socket?.remoteAddress)) {
97
- return true;
98
- }
99
- const host = req.headers.host || "";
100
- return host.startsWith("localhost:") || host.startsWith("127.0.0.1:");
101
- }
102
-
103
119
  export function server(
104
120
  core: PicoEngineCore,
105
121
  uiECI: string | null,
106
122
  auth?: AuthService,
107
123
  oauth?: OAuthService,
108
- identity?: IdentityService
124
+ identity?: IdentityService,
125
+ internalToken = ""
109
126
  ): Express {
110
127
  const pf = core.picoFramework;
111
128
  const app = express();
129
+ // Captured per engine. A later startEngine() in this process must not
130
+ // change an engine that is already listening.
131
+ const localhostBypass = getEngineRuntimeSettings().allowLocalhostChannelBypass;
132
+
133
+ function allowInternal(req: Request): boolean {
134
+ const presented = req.headers["x-pico-internal"];
135
+ if (internalTokenAccepted(presented, internalToken)) {
136
+ return true;
137
+ }
138
+ return localhostBypass && isDirectLoopbackRequest(req);
139
+ }
112
140
  function cookies(): AuthCookieNames {
113
141
  return auth
114
142
  ? authCookieNames(auth.rp().origin)
@@ -165,6 +193,40 @@ export function server(
165
193
  registerWebvhRoutes(app, identity);
166
194
  }
167
195
 
196
+ function channelKeepsRawBody(eci: string): boolean {
197
+ try {
198
+ return pf.lookupChannel(eci).rawBody === true;
199
+ } catch {
200
+ return false;
201
+ }
202
+ }
203
+
204
+ // Hold the raw bytes only when this channel opted in. Other requests drop
205
+ // them with the parser.
206
+ function rememberRawBody(
207
+ req: IncomingMessage,
208
+ _res: ServerResponse,
209
+ buf: Buffer
210
+ ): void {
211
+ const eci = eciFromEventPath(req.url);
212
+ if (!eci || !channelKeepsRawBody(eci)) {
213
+ return;
214
+ }
215
+ Object.defineProperty(req, RAW_BODY_BUF, {
216
+ value: Buffer.from(buf),
217
+ enumerable: false,
218
+ configurable: true,
219
+ });
220
+ }
221
+
222
+ function withRawBody<T extends object>(req: Request, eci: string, target: T): T {
223
+ const buf = (req as Request & { [RAW_BODY_BUF]?: Buffer })[RAW_BODY_BUF];
224
+ if (Buffer.isBuffer(buf) && channelKeepsRawBody(eci)) {
225
+ attachRawBody(target, buf.toString("utf8"));
226
+ }
227
+ return target;
228
+ }
229
+
168
230
  app.use(
169
231
  bodyParser.json({
170
232
  type: [
@@ -173,6 +235,7 @@ export function server(
173
235
  "application/ssi-agent-wire",
174
236
  "application/didcomm-encrypted+json",
175
237
  ],
238
+ verify: rememberRawBody,
176
239
  })
177
240
  );
178
241
  app.use(
@@ -180,6 +243,7 @@ export function server(
180
243
  limit: "512mb",
181
244
  type: "application/x-www-form-urlencoded",
182
245
  extended: false,
246
+ verify: rememberRawBody,
183
247
  })
184
248
  );
185
249
 
@@ -237,7 +301,11 @@ export function server(
237
301
  .catch(next);
238
302
  }
239
303
 
240
- /** `/c/*` is internal: passkey session, or localhost for in-engine HTTP loops. */
304
+ /**
305
+ * `/c/*` is internal. Accept the startup internal token, a passkey session
306
+ * for this mesh, or (only when the operator opted in) a direct loopback
307
+ * connection. The Host header is not a credential.
308
+ */
241
309
  function requireChannelSession(
242
310
  req: Request,
243
311
  res: Response,
@@ -247,7 +315,20 @@ export function server(
247
315
  next();
248
316
  return;
249
317
  }
250
- if (localhostChannelBypassEnabled() && isLocalhostRequest(req)) {
318
+ if (allowInternal(req)) {
319
+ next();
320
+ return;
321
+ }
322
+ requireAuthSession(req, res, next);
323
+ }
324
+
325
+ /** Session, internal token, or an opted-in direct loopback connection. */
326
+ function requireSessionOrInternal(
327
+ req: Request,
328
+ res: Response,
329
+ next: express.NextFunction
330
+ ) {
331
+ if (allowInternal(req)) {
251
332
  next();
252
333
  return;
253
334
  }
@@ -384,7 +465,7 @@ export function server(
384
465
  }
385
466
  });
386
467
 
387
- app.get("/api/try-it", function (req, res, next) {
468
+ app.get("/api/try-it", requireSessionOrInternal, function (req, res, next) {
388
469
  try {
389
470
  let baseUrl = core.base_url;
390
471
  if (!baseUrl) {
@@ -434,6 +515,9 @@ export function server(
434
515
  });
435
516
  });
436
517
 
518
+ // Pre-login bootstrap. Version, hasRoots, allowSelfSignup, and showTryItMenu
519
+ // are public. The ui ECI is added only when the passkey cookie is valid.
520
+ // This route does not use the localhost bypass (1.10 §1 review).
437
521
  app.get("/api/ui-context", function (req, res, next) {
438
522
  const hasRoots = pf.rootPicos().length > 0;
439
523
  const base: any = {
@@ -509,10 +593,14 @@ export function server(
509
593
  });
510
594
  });
511
595
 
512
- /** Localhost-only context for dev MCP (stdio) and other local tooling. */
596
+ /**
597
+ * Dev MCP context: root UI ECI and log paths. Internal token, or an opted-in
598
+ * direct loopback connection. A browser session is not enough; this returns
599
+ * the data directory.
600
+ */
513
601
  app.get("/api/dev/local", function (req, res) {
514
- if (!localhostChannelBypassEnabled() || !isLocalhostRequest(req)) {
515
- res.status(403).json({ error: "localhost only" });
602
+ if (!allowInternal(req)) {
603
+ res.status(403).json({ error: "internal only" });
516
604
  return;
517
605
  }
518
606
  const roots = pf.rootPicos();
@@ -571,13 +659,13 @@ export function server(
571
659
 
572
660
  app.all("/c/:eci/event/:domain/:name", requireChannelSession, function (req, res, next) {
573
661
  core
574
- .event({
662
+ .event(withRawBody(req, req.params.eci, withRequestCookies(req, {
575
663
  eci: req.params.eci,
576
664
  domain: req.params.domain,
577
665
  name: req.params.name,
578
666
  data: { attrs: mergeGetPost(req) },
579
667
  time: 0, // TODO remove this typescript requirement
580
- })
668
+ })))
581
669
  .then((eid) => {
582
670
  res.json(eid);
583
671
  })
@@ -586,13 +674,13 @@ export function server(
586
674
 
587
675
  app.all("/c/:eci/event-wait/:domain/:name", requireChannelSession, function (req, res, next) {
588
676
  core
589
- .eventWait({
677
+ .eventWait(withRawBody(req, req.params.eci, withRequestCookies(req, {
590
678
  eci: req.params.eci,
591
679
  domain: req.params.domain,
592
680
  name: req.params.name,
593
681
  data: { attrs: mergeGetPost(req) },
594
682
  time: 0, // TODO remove this typescript requirement
595
- })
683
+ })))
596
684
  .then((data) => {
597
685
  res.json(data);
598
686
  })
@@ -605,13 +693,13 @@ export function server(
605
693
  attrs.__eid = req.params.eid;
606
694
  }
607
695
  core
608
- .eventWait({
696
+ .eventWait(withRawBody(req, req.params.eci, withRequestCookies(req, {
609
697
  eci: req.params.eci,
610
698
  domain: req.params.domain,
611
699
  name: req.params["type"],
612
700
  data: { attrs },
613
701
  time: 0, // TODO remove this typescript requirement
614
- })
702
+ })))
615
703
  .then((data) => {
616
704
  if (data.directives) {
617
705
  var _res = _.filter(data.directives, { name: "_cookie" });
@@ -643,19 +731,19 @@ export function server(
643
731
  const attrs = mergeGetPost(req);
644
732
  core
645
733
  .eventQuery(
646
- {
734
+ withRawBody(req, req.params.eci, withRequestCookies(req, {
647
735
  eci: req.params.eci,
648
736
  domain: req.params.domain,
649
737
  name: req.params.name,
650
738
  data: { attrs },
651
739
  time: 0, // TODO remove this typescript requirement
652
- },
653
- {
740
+ })),
741
+ withRequestCookies(req, {
654
742
  eci: req.params.eci,
655
743
  rid: req.params.rid,
656
744
  name: req.params.qname,
657
745
  args: attrs,
658
- }
746
+ })
659
747
  )
660
748
  .then((data) => {
661
749
  res.json(data);
@@ -667,12 +755,12 @@ export function server(
667
755
  function handleSkyQuery(req: Request, res: Response, next: express.NextFunction) {
668
756
  const funcPart = req.params["function"].split(".");
669
757
  core
670
- .query({
758
+ .query(withRequestCookies(req, {
671
759
  eci: req.params.eci,
672
760
  rid: req.params.rid,
673
761
  name: funcPart[0],
674
762
  args: mergeGetPost(req),
675
- })
763
+ }))
676
764
  .then((data: any) => {
677
765
  if (funcPart[1] === "html") {
678
766
  res.header("Content-Type", "text/html");
@@ -690,12 +778,12 @@ export function server(
690
778
  app.all("/c/:eci/query/:rid/:name", requireChannelSession, function (req, res, next) {
691
779
  const funcPart = req.params.name.split(".");
692
780
  core
693
- .query({
781
+ .query(withRequestCookies(req, {
694
782
  eci: req.params.eci,
695
783
  rid: req.params.rid,
696
784
  name: funcPart[0],
697
785
  args: mergeGetPost(req),
698
- })
786
+ }))
699
787
  .then((data: any) => {
700
788
  if (funcPart[1] === "html") {
701
789
  res.header("Content-Type", "text/html");
@@ -837,16 +925,86 @@ export function server(
837
925
  // Legacy alias; prefer /sky/query/ per Sky Query API docs.
838
926
  app.all("/sky/cloud/:eci/:rid/:function", requireSkyBearerIfOAuth, handleSkyQuery);
839
927
 
928
+ // MCP authorization discovery (RFC 8414, RFC 9728). Unauthenticated.
929
+ function discoveryOrigin(req: Request): string {
930
+ return canonicalBaseUrl(core.base_url, req);
931
+ }
932
+ function knownChannel(eci: string): boolean {
933
+ try {
934
+ pf.lookupChannel(eci);
935
+ return true;
936
+ } catch (_e) {
937
+ return false;
938
+ }
939
+ }
940
+ app.get("/.well-known/oauth-authorization-server", function (req, res) {
941
+ res.json(authorizationServerMetadata(discoveryOrigin(req)));
942
+ });
943
+ // Claude inserts the MCP path into this well-known URL. A 404 there makes
944
+ // it skip the root document and report that client registration is missing.
945
+ function pathAuthorizationServer(req: Request, res: Response) {
946
+ if (!knownChannel(req.params.eci)) {
947
+ res.status(404).json({ error: "Unknown channel ECI" });
948
+ return;
949
+ }
950
+ res.json(authorizationServerMetadata(discoveryOrigin(req)));
951
+ }
952
+ app.get("/.well-known/oauth-authorization-server/mcp/mesh/:eci", function (req, res) {
953
+ pathAuthorizationServer(req, res);
954
+ });
955
+ app.get("/.well-known/oauth-authorization-server/mcp/:eci", function (req, res) {
956
+ pathAuthorizationServer(req, res);
957
+ });
958
+ app.get("/.well-known/openid-configuration", function (req, res) {
959
+ res.json(authorizationServerMetadata(discoveryOrigin(req)));
960
+ });
961
+ app.get("/.well-known/openid-configuration/mcp/mesh/:eci", function (req, res) {
962
+ pathAuthorizationServer(req, res);
963
+ });
964
+ app.get("/.well-known/openid-configuration/mcp/:eci", function (req, res) {
965
+ pathAuthorizationServer(req, res);
966
+ });
967
+ app.get(
968
+ "/.well-known/oauth-protected-resource/mcp/mesh/:eci",
969
+ function (req, res) {
970
+ if (!knownChannel(req.params.eci)) {
971
+ res.status(404).json({ error: "Unknown channel ECI" });
972
+ return;
973
+ }
974
+ res.json(protectedResourceMetadata(discoveryOrigin(req), req.params.eci, "mesh"));
975
+ }
976
+ );
977
+ app.get("/.well-known/oauth-protected-resource/mcp/:eci", function (req, res) {
978
+ if (!knownChannel(req.params.eci)) {
979
+ res.status(404).json({ error: "Unknown channel ECI" });
980
+ return;
981
+ }
982
+ res.json(protectedResourceMetadata(discoveryOrigin(req), req.params.eci, "channel"));
983
+ });
984
+
840
985
  // Mesh MCP (Streamable HTTP, OAuth bearer scoped to :eci)
841
986
  // eslint-disable-next-line @typescript-eslint/no-require-imports
842
987
  const { registerMeshMcpRoutes } = require("../mcp/meshHttp.js") as {
843
988
  registerMeshMcpRoutes: (
844
989
  app: Express,
845
990
  core: PicoEngineCore,
846
- oauth?: OAuthService
991
+ oauth: OAuthService | undefined,
992
+ wwwAuthenticate: (
993
+ eci: string,
994
+ error: "invalid_token" | "insufficient_scope" | undefined,
995
+ req: Request,
996
+ surface: "channel" | "mesh",
997
+ scope?: string
998
+ ) => string
847
999
  ) => void;
848
1000
  };
849
- registerMeshMcpRoutes(app, core, oauth);
1001
+ registerMeshMcpRoutes(app, core, oauth, (eci, error, req, surface, scope) =>
1002
+ bearerChallengeHeader(
1003
+ protectedResourceMetadataUrl(discoveryOrigin(req), eci, surface),
1004
+ scope || MCP_CHANNEL_SCOPE,
1005
+ error
1006
+ )
1007
+ );
850
1008
 
851
1009
  app.use(function (
852
1010
  err: any,
@@ -1178,9 +1336,10 @@ function registerOAuthRoutes(
1178
1336
  next(err);
1179
1337
  return;
1180
1338
  }
1181
- oauth
1339
+ const showConsent = () =>
1340
+ oauth
1182
1341
  .getAppForAuthorize(params)
1183
- .then(async (appRecord) => {
1342
+ .then(async (resolved) => {
1184
1343
  if (!auth) {
1185
1344
  res.status(503).send("Authentication is not configured");
1186
1345
  return;
@@ -1194,13 +1353,54 @@ function registerOAuthRoutes(
1194
1353
  );
1195
1354
  return;
1196
1355
  }
1197
- if (session.rootPicoId !== appRecord.rootPicoId) {
1356
+ if (resolved.cimd) {
1357
+ if (!oauth.meshOAuthEnabled(session.rootPicoId)) {
1358
+ res.status(400).send("Install io.picolabs.oauth on the root pico first");
1359
+ return;
1360
+ }
1361
+ if (params.resource !== undefined) {
1362
+ params.resource = oauth.bindAuthorizeResource(
1363
+ params.resource,
1364
+ session.rootPicoId
1365
+ );
1366
+ }
1367
+ } else if (session.rootPicoId !== resolved.app.rootPicoId) {
1198
1368
  res.status(403).send("Signed in to a different mesh");
1199
1369
  return;
1200
1370
  }
1201
- res.type("html").send(renderConsentHtml(appRecord, params));
1371
+ const account = await auth.getAccount(session.accountId);
1372
+ const meshName = (account?.displayName || "").trim() || "this mesh";
1373
+ res.type("html").send(
1374
+ renderConsentHtml(resolved.app, params, {
1375
+ ...resolved.consent,
1376
+ meshName,
1377
+ })
1378
+ );
1202
1379
  })
1203
1380
  .catch(next);
1381
+
1382
+ // A metadata URL is fetched from here. Require a session first so an
1383
+ // anonymous request cannot make the engine request an arbitrary URL.
1384
+ if (isClientMetadataUrl(params.client_id)) {
1385
+ if (!auth) {
1386
+ res.status(503).send("Authentication is not configured");
1387
+ return;
1388
+ }
1389
+ const token = parseCookiesFn(req)[cookies().session] || "";
1390
+ auth
1391
+ .getSession(token)
1392
+ .then((session) => {
1393
+ if (!session) {
1394
+ const returnPath = req.originalUrl || "/oauth/authorize";
1395
+ res.redirect("/?oauth_return=" + encodeURIComponent(returnPath));
1396
+ return;
1397
+ }
1398
+ showConsent();
1399
+ })
1400
+ .catch(next);
1401
+ return;
1402
+ }
1403
+ showConsent();
1204
1404
  });
1205
1405
 
1206
1406
  app.post("/oauth/approve", function (req, res, next) {
@@ -89,13 +89,20 @@ async function rulesetFromParent(
89
89
  return { rs: loaded.ruleset, config };
90
90
  }
91
91
 
92
+ /** What ctx:newPico runs for a new pico (identity); parent.newPico doesn't. */
93
+ export type PicoCreatedHook = (
94
+ picoId: string,
95
+ ctx: { isRoot: boolean; parentPicoId: string }
96
+ ) => Promise<void>;
97
+
92
98
  /** Same bootstrap as wrangler bootstrapNewChild, without blocking the parent's event queue. */
93
99
  async function bootstrapImportChildSync(
94
100
  pf: PicoFramework,
95
101
  parent: Pico,
96
102
  name: string,
97
103
  rsRegistry: RulesetRegistry,
98
- options?: CreateImportChildOptions
104
+ options?: CreateImportChildOptions,
105
+ onPicoCreated?: PicoCreatedHook
99
106
  ): Promise<{ familyEci: string; child: Pico }> {
100
107
  const ui = await rulesetFromParent(parent, ENGINE_UI_RID, rsRegistry);
101
108
  const wrangler = await rulesetFromParent(parent, WRANGLER_RID, rsRegistry);
@@ -106,6 +113,9 @@ async function bootstrapImportChildSync(
106
113
  if (!child) {
107
114
  throw new Error(`Failed to resolve child for family ECI ${familyEci}`);
108
115
  }
116
+ if (onPicoCreated) {
117
+ await onPicoCreated(child.id, { isRoot: false, parentPicoId: parent.id });
118
+ }
109
119
 
110
120
  const parentUi = parent.toReadOnly().channels.find(
111
121
  (c) => [...c.tags].sort().join(",") === "engine,ui"
@@ -228,10 +238,11 @@ export async function createImportChildViaWrangler(
228
238
  parent: Pico,
229
239
  name: string,
230
240
  rsRegistry: RulesetRegistry,
231
- options?: CreateImportChildOptions
241
+ options?: CreateImportChildOptions,
242
+ onPicoCreated?: PicoCreatedHook
232
243
  ): Promise<{ familyEci: string; child: Pico }> {
233
244
  if (parentIsHandlingEvent(parent)) {
234
- return bootstrapImportChildSync(pf, parent, name, rsRegistry, options);
245
+ return bootstrapImportChildSync(pf, parent, name, rsRegistry, options, onPicoCreated);
235
246
  }
236
247
 
237
248
  const newChildRequest = {
@@ -269,10 +280,11 @@ export async function createImportChildViaWrangler(
269
280
 
270
281
  /** Wrangler-backed child creation wired into ctx subtree import. */
271
282
  export function wranglerSubtreeImportServices(
272
- rsRegistry: RulesetRegistry
283
+ rsRegistry: RulesetRegistry,
284
+ onPicoCreated?: PicoCreatedHook
273
285
  ): Pick<RulesetStateServices, "createImportChild"> {
274
286
  return {
275
287
  createImportChild: (pf, parent, name, opts) =>
276
- createImportChildViaWrangler(pf, parent, name, rsRegistry, opts),
288
+ createImportChildViaWrangler(pf, parent, name, rsRegistry, opts, onPicoCreated),
277
289
  };
278
290
  }
@@ -38,6 +38,7 @@ export const UI_CHANNEL_EVENT_POLICY: EventPolicy = {
38
38
  { domain: "wrangler", name: "new_child_created" },
39
39
  { domain: "wrangler", name: "install_ruleset_request" },
40
40
  { domain: "wrangler", name: "new_channel_request" },
41
+ { domain: "pds", name: "add_settings" },
41
42
  ],
42
43
  deny: [],
43
44
  };
@@ -63,6 +64,7 @@ export const UI_CHANNEL_QUERY_POLICY: QueryPolicy = {
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
  };