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/oauth/acg.ts CHANGED
@@ -1,5 +1,11 @@
1
1
  import * as crypto from "crypto";
2
2
  import { PicoDb, PicoDbKey, PicoFramework } from "pico-framework";
3
+ import {
4
+ isClientMetadataUrl,
5
+ rejectsAsMetadataUrl,
6
+ safeDisplayUrl,
7
+ type ClientMetadataDocument,
8
+ } from "./cimd";
3
9
  import { OAuthError } from "./errors";
4
10
  import { rootHasOAuthMeshRuleset } from "./meshOAuth";
5
11
 
@@ -14,10 +20,13 @@ export interface OAuthTokenResponse {
14
20
  export const OAUTH_APP_PREFIX = "oauth-app";
15
21
  export const OAUTH_AUTH_CODE_PREFIX = "oauth-auth-code";
16
22
  export const OAUTH_REFRESH_PREFIX = "oauth-refresh";
23
+ export const OAUTH_REFRESH_USED_PREFIX = "oauth-refresh-used";
17
24
 
18
25
  export const DEFAULT_ACG_SCOPE = "mesh";
19
26
  export const AUTH_CODE_TTL_MS = 10 * 60 * 1000;
20
27
  export const REFRESH_TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000;
28
+ /** Public clients (no secret) get a short access token and refresh with the rotated token. */
29
+ export const PUBLIC_ACCESS_TTL_MS = 60 * 60 * 1000;
21
30
 
22
31
  export interface StoredOAuthApp {
23
32
  clientId: string;
@@ -57,6 +66,7 @@ interface StoredAuthCode {
57
66
  scope: string;
58
67
  codeChallenge: string;
59
68
  codeChallengeMethod: string;
69
+ resource?: string;
60
70
  expiresAt: number;
61
71
  createdAt: string;
62
72
  }
@@ -69,10 +79,19 @@ interface StoredRefreshToken {
69
79
  appId: string;
70
80
  accountId: string;
71
81
  scope: string;
82
+ resource?: string;
83
+ /** Shared by every refresh token descended from one authorization. */
84
+ familyId?: string;
72
85
  expiresAt: number;
73
86
  createdAt: string;
74
87
  }
75
88
 
89
+ interface UsedRefreshToken {
90
+ familyId: string;
91
+ clientId: string;
92
+ expiresAt: number;
93
+ }
94
+
76
95
  export interface AuthorizeParams {
77
96
  client_id: string;
78
97
  redirect_uri: string;
@@ -81,6 +100,8 @@ export interface AuthorizeParams {
81
100
  scope?: string;
82
101
  code_challenge: string;
83
102
  code_challenge_method: string;
103
+ /** RFC 8707 resource, already a single absolute URI. Canonicalized by the service. */
104
+ resource?: string;
84
105
  }
85
106
 
86
107
  export interface ApproveParams {
@@ -90,9 +111,26 @@ export interface ApproveParams {
90
111
  scope?: string;
91
112
  code_challenge: string;
92
113
  code_challenge_method: string;
114
+ resource?: string;
93
115
  approved: boolean;
94
116
  }
95
117
 
118
+ /** One resource parameter, or none. An empty value is the same as omitting it. */
119
+ export function readResource(value: unknown): string | undefined {
120
+ if (value === undefined || value === null || value === "") {
121
+ return undefined;
122
+ }
123
+ if (Array.isArray(value)) {
124
+ throw new OAuthError(
125
+ "resource must be a single absolute URI",
126
+ "invalid_target",
127
+ 400
128
+ );
129
+ }
130
+ const resource = String(value).trim();
131
+ return resource || undefined;
132
+ }
133
+
96
134
  export function parseApproveBody(body: Record<string, unknown>): ApproveParams {
97
135
  return {
98
136
  client_id: String(body.client_id || "").trim(),
@@ -101,6 +139,7 @@ export function parseApproveBody(body: Record<string, unknown>): ApproveParams {
101
139
  scope: body.scope !== undefined ? String(body.scope) : undefined,
102
140
  code_challenge: String(body.code_challenge || "").trim(),
103
141
  code_challenge_method: String(body.code_challenge_method || "S256").trim(),
142
+ resource: readResource(body.resource),
104
143
  approved:
105
144
  body.approved === true ||
106
145
  String(body.approved ?? "")
@@ -120,7 +159,25 @@ export interface AcgContext {
120
159
  accountId: string;
121
160
  scope: string;
122
161
  expiresAt: number;
162
+ resource?: string;
123
163
  }) => Promise<void>;
164
+ /** Fetch a Client ID Metadata Document. Required when client_id is an https URL. */
165
+ loadClientMetadata?: (url: string) => Promise<ClientMetadataDocument>;
166
+ }
167
+
168
+ export interface ConsentClient {
169
+ name: string;
170
+ /** Host of a URL client_id. Absent for a pre-registered app. */
171
+ clientIdHost?: string;
172
+ logoUri?: string;
173
+ clientUri?: string;
174
+ meshName?: string;
175
+ }
176
+
177
+ export interface ResolvedAuthorizeClient {
178
+ app: StoredOAuthApp;
179
+ cimd: boolean;
180
+ consent: ConsentClient;
124
181
  }
125
182
 
126
183
  export function parseAuthorizeQuery(query: Record<string, unknown>): AuthorizeParams {
@@ -140,8 +197,8 @@ export function parseAuthorizeQuery(query: Record<string, unknown>): AuthorizePa
140
197
  if (response_type !== "code") {
141
198
  throw new OAuthError("Unsupported response_type", "unsupported_response_type", 400);
142
199
  }
143
- if (!["S256", "plain"].includes(code_challenge_method)) {
144
- throw new OAuthError("Unsupported code_challenge_method", "invalid_request", 400);
200
+ if (code_challenge_method !== "S256") {
201
+ throw new OAuthError("PKCE S256 is required", "invalid_request", 400);
145
202
  }
146
203
  return {
147
204
  client_id,
@@ -151,6 +208,7 @@ export function parseAuthorizeQuery(query: Record<string, unknown>): AuthorizePa
151
208
  scope,
152
209
  code_challenge,
153
210
  code_challenge_method,
211
+ resource: readResource(query.resource),
154
212
  };
155
213
  }
156
214
 
@@ -229,7 +287,17 @@ export async function revokeApp(
229
287
  export async function getAppForAuthorize(
230
288
  ctx: AcgContext,
231
289
  params: AuthorizeParams
232
- ): Promise<StoredOAuthApp> {
290
+ ): Promise<ResolvedAuthorizeClient> {
291
+ if (isClientMetadataUrl(params.client_id)) {
292
+ return resolveCimdClient(ctx, params);
293
+ }
294
+ if (rejectsAsMetadataUrl(params.client_id)) {
295
+ throw new OAuthError(
296
+ "client_id must be an https URL without a fragment or userinfo",
297
+ "invalid_client",
298
+ 401
299
+ );
300
+ }
233
301
  const app = await getApp(ctx, params.client_id);
234
302
  if (!app) {
235
303
  throw new OAuthError("Unknown client", "invalid_client", 401);
@@ -241,10 +309,14 @@ export async function getAppForAuthorize(
241
309
  if (app.publicClient && !params.code_challenge) {
242
310
  throw new OAuthError("PKCE code_challenge is required", "invalid_request", 400);
243
311
  }
244
- return app;
312
+ return { app, cimd: false, consent: { name: app.name } };
245
313
  }
246
314
 
247
- export function renderConsentHtml(app: StoredOAuthApp, params: AuthorizeParams): string {
315
+ export function renderConsentHtml(
316
+ app: StoredOAuthApp,
317
+ params: AuthorizeParams,
318
+ client?: ConsentClient
319
+ ): string {
248
320
  const esc = escapeHtml;
249
321
  const fields = [
250
322
  ["client_id", params.client_id],
@@ -252,6 +324,7 @@ export function renderConsentHtml(app: StoredOAuthApp, params: AuthorizeParams):
252
324
  ["scope", params.scope || DEFAULT_ACG_SCOPE],
253
325
  ["code_challenge", params.code_challenge],
254
326
  ["code_challenge_method", params.code_challenge_method],
327
+ ...(params.resource ? [["resource", params.resource] as [string, string]] : []),
255
328
  ...(params.state !== undefined ? [["state", params.state] as [string, string]] : []),
256
329
  ];
257
330
  const hidden = fields
@@ -264,7 +337,7 @@ export function renderConsentHtml(app: StoredOAuthApp, params: AuthorizeParams):
264
337
  <html lang="en">
265
338
  <head>
266
339
  <meta charset="utf-8"/>
267
- <title>Authorize ${esc(app.name)}</title>
340
+ <title>Authorize ${esc(client?.name || app.name)}</title>
268
341
  <style>
269
342
  body { font-family: system-ui, sans-serif; max-width: 36rem; margin: 3rem auto; padding: 0 1rem; }
270
343
  .card { border: 1px solid #ddd; border-radius: 8px; padding: 1.25rem; }
@@ -277,8 +350,12 @@ export function renderConsentHtml(app: StoredOAuthApp, params: AuthorizeParams):
277
350
  <body>
278
351
  <div class="card">
279
352
  <h1>Authorize application</h1>
280
- <p><strong>${esc(app.name)}</strong> is requesting access to this pico mesh.</p>
281
- <p class="muted">Scope: <code>${esc(params.scope || DEFAULT_ACG_SCOPE)}</code> (read and control this mesh via /sky/*)</p>
353
+ ${consentLogo(client)}
354
+ <p><strong>${esc(client?.name || app.name)}</strong> is requesting access to <strong>${esc(client?.meshName || "this mesh")}</strong>.</p>
355
+ <p class="muted">Client: <code>${esc(client?.clientIdHost || app.clientId)}</code></p>
356
+ ${consentLink(client)}
357
+ <p class="muted">Scopes: ${scopeCodes(params.scope)}</p>
358
+ ${params.resource ? `<p class="muted">Resource: <code>${esc(params.resource)}</code></p>` : ""}
282
359
  <p class="muted">Redirect: <code>${esc(params.redirect_uri)}</code></p>
283
360
  <form method="POST" action="/oauth/approve">
284
361
  ${hidden}
@@ -302,7 +379,10 @@ export async function approveAuthorization(
302
379
  session: { accountId: string; rootPicoId: string },
303
380
  params: ApproveParams
304
381
  ): Promise<string> {
305
- const app = await getAppForAuthorize(ctx, {
382
+ if (params.code_challenge_method !== "S256") {
383
+ throw new OAuthError("PKCE S256 is required", "invalid_request", 400);
384
+ }
385
+ const resolved = await getAppForAuthorize(ctx, {
306
386
  client_id: params.client_id,
307
387
  redirect_uri: params.redirect_uri,
308
388
  response_type: "code",
@@ -311,7 +391,11 @@ export async function approveAuthorization(
311
391
  code_challenge: params.code_challenge,
312
392
  code_challenge_method: params.code_challenge_method,
313
393
  });
314
- if (app.rootPicoId !== session.rootPicoId) {
394
+ let app = resolved.app;
395
+ if (resolved.cimd) {
396
+ assertMeshOAuthRoot(ctx, session.rootPicoId);
397
+ app = { ...app, rootPicoId: session.rootPicoId };
398
+ } else if (app.rootPicoId !== session.rootPicoId) {
315
399
  throw new OAuthError("Not authorized for this mesh", "access_denied", 403);
316
400
  }
317
401
  if (!params.approved) {
@@ -327,6 +411,7 @@ export async function approveAuthorization(
327
411
  scope: normalizeScope(params.scope || DEFAULT_ACG_SCOPE),
328
412
  codeChallenge: params.code_challenge,
329
413
  codeChallengeMethod: params.code_challenge_method,
414
+ resource: params.resource,
330
415
  expiresAt: Date.now() + AUTH_CODE_TTL_MS,
331
416
  createdAt: new Date().toISOString(),
332
417
  };
@@ -343,6 +428,7 @@ export async function authorizationCodeGrant(
343
428
  client_id?: string;
344
429
  client_secret?: string;
345
430
  code_verifier?: string;
431
+ resource?: string;
346
432
  }
347
433
  ): Promise<OAuthTokenResponse & { refresh_token?: string; scope?: string }> {
348
434
  const code = (input.code || "").trim();
@@ -367,19 +453,18 @@ export async function authorizationCodeGrant(
367
453
  ) {
368
454
  throw new OAuthError("Authorization code mismatch", "invalid_grant", 400);
369
455
  }
370
- const app = await getApp(ctx, client_id);
371
- if (!app) {
372
- throw new OAuthError("Invalid client", "invalid_client", 401);
373
- }
456
+ const app = await clientForGrant(ctx, client_id, redirect_uri, stored.rootPicoId);
374
457
  await assertClientAuth(app, client_secret);
375
458
  if (!verifyPkce(code_verifier, stored.codeChallenge, stored.codeChallengeMethod)) {
376
459
  throw new OAuthError("Invalid PKCE verifier", "invalid_grant", 400);
377
460
  }
461
+ assertResourceBinding(stored.resource, input.resource);
378
462
  await ctx.db.del([OAUTH_AUTH_CODE_PREFIX, code]);
379
463
  return mintAcgTokens(ctx, {
380
464
  app,
381
465
  accountId: stored.accountId,
382
466
  scope: stored.scope,
467
+ resource: stored.resource,
383
468
  });
384
469
  }
385
470
 
@@ -390,6 +475,7 @@ export async function refreshTokenGrant(
390
475
  refresh_token?: string;
391
476
  client_id?: string;
392
477
  client_secret?: string;
478
+ resource?: string;
393
479
  }
394
480
  ): Promise<OAuthTokenResponse & { refresh_token?: string; scope?: string }> {
395
481
  const refresh_token = (input.refresh_token || "").trim();
@@ -403,33 +489,108 @@ export async function refreshTokenGrant(
403
489
  refresh_token,
404
490
  ]);
405
491
  if (!stored || stored.clientId !== client_id) {
492
+ if (!stored) {
493
+ await rejectReusedRefresh(ctx, refresh_token, client_id);
494
+ }
406
495
  throw new OAuthError("Invalid refresh token", "invalid_grant", 400);
407
496
  }
408
497
  if (stored.expiresAt < Date.now()) {
409
498
  await ctx.db.del([OAUTH_REFRESH_PREFIX, refresh_token]);
410
499
  throw new OAuthError("Refresh token expired", "invalid_grant", 400);
411
500
  }
412
- const app = await getApp(ctx, client_id);
413
- if (!app) {
414
- throw new OAuthError("Invalid client", "invalid_client", 401);
415
- }
501
+ const app = await clientForGrant(ctx, client_id, undefined, stored.rootPicoId);
416
502
  await assertClientAuth(app, client_secret);
503
+ assertResourceBinding(stored.resource, input.resource);
504
+ const familyId = stored.familyId || crypto.randomBytes(16).toString("base64url");
417
505
  await ctx.db.del([OAUTH_REFRESH_PREFIX, refresh_token]);
418
506
  await ctx.db.del(["oauth-token", stored.accessToken] as PicoDbKey);
419
- return mintAcgTokens(ctx, {
507
+ const minted = await mintAcgTokens(ctx, {
420
508
  app,
421
509
  accountId: stored.accountId,
422
510
  scope: stored.scope,
511
+ resource: stored.resource,
512
+ familyId,
423
513
  });
514
+ const refreshExpiresAt = Date.now() + REFRESH_TOKEN_TTL_MS;
515
+ await rememberRefreshUse(ctx, refresh_token, {
516
+ familyId,
517
+ clientId: client_id,
518
+ expiresAt: refreshExpiresAt,
519
+ });
520
+ await extendRefreshUses(ctx, familyId, refreshExpiresAt);
521
+ return minted;
522
+ }
523
+
524
+ /**
525
+ * A refresh token that was already rotated is a replay. Revoke every token in
526
+ * its family so a stolen copy cannot keep the grant alive.
527
+ */
528
+ async function rejectReusedRefresh(
529
+ ctx: AcgContext,
530
+ refreshToken: string,
531
+ clientId: string
532
+ ): Promise<void> {
533
+ const used = await dbGet<UsedRefreshToken>(ctx.db, [
534
+ OAUTH_REFRESH_USED_PREFIX,
535
+ refreshToken,
536
+ ]);
537
+ if (!used || used.clientId !== clientId || used.expiresAt < Date.now()) {
538
+ return;
539
+ }
540
+ await revokeRefreshFamily(ctx, used.familyId);
541
+ }
542
+
543
+ async function revokeRefreshFamily(ctx: AcgContext, familyId: string): Promise<void> {
544
+ const refreshes = await dbList<StoredRefreshToken>(ctx.db, [OAUTH_REFRESH_PREFIX]);
545
+ for (const row of refreshes) {
546
+ if (row.value.familyId !== familyId) {
547
+ continue;
548
+ }
549
+ await ctx.db.del(row.key);
550
+ if (row.value.accessToken) {
551
+ await ctx.db.del(["oauth-token", row.value.accessToken] as PicoDbKey);
552
+ }
553
+ }
554
+ }
555
+
556
+ async function rememberRefreshUse(
557
+ ctx: AcgContext,
558
+ refreshToken: string,
559
+ used: UsedRefreshToken
560
+ ): Promise<void> {
561
+ await ctx.db.put([OAUTH_REFRESH_USED_PREFIX, refreshToken], used);
562
+ }
563
+
564
+ async function extendRefreshUses(
565
+ ctx: AcgContext,
566
+ familyId: string,
567
+ expiresAt: number
568
+ ): Promise<void> {
569
+ const rows = await dbList<UsedRefreshToken>(ctx.db, [OAUTH_REFRESH_USED_PREFIX]);
570
+ for (const row of rows) {
571
+ if (row.value.familyId !== familyId || row.value.expiresAt >= expiresAt) {
572
+ continue;
573
+ }
574
+ await ctx.db.put(row.key, { ...row.value, expiresAt });
575
+ }
424
576
  }
425
577
 
426
578
  async function mintAcgTokens(
427
579
  ctx: AcgContext,
428
- input: { app: StoredOAuthApp; accountId: string; scope: string }
580
+ input: {
581
+ app: StoredOAuthApp;
582
+ accountId: string;
583
+ scope: string;
584
+ resource?: string;
585
+ familyId?: string;
586
+ }
429
587
  ): Promise<OAuthTokenResponse & { refresh_token?: string; scope?: string }> {
430
588
  const access_token = mintAccessToken();
431
589
  const refresh_token = mintRefreshToken();
432
- const expiresAt = Date.now() + ctx.tokenTtlMs;
590
+ const accessTtlMs = input.app.publicClient
591
+ ? Math.min(ctx.tokenTtlMs, PUBLIC_ACCESS_TTL_MS)
592
+ : ctx.tokenTtlMs;
593
+ const expiresAt = Date.now() + accessTtlMs;
433
594
  await ctx.putAccessToken({
434
595
  token: access_token,
435
596
  rootPicoId: input.app.rootPicoId,
@@ -437,6 +598,7 @@ async function mintAcgTokens(
437
598
  accountId: input.accountId,
438
599
  scope: input.scope,
439
600
  expiresAt,
601
+ resource: input.resource,
440
602
  });
441
603
  const refreshRecord: StoredRefreshToken = {
442
604
  refreshToken: refresh_token,
@@ -446,6 +608,8 @@ async function mintAcgTokens(
446
608
  appId: input.app.clientId,
447
609
  accountId: input.accountId,
448
610
  scope: input.scope,
611
+ resource: input.resource,
612
+ familyId: input.familyId || crypto.randomBytes(16).toString("base64url"),
449
613
  expiresAt: Date.now() + REFRESH_TOKEN_TTL_MS,
450
614
  createdAt: new Date().toISOString(),
451
615
  };
@@ -453,7 +617,7 @@ async function mintAcgTokens(
453
617
  return {
454
618
  access_token,
455
619
  token_type: "Bearer",
456
- expires_in: Math.floor(ctx.tokenTtlMs / 1000),
620
+ expires_in: Math.floor(accessTtlMs / 1000),
457
621
  refresh_token,
458
622
  scope: input.scope,
459
623
  };
@@ -469,6 +633,99 @@ function assertMeshOAuthRoot(ctx: AcgContext, rootPicoId: string): void {
469
633
  }
470
634
  }
471
635
 
636
+ async function resolveCimdClient(
637
+ ctx: AcgContext,
638
+ params: AuthorizeParams
639
+ ): Promise<ResolvedAuthorizeClient> {
640
+ if (!ctx.loadClientMetadata) {
641
+ throw new OAuthError("Invalid client", "invalid_client", 401);
642
+ }
643
+ if (!params.code_challenge) {
644
+ throw new OAuthError("PKCE code_challenge is required", "invalid_request", 400);
645
+ }
646
+ const doc = await ctx.loadClientMetadata(params.client_id);
647
+ if (!doc.redirectUris.includes(params.redirect_uri)) {
648
+ throw new OAuthError("Invalid redirect_uri", "invalid_request", 400);
649
+ }
650
+ const app = cimdApp(doc);
651
+ return {
652
+ app,
653
+ cimd: true,
654
+ consent: {
655
+ name: doc.clientName,
656
+ clientIdHost: new URL(doc.clientId).host,
657
+ logoUri: doc.logoUri,
658
+ clientUri: doc.clientUri,
659
+ },
660
+ };
661
+ }
662
+
663
+ async function clientForGrant(
664
+ ctx: AcgContext,
665
+ clientId: string,
666
+ redirectUri: string | undefined,
667
+ rootPicoId: string
668
+ ): Promise<StoredOAuthApp> {
669
+ if (isClientMetadataUrl(clientId)) {
670
+ if (!ctx.loadClientMetadata) {
671
+ throw new OAuthError("Invalid client", "invalid_client", 401);
672
+ }
673
+ const doc = await ctx.loadClientMetadata(clientId);
674
+ if (redirectUri !== undefined && !doc.redirectUris.includes(redirectUri)) {
675
+ throw new OAuthError("Invalid redirect_uri", "invalid_grant", 400);
676
+ }
677
+ return { ...cimdApp(doc), rootPicoId };
678
+ }
679
+ if (rejectsAsMetadataUrl(clientId)) {
680
+ throw new OAuthError(
681
+ "client_id must be an https URL without a fragment or userinfo",
682
+ "invalid_client",
683
+ 401
684
+ );
685
+ }
686
+ const app = await getApp(ctx, clientId);
687
+ if (!app) {
688
+ throw new OAuthError("Invalid client", "invalid_client", 401);
689
+ }
690
+ return app;
691
+ }
692
+
693
+ function cimdApp(doc: ClientMetadataDocument): StoredOAuthApp {
694
+ return {
695
+ clientId: doc.clientId,
696
+ rootPicoId: "",
697
+ name: doc.clientName,
698
+ redirectUris: doc.redirectUris.slice(),
699
+ publicClient: true,
700
+ scopes: [DEFAULT_ACG_SCOPE],
701
+ createdAt: new Date().toISOString(),
702
+ };
703
+ }
704
+
705
+ function consentLogo(client?: ConsentClient): string {
706
+ const logo = safeDisplayUrl(client?.logoUri);
707
+ if (!logo) {
708
+ return "";
709
+ }
710
+ return `<img src="${escapeHtml(logo)}" alt="" referrerpolicy="no-referrer" style="max-height:48px;max-width:48px"/>`;
711
+ }
712
+
713
+ function consentLink(client?: ConsentClient): string {
714
+ const uri = safeDisplayUrl(client?.clientUri);
715
+ if (!uri) {
716
+ return "";
717
+ }
718
+ return `<p class="muted">Client page: <a href="${escapeHtml(uri)}" rel="noopener noreferrer">${escapeHtml(uri)}</a></p>`;
719
+ }
720
+
721
+ function scopeCodes(scope: string | undefined): string {
722
+ const raw = (scope || DEFAULT_ACG_SCOPE).trim() || DEFAULT_ACG_SCOPE;
723
+ return raw
724
+ .split(/\s+/)
725
+ .map((item) => `<code>${escapeHtml(item)}</code>`)
726
+ .join(" ");
727
+ }
728
+
472
729
  async function getApp(
473
730
  ctx: AcgContext,
474
731
  clientId: string
@@ -531,9 +788,6 @@ function verifyPkce(
531
788
  challenge: string,
532
789
  method: string
533
790
  ): boolean {
534
- if (method === "plain") {
535
- return verifier === challenge;
536
- }
537
791
  if (method === "S256") {
538
792
  const digest = crypto
539
793
  .createHash("sha256")
@@ -566,6 +820,16 @@ function redirectWithError(
566
820
  return url.toString();
567
821
  }
568
822
 
823
+ function assertResourceBinding(stored: string | undefined, presented: string | undefined): void {
824
+ if ((stored || undefined) !== (presented || undefined)) {
825
+ throw new OAuthError(
826
+ "resource does not match the authorization",
827
+ "invalid_target",
828
+ 400
829
+ );
830
+ }
831
+ }
832
+
569
833
  function normalizeScope(scope: string): string {
570
834
  const trimmed = (scope || DEFAULT_ACG_SCOPE).trim();
571
835
  return trimmed || DEFAULT_ACG_SCOPE;