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/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";
@@ -8,6 +9,7 @@ import * as path from "path";
8
9
  import {
9
10
  bundledKrlDir,
10
11
  listEngineKrlSources,
12
+ listTryItDemos,
11
13
  resolveEngineKrlFile,
12
14
  } from "./bundledKrl";
13
15
  import {
@@ -26,8 +28,17 @@ import {
26
28
  renderConsentHtml,
27
29
  rootHasOAuthMeshRuleset,
28
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";
29
40
  import { uiECIForRoot } from "./provisionRoot";
30
- import { channelSchemaForEci } from "pico-engine-core";
41
+ import { attachRawBody, attachRequestCookies, channelSchemaForEci } from "pico-engine-core";
31
42
  import {
32
43
  contentTypeForUiPath,
33
44
  isXmluiCodeBehindPath,
@@ -41,6 +52,11 @@ import { registerWebvhRoutes } from "./identity/webvhRoutes";
41
52
  import { registerDidcommIngressRoutes } from "./identity/didcommIngressRoutes";
42
53
 
43
54
  import { getEngineRuntimeSettings } from "./engineConfig";
55
+ import {
56
+ headersForKrl,
57
+ internalTokenAccepted,
58
+ isDirectLoopbackRequest,
59
+ } from "./internalAccess";
44
60
  import {
45
61
  picoLogEntries,
46
62
  resolveEngineLogFilePath,
@@ -51,13 +67,33 @@ import { stageKrlContent } from "./stageKrl";
51
67
 
52
68
  const engineVersion = require("../package.json").version;
53
69
 
54
- function localhostChannelBypassEnabled(): boolean {
55
- 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) });
56
73
  }
57
74
 
58
- function mergeGetPost(req: Request) {
59
- // give preference to post body params
60
- return _.assign({}, req.query, req.body, { _headers: req.headers });
75
+ function withRequestCookies<T extends object>(req: Request, target: T): T {
76
+ attachRequestCookies(target, req.headers.cookie);
77
+ return target;
78
+ }
79
+
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;
61
97
  }
62
98
 
63
99
  function parseCookies(req: Request): { [name: string]: string } {
@@ -80,34 +116,27 @@ function parseCookies(req: Request): { [name: string]: string } {
80
116
  return out;
81
117
  }
82
118
 
83
- function isLocalhostAddress(addr: string | undefined): boolean {
84
- if (!addr) {
85
- return false;
86
- }
87
- const normalized = addr.replace(/^::ffff:/, "");
88
- return normalized === "127.0.0.1" || normalized === "::1";
89
- }
90
-
91
- function isLocalhostRequest(req: Request): boolean {
92
- if (isLocalhostAddress(req.ip)) {
93
- return true;
94
- }
95
- if (isLocalhostAddress(req.socket?.remoteAddress)) {
96
- return true;
97
- }
98
- const host = req.headers.host || "";
99
- return host.startsWith("localhost:") || host.startsWith("127.0.0.1:");
100
- }
101
-
102
119
  export function server(
103
120
  core: PicoEngineCore,
104
121
  uiECI: string | null,
105
122
  auth?: AuthService,
106
123
  oauth?: OAuthService,
107
- identity?: IdentityService
124
+ identity?: IdentityService,
125
+ internalToken = ""
108
126
  ): Express {
109
127
  const pf = core.picoFramework;
110
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
+ }
111
140
  function cookies(): AuthCookieNames {
112
141
  return auth
113
142
  ? authCookieNames(auth.rp().origin)
@@ -164,6 +193,40 @@ export function server(
164
193
  registerWebvhRoutes(app, identity);
165
194
  }
166
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
+
167
230
  app.use(
168
231
  bodyParser.json({
169
232
  type: [
@@ -172,6 +235,7 @@ export function server(
172
235
  "application/ssi-agent-wire",
173
236
  "application/didcomm-encrypted+json",
174
237
  ],
238
+ verify: rememberRawBody,
175
239
  })
176
240
  );
177
241
  app.use(
@@ -179,6 +243,7 @@ export function server(
179
243
  limit: "512mb",
180
244
  type: "application/x-www-form-urlencoded",
181
245
  extended: false,
246
+ verify: rememberRawBody,
182
247
  })
183
248
  );
184
249
 
@@ -236,7 +301,11 @@ export function server(
236
301
  .catch(next);
237
302
  }
238
303
 
239
- /** `/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
+ */
240
309
  function requireChannelSession(
241
310
  req: Request,
242
311
  res: Response,
@@ -246,7 +315,20 @@ export function server(
246
315
  next();
247
316
  return;
248
317
  }
249
- 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)) {
250
332
  next();
251
333
  return;
252
334
  }
@@ -383,6 +465,19 @@ export function server(
383
465
  }
384
466
  });
385
467
 
468
+ app.get("/api/try-it", requireSessionOrInternal, function (req, res, next) {
469
+ try {
470
+ let baseUrl = core.base_url;
471
+ if (!baseUrl) {
472
+ baseUrl = `${req.protocol}://${req.get("host") || "localhost"}`;
473
+ }
474
+ const show = getEngineRuntimeSettings().showTryItMenu;
475
+ res.json({ show, demos: show === "off" ? [] : listTryItDemos(baseUrl) });
476
+ } catch (err) {
477
+ next(err);
478
+ }
479
+ });
480
+
386
481
  app.post("/api/stage-krl", function (req, res, next) {
387
482
  try {
388
483
  const content = req.body?.content;
@@ -420,12 +515,16 @@ export function server(
420
515
  });
421
516
  });
422
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).
423
521
  app.get("/api/ui-context", function (req, res, next) {
424
522
  const hasRoots = pf.rootPicos().length > 0;
425
523
  const base: any = {
426
524
  version: engineVersion,
427
525
  hasRoots,
428
526
  allowSelfSignup: auth ? auth.allowSelfSignup() : false,
527
+ showTryItMenu: getEngineRuntimeSettings().showTryItMenu,
429
528
  };
430
529
  if (!auth) {
431
530
  base.eci = uiECI;
@@ -494,10 +593,14 @@ export function server(
494
593
  });
495
594
  });
496
595
 
497
- /** 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
+ */
498
601
  app.get("/api/dev/local", function (req, res) {
499
- if (!localhostChannelBypassEnabled() || !isLocalhostRequest(req)) {
500
- res.status(403).json({ error: "localhost only" });
602
+ if (!allowInternal(req)) {
603
+ res.status(403).json({ error: "internal only" });
501
604
  return;
502
605
  }
503
606
  const roots = pf.rootPicos();
@@ -556,13 +659,13 @@ export function server(
556
659
 
557
660
  app.all("/c/:eci/event/:domain/:name", requireChannelSession, function (req, res, next) {
558
661
  core
559
- .event({
662
+ .event(withRawBody(req, req.params.eci, withRequestCookies(req, {
560
663
  eci: req.params.eci,
561
664
  domain: req.params.domain,
562
665
  name: req.params.name,
563
666
  data: { attrs: mergeGetPost(req) },
564
667
  time: 0, // TODO remove this typescript requirement
565
- })
668
+ })))
566
669
  .then((eid) => {
567
670
  res.json(eid);
568
671
  })
@@ -571,13 +674,13 @@ export function server(
571
674
 
572
675
  app.all("/c/:eci/event-wait/:domain/:name", requireChannelSession, function (req, res, next) {
573
676
  core
574
- .eventWait({
677
+ .eventWait(withRawBody(req, req.params.eci, withRequestCookies(req, {
575
678
  eci: req.params.eci,
576
679
  domain: req.params.domain,
577
680
  name: req.params.name,
578
681
  data: { attrs: mergeGetPost(req) },
579
682
  time: 0, // TODO remove this typescript requirement
580
- })
683
+ })))
581
684
  .then((data) => {
582
685
  res.json(data);
583
686
  })
@@ -590,13 +693,13 @@ export function server(
590
693
  attrs.__eid = req.params.eid;
591
694
  }
592
695
  core
593
- .eventWait({
696
+ .eventWait(withRawBody(req, req.params.eci, withRequestCookies(req, {
594
697
  eci: req.params.eci,
595
698
  domain: req.params.domain,
596
699
  name: req.params["type"],
597
700
  data: { attrs },
598
701
  time: 0, // TODO remove this typescript requirement
599
- })
702
+ })))
600
703
  .then((data) => {
601
704
  if (data.directives) {
602
705
  var _res = _.filter(data.directives, { name: "_cookie" });
@@ -628,19 +731,19 @@ export function server(
628
731
  const attrs = mergeGetPost(req);
629
732
  core
630
733
  .eventQuery(
631
- {
734
+ withRawBody(req, req.params.eci, withRequestCookies(req, {
632
735
  eci: req.params.eci,
633
736
  domain: req.params.domain,
634
737
  name: req.params.name,
635
738
  data: { attrs },
636
739
  time: 0, // TODO remove this typescript requirement
637
- },
638
- {
740
+ })),
741
+ withRequestCookies(req, {
639
742
  eci: req.params.eci,
640
743
  rid: req.params.rid,
641
744
  name: req.params.qname,
642
745
  args: attrs,
643
- }
746
+ })
644
747
  )
645
748
  .then((data) => {
646
749
  res.json(data);
@@ -652,12 +755,12 @@ export function server(
652
755
  function handleSkyQuery(req: Request, res: Response, next: express.NextFunction) {
653
756
  const funcPart = req.params["function"].split(".");
654
757
  core
655
- .query({
758
+ .query(withRequestCookies(req, {
656
759
  eci: req.params.eci,
657
760
  rid: req.params.rid,
658
761
  name: funcPart[0],
659
762
  args: mergeGetPost(req),
660
- })
763
+ }))
661
764
  .then((data: any) => {
662
765
  if (funcPart[1] === "html") {
663
766
  res.header("Content-Type", "text/html");
@@ -675,12 +778,12 @@ export function server(
675
778
  app.all("/c/:eci/query/:rid/:name", requireChannelSession, function (req, res, next) {
676
779
  const funcPart = req.params.name.split(".");
677
780
  core
678
- .query({
781
+ .query(withRequestCookies(req, {
679
782
  eci: req.params.eci,
680
783
  rid: req.params.rid,
681
784
  name: funcPart[0],
682
785
  args: mergeGetPost(req),
683
- })
786
+ }))
684
787
  .then((data: any) => {
685
788
  if (funcPart[1] === "html") {
686
789
  res.header("Content-Type", "text/html");
@@ -822,16 +925,86 @@ export function server(
822
925
  // Legacy alias; prefer /sky/query/ per Sky Query API docs.
823
926
  app.all("/sky/cloud/:eci/:rid/:function", requireSkyBearerIfOAuth, handleSkyQuery);
824
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
+
825
985
  // Mesh MCP (Streamable HTTP, OAuth bearer scoped to :eci)
826
986
  // eslint-disable-next-line @typescript-eslint/no-require-imports
827
987
  const { registerMeshMcpRoutes } = require("../mcp/meshHttp.js") as {
828
988
  registerMeshMcpRoutes: (
829
989
  app: Express,
830
990
  core: PicoEngineCore,
831
- 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
832
999
  ) => void;
833
1000
  };
834
- 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
+ );
835
1008
 
836
1009
  app.use(function (
837
1010
  err: any,
@@ -1163,9 +1336,10 @@ function registerOAuthRoutes(
1163
1336
  next(err);
1164
1337
  return;
1165
1338
  }
1166
- oauth
1339
+ const showConsent = () =>
1340
+ oauth
1167
1341
  .getAppForAuthorize(params)
1168
- .then(async (appRecord) => {
1342
+ .then(async (resolved) => {
1169
1343
  if (!auth) {
1170
1344
  res.status(503).send("Authentication is not configured");
1171
1345
  return;
@@ -1179,13 +1353,54 @@ function registerOAuthRoutes(
1179
1353
  );
1180
1354
  return;
1181
1355
  }
1182
- 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) {
1183
1368
  res.status(403).send("Signed in to a different mesh");
1184
1369
  return;
1185
1370
  }
1186
- 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
+ );
1187
1379
  })
1188
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();
1189
1404
  });
1190
1405
 
1191
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
  };