@kya-os/mcp-i-cloudflare 1.6.44 → 1.6.46

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 (59) hide show
  1. package/dist/adapter.d.ts.map +1 -1
  2. package/dist/adapter.js +72 -53
  3. package/dist/adapter.js.map +1 -1
  4. package/dist/agent.d.ts.map +1 -1
  5. package/dist/agent.js +81 -48
  6. package/dist/agent.js.map +1 -1
  7. package/dist/app.d.ts.map +1 -1
  8. package/dist/app.js +53 -42
  9. package/dist/app.js.map +1 -1
  10. package/dist/config.d.ts.map +1 -1
  11. package/dist/config.js +55 -47
  12. package/dist/config.js.map +1 -1
  13. package/dist/constants/storage-keys.d.ts +6 -0
  14. package/dist/constants/storage-keys.d.ts.map +1 -1
  15. package/dist/constants/storage-keys.js +6 -0
  16. package/dist/constants/storage-keys.js.map +1 -1
  17. package/dist/helpers/env-mapper.d.ts.map +1 -1
  18. package/dist/helpers/env-mapper.js +70 -34
  19. package/dist/helpers/env-mapper.js.map +1 -1
  20. package/dist/index.js +1 -1
  21. package/dist/index.js.map +1 -1
  22. package/dist/providers/storage.d.ts +1 -1
  23. package/dist/providers/storage.d.ts.map +1 -1
  24. package/dist/providers/storage.js +6 -4
  25. package/dist/providers/storage.js.map +1 -1
  26. package/dist/runtime/oauth-handler.d.ts.map +1 -1
  27. package/dist/runtime/oauth-handler.js +34 -29
  28. package/dist/runtime/oauth-handler.js.map +1 -1
  29. package/dist/runtime.d.ts +4 -2
  30. package/dist/runtime.d.ts.map +1 -1
  31. package/dist/runtime.js +12 -7
  32. package/dist/runtime.js.map +1 -1
  33. package/dist/server.js +8 -8
  34. package/dist/server.js.map +1 -1
  35. package/dist/services/admin.service.d.ts.map +1 -1
  36. package/dist/services/admin.service.js +21 -17
  37. package/dist/services/admin.service.js.map +1 -1
  38. package/dist/services/consent-config.service.d.ts.map +1 -1
  39. package/dist/services/consent-config.service.js +7 -5
  40. package/dist/services/consent-config.service.js.map +1 -1
  41. package/dist/services/consent.service.d.ts.map +1 -1
  42. package/dist/services/consent.service.js +86 -65
  43. package/dist/services/consent.service.js.map +1 -1
  44. package/dist/services/delegation.service.d.ts.map +1 -1
  45. package/dist/services/delegation.service.js +32 -32
  46. package/dist/services/delegation.service.js.map +1 -1
  47. package/dist/services/proof-batch-queue.d.ts +1 -1
  48. package/dist/services/proof-batch-queue.d.ts.map +1 -1
  49. package/dist/services/proof-batch-queue.js +15 -13
  50. package/dist/services/proof-batch-queue.js.map +1 -1
  51. package/dist/services/proof.service.d.ts +15 -0
  52. package/dist/services/proof.service.d.ts.map +1 -1
  53. package/dist/services/proof.service.js +96 -19
  54. package/dist/services/proof.service.js.map +1 -1
  55. package/dist/utils/consent-defaults.d.ts +100 -0
  56. package/dist/utils/consent-defaults.d.ts.map +1 -0
  57. package/dist/utils/consent-defaults.js +107 -0
  58. package/dist/utils/consent-defaults.js.map +1 -0
  59. package/package.json +3 -3
@@ -94,7 +94,7 @@ export class ConsentService {
94
94
  // ✅ CRITICAL: Fetch config from remote API
95
95
  const config = await this.getConfigFromRemoteAPI(projectId);
96
96
  if (!config?.proofing?.enabled) {
97
- console.log("[ConsentService] Proofing not enabled in remote config");
97
+ console.error("[ConsentService] Proofing not enabled in remote config");
98
98
  return; // Proofing not enabled
99
99
  }
100
100
  // Get identity (async - requires runtime to be initialized)
@@ -110,7 +110,7 @@ export class ConsentService {
110
110
  // Create audit service with fetched config
111
111
  this.auditService = new ConsentAuditService(new ProofService(config, this.runtime), auditLogger, proofGenerator, config, // ✅ Config fetched from remote API
112
112
  this.runtime);
113
- console.log("[ConsentService] Audit service initialized successfully");
113
+ console.error("[ConsentService] Audit service initialized successfully");
114
114
  }
115
115
  catch (error) {
116
116
  console.error("[ConsentService] Failed to initialize audit service:", error);
@@ -165,7 +165,7 @@ export class ConsentService {
165
165
  const runtimeIdentity = await this.runtime?.getIdentity();
166
166
  if (runtimeIdentity?.did) {
167
167
  identityConfig.serverDid = runtimeIdentity.did;
168
- console.log("[ConsentService] Populated serverDid from runtime identity");
168
+ console.error("[ConsentService] Populated serverDid from runtime identity");
169
169
  }
170
170
  }
171
171
  catch (error) {
@@ -209,7 +209,7 @@ export class ConsentService {
209
209
  const oauthKey = STORAGE_KEYS.oauthIdentity(oauthIdentity.provider, oauthIdentity.subject);
210
210
  const mappedUserDid = await this.env.DELEGATION_STORAGE.get(oauthKey, "text");
211
211
  if (mappedUserDid) {
212
- console.log("[ConsentService] Found persistent User DID from OAuth mapping:", {
212
+ console.error("[ConsentService] Found persistent User DID from OAuth mapping:", {
213
213
  provider: oauthIdentity.provider,
214
214
  userDid: mappedUserDid.substring(0, 20) + "...",
215
215
  });
@@ -269,7 +269,7 @@ export class ConsentService {
269
269
  await this.env.DELEGATION_STORAGE.put(userAgentKey, delegationToken, {
270
270
  expirationTtl: delegationTtl,
271
271
  });
272
- console.log("[ConsentService] 🔄 DELEGATION UPGRADE: Migrated consent-only delegation to user+agent scoped:", {
272
+ console.error("[ConsentService] 🔄 DELEGATION UPGRADE: Migrated consent-only delegation to user+agent scoped:", {
273
273
  sessionId: sessionId.substring(0, 8) + "...",
274
274
  userDid: userDid.substring(0, 20) + "...",
275
275
  agentDid: agentDid.substring(0, 20) + "...",
@@ -293,7 +293,7 @@ export class ConsentService {
293
293
  }),
294
294
  };
295
295
  await this.env.DELEGATION_STORAGE.put(sessionKey, JSON.stringify(sessionData), { expirationTtl: DEFAULT_SESSION_CACHE_TTL });
296
- console.log("[ConsentService] Session identity updated:", {
296
+ console.error("[ConsentService] Session identity updated:", {
297
297
  sessionId: sessionId.substring(0, 8) + "...",
298
298
  userDid: userDid.substring(0, 20) + "...",
299
299
  provider: oauthIdentity?.provider,
@@ -311,7 +311,7 @@ export class ConsentService {
311
311
  await this.env.DELEGATION_STORAGE.put(oauthKey, userDid, {
312
312
  expirationTtl: 90 * 24 * 60 * 60, // 90 days for persistent mapping
313
313
  });
314
- console.log("[ConsentService] Created OAuth → DID mapping:", {
314
+ console.error("[ConsentService] Created OAuth → DID mapping:", {
315
315
  provider: oauthIdentity.provider,
316
316
  userDid: userDid.substring(0, 20) + "...",
317
317
  });
@@ -342,7 +342,7 @@ export class ConsentService {
342
342
  const key = STORAGE_KEYS.userKeyPair(oauthIdentity.provider, oauthIdentity.subject);
343
343
  const stored = (await this.env.DELEGATION_STORAGE.get(key, "json"));
344
344
  if (stored) {
345
- console.log("[ConsentService] Found key pair in KV storage");
345
+ console.error("[ConsentService] Found key pair in KV storage");
346
346
  return stored;
347
347
  }
348
348
  }
@@ -383,7 +383,7 @@ export class ConsentService {
383
383
  // 1. Try existing lookup first
384
384
  const existingKeyPair = await this.getKeyPairForSession(sessionId, oauthIdentity);
385
385
  if (existingKeyPair) {
386
- console.log("[ConsentService] Found existing key pair for OAuth identity");
386
+ console.error("[ConsentService] Found existing key pair for OAuth identity");
387
387
  return existingKeyPair;
388
388
  }
389
389
  // 2. Check KV storage directly by OAuth identity
@@ -394,7 +394,7 @@ export class ConsentService {
394
394
  const key = STORAGE_KEYS.userKeyPair(oauthIdentity.provider, oauthIdentity.subject);
395
395
  const stored = (await this.env.DELEGATION_STORAGE.get(key, "json"));
396
396
  if (stored) {
397
- console.log("[ConsentService] Found key pair in KV storage");
397
+ console.error("[ConsentService] Found key pair in KV storage");
398
398
  return stored;
399
399
  }
400
400
  }
@@ -403,7 +403,7 @@ export class ConsentService {
403
403
  }
404
404
  }
405
405
  // 3. Generate new key pair
406
- console.log("[ConsentService] Generating new key pair for OAuth identity");
406
+ console.error("[ConsentService] Generating new key pair for OAuth identity");
407
407
  try {
408
408
  const crypto = new WebCryptoProvider();
409
409
  const rawKeyPair = await crypto.generateKeyPair();
@@ -426,13 +426,13 @@ export class ConsentService {
426
426
  await this.env.DELEGATION_STORAGE.put(key, JSON.stringify(keyPair), {
427
427
  expirationTtl: KEY_PAIR_TTL_SECONDS,
428
428
  });
429
- console.log("[ConsentService] Key pair persisted to KV storage");
429
+ console.error("[ConsentService] Key pair persisted to KV storage");
430
430
  }
431
431
  catch (persistError) {
432
432
  console.warn("[ConsentService] KV key pair persistence failed (non-fatal):", persistError);
433
433
  }
434
434
  }
435
- console.log("[ConsentService] Key pair generated:", {
435
+ console.error("[ConsentService] Key pair generated:", {
436
436
  did: did.substring(0, 30) + "...",
437
437
  keyId,
438
438
  });
@@ -496,7 +496,7 @@ export class ConsentService {
496
496
  const signature = base64urlEncodeFromBytes(signatureBytes);
497
497
  // Step 4: Complete the JWT
498
498
  const jwt = completeVCJWT(signingInput, signature);
499
- console.log("[ConsentService] VC issued successfully:", {
499
+ console.error("[ConsentService] VC issued successfully:", {
500
500
  issuerDid: keyPair.did.substring(0, 20) + "...",
501
501
  subjectDid: delegation.subjectDid.substring(0, 20) + "...",
502
502
  delegationId: delegation.id,
@@ -590,7 +590,7 @@ export class ConsentService {
590
590
  metrics: { totalMs: Date.now() - startTime },
591
591
  };
592
592
  }
593
- console.log("[ConsentService] verifyDelegationVC: JWT signature verified successfully");
593
+ console.error("[ConsentService] verifyDelegationVC: JWT signature verified successfully");
594
594
  }
595
595
  // Step 4: Run basic VC validation via DelegationCredentialVerifier
596
596
  // Skip signature verification since we already verified the JWT signature above
@@ -606,7 +606,7 @@ export class ConsentService {
606
606
  result.metrics.totalMs = Date.now() - startTime;
607
607
  }
608
608
  if (result.valid) {
609
- console.log("[ConsentService] verifyDelegationVC: VC verified successfully", {
609
+ console.error("[ConsentService] verifyDelegationVC: VC verified successfully", {
610
610
  issuer: vc.issuer,
611
611
  subject: vc.credentialSubject?.id,
612
612
  });
@@ -633,6 +633,15 @@ export class ConsentService {
633
633
  * @returns True if OAuth redirect is required
634
634
  */
635
635
  async isOAuthRequired(projectId, oauthIdentity, toolOAuthProvider, toolProtection) {
636
+ // Priority 0: Check for consent-only mode (authorization.type === 'none')
637
+ // Consent-only means delegation is required but NO OAuth provider is needed
638
+ if (toolProtection?.authorization?.type === "none") {
639
+ console.error("[ConsentService] Tool is consent-only mode (authorization.type=none), OAuth NOT required", {
640
+ projectId,
641
+ requiresDelegation: toolProtection.requiresDelegation,
642
+ });
643
+ return false;
644
+ }
636
645
  // If OAuth identity is already present, OAuth is not required
637
646
  if (oauthIdentity && oauthIdentity.provider && oauthIdentity.subject) {
638
647
  return false;
@@ -650,7 +659,7 @@ export class ConsentService {
650
659
  try {
651
660
  const resolvedProvider = await this.providerResolver.resolveProvider(toolProtection, projectId);
652
661
  if (resolvedProvider) {
653
- console.log("[ConsentService] OAuth required: ProviderResolver resolved provider", {
662
+ console.error("[ConsentService] OAuth required: ProviderResolver resolved provider", {
654
663
  projectId,
655
664
  provider: resolvedProvider,
656
665
  toolRequiresDelegation: toolProtection.requiresDelegation,
@@ -660,6 +669,11 @@ export class ConsentService {
660
669
  }
661
670
  }
662
671
  catch (error) {
672
+ // Check if this is ConsentOnlyModeError - not a real error
673
+ if (error instanceof Error && error.name === "ConsentOnlyModeError") {
674
+ console.error("[ConsentService] Tool is consent-only mode (ConsentOnlyModeError), OAuth NOT required", { projectId });
675
+ return false;
676
+ }
663
677
  // ProviderResolver failed - log but continue to fallback check
664
678
  console.warn("[ConsentService] ProviderResolver failed to resolve provider, falling back to project config check:", {
665
679
  projectId,
@@ -771,7 +785,7 @@ export class ConsentService {
771
785
  // Store state data securely in KV (10 minute TTL for OAuth flow)
772
786
  await oauthSecurityService.storeOAuthState(stateValue, stateData, 600);
773
787
  stateParam = stateValue;
774
- console.log("[ConsentService] 🔒 SECURITY EVENT: OAuth state stored securely:", {
788
+ console.error("[ConsentService] 🔒 SECURITY EVENT: OAuth state stored securely:", {
775
789
  projectId,
776
790
  agentDid: agentDid.substring(0, 20) + "...",
777
791
  sessionId: sessionId.substring(0, 20) + "...",
@@ -794,13 +808,13 @@ export class ConsentService {
794
808
  if (provider && this.providerRegistry) {
795
809
  // Lazy load providers if registry is empty (first request for this project)
796
810
  if (this.providerRegistry.getProviderNames().length === 0) {
797
- console.log("[ConsentService] Loading providers from AgentShield", {
811
+ console.error("[ConsentService] Loading providers from AgentShield", {
798
812
  projectId,
799
813
  provider,
800
814
  });
801
815
  try {
802
816
  await this.providerRegistry.loadFromAgentShield(projectId);
803
- console.log("[ConsentService] Providers loaded successfully", {
817
+ console.error("[ConsentService] Providers loaded successfully", {
804
818
  projectId,
805
819
  providers: this.providerRegistry.getProviderNames(),
806
820
  configuredProvider: this.providerRegistry.getConfiguredProvider(),
@@ -819,7 +833,7 @@ export class ConsentService {
819
833
  providerConfig = this.providerRegistry.getProvider(provider);
820
834
  }
821
835
  // Diagnostic logging to track race condition and OAuth mode selection
822
- console.log("[ConsentService] OAuth mode decision:", {
836
+ console.error("[ConsentService] OAuth mode decision:", {
823
837
  provider: provider || "none",
824
838
  hasProviderRegistry: !!this.providerRegistry,
825
839
  hasProviderConfig: !!providerConfig,
@@ -858,7 +872,7 @@ export class ConsentService {
858
872
  !providerConfig.proxyMode) {
859
873
  // Use providerConfig.clientId from AgentShield dashboard config
860
874
  const oauthClientId = providerConfig.clientId || projectId;
861
- console.log("[ConsentService] Using direct OAuth mode (PKCE)", {
875
+ console.error("[ConsentService] Using direct OAuth mode (PKCE)", {
862
876
  provider: provider || "unknown",
863
877
  authorizationUrl: providerConfig.authorizationUrl,
864
878
  supportsPKCE: providerConfig.supportsPKCE,
@@ -1009,7 +1023,7 @@ export class ConsentService {
1009
1023
  try {
1010
1024
  const existingUserDid = await this.env.DELEGATION_STORAGE.get(oauthKey, "text");
1011
1025
  if (existingUserDid) {
1012
- console.log("[ConsentService] OAuth identity already mapped:", {
1026
+ console.error("[ConsentService] OAuth identity already mapped:", {
1013
1027
  provider: oauthIdentity.provider,
1014
1028
  subject: oauthIdentity.subject.substring(0, 20) + "...",
1015
1029
  userDid: existingUserDid.substring(0, 20) + "...",
@@ -1037,7 +1051,7 @@ export class ConsentService {
1037
1051
  await this.env.DELEGATION_STORAGE.put(oauthIdentityKey, JSON.stringify(oauthIdentity), {
1038
1052
  expirationTtl: 90 * 24 * 60 * 60, // 90 days
1039
1053
  });
1040
- console.log("[ConsentService] OAuth identity linked to User DID:", {
1054
+ console.error("[ConsentService] OAuth identity linked to User DID:", {
1041
1055
  provider: oauthIdentity.provider,
1042
1056
  subject: oauthIdentity.subject.substring(0, 20) + "...",
1043
1057
  userDid: userDid.substring(0, 20) + "...",
@@ -1097,7 +1111,7 @@ export class ConsentService {
1097
1111
  await this.env.DELEGATION_STORAGE.put(oauthIdentityKey, JSON.stringify(oauthIdentity), {
1098
1112
  expirationTtl: 90 * 24 * 60 * 60, // 90 days
1099
1113
  });
1100
- console.log("[ConsentService] Cached external User DID from AgentShield:", {
1114
+ console.error("[ConsentService] Cached external User DID from AgentShield:", {
1101
1115
  provider: oauthIdentity.provider,
1102
1116
  subject: oauthIdentity.subject.substring(0, 20) + "...",
1103
1117
  userDid: userDid.substring(0, 30) + "...",
@@ -1264,7 +1278,7 @@ export class ConsentService {
1264
1278
  // This is the most explicit - passed from buildConsentUrl when tool has oauthProvider configured
1265
1279
  if (urlProvider) {
1266
1280
  provider = urlProvider;
1267
- console.log("[ConsentService] Using provider from URL query param:", {
1281
+ console.error("[ConsentService] Using provider from URL query param:", {
1268
1282
  provider,
1269
1283
  projectId,
1270
1284
  tool,
@@ -1281,7 +1295,7 @@ export class ConsentService {
1281
1295
  if (protection) {
1282
1296
  provider = await this.providerResolver.resolveProvider(protection, projectId);
1283
1297
  if (provider) {
1284
- console.log("[ConsentService] Using provider from resolver:", {
1298
+ console.error("[ConsentService] Using provider from resolver:", {
1285
1299
  provider,
1286
1300
  projectId,
1287
1301
  tool,
@@ -1291,15 +1305,22 @@ export class ConsentService {
1291
1305
  }
1292
1306
  }
1293
1307
  catch (error) {
1294
- // Non-fatal - continue without provider info
1295
- console.warn("[ConsentService] Failed to resolve provider for consent page:", error);
1308
+ // Check if this is ConsentOnlyModeError - expected behavior, not an error
1309
+ if (error instanceof Error && error.name === "ConsentOnlyModeError") {
1310
+ console.error("[ConsentService] Tool is consent-only mode, no provider needed for consent page", { projectId, tool });
1311
+ // Continue without provider - consent-only mode just needs clickwrap
1312
+ }
1313
+ else {
1314
+ // Non-fatal - continue without provider info
1315
+ console.warn("[ConsentService] Failed to resolve provider for consent page:", error);
1316
+ }
1296
1317
  }
1297
1318
  }
1298
1319
  // PRIORITY 3: Fallback to toolOAuthProvider if still undefined
1299
1320
  // This is a SEPARATE check (not else-if) to handle when providerResolver exists but returns undefined
1300
1321
  if (!provider && toolOAuthProvider) {
1301
1322
  provider = toolOAuthProvider;
1302
- console.log("[ConsentService] Using provider from tool protection (fallback):", {
1323
+ console.error("[ConsentService] Using provider from tool protection (fallback):", {
1303
1324
  provider,
1304
1325
  projectId,
1305
1326
  tool,
@@ -1320,7 +1341,7 @@ export class ConsentService {
1320
1341
  oauthSecurityService, agentName || undefined // Human-readable agent name for AgentShield dashboard
1321
1342
  );
1322
1343
  isOAuthRequired = true;
1323
- console.log("[ConsentService] 🔒 SECURITY EVENT: OAuth required, preparing consent page with redirect:", {
1344
+ console.error("[ConsentService] 🔒 SECURITY EVENT: OAuth required, preparing consent page with redirect:", {
1324
1345
  projectId,
1325
1346
  agentDid: agentDid.substring(0, 20) + "...",
1326
1347
  oauthUrl: resolvedOAuthUrl.substring(0, 100) + "...",
@@ -1377,7 +1398,7 @@ export class ConsentService {
1377
1398
  try {
1378
1399
  const credentialProviderConfig = await this.getCredentialProviderConfig(projectId, provider);
1379
1400
  if (credentialProviderConfig) {
1380
- console.log("[ConsentService] Credential provider detected, rendering credential page", {
1401
+ console.error("[ConsentService] Credential provider detected, rendering credential page", {
1381
1402
  projectId,
1382
1403
  provider,
1383
1404
  providerType: credentialProviderConfig.type,
@@ -2506,11 +2527,11 @@ export class ConsentService {
2506
2527
  * @returns JSON response
2507
2528
  */
2508
2529
  async handleApproval(request) {
2509
- console.log("[ConsentService] Approval request received");
2530
+ console.error("[ConsentService] Approval request received");
2510
2531
  try {
2511
2532
  // Parse and validate request body (supports both JSON and FormData)
2512
2533
  const body = await this.parseRequestBody(request);
2513
- console.log("[ConsentService] Request body parsed:", {
2534
+ console.error("[ConsentService] Request body parsed:", {
2514
2535
  hasBody: !!body,
2515
2536
  bodyKeys: Object.keys(body || {}),
2516
2537
  hasOAuthIdentity: !!body?.oauth_identity,
@@ -2524,14 +2545,14 @@ export class ConsentService {
2524
2545
  // CRED-003: Check for credential provider submission
2525
2546
  // Credential submissions include `provider_type: 'credential'` and are handled separately
2526
2547
  if (providerType === "credential") {
2527
- console.log("[ConsentService] Credential submission detected");
2548
+ console.error("[ConsentService] Credential submission detected");
2528
2549
  return this.handleCredentialApproval(bodyObj);
2529
2550
  }
2530
2551
  // ✅ Consent-only mode (provider_type: 'none')
2531
2552
  // User consents without authentication - clickwrap only
2532
2553
  // Delegation is created without user_did (anonymous consent)
2533
2554
  if (providerType === "none") {
2534
- console.log("[ConsentService] Consent-only mode detected (clickwrap)");
2555
+ console.error("[ConsentService] Consent-only mode detected (clickwrap)");
2535
2556
  // Continue to normal delegation flow - user_did will be null/undefined
2536
2557
  // This is intentional for consent-only scenarios where user identity isn't required
2537
2558
  }
@@ -2564,7 +2585,7 @@ export class ConsentService {
2564
2585
  });
2565
2586
  }
2566
2587
  const approvalRequest = validation.data;
2567
- console.log("[ConsentService] Approval request validated:", {
2588
+ console.error("[ConsentService] Approval request validated:", {
2568
2589
  agentDid: approvalRequest.agent_did?.substring(0, 20) + "...",
2569
2590
  sessionId: approvalRequest.session_id?.substring(0, 20) + "...",
2570
2591
  scopes: approvalRequest.scopes,
@@ -2614,7 +2635,7 @@ export class ConsentService {
2614
2635
  // The credential_required event is just for audit tracking
2615
2636
  }
2616
2637
  // Create delegation via AgentShield API
2617
- console.log("[ConsentService] Creating delegation...");
2638
+ console.error("[ConsentService] Creating delegation...");
2618
2639
  const delegationResult = await this.createDelegation(approvalRequest);
2619
2640
  if (!delegationResult.success) {
2620
2641
  console.error("[ConsentService] Delegation creation failed:", {
@@ -2630,7 +2651,7 @@ export class ConsentService {
2630
2651
  headers: { "Content-Type": "application/json" },
2631
2652
  });
2632
2653
  }
2633
- console.log("[ConsentService] ✅ Delegation created successfully:", {
2654
+ console.error("[ConsentService] ✅ Delegation created successfully:", {
2634
2655
  delegationId: delegationResult.delegation_id?.substring(0, 20) + "...",
2635
2656
  });
2636
2657
  // Store delegation token in KV
@@ -2736,7 +2757,7 @@ export class ConsentService {
2736
2757
  // Only fetch from storage if not already provided in request
2737
2758
  if (!userDid && request.session_id) {
2738
2759
  try {
2739
- console.log("[ConsentService] Getting User DID for session:", {
2760
+ console.error("[ConsentService] Getting User DID for session:", {
2740
2761
  sessionId: request.session_id.substring(0, 20) + "...",
2741
2762
  hasOAuthIdentity: !!request.oauth_identity,
2742
2763
  oauthProvider: request.oauth_identity?.provider,
@@ -2748,7 +2769,7 @@ export class ConsentService {
2748
2769
  userDid =
2749
2770
  (await this.getUserDidForSession(request.session_id, request.oauth_identity || undefined // Explicitly handle null as undefined
2750
2771
  )) ?? undefined;
2751
- console.log("[ConsentService] User DID retrieved from storage:", {
2772
+ console.error("[ConsentService] User DID retrieved from storage:", {
2752
2773
  userDid: userDid?.substring(0, 20) + "...",
2753
2774
  hasUserDid: !!userDid,
2754
2775
  });
@@ -2762,13 +2783,13 @@ export class ConsentService {
2762
2783
  }
2763
2784
  else if (userDid) {
2764
2785
  // userDid was provided in request (e.g., from credential auth flow)
2765
- console.log("[ConsentService] Using provided user_did from request:", {
2786
+ console.error("[ConsentService] Using provided user_did from request:", {
2766
2787
  userDid: userDid.substring(0, 20) + "...",
2767
2788
  source: "request.user_did",
2768
2789
  });
2769
2790
  }
2770
2791
  else {
2771
- console.log("[ConsentService] No session_id provided - skipping User DID generation");
2792
+ console.error("[ConsentService] No session_id provided - skipping User DID generation");
2772
2793
  }
2773
2794
  const expiresInDays = 7; // Default to 7 days
2774
2795
  // Phase 2 VC-Only: Issue Delegation VC if we have a session and userDid
@@ -2799,7 +2820,7 @@ export class ConsentService {
2799
2820
  const vcResult = await this.issueDelegationVC(localDelegation, request.session_id, request.oauth_identity || undefined);
2800
2821
  credentialJwt = vcResult ?? undefined;
2801
2822
  if (credentialJwt) {
2802
- console.log("[ConsentService] VC issued for delegation:", {
2823
+ console.error("[ConsentService] VC issued for delegation:", {
2803
2824
  delegationId,
2804
2825
  jwtLength: credentialJwt.length,
2805
2826
  });
@@ -2813,7 +2834,7 @@ export class ConsentService {
2813
2834
  // Build delegation request with error-based format detection
2814
2835
  // Try full format first, fallback to simplified format on error
2815
2836
  const delegationRequest = await this.buildDelegationRequest(request, userDid, expiresInDays, fieldName, credentialJwt);
2816
- console.log("[ConsentService] Creating delegation:", {
2837
+ console.error("[ConsentService] Creating delegation:", {
2817
2838
  url: `${agentShieldUrl}${AGENTSHIELD_ENDPOINTS.DELEGATIONS_CREATE}`,
2818
2839
  agentDid: request.agent_did.substring(0, 20) + "...",
2819
2840
  scopes: request.scopes,
@@ -2844,7 +2865,7 @@ export class ConsentService {
2844
2865
  // AgentShield now returns delegation_token for stateless verification
2845
2866
  const responseDataObj = wrappedResponse.data;
2846
2867
  const delegationToken = responseDataObj.delegation_token;
2847
- console.log("[ConsentService] ✅ Delegation created successfully:", {
2868
+ console.error("[ConsentService] ✅ Delegation created successfully:", {
2848
2869
  delegationId,
2849
2870
  agentDid: wrappedResponse.data.agent_did.substring(0, 20) + "...",
2850
2871
  scopes: wrappedResponse.data.scopes,
@@ -2867,7 +2888,7 @@ export class ConsentService {
2867
2888
  // Extract delegation_token (JWT) if present in response
2868
2889
  const unwrappedDataObj = unwrappedResponse;
2869
2890
  const delegationToken = unwrappedDataObj.delegation_token;
2870
- console.log("[ConsentService] ✅ Delegation created successfully:", {
2891
+ console.error("[ConsentService] ✅ Delegation created successfully:", {
2871
2892
  delegationId,
2872
2893
  agentDid: unwrappedResponse.agent_did.substring(0, 20) + "...",
2873
2894
  scopes: unwrappedResponse.scopes,
@@ -2953,7 +2974,7 @@ export class ConsentService {
2953
2974
  await delegationStorage.put(userAgentKey, token, {
2954
2975
  expirationTtl: ttl,
2955
2976
  });
2956
- console.log("[ConsentService] ✅ Token stored with user+agent DID:", {
2977
+ console.error("[ConsentService] ✅ Token stored with user+agent DID:", {
2957
2978
  key: userAgentKey,
2958
2979
  ttl,
2959
2980
  delegationId,
@@ -2976,14 +2997,14 @@ export class ConsentService {
2976
2997
  await delegationStorage.put(sessionKey, JSON.stringify(sessionDataToStore), {
2977
2998
  expirationTtl: ttl, // Use full TTL - this is the primary storage for session
2978
2999
  });
2979
- console.log("[ConsentService] ✅ Token stored for session:", {
3000
+ console.error("[ConsentService] ✅ Token stored for session:", {
2980
3001
  key: sessionKey,
2981
3002
  ttl,
2982
3003
  sessionId: sessionId.substring(0, 20) + "...",
2983
3004
  hasUserDid: !!userDid,
2984
3005
  });
2985
3006
  // Metrics: Log delegation key type for monitoring
2986
- console.log("[ConsentService] 📊 Delegation storage metrics:", {
3007
+ console.error("[ConsentService] 📊 Delegation storage metrics:", {
2987
3008
  delegationKeyType: userDid ? "user_agent_scoped" : "session_scoped",
2988
3009
  hasUserDid: !!userDid,
2989
3010
  userDidPrefix: userDid
@@ -3098,7 +3119,7 @@ export class ConsentService {
3098
3119
  * @returns JSON response
3099
3120
  */
3100
3121
  async handleCredentialApproval(body) {
3101
- console.log("[ConsentService] Processing credential approval");
3122
+ console.error("[ConsentService] Processing credential approval");
3102
3123
  // Extract standard fields
3103
3124
  const { tool, scopes: rawScopes, agent_did, session_id, project_id, provider, provider_type, csrf_token, ...credentials } = body;
3104
3125
  // Parse scopes - handles double JSON encoding from form submission
@@ -3160,7 +3181,7 @@ export class ConsentService {
3160
3181
  // See: https://developers.cloudflare.com/workers/observability/errors/#illegal-invocation-errors
3161
3182
  const credentialHandler = createCredentialAuthHandler({
3162
3183
  fetch: (...args) => globalThis.fetch(...args),
3163
- logger: (msg, data) => console.log(msg, data),
3184
+ logger: (msg, data) => console.error(msg, data),
3164
3185
  });
3165
3186
  const authResult = await credentialHandler.authenticate(providerConfig, credentials);
3166
3187
  if (!authResult.success) {
@@ -3173,7 +3194,7 @@ export class ConsentService {
3173
3194
  error_code: "auth_failed",
3174
3195
  }), { status: 401, headers: { "Content-Type": "application/json" } });
3175
3196
  }
3176
- console.log("[ConsentService] ✅ Credential authentication successful");
3197
+ console.error("[ConsentService] ✅ Credential authentication successful");
3177
3198
  // 3. Resolve identity via AgentShield
3178
3199
  const identityResult = await this.resolveCredentialIdentity({
3179
3200
  projectId: project_id,
@@ -3189,7 +3210,7 @@ export class ConsentService {
3189
3210
  error_code: "identity_resolution_failed",
3190
3211
  }), { status: 500, headers: { "Content-Type": "application/json" } });
3191
3212
  }
3192
- console.log("[ConsentService] ✅ Identity resolved", {
3213
+ console.error("[ConsentService] ✅ Identity resolved", {
3193
3214
  userDid: identityResult.userDid.substring(0, 30) + "...",
3194
3215
  });
3195
3216
  // NEW: Update session cache with userDid for proper delegation scoping
@@ -3197,7 +3218,7 @@ export class ConsentService {
3197
3218
  // instead of falling back to legacy agent-only keys
3198
3219
  await this.updateSessionWithIdentity(session_id, identityResult.userDid, null // No OAuth identity for credential auth
3199
3220
  );
3200
- console.log("[ConsentService] ✅ Session updated with identity");
3221
+ console.error("[ConsentService] ✅ Session updated with identity");
3201
3222
  // 4. Store token in IdpTokenStorage with usage metadata
3202
3223
  // Include userId from authResult for ToolExecutionContext.userId
3203
3224
  await this.storeCredentialToken({
@@ -3209,7 +3230,7 @@ export class ConsentService {
3209
3230
  scopes,
3210
3231
  userId: authResult.userId, // Pass extracted userId from credential provider response
3211
3232
  });
3212
- console.log("[ConsentService] ✅ Token stored");
3233
+ console.error("[ConsentService] ✅ Token stored");
3213
3234
  // 5. Create delegation using standard flow
3214
3235
  // Include provider_type and provider in customFields for AgentShield dashboard display
3215
3236
  const approvalRequest = {
@@ -3233,7 +3254,7 @@ export class ConsentService {
3233
3254
  error_code: delegationResult.error_code || "delegation_failed",
3234
3255
  }), { status: 500, headers: { "Content-Type": "application/json" } });
3235
3256
  }
3236
- console.log("[ConsentService] ✅ Credential approval complete", {
3257
+ console.error("[ConsentService] ✅ Credential approval complete", {
3237
3258
  delegationId: delegationResult.delegation_id?.substring(0, 20) + "...",
3238
3259
  });
3239
3260
  // Store delegation token
@@ -3348,7 +3369,7 @@ export class ConsentService {
3348
3369
  });
3349
3370
  return null;
3350
3371
  }
3351
- console.log("[ConsentService] Found credential provider:", {
3372
+ console.error("[ConsentService] Found credential provider:", {
3352
3373
  providerName,
3353
3374
  hasAuthEndpoint: !!provider.authEndpoint,
3354
3375
  hasResponseFields: !!provider.responseFields,
@@ -3586,7 +3607,7 @@ export class ConsentService {
3586
3607
  const csrfKey = STORAGE_KEYS.credentialCsrf(sessionId);
3587
3608
  // 10 minute TTL matches OAuth state TTL
3588
3609
  await delegationStorage.put(csrfKey, token, { expirationTtl: 600 });
3589
- console.log("[ConsentService] CSRF token stored for credential form");
3610
+ console.error("[ConsentService] CSRF token stored for credential form");
3590
3611
  }
3591
3612
  catch (error) {
3592
3613
  console.error("[ConsentService] CSRF token storage error:", error);
@@ -3671,17 +3692,17 @@ export class ConsentService {
3671
3692
  // CRITICAL: user_identifier is optional - delegation works without it
3672
3693
  if (userDid) {
3673
3694
  simplifiedRequest.user_identifier = userDid;
3674
- console.log("[ConsentService] Including user_identifier in delegation request:", {
3695
+ console.error("[ConsentService] Including user_identifier in delegation request:", {
3675
3696
  userDid: userDid.substring(0, 20) + "...",
3676
3697
  });
3677
3698
  }
3678
3699
  else {
3679
- console.log("[ConsentService] No user_identifier (session is anonymous) - delegation will proceed without it");
3700
+ console.error("[ConsentService] No user_identifier (session is anonymous) - delegation will proceed without it");
3680
3701
  }
3681
3702
  // Phase 2 VC-Only: Include credential_jwt if available
3682
3703
  if (credentialJwt) {
3683
3704
  simplifiedRequest.credential_jwt = credentialJwt;
3684
- console.log("[ConsentService] Including credential_jwt in delegation request");
3705
+ console.error("[ConsentService] Including credential_jwt in delegation request");
3685
3706
  }
3686
3707
  // AgentShield API only accepts "custom_fields", not "metadata"
3687
3708
  // Always use "custom_fields" regardless of Day0 config
@@ -3703,7 +3724,7 @@ export class ConsentService {
3703
3724
  ...customFieldsFromRequest,
3704
3725
  };
3705
3726
  if (hasProviderInfo) {
3706
- console.log("[ConsentService] Including provider info in custom_fields:", {
3727
+ console.error("[ConsentService] Including provider info in custom_fields:", {
3707
3728
  provider_type: customFieldsFromRequest.provider_type,
3708
3729
  provider: customFieldsFromRequest.provider,
3709
3730
  });
@@ -3736,7 +3757,7 @@ export class ConsentService {
3736
3757
  return fullResponse;
3737
3758
  }
3738
3759
  // Full format failed with validation error, try simplified
3739
- console.log("[ConsentService] Full format failed, trying simplified format...");
3760
+ console.error("[ConsentService] Full format failed, trying simplified format...");
3740
3761
  const simplifiedResponse = await this.makeAPICall(agentShieldUrl, apiKey, request.simplifiedFormat);
3741
3762
  if (simplifiedResponse.success) {
3742
3763
  await this.cacheFormatPreference("simplified");
@@ -3838,7 +3859,7 @@ export class ConsentService {
3838
3859
  }), {
3839
3860
  expirationTtl: 3600, // 1 hour
3840
3861
  });
3841
- console.log(`[ConsentService] Cached format preference: ${format}`);
3862
+ console.error(`[ConsentService] Cached format preference: ${format}`);
3842
3863
  }
3843
3864
  catch (error) {
3844
3865
  console.warn("[ConsentService] Failed to cache format preference:", error);