pico-engine 1.9.5 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/README.md +11 -5
  2. package/demos/bootstrap/com.example.visitors.bootstrap.krl +9 -5
  3. package/demos/child_tasks/com.example.task_runner.bootstrap.krl +10 -7
  4. package/demos/echo/com.example.echo.bootstrap.krl +10 -7
  5. package/demos/guard_rules/com.example.archive.bootstrap.krl +10 -7
  6. package/demos/json_query/README.md +11 -0
  7. package/demos/json_query/com.example.json_query.bootstrap.krl +84 -0
  8. package/demos/json_query/com.example.json_query.krl +162 -0
  9. package/demos/json_query/try-it.md +5 -0
  10. package/demos/kblog/com.example.kblog.bootstrap.krl +10 -7
  11. package/demos/layered_rulesets/com.example.invitations.bootstrap.krl +10 -7
  12. package/demos/score_tracker/com.example.score_tracker.bootstrap.krl +10 -7
  13. package/demos/secrets/com.example.notifier.bootstrap.krl +10 -7
  14. package/demos/try-it-order.json +1 -1
  15. package/demos/two_picos/com.example.two_picos.bootstrap.krl +5 -2
  16. package/demos/xmlui/com.example.thermostat.bootstrap.krl +10 -7
  17. package/dist/cli.js +5 -1
  18. package/dist/engineConfig.js +1 -1
  19. package/dist/identity/portableMove.js +5 -1
  20. package/dist/index.js +44 -12
  21. package/dist/internalAccess.js +110 -0
  22. package/dist/oauth/OAuthService.js +172 -10
  23. package/dist/oauth/acg.js +194 -24
  24. package/dist/oauth/cimd.js +381 -0
  25. package/dist/oauth/discovery.js +175 -0
  26. package/dist/runMcp.js +1 -1
  27. package/dist/server.js +197 -48
  28. package/dist/subtreeWrangler.js +8 -5
  29. package/dist/uiChannelPolicies.js +2 -0
  30. package/krl/io.picolabs.pds.krl +109 -21
  31. package/krl/io.picolabs.pico-engine-ui.krl +13 -7
  32. package/krl/io.picolabs.wrangler.krl +21 -9
  33. package/mcp/devResources.js +52 -0
  34. package/mcp/devTools.js +40 -9
  35. package/mcp/docs/CLAUDE.md +3 -2
  36. package/mcp/docs/cookbook/README.md +23 -0
  37. package/mcp/docs/cookbook/bootstrap/README.md +23 -0
  38. package/mcp/docs/cookbook/bootstrap/instructions.md +75 -0
  39. package/mcp/docs/cookbook/child_tasks/README.md +20 -0
  40. package/mcp/docs/cookbook/child_tasks/instructions.md +60 -0
  41. package/mcp/docs/cookbook/collection/README.md +21 -0
  42. package/mcp/docs/cookbook/collection/instructions.md +93 -0
  43. package/mcp/docs/cookbook/echo/README.md +19 -0
  44. package/mcp/docs/cookbook/echo/instructions.md +59 -0
  45. package/mcp/docs/cookbook/guard_rules/README.md +22 -0
  46. package/mcp/docs/cookbook/guard_rules/instructions.md +73 -0
  47. package/mcp/docs/cookbook/json_query/README.md +26 -0
  48. package/mcp/docs/cookbook/json_query/instructions.md +64 -0
  49. package/mcp/docs/cookbook/kblog/README.md +60 -0
  50. package/mcp/docs/cookbook/kblog/instructions.md +102 -0
  51. package/mcp/docs/cookbook/layered_rulesets/README.md +24 -0
  52. package/mcp/docs/cookbook/layered_rulesets/instructions.md +87 -0
  53. package/mcp/docs/cookbook/moving_picos/README.md +44 -0
  54. package/mcp/docs/cookbook/moving_picos/instructions.md +150 -0
  55. package/mcp/docs/cookbook/score_tracker/README.md +19 -0
  56. package/mcp/docs/cookbook/score_tracker/instructions.md +73 -0
  57. package/mcp/docs/cookbook/secrets/README.md +25 -0
  58. package/mcp/docs/cookbook/secrets/instructions.md +98 -0
  59. package/mcp/docs/cookbook/two_picos/README.md +20 -0
  60. package/mcp/docs/cookbook/two_picos/instructions.md +88 -0
  61. package/mcp/docs/cookbook/xmlui/README.md +23 -0
  62. package/mcp/docs/cookbook/xmlui/instructions.md +84 -0
  63. package/mcp/docs/developing/README.md +28 -0
  64. package/mcp/docs/developing/accepting-relationship-requests.md +65 -0
  65. package/mcp/docs/developing/arrays-and-maps.md +77 -0
  66. package/mcp/docs/developing/converting-time-formats.md +28 -0
  67. package/mcp/docs/developing/cookies-and-redirects.md +81 -0
  68. package/mcp/docs/developing/decoding-form-data.md +67 -0
  69. package/mcp/docs/developing/engine-log-files.md +34 -0
  70. package/mcp/docs/developing/event-loop.md +77 -0
  71. package/mcp/docs/developing/events-from-email.md +80 -0
  72. package/mcp/docs/developing/initializing-entity-variables.md +83 -0
  73. package/mcp/docs/developing/mcp-ai-tools.md +98 -0
  74. package/mcp/docs/developing/misconceptions.md +467 -0
  75. package/mcp/docs/developing/names-and-scope.md +44 -0
  76. package/mcp/docs/developing/postman.md +159 -0
  77. package/mcp/docs/developing/querying-another-pico.md +47 -0
  78. package/mcp/docs/developing/singleton-picos.md +36 -0
  79. package/mcp/docs/developing/tabular-data.md +67 -0
  80. package/mcp/docs/developing/tips.md +251 -0
  81. package/mcp/docs/developing/webhook-signatures.md +56 -0
  82. package/mcp/docs/developing/workflow.md +106 -0
  83. package/mcp/docs/exp/README.md +46 -0
  84. package/mcp/docs/exp/event.md +110 -0
  85. package/mcp/docs/exp/query.md +94 -0
  86. package/mcp/docs/lessons/README.md +59 -0
  87. package/mcp/docs/lessons/events-and-queries.md +247 -0
  88. package/mcp/docs/lessons/gossip.md +28 -0
  89. package/mcp/docs/lessons/modules-and-apis.md +270 -0
  90. package/mcp/docs/lessons/pico-based-systems.md +470 -0
  91. package/mcp/docs/lessons/pico-state.md +267 -0
  92. package/mcp/docs/lessons/pico-views.md +290 -0
  93. package/mcp/docs/lessons/quickstart.md +157 -0
  94. package/mcp/docs/lessons/relationships.md +530 -0
  95. package/mcp/docs/lessons/scatter-gather.md +362 -0
  96. package/mcp/docs/pico-engine.md +7 -5
  97. package/mcp/docs/pico-overview.md +3 -3
  98. package/mcp/docs/wrangler/README.md +47 -0
  99. package/mcp/docs/wrangler/channels.md +235 -0
  100. package/mcp/docs/wrangler/oauth.md +56 -0
  101. package/mcp/docs/wrangler/pds.md +423 -0
  102. package/mcp/docs/wrangler/portable-subtree.md +44 -0
  103. package/mcp/docs/wrangler/relationships.md +297 -0
  104. package/mcp/docs/wrangler/wrangler.md +253 -0
  105. package/mcp/docs/wrangler/xmlui.md +60 -0
  106. package/mcp/engineClient.js +57 -5
  107. package/mcp/mcpScopes.js +118 -0
  108. package/mcp/meshHttp.js +151 -45
  109. package/mcp/runStdio.js +2 -0
  110. package/mcp/subtreeTools.js +184 -0
  111. package/mcp/tryItTools.js +202 -0
  112. package/package.json +14 -8
  113. package/public/pico-engine-ui.js +26 -26
  114. package/src/cli.ts +6 -2
  115. package/src/engineConfig.ts +5 -2
  116. package/src/identity/portableMove.ts +6 -1
  117. package/src/index.ts +469 -430
  118. package/src/internalAccess.ts +127 -0
  119. package/src/oauth/OAuthService.ts +243 -11
  120. package/src/oauth/acg.ts +289 -25
  121. package/src/oauth/cimd.ts +508 -0
  122. package/src/oauth/discovery.ts +233 -0
  123. package/src/runMcp.ts +3 -1
  124. package/src/server.ts +252 -52
  125. package/src/subtreeWrangler.ts +17 -5
  126. package/src/uiChannelPolicies.ts +2 -0
@@ -0,0 +1,127 @@
1
+ import * as crypto from "crypto";
2
+ import * as fs from "fs";
3
+ import * as path from "path";
4
+
5
+ /** File name under `PICO_ENGINE_HOME`. The dev MCP client reads the same file. */
6
+ export const INTERNAL_TOKEN_FILENAME = "internal-token";
7
+
8
+ /** HTTP header the dev MCP sends. Express stores it lower-case. */
9
+ export const INTERNAL_TOKEN_HEADER = "x-pico-internal";
10
+
11
+ /**
12
+ * Request headers that must not reach KRL. `x-pico-internal` is the engine's
13
+ * own dev credential; the others are caller credentials (1.10 §5 H1).
14
+ */
15
+ const CREDENTIAL_HEADERS = new Set([
16
+ "authorization",
17
+ "proxy-authorization",
18
+ "cookie",
19
+ "x-pico-internal",
20
+ ]);
21
+
22
+ const PROXY_CLIENT_HEADERS = ["x-forwarded-for", "x-real-ip", "forwarded"];
23
+
24
+ export interface ClientAddressRequest {
25
+ ip?: string;
26
+ socket?: { remoteAddress?: string | null };
27
+ headers: NodeJS.Dict<string | string[] | undefined>;
28
+ }
29
+
30
+ export function internalTokenPath(home: string): string {
31
+ return path.join(home, INTERNAL_TOKEN_FILENAME);
32
+ }
33
+
34
+ /** New secret on every startup. Mode 0600 even when umask would loosen the write. */
35
+ export function writeInternalToken(home: string): string {
36
+ const token = crypto.randomBytes(32).toString("base64url");
37
+ const file = internalTokenPath(home);
38
+ fs.writeFileSync(file, `${token}\n`, { encoding: "utf8", mode: 0o600 });
39
+ fs.chmodSync(file, 0o600);
40
+ return token;
41
+ }
42
+
43
+ export function readInternalToken(home: string): string | null {
44
+ try {
45
+ const token = fs.readFileSync(internalTokenPath(home), "utf8").trim();
46
+ return token.length > 0 ? token : null;
47
+ } catch (_err) {
48
+ return null;
49
+ }
50
+ }
51
+
52
+ export function timingSafeEqualString(actual: string, expected: string): boolean {
53
+ const a = Buffer.from(actual);
54
+ const b = Buffer.from(expected);
55
+ if (a.length !== b.length) {
56
+ return false;
57
+ }
58
+ return crypto.timingSafeEqual(a, b);
59
+ }
60
+
61
+ export function internalTokenAccepted(
62
+ presented: string | string[] | undefined,
63
+ expected: string
64
+ ): boolean {
65
+ if (!expected || typeof presented !== "string") {
66
+ return false;
67
+ }
68
+ const token = presented.trim();
69
+ if (!token) {
70
+ return false;
71
+ }
72
+ return timingSafeEqualString(token, expected);
73
+ }
74
+
75
+ function headerIsPresent(
76
+ headers: ClientAddressRequest["headers"],
77
+ name: string
78
+ ): boolean {
79
+ const value = headers[name];
80
+ if (typeof value === "string") {
81
+ return true;
82
+ }
83
+ return Array.isArray(value) && value.length > 0;
84
+ }
85
+
86
+ /** A proxy sat in front of this request. Its socket address is the proxy, not the client. */
87
+ export function requestCarriesProxyClientHeaders(
88
+ headers: ClientAddressRequest["headers"]
89
+ ): boolean {
90
+ return PROXY_CLIENT_HEADERS.some((name) => headerIsPresent(headers, name));
91
+ }
92
+
93
+ function isLoopbackAddress(addr: string | undefined | null): boolean {
94
+ if (!addr) {
95
+ return false;
96
+ }
97
+ const normalized = addr.replace(/^::ffff:/, "");
98
+ return normalized === "127.0.0.1" || normalized === "::1";
99
+ }
100
+
101
+ /**
102
+ * Direct TCP from this machine. The `Host` header is not consulted: clients set it.
103
+ * `X-Forwarded-For`, `X-Real-IP`, and `Forwarded` mean the peer is a proxy.
104
+ */
105
+ export function isDirectLoopbackRequest(req: ClientAddressRequest): boolean {
106
+ if (requestCarriesProxyClientHeaders(req.headers)) {
107
+ return false;
108
+ }
109
+ if (isLoopbackAddress(req.ip)) {
110
+ return true;
111
+ }
112
+ return isLoopbackAddress(req.socket?.remoteAddress);
113
+ }
114
+
115
+ /** Copy of the request headers with credential headers removed. */
116
+ export function headersForKrl(
117
+ headers: NodeJS.Dict<string | string[] | undefined>
118
+ ): { [name: string]: string | string[] } {
119
+ const out: { [name: string]: string | string[] } = {};
120
+ for (const [key, value] of Object.entries(headers)) {
121
+ if (value === undefined || CREDENTIAL_HEADERS.has(key.toLowerCase())) {
122
+ continue;
123
+ }
124
+ out[key] = value;
125
+ }
126
+ return out;
127
+ }
@@ -5,8 +5,21 @@ import {
5
5
  isMeshOAuthExemptChannel,
6
6
  isOAuthEligibleChannel,
7
7
  } from "./channelEligibility";
8
+ import {
9
+ assertMcpScopes,
10
+ canonicalResourceUrl,
11
+ classifyResource,
12
+ MCP_CHANNEL_SCOPE,
13
+ mcpResourceUrl,
14
+ skyResourceUrl,
15
+ } from "./discovery";
16
+ import { loadClientMetadata, type ClientMetadataDocument } from "./cimd";
8
17
  import { OAuthError } from "./errors";
9
- import { isChannelUnderRoot, meshRequiresOAuth as meshRequiresOAuthForEci } from "./meshOAuth";
18
+ import {
19
+ isChannelUnderRoot,
20
+ meshRequiresOAuth as meshRequiresOAuthForEci,
21
+ rootHasOAuthMeshRuleset,
22
+ } from "./meshOAuth";
10
23
  import {
11
24
  channelHasUnrestrictedAllow,
12
25
  isDidcommIngressChannel,
@@ -38,6 +51,8 @@ interface StoredOAuthToken {
38
51
  appId?: string;
39
52
  accountId?: string;
40
53
  scope?: string;
54
+ /** Canonical RFC 8707 resource. Absent on legacy Sky tokens. */
55
+ resource?: string;
41
56
  expiresAt: number;
42
57
  createdAt: string;
43
58
  }
@@ -77,13 +92,19 @@ export interface OAuthServiceDeps {
77
92
  db: PicoDb;
78
93
  pf: PicoFramework;
79
94
  tokenTtlMs?: number;
95
+ /** Read at request time. `base_url` is assigned after the service is constructed. */
96
+ getBaseUrl?: () => string | undefined;
97
+ /** Override the Client ID Metadata Document fetch (tests). */
98
+ loadClientMetadata?: (url: string) => Promise<ClientMetadataDocument>;
80
99
  }
81
100
 
82
101
  export class OAuthService {
83
102
  private deps: OAuthServiceDeps;
103
+ loadClientMetadata: (url: string) => Promise<ClientMetadataDocument>;
84
104
 
85
105
  constructor(deps: OAuthServiceDeps) {
86
106
  this.deps = deps;
107
+ this.loadClientMetadata = deps.loadClientMetadata ?? ((url) => loadClientMetadata(url));
87
108
  }
88
109
 
89
110
  get tokenTtlMs(): number {
@@ -196,6 +217,8 @@ export class OAuthService {
196
217
  client_id?: string;
197
218
  client_secret?: string;
198
219
  expires_in?: number | string;
220
+ resource?: string;
221
+ scope?: string;
199
222
  }): Promise<OAuthTokenResponse> {
200
223
  const client_id = (input.client_id || "").trim();
201
224
  const client_secret = (input.client_secret || "").trim();
@@ -220,11 +243,18 @@ export class OAuthService {
220
243
  const tokenTtlMs = resolveTokenTtlMs(input.expires_in, this.tokenTtlMs);
221
244
  const token = acg.mintAccessToken();
222
245
  const expiresAt = tokenTtlMs === null ? 0 : Date.now() + tokenTtlMs;
246
+ const resource = this.bindClientCredentialsResource(
247
+ acg.readResource(input.resource),
248
+ client_id
249
+ );
250
+ const scope = this.clientCredentialsScope(resource, input.scope);
223
251
  const tokenRecord: StoredOAuthToken = {
224
252
  token,
225
253
  grant: "client_credentials",
226
254
  channelEci: client_id,
227
255
  rootPicoId: stored.rootPicoId,
256
+ scope,
257
+ resource,
228
258
  expiresAt,
229
259
  createdAt: new Date().toISOString(),
230
260
  };
@@ -233,6 +263,9 @@ export class OAuthService {
233
263
  access_token: token,
234
264
  token_type: "Bearer",
235
265
  };
266
+ if (scope) {
267
+ response.scope = scope;
268
+ }
236
269
  if (tokenTtlMs !== null) {
237
270
  response.expires_in = Math.floor(tokenTtlMs / 1000);
238
271
  }
@@ -286,7 +319,7 @@ export class OAuthService {
286
319
  if ((record.grant || "client_credentials") !== "authorization_code") {
287
320
  return null;
288
321
  }
289
- if (!record.rootPicoId) {
322
+ if (!record.rootPicoId || !this.acceptsSkyResource(record.resource)) {
290
323
  return null;
291
324
  }
292
325
  return { rootPicoId: record.rootPicoId, scope: record.scope };
@@ -308,11 +341,38 @@ export class OAuthService {
308
341
  await this.deps.db.del([OAUTH_TOKEN_PREFIX, trimmed]);
309
342
  return false;
310
343
  }
311
- const grant = record.grant || "client_credentials";
312
- if (grant === "authorization_code") {
313
- return isChannelUnderRoot(this.deps.pf, channelEci, record.rootPicoId);
344
+ if (!this.acceptsSkyResource(record.resource)) {
345
+ return false;
314
346
  }
315
- return record.channelEci === channelEci;
347
+ return this.grantAllowsChannel(record, channelEci);
348
+ }
349
+
350
+ /** Channel MCP audience only. A Sky token, or a token for another ECI, is rejected. */
351
+ async validateMcpBearerToken(
352
+ token: string,
353
+ channelEci: string
354
+ ): Promise<boolean> {
355
+ return (await this.resolveMcpChannelToken(token, channelEci)) !== null;
356
+ }
357
+
358
+ /**
359
+ * A live token whose resource is exactly this channel's MCP URL.
360
+ * Scope is not checked here; the route answers 403 when a call needs a scope
361
+ * the token does not have.
362
+ */
363
+ async resolveMcpChannelToken(
364
+ token: string,
365
+ channelEci: string
366
+ ): Promise<{ scope: string; rootPicoId: string } | null> {
367
+ return this.resolveMcpToken(token, channelEci, "channel");
368
+ }
369
+
370
+ /** Authorization-code token whose resource is exactly this mesh MCP URL. */
371
+ async resolveMcpMeshToken(
372
+ token: string,
373
+ channelEci: string
374
+ ): Promise<{ scope: string; rootPicoId: string } | null> {
375
+ return this.resolveMcpToken(token, channelEci, "mesh");
316
376
  }
317
377
 
318
378
  listApps(rootPicoId: string): Promise<acg.OAuthAppSummary[]> {
@@ -334,15 +394,34 @@ export class OAuthService {
334
394
  return acg.revokeApp(this.acgContext(), rootPicoId, clientId);
335
395
  }
336
396
 
337
- getAppForAuthorize(params: acg.AuthorizeParams): Promise<acg.StoredOAuthApp> {
338
- return acg.getAppForAuthorize(this.acgContext(), params);
397
+ async getAppForAuthorize(
398
+ params: acg.AuthorizeParams
399
+ ): Promise<acg.ResolvedAuthorizeClient> {
400
+ const resolved = await acg.getAppForAuthorize(this.acgContext(), params);
401
+ if (!resolved.cimd && params.resource !== undefined) {
402
+ params.resource = this.bindAcgResource(params.resource, resolved.app.rootPicoId);
403
+ }
404
+ return resolved;
405
+ }
406
+
407
+ meshOAuthEnabled(rootPicoId: string): boolean {
408
+ return rootHasOAuthMeshRuleset(this.deps.pf, rootPicoId);
409
+ }
410
+
411
+ /** Canonical resource for the consent form, once the mesh is known. */
412
+ bindAuthorizeResource(resource: string | undefined, rootPicoId: string): string | undefined {
413
+ return this.bindAcgResource(resource, rootPicoId);
339
414
  }
340
415
 
341
416
  approveAuthorization(
342
417
  session: { accountId: string; rootPicoId: string },
343
418
  params: acg.ApproveParams
344
419
  ): Promise<string> {
345
- return acg.approveAuthorization(this.acgContext(), session, params);
420
+ const resource = this.bindAcgResource(params.resource, session.rootPicoId);
421
+ return acg.approveAuthorization(this.acgContext(), session, {
422
+ ...params,
423
+ resource,
424
+ });
346
425
  }
347
426
 
348
427
  authorizationCodeGrant(input: {
@@ -352,8 +431,12 @@ export class OAuthService {
352
431
  client_id?: string;
353
432
  client_secret?: string;
354
433
  code_verifier?: string;
434
+ resource?: string;
355
435
  }): Promise<OAuthTokenResponse> {
356
- return acg.authorizationCodeGrant(this.acgContext(), input);
436
+ return acg.authorizationCodeGrant(this.acgContext(), {
437
+ ...input,
438
+ resource: this.presentedResource(input.resource),
439
+ });
357
440
  }
358
441
 
359
442
  refreshTokenGrant(input: {
@@ -361,8 +444,12 @@ export class OAuthService {
361
444
  refresh_token?: string;
362
445
  client_id?: string;
363
446
  client_secret?: string;
447
+ resource?: string;
364
448
  }): Promise<OAuthTokenResponse> {
365
- return acg.refreshTokenGrant(this.acgContext(), input);
449
+ return acg.refreshTokenGrant(this.acgContext(), {
450
+ ...input,
451
+ resource: this.presentedResource(input.resource),
452
+ });
366
453
  }
367
454
 
368
455
  tokenGrant(body: Record<string, unknown>): Promise<OAuthTokenResponse> {
@@ -381,6 +468,7 @@ export class OAuthService {
381
468
  db: this.deps.db,
382
469
  pf: this.deps.pf,
383
470
  tokenTtlMs: this.tokenTtlMs,
471
+ loadClientMetadata: (url) => this.loadClientMetadata(url),
384
472
  putAccessToken: async (record) => {
385
473
  const tokenRecord: StoredOAuthToken = {
386
474
  token: record.token,
@@ -389,6 +477,7 @@ export class OAuthService {
389
477
  appId: record.appId,
390
478
  accountId: record.accountId,
391
479
  scope: record.scope,
480
+ resource: record.resource,
392
481
  expiresAt: record.expiresAt,
393
482
  createdAt: new Date().toISOString(),
394
483
  };
@@ -397,6 +486,149 @@ export class OAuthService {
397
486
  };
398
487
  }
399
488
 
489
+ private grantAllowsChannel(record: StoredOAuthToken, channelEci: string): boolean {
490
+ const grant = record.grant || "client_credentials";
491
+ if (grant === "authorization_code") {
492
+ return isChannelUnderRoot(this.deps.pf, channelEci, record.rootPicoId);
493
+ }
494
+ return record.channelEci === channelEci;
495
+ }
496
+
497
+ /** No resource is a legacy Sky token. A recorded resource must be this engine's /sky. */
498
+ private acceptsSkyResource(resource: string | undefined): boolean {
499
+ if (!resource) {
500
+ return true;
501
+ }
502
+ const base = this.baseUrl();
503
+ return !!base && resource === skyResourceUrl(base);
504
+ }
505
+
506
+ private baseUrl(): string | undefined {
507
+ const raw = this.deps.getBaseUrl?.();
508
+ const base = raw && raw.trim();
509
+ return base || undefined;
510
+ }
511
+
512
+ private requireBaseUrl(): string {
513
+ const base = this.baseUrl();
514
+ if (!base) {
515
+ throw new OAuthError("Engine base URL is not configured", "invalid_target", 400);
516
+ }
517
+ return base;
518
+ }
519
+
520
+ /** Canonical form of a presented resource, or undefined when the client omitted it. */
521
+ private presentedResource(resource: string | undefined): string | undefined {
522
+ const value = acg.readResource(resource);
523
+ if (!value) {
524
+ return undefined;
525
+ }
526
+ return this.canonicalResource(value);
527
+ }
528
+
529
+ private canonicalResource(resource: string): string {
530
+ const base = this.requireBaseUrl();
531
+ return canonicalResourceUrl(base, classifyResource(base, resource));
532
+ }
533
+
534
+ /**
535
+ * A channel MCP client that omits scope receives query and event access.
536
+ * A named scope must be one of the advertised MCP scopes. Sky tokens do
537
+ * not gain MCP scopes.
538
+ */
539
+ private clientCredentialsScope(
540
+ resource: string | undefined,
541
+ requested: string | undefined
542
+ ): string | undefined {
543
+ const base = this.baseUrl();
544
+ let mcp = false;
545
+ let channel = false;
546
+ if (resource && base) {
547
+ const target = classifyResource(base, resource);
548
+ if (target.kind === "mcp") {
549
+ mcp = true;
550
+ channel = target.surface === "channel";
551
+ }
552
+ }
553
+ const asked = requested !== undefined ? String(requested).trim() : "";
554
+ if (asked) {
555
+ return mcp ? assertMcpScopes(asked) : asked.split(/\s+/).filter(Boolean).join(" ") || undefined;
556
+ }
557
+ if (channel) {
558
+ return MCP_CHANNEL_SCOPE;
559
+ }
560
+ return undefined;
561
+ }
562
+
563
+ private bindClientCredentialsResource(
564
+ resource: string | undefined,
565
+ clientId: string
566
+ ): string | undefined {
567
+ if (!resource) {
568
+ return undefined;
569
+ }
570
+ const base = this.requireBaseUrl();
571
+ const target = classifyResource(base, resource);
572
+ if (target.kind === "mcp") {
573
+ if (target.surface !== "channel" || target.eci !== clientId) {
574
+ throw new OAuthError("Invalid resource", "invalid_target", 400);
575
+ }
576
+ }
577
+ return canonicalResourceUrl(base, target);
578
+ }
579
+
580
+ private bindAcgResource(
581
+ resource: string | undefined,
582
+ rootPicoId: string
583
+ ): string | undefined {
584
+ if (!resource) {
585
+ return undefined;
586
+ }
587
+ const base = this.requireBaseUrl();
588
+ const target = classifyResource(base, resource);
589
+ if (target.kind === "mcp") {
590
+ try {
591
+ this.lookupChannelReadOnly(target.eci);
592
+ } catch (_e) {
593
+ throw new OAuthError("Invalid resource", "invalid_target", 400);
594
+ }
595
+ if (!isChannelUnderRoot(this.deps.pf, target.eci, rootPicoId)) {
596
+ throw new OAuthError("Invalid resource", "invalid_target", 400);
597
+ }
598
+ }
599
+ return canonicalResourceUrl(base, target);
600
+ }
601
+
602
+ private async resolveMcpToken(
603
+ token: string,
604
+ channelEci: string,
605
+ surface: "channel" | "mesh"
606
+ ): Promise<{ scope: string; rootPicoId: string } | null> {
607
+ const trimmed = (token || "").trim();
608
+ if (!trimmed || !channelEci) {
609
+ return null;
610
+ }
611
+ const record = await this.getTokenRecord(trimmed);
612
+ if (!record || !record.resource || !record.rootPicoId) {
613
+ return null;
614
+ }
615
+ if (surface === "mesh" && (record.grant || "client_credentials") !== "authorization_code") {
616
+ return null;
617
+ }
618
+ if (record.expiresAt !== 0 && record.expiresAt < Date.now()) {
619
+ await this.deps.db.del([OAUTH_TOKEN_PREFIX, trimmed]);
620
+ return null;
621
+ }
622
+ const base = this.baseUrl();
623
+ if (!base || record.resource !== mcpResourceUrl(base, channelEci, surface)) {
624
+ return null;
625
+ }
626
+ if (!this.grantAllowsChannel(record, channelEci)) {
627
+ return null;
628
+ }
629
+ return { scope: record.scope || "", rootPicoId: record.rootPicoId };
630
+ }
631
+
400
632
  private async getTokenRecord(token: string): Promise<StoredOAuthToken | null> {
401
633
  return dbGet<StoredOAuthToken>(this.deps.db, [OAUTH_TOKEN_PREFIX, token]);
402
634
  }