pico-engine 1.9.4 → 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 (186) hide show
  1. package/README.md +13 -5
  2. package/demos/bootstrap/README.md +12 -0
  3. package/demos/bootstrap/com.example.visitors.bootstrap.krl +101 -0
  4. package/demos/bootstrap/com.example.visitors.format.krl +25 -0
  5. package/demos/bootstrap/com.example.visitors.krl +228 -0
  6. package/demos/bootstrap/try-it.md +5 -0
  7. package/demos/child_tasks/README.md +12 -0
  8. package/demos/child_tasks/com.example.task_runner.bootstrap.krl +88 -0
  9. package/demos/child_tasks/com.example.task_runner.krl +139 -0
  10. package/demos/child_tasks/com.example.task_worker.krl +45 -0
  11. package/demos/child_tasks/try-it.md +5 -0
  12. package/demos/collection/README.md +13 -0
  13. package/demos/collection/com.example.collection.bootstrap.krl +148 -0
  14. package/demos/collection/com.example.collection.krl +95 -0
  15. package/demos/collection/com.example.collection.report.krl +93 -0
  16. package/demos/collection/com.example.collection.room.krl +101 -0
  17. package/demos/collection/try-it.md +6 -0
  18. package/demos/echo/README.md +11 -0
  19. package/demos/echo/com.example.echo.bootstrap.krl +84 -0
  20. package/demos/echo/com.example.echo.krl +73 -0
  21. package/demos/echo/try-it.md +5 -0
  22. package/demos/guard_rules/README.md +12 -0
  23. package/demos/guard_rules/com.example.archive.bootstrap.krl +98 -0
  24. package/demos/guard_rules/com.example.archive.krl +213 -0
  25. package/demos/guard_rules/com.example.archive_store.krl +36 -0
  26. package/demos/guard_rules/try-it.md +5 -0
  27. package/demos/json_query/README.md +11 -0
  28. package/demos/json_query/com.example.json_query.bootstrap.krl +84 -0
  29. package/demos/json_query/com.example.json_query.krl +162 -0
  30. package/demos/json_query/try-it.md +5 -0
  31. package/demos/kblog/README.md +14 -0
  32. package/demos/kblog/com.example.kblog.bootstrap.krl +135 -0
  33. package/demos/kblog/com.example.kblog.config.krl +50 -0
  34. package/demos/kblog/com.example.kblog.data.krl +75 -0
  35. package/demos/kblog/com.example.kblog.krl +184 -0
  36. package/demos/kblog/com.example.kblog.posting.krl +109 -0
  37. package/demos/kblog/try-it.md +6 -0
  38. package/demos/layered_rulesets/README.md +13 -0
  39. package/demos/layered_rulesets/com.example.invitations.bootstrap.krl +87 -0
  40. package/demos/layered_rulesets/com.example.invitations.krl +164 -0
  41. package/demos/layered_rulesets/com.example.invitations.short_links.krl +45 -0
  42. package/demos/layered_rulesets/com.example.invitations.welcome.krl +39 -0
  43. package/demos/layered_rulesets/try-it.md +5 -0
  44. package/demos/moving_picos/README.md +15 -0
  45. package/demos/moving_picos/io.picolabs.club_gear_demo.krl +650 -0
  46. package/demos/moving_picos/io.picolabs.ride_coordinator_demo.krl +331 -0
  47. package/demos/score_tracker/README.md +11 -0
  48. package/demos/score_tracker/com.example.score_tracker.bootstrap.krl +107 -0
  49. package/demos/score_tracker/com.example.score_tracker.krl +162 -0
  50. package/demos/score_tracker/try-it.md +5 -0
  51. package/demos/secrets/README.md +12 -0
  52. package/demos/secrets/com.example.hook_service.krl +120 -0
  53. package/demos/secrets/com.example.notifier.bootstrap.krl +130 -0
  54. package/demos/secrets/com.example.notifier.krl +138 -0
  55. package/demos/secrets/try-it.md +5 -0
  56. package/demos/try-it-order.json +1 -0
  57. package/demos/two_picos/README.md +12 -0
  58. package/demos/two_picos/com.example.two_picos.answerer.krl +125 -0
  59. package/demos/two_picos/com.example.two_picos.asker.krl +124 -0
  60. package/demos/two_picos/com.example.two_picos.bootstrap.krl +134 -0
  61. package/demos/two_picos/try-it.md +5 -0
  62. package/demos/xmlui/README.md +17 -0
  63. package/demos/xmlui/com.example.contacts.krl +132 -0
  64. package/demos/xmlui/com.example.fav_color.krl +39 -0
  65. package/demos/xmlui/com.example.guestbook.krl +61 -0
  66. package/demos/xmlui/com.example.hello.krl +19 -0
  67. package/demos/xmlui/com.example.temperature_sensors_view.krl +105 -0
  68. package/demos/xmlui/com.example.thermostat.bootstrap.krl +95 -0
  69. package/demos/xmlui/com.example.thermostat.krl +124 -0
  70. package/demos/xmlui/temperature_sensors.krl +56 -0
  71. package/demos/xmlui/try-it.md +5 -0
  72. package/dist/bundledKrl.js +97 -12
  73. package/dist/cli.js +7 -1
  74. package/dist/engineConfig.js +20 -1
  75. package/dist/identity/portableMove.js +5 -1
  76. package/dist/index.js +45 -12
  77. package/dist/internalAccess.js +110 -0
  78. package/dist/oauth/OAuthService.js +172 -10
  79. package/dist/oauth/acg.js +194 -24
  80. package/dist/oauth/cimd.js +381 -0
  81. package/dist/oauth/discovery.js +175 -0
  82. package/dist/runMcp.js +1 -1
  83. package/dist/server.js +210 -47
  84. package/dist/subtreeWrangler.js +8 -5
  85. package/dist/uiChannelPolicies.js +2 -0
  86. package/krl/io.picolabs.pds.krl +109 -21
  87. package/krl/io.picolabs.pico-engine-ui.krl +13 -7
  88. package/krl/io.picolabs.wrangler.krl +21 -9
  89. package/krl/io.picolabs.xmlui.krl +3 -2
  90. package/mcp/devResources.js +52 -0
  91. package/mcp/devTools.js +40 -9
  92. package/mcp/docs/CLAUDE.md +6 -4
  93. package/mcp/docs/cookbook/README.md +23 -0
  94. package/mcp/docs/cookbook/bootstrap/README.md +23 -0
  95. package/mcp/docs/cookbook/bootstrap/instructions.md +75 -0
  96. package/mcp/docs/cookbook/child_tasks/README.md +20 -0
  97. package/mcp/docs/cookbook/child_tasks/instructions.md +60 -0
  98. package/mcp/docs/cookbook/collection/README.md +21 -0
  99. package/mcp/docs/cookbook/collection/instructions.md +93 -0
  100. package/mcp/docs/cookbook/echo/README.md +19 -0
  101. package/mcp/docs/cookbook/echo/instructions.md +59 -0
  102. package/mcp/docs/cookbook/guard_rules/README.md +22 -0
  103. package/mcp/docs/cookbook/guard_rules/instructions.md +73 -0
  104. package/mcp/docs/cookbook/json_query/README.md +26 -0
  105. package/mcp/docs/cookbook/json_query/instructions.md +64 -0
  106. package/mcp/docs/cookbook/kblog/README.md +60 -0
  107. package/mcp/docs/cookbook/kblog/instructions.md +102 -0
  108. package/mcp/docs/cookbook/layered_rulesets/README.md +24 -0
  109. package/mcp/docs/cookbook/layered_rulesets/instructions.md +87 -0
  110. package/mcp/docs/cookbook/moving_picos/README.md +44 -0
  111. package/mcp/docs/cookbook/moving_picos/instructions.md +150 -0
  112. package/mcp/docs/cookbook/score_tracker/README.md +19 -0
  113. package/mcp/docs/cookbook/score_tracker/instructions.md +73 -0
  114. package/mcp/docs/cookbook/secrets/README.md +25 -0
  115. package/mcp/docs/cookbook/secrets/instructions.md +98 -0
  116. package/mcp/docs/cookbook/two_picos/README.md +20 -0
  117. package/mcp/docs/cookbook/two_picos/instructions.md +88 -0
  118. package/mcp/docs/cookbook/xmlui/README.md +23 -0
  119. package/mcp/docs/cookbook/xmlui/instructions.md +84 -0
  120. package/mcp/docs/developing/README.md +28 -0
  121. package/mcp/docs/developing/accepting-relationship-requests.md +65 -0
  122. package/mcp/docs/developing/arrays-and-maps.md +77 -0
  123. package/mcp/docs/developing/converting-time-formats.md +28 -0
  124. package/mcp/docs/developing/cookies-and-redirects.md +81 -0
  125. package/mcp/docs/developing/decoding-form-data.md +67 -0
  126. package/mcp/docs/developing/engine-log-files.md +34 -0
  127. package/mcp/docs/developing/event-loop.md +77 -0
  128. package/mcp/docs/developing/events-from-email.md +80 -0
  129. package/mcp/docs/developing/initializing-entity-variables.md +83 -0
  130. package/mcp/docs/developing/mcp-ai-tools.md +98 -0
  131. package/mcp/docs/developing/misconceptions.md +467 -0
  132. package/mcp/docs/developing/names-and-scope.md +44 -0
  133. package/mcp/docs/developing/postman.md +159 -0
  134. package/mcp/docs/developing/querying-another-pico.md +47 -0
  135. package/mcp/docs/developing/singleton-picos.md +36 -0
  136. package/mcp/docs/developing/tabular-data.md +67 -0
  137. package/mcp/docs/developing/tips.md +251 -0
  138. package/mcp/docs/developing/webhook-signatures.md +56 -0
  139. package/mcp/docs/developing/workflow.md +106 -0
  140. package/mcp/docs/exp/README.md +46 -0
  141. package/mcp/docs/exp/event.md +110 -0
  142. package/mcp/docs/exp/query.md +94 -0
  143. package/mcp/docs/lessons/README.md +59 -0
  144. package/mcp/docs/lessons/events-and-queries.md +247 -0
  145. package/mcp/docs/lessons/gossip.md +28 -0
  146. package/mcp/docs/lessons/modules-and-apis.md +270 -0
  147. package/mcp/docs/lessons/pico-based-systems.md +470 -0
  148. package/mcp/docs/lessons/pico-state.md +267 -0
  149. package/mcp/docs/lessons/pico-views.md +290 -0
  150. package/mcp/docs/lessons/quickstart.md +157 -0
  151. package/mcp/docs/lessons/relationships.md +530 -0
  152. package/mcp/docs/lessons/scatter-gather.md +362 -0
  153. package/mcp/docs/pico-engine.md +10 -5
  154. package/mcp/docs/pico-overview.md +3 -3
  155. package/mcp/docs/wrangler/README.md +47 -0
  156. package/mcp/docs/wrangler/channels.md +235 -0
  157. package/mcp/docs/wrangler/oauth.md +56 -0
  158. package/mcp/docs/wrangler/pds.md +423 -0
  159. package/mcp/docs/wrangler/portable-subtree.md +44 -0
  160. package/mcp/docs/wrangler/relationships.md +297 -0
  161. package/mcp/docs/wrangler/wrangler.md +253 -0
  162. package/mcp/docs/wrangler/xmlui.md +60 -0
  163. package/mcp/engineClient.js +57 -5
  164. package/mcp/mcpScopes.js +118 -0
  165. package/mcp/meshHttp.js +151 -45
  166. package/mcp/runStdio.js +2 -0
  167. package/mcp/subtreeTools.js +184 -0
  168. package/mcp/tryItTools.js +202 -0
  169. package/package.json +18 -9
  170. package/public/.DS_Store +0 -0
  171. package/public/pico-engine-ui.css +1 -1
  172. package/public/pico-engine-ui.js +26 -25
  173. package/src/bundledKrl.ts +118 -12
  174. package/src/cli.ts +8 -2
  175. package/src/engineConfig.ts +33 -2
  176. package/src/identity/portableMove.ts +6 -1
  177. package/src/index.ts +469 -422
  178. package/src/internalAccess.ts +127 -0
  179. package/src/oauth/OAuthService.ts +243 -11
  180. package/src/oauth/acg.ts +289 -25
  181. package/src/oauth/cimd.ts +508 -0
  182. package/src/oauth/discovery.ts +233 -0
  183. package/src/runMcp.ts +3 -1
  184. package/src/server.ts +266 -51
  185. package/src/subtreeWrangler.ts +17 -5
  186. 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,6 +357,19 @@ function server(core, uiECI, auth, oauth, identity) {
302
357
  next(err);
303
358
  }
304
359
  });
360
+ app.get("/api/try-it", requireSessionOrInternal, function (req, res, next) {
361
+ try {
362
+ let baseUrl = core.base_url;
363
+ if (!baseUrl) {
364
+ baseUrl = `${req.protocol}://${req.get("host") || "localhost"}`;
365
+ }
366
+ const show = (0, engineConfig_1.getEngineRuntimeSettings)().showTryItMenu;
367
+ res.json({ show, demos: show === "off" ? [] : (0, bundledKrl_1.listTryItDemos)(baseUrl) });
368
+ }
369
+ catch (err) {
370
+ next(err);
371
+ }
372
+ });
305
373
  app.post("/api/stage-krl", function (req, res, next) {
306
374
  var _a, _b;
307
375
  try {
@@ -338,12 +406,16 @@ function server(core, uiECI, auth, oauth, identity) {
338
406
  res.type("text/plain").send(data);
339
407
  });
340
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).
341
412
  app.get("/api/ui-context", function (req, res, next) {
342
413
  const hasRoots = pf.rootPicos().length > 0;
343
414
  const base = {
344
415
  version: engineVersion,
345
416
  hasRoots,
346
417
  allowSelfSignup: auth ? auth.allowSelfSignup() : false,
418
+ showTryItMenu: (0, engineConfig_1.getEngineRuntimeSettings)().showTryItMenu,
347
419
  };
348
420
  if (!auth) {
349
421
  base.eci = uiECI;
@@ -413,11 +485,15 @@ function server(core, uiECI, auth, oauth, identity) {
413
485
  unsubscribe();
414
486
  });
415
487
  });
416
- /** 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
+ */
417
493
  app.get("/api/dev/local", function (req, res) {
418
494
  var _a;
419
- if (!localhostChannelBypassEnabled() || !isLocalhostRequest(req)) {
420
- res.status(403).json({ error: "localhost only" });
495
+ if (!allowInternal(req)) {
496
+ res.status(403).json({ error: "internal only" });
421
497
  return;
422
498
  }
423
499
  const roots = pf.rootPicos();
@@ -474,13 +550,13 @@ function server(core, uiECI, auth, oauth, identity) {
474
550
  });
475
551
  app.all("/c/:eci/event/:domain/:name", requireChannelSession, function (req, res, next) {
476
552
  core
477
- .event({
553
+ .event(withRawBody(req, req.params.eci, withRequestCookies(req, {
478
554
  eci: req.params.eci,
479
555
  domain: req.params.domain,
480
556
  name: req.params.name,
481
557
  data: { attrs: mergeGetPost(req) },
482
558
  time: 0, // TODO remove this typescript requirement
483
- })
559
+ })))
484
560
  .then((eid) => {
485
561
  res.json(eid);
486
562
  })
@@ -488,13 +564,13 @@ function server(core, uiECI, auth, oauth, identity) {
488
564
  });
489
565
  app.all("/c/:eci/event-wait/:domain/:name", requireChannelSession, function (req, res, next) {
490
566
  core
491
- .eventWait({
567
+ .eventWait(withRawBody(req, req.params.eci, withRequestCookies(req, {
492
568
  eci: req.params.eci,
493
569
  domain: req.params.domain,
494
570
  name: req.params.name,
495
571
  data: { attrs: mergeGetPost(req) },
496
572
  time: 0, // TODO remove this typescript requirement
497
- })
573
+ })))
498
574
  .then((data) => {
499
575
  res.json(data);
500
576
  })
@@ -506,13 +582,13 @@ function server(core, uiECI, auth, oauth, identity) {
506
582
  attrs.__eid = req.params.eid;
507
583
  }
508
584
  core
509
- .eventWait({
585
+ .eventWait(withRawBody(req, req.params.eci, withRequestCookies(req, {
510
586
  eci: req.params.eci,
511
587
  domain: req.params.domain,
512
588
  name: req.params["type"],
513
589
  data: { attrs },
514
590
  time: 0, // TODO remove this typescript requirement
515
- })
591
+ })))
516
592
  .then((data) => {
517
593
  if (data.directives) {
518
594
  var _res = _.filter(data.directives, { name: "_cookie" });
@@ -539,18 +615,18 @@ function server(core, uiECI, auth, oauth, identity) {
539
615
  app.all("/c/:eci/event/:domain/:name/query/:rid/:qname", requireChannelSession, function (req, res, next) {
540
616
  const attrs = mergeGetPost(req);
541
617
  core
542
- .eventQuery({
618
+ .eventQuery(withRawBody(req, req.params.eci, withRequestCookies(req, {
543
619
  eci: req.params.eci,
544
620
  domain: req.params.domain,
545
621
  name: req.params.name,
546
622
  data: { attrs },
547
623
  time: 0, // TODO remove this typescript requirement
548
- }, {
624
+ })), withRequestCookies(req, {
549
625
  eci: req.params.eci,
550
626
  rid: req.params.rid,
551
627
  name: req.params.qname,
552
628
  args: attrs,
553
- })
629
+ }))
554
630
  .then((data) => {
555
631
  res.json(data);
556
632
  })
@@ -559,12 +635,12 @@ function server(core, uiECI, auth, oauth, identity) {
559
635
  function handleSkyQuery(req, res, next) {
560
636
  const funcPart = req.params["function"].split(".");
561
637
  core
562
- .query({
638
+ .query(withRequestCookies(req, {
563
639
  eci: req.params.eci,
564
640
  rid: req.params.rid,
565
641
  name: funcPart[0],
566
642
  args: mergeGetPost(req),
567
- })
643
+ }))
568
644
  .then((data) => {
569
645
  if (funcPart[1] === "html") {
570
646
  res.header("Content-Type", "text/html");
@@ -583,12 +659,12 @@ function server(core, uiECI, auth, oauth, identity) {
583
659
  app.all("/c/:eci/query/:rid/:name", requireChannelSession, function (req, res, next) {
584
660
  const funcPart = req.params.name.split(".");
585
661
  core
586
- .query({
662
+ .query(withRequestCookies(req, {
587
663
  eci: req.params.eci,
588
664
  rid: req.params.rid,
589
665
  name: funcPart[0],
590
666
  args: mergeGetPost(req),
591
- })
667
+ }))
592
668
  .then((data) => {
593
669
  if (funcPart[1] === "html") {
594
670
  res.header("Content-Type", "text/html");
@@ -703,10 +779,64 @@ function server(core, uiECI, auth, oauth, identity) {
703
779
  app.all("/sky/query/:eci/:rid/:function", requireSkyBearerIfOAuth, handleSkyQuery);
704
780
  // Legacy alias; prefer /sky/query/ per Sky Query API docs.
705
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
+ });
706
836
  // Mesh MCP (Streamable HTTP, OAuth bearer scoped to :eci)
707
837
  // eslint-disable-next-line @typescript-eslint/no-require-imports
708
838
  const { registerMeshMcpRoutes } = require("../mcp/meshHttp.js");
709
- 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));
710
840
  app.use(function (err, req, res, next) {
711
841
  var _a, _b, _c;
712
842
  if (err instanceof auth_1.AuthError) {
@@ -984,9 +1114,9 @@ function registerOAuthRoutes(app, oauth, auth, requireAuthSession, parseCookiesF
984
1114
  next(err);
985
1115
  return;
986
1116
  }
987
- oauth
1117
+ const showConsent = () => oauth
988
1118
  .getAppForAuthorize(params)
989
- .then(async (appRecord) => {
1119
+ .then(async (resolved) => {
990
1120
  if (!auth) {
991
1121
  res.status(503).send("Authentication is not configured");
992
1122
  return;
@@ -998,13 +1128,46 @@ function registerOAuthRoutes(app, oauth, auth, requireAuthSession, parseCookiesF
998
1128
  res.redirect("/?oauth_return=" + encodeURIComponent(returnPath));
999
1129
  return;
1000
1130
  }
1001
- 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) {
1002
1141
  res.status(403).send("Signed in to a different mesh");
1003
1142
  return;
1004
1143
  }
1005
- 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 })));
1006
1147
  })
1007
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();
1008
1171
  });
1009
1172
  app.post("/oauth/approve", function (req, res, next) {
1010
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
  };