@kya-os/mcp-i-cloudflare 1.5.8-canary.7 → 1.5.8-canary.70

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 (93) hide show
  1. package/README.md +130 -0
  2. package/dist/__tests__/e2e/test-config.d.ts +37 -0
  3. package/dist/__tests__/e2e/test-config.d.ts.map +1 -0
  4. package/dist/__tests__/e2e/test-config.js +62 -0
  5. package/dist/__tests__/e2e/test-config.js.map +1 -0
  6. package/dist/adapter.d.ts +44 -0
  7. package/dist/adapter.d.ts.map +1 -1
  8. package/dist/adapter.js +677 -88
  9. package/dist/adapter.js.map +1 -1
  10. package/dist/agent.d.ts +79 -25
  11. package/dist/agent.d.ts.map +1 -1
  12. package/dist/agent.js +521 -40
  13. package/dist/agent.js.map +1 -1
  14. package/dist/app.d.ts +0 -8
  15. package/dist/app.d.ts.map +1 -1
  16. package/dist/app.js +208 -55
  17. package/dist/app.js.map +1 -1
  18. package/dist/cache/kv-oauth-config-cache.d.ts +47 -0
  19. package/dist/cache/kv-oauth-config-cache.d.ts.map +1 -0
  20. package/dist/cache/kv-oauth-config-cache.js +82 -0
  21. package/dist/cache/kv-oauth-config-cache.js.map +1 -0
  22. package/dist/config.d.ts.map +1 -1
  23. package/dist/config.js +33 -4
  24. package/dist/config.js.map +1 -1
  25. package/dist/helpers/env-mapper.d.ts +60 -1
  26. package/dist/helpers/env-mapper.d.ts.map +1 -1
  27. package/dist/helpers/env-mapper.js +136 -6
  28. package/dist/helpers/env-mapper.js.map +1 -1
  29. package/dist/index.d.ts +4 -2
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +8 -3
  32. package/dist/index.js.map +1 -1
  33. package/dist/runtime/audit-logger.d.ts +96 -0
  34. package/dist/runtime/audit-logger.d.ts.map +1 -0
  35. package/dist/runtime/audit-logger.js +276 -0
  36. package/dist/runtime/audit-logger.js.map +1 -0
  37. package/dist/runtime/oauth-handler.d.ts +5 -0
  38. package/dist/runtime/oauth-handler.d.ts.map +1 -1
  39. package/dist/runtime/oauth-handler.js +287 -35
  40. package/dist/runtime/oauth-handler.js.map +1 -1
  41. package/dist/runtime.d.ts +12 -1
  42. package/dist/runtime.d.ts.map +1 -1
  43. package/dist/runtime.js +34 -4
  44. package/dist/runtime.js.map +1 -1
  45. package/dist/server.d.ts +7 -0
  46. package/dist/server.d.ts.map +1 -1
  47. package/dist/server.js +93 -3
  48. package/dist/server.js.map +1 -1
  49. package/dist/services/admin.service.d.ts.map +1 -1
  50. package/dist/services/admin.service.js +89 -10
  51. package/dist/services/admin.service.js.map +1 -1
  52. package/dist/services/consent-audit.service.d.ts +91 -0
  53. package/dist/services/consent-audit.service.d.ts.map +1 -0
  54. package/dist/services/consent-audit.service.js +243 -0
  55. package/dist/services/consent-audit.service.js.map +1 -0
  56. package/dist/services/consent-config.service.d.ts +2 -2
  57. package/dist/services/consent-config.service.d.ts.map +1 -1
  58. package/dist/services/consent-config.service.js +55 -24
  59. package/dist/services/consent-config.service.js.map +1 -1
  60. package/dist/services/consent-page-renderer.d.ts +14 -0
  61. package/dist/services/consent-page-renderer.d.ts.map +1 -1
  62. package/dist/services/consent-page-renderer.js +42 -0
  63. package/dist/services/consent-page-renderer.js.map +1 -1
  64. package/dist/services/consent.service.d.ts +82 -4
  65. package/dist/services/consent.service.d.ts.map +1 -1
  66. package/dist/services/consent.service.js +1653 -34
  67. package/dist/services/consent.service.js.map +1 -1
  68. package/dist/services/delegation.service.d.ts.map +1 -1
  69. package/dist/services/delegation.service.js +67 -29
  70. package/dist/services/delegation.service.js.map +1 -1
  71. package/dist/services/idp-token-storage.d.ts +68 -0
  72. package/dist/services/idp-token-storage.d.ts.map +1 -0
  73. package/dist/services/idp-token-storage.js +157 -0
  74. package/dist/services/idp-token-storage.js.map +1 -0
  75. package/dist/services/oauth-service.d.ts +66 -0
  76. package/dist/services/oauth-service.d.ts.map +1 -0
  77. package/dist/services/oauth-service.js +223 -0
  78. package/dist/services/oauth-service.js.map +1 -0
  79. package/dist/services/proof.service.d.ts +8 -6
  80. package/dist/services/proof.service.d.ts.map +1 -1
  81. package/dist/services/proof.service.js +131 -75
  82. package/dist/services/proof.service.js.map +1 -1
  83. package/dist/services/tool-context-builder.d.ts +55 -0
  84. package/dist/services/tool-context-builder.d.ts.map +1 -0
  85. package/dist/services/tool-context-builder.js +124 -0
  86. package/dist/services/tool-context-builder.js.map +1 -0
  87. package/dist/types/tool-context.d.ts +35 -0
  88. package/dist/types/tool-context.d.ts.map +1 -0
  89. package/dist/types/tool-context.js +13 -0
  90. package/dist/types/tool-context.js.map +1 -0
  91. package/dist/types.d.ts +30 -0
  92. package/dist/types.d.ts.map +1 -1
  93. package/package.json +27 -60
@@ -15,17 +15,169 @@ import { validateConsentApprovalRequest, } from "@kya-os/contracts/consent";
15
15
  import { AGENTSHIELD_ENDPOINTS, createDelegationAPIResponseSchema, createDelegationResponseSchema, } from "@kya-os/contracts/agentshield-api";
16
16
  import { UserDidManager } from "@kya-os/mcp-i-core";
17
17
  import { WebCryptoProvider } from "../providers/crypto";
18
+ import { ConsentAuditService } from "./consent-audit.service";
19
+ import { CloudflareProofGenerator } from "../proof-generator";
20
+ import { ProofService } from "./proof.service";
21
+ import { fetchRemoteConfig } from "@kya-os/mcp-i-core";
18
22
  export class ConsentService {
19
23
  configService;
20
24
  renderer;
21
25
  env;
22
26
  runtime;
23
27
  userDidManager; // Cached instance for consistent DID generation
24
- constructor(env, runtime) {
28
+ // Audit service - lazy initialized
29
+ auditService;
30
+ auditInitPromise; // Cache promise to prevent race conditions
31
+ // Phase 2: Provider resolution services (optional for backward compatibility)
32
+ providerResolver;
33
+ providerRegistry;
34
+ /**
35
+ * ✅ FIXED: Constructor takes env: CloudflareEnv, not config
36
+ * Phase 2: Optional providerResolver and providerRegistry for tool-specific providers
37
+ */
38
+ constructor(env, runtime, providerResolver, providerRegistry) {
25
39
  this.env = env;
26
40
  this.runtime = runtime;
27
41
  this.configService = new ConsentConfigService(env);
28
42
  this.renderer = new ConsentPageRenderer();
43
+ this.providerResolver = providerResolver;
44
+ this.providerRegistry = providerRegistry;
45
+ // No initialization here - keep constructor synchronous
46
+ }
47
+ /**
48
+ * Get or initialize audit service (lazy initialization)
49
+ *
50
+ * Fetches config from remote API when projectId is available.
51
+ * Uses promise caching to prevent race conditions.
52
+ *
53
+ * @param projectId - Project ID from consent request (required for config fetch)
54
+ */
55
+ async getAuditService(projectId) {
56
+ // Already initialized
57
+ if (this.auditService) {
58
+ return this.auditService;
59
+ }
60
+ // No runtime - audit not available
61
+ if (!this.runtime) {
62
+ return undefined;
63
+ }
64
+ // Initialization in progress - wait for it
65
+ if (this.auditInitPromise) {
66
+ await this.auditInitPromise;
67
+ return this.auditService;
68
+ }
69
+ // Start initialization (with projectId for config fetch)
70
+ this.auditInitPromise = this.initializeAuditService(projectId);
71
+ try {
72
+ await this.auditInitPromise;
73
+ }
74
+ catch (error) {
75
+ console.warn("[ConsentService] Audit service initialization failed:", error);
76
+ // Don't throw - audit failures shouldn't break consent flow
77
+ }
78
+ return this.auditService;
79
+ }
80
+ /**
81
+ * Initialize audit service - fetches config from remote API
82
+ *
83
+ * ⚠️ CRITICAL: Fetches config from remote API using fetchRemoteConfig()
84
+ * This is the ONLY way to get CloudflareRuntimeConfig per requirement.
85
+ */
86
+ async initializeAuditService(projectId) {
87
+ if (!this.runtime) {
88
+ return;
89
+ }
90
+ try {
91
+ // ✅ CRITICAL: Fetch config from remote API
92
+ const config = await this.getConfigFromRemoteAPI(projectId);
93
+ if (!config?.proofing?.enabled) {
94
+ console.log("[ConsentService] Proofing not enabled in remote config");
95
+ return; // Proofing not enabled
96
+ }
97
+ // Get identity (async - requires runtime to be initialized)
98
+ const identity = await this.runtime.getIdentity();
99
+ // ✅ FIXED: CloudflareProofGenerator only takes identity, not providers
100
+ const proofGenerator = new CloudflareProofGenerator(identity);
101
+ // Get audit logger
102
+ const auditLogger = this.runtime.getAuditLogger();
103
+ if (!auditLogger) {
104
+ console.warn("[ConsentService] AuditLogger not available");
105
+ return;
106
+ }
107
+ // Create audit service with fetched config
108
+ this.auditService = new ConsentAuditService(new ProofService(config, this.runtime), auditLogger, proofGenerator, config, // ✅ Config fetched from remote API
109
+ this.runtime);
110
+ console.log("[ConsentService] Audit service initialized successfully");
111
+ }
112
+ catch (error) {
113
+ console.error("[ConsentService] Failed to initialize audit service:", error);
114
+ // Don't throw - audit failures shouldn't break consent flow
115
+ }
116
+ }
117
+ /**
118
+ * Fetch CloudflareRuntimeConfig from remote API (AgentShield)
119
+ *
120
+ * ⚠️ CRITICAL: Config MUST be fetched from remote API, not constructed from env.
121
+ *
122
+ * Uses existing `fetchRemoteConfig()` from `@kya-os/mcp-i-core/config/remote-config`
123
+ * which handles caching, error handling, and API communication.
124
+ *
125
+ * @param projectId - Project ID from consent request
126
+ * @returns Runtime config or undefined if unavailable
127
+ */
128
+ async getConfigFromRemoteAPI(projectId) {
129
+ if (!this.env.AGENTSHIELD_API_KEY) {
130
+ console.warn("[ConsentService] No API key for runtime config fetch");
131
+ return undefined;
132
+ }
133
+ try {
134
+ // Create KV cache adapter
135
+ const cache = this.env.TOOL_PROTECTION_KV
136
+ ? {
137
+ get: async (key) => {
138
+ return ((await this.env.TOOL_PROTECTION_KV.get(key, "text")) || null);
139
+ },
140
+ set: async (key, value, ttl) => {
141
+ await this.env.TOOL_PROTECTION_KV.put(key, value, {
142
+ expirationTtl: Math.floor(ttl / 1000),
143
+ });
144
+ },
145
+ }
146
+ : undefined;
147
+ const config = await fetchRemoteConfig({
148
+ apiUrl: this.env.AGENTSHIELD_API_URL || "https://kya.vouched.id",
149
+ apiKey: this.env.AGENTSHIELD_API_KEY,
150
+ projectId, // ✅ Use projectId from consent request
151
+ cacheTtl: 300000, // 5 minutes
152
+ fetchProvider: fetch,
153
+ }, cache);
154
+ // Populate serverDid from runtime identity if missing or empty
155
+ // This prevents AgentShield validation errors (serverDid must be at least 1 character)
156
+ // Note: MCPIConfig.identity is RuntimeIdentityConfig (no serverDid), but AgentShield
157
+ // may return MCPIServerConfig format (has serverDid). We need to handle both.
158
+ if (config && config.identity) {
159
+ const identityConfig = config.identity; // Type assertion for serverDid field
160
+ if (!identityConfig.serverDid || identityConfig.serverDid === "") {
161
+ try {
162
+ const runtimeIdentity = await this.runtime?.getIdentity();
163
+ if (runtimeIdentity?.did) {
164
+ identityConfig.serverDid = runtimeIdentity.did;
165
+ console.log("[ConsentService] Populated serverDid from runtime identity");
166
+ }
167
+ }
168
+ catch (error) {
169
+ console.warn("[ConsentService] Failed to get runtime identity for serverDid:", error);
170
+ }
171
+ }
172
+ }
173
+ // fetchRemoteConfig returns MCPIConfig | null
174
+ // CloudflareRuntimeConfig extends MCPIConfig, so cast is safe
175
+ return config;
176
+ }
177
+ catch (error) {
178
+ console.warn("[ConsentService] Error fetching runtime config:", error);
179
+ return undefined;
180
+ }
29
181
  }
30
182
  /**
31
183
  * Get or generate User DID for a session
@@ -37,10 +189,20 @@ export class ConsentService {
37
189
  * @param oauthIdentity - Optional OAuth provider identity
38
190
  * @returns User DID (did:key format)
39
191
  */
192
+ /**
193
+ * Get user DID for a session
194
+ *
195
+ * Public method to retrieve user DID from session storage or OAuth identity mapping.
196
+ * Used by OAuth handler to get userDid when OAuth linking fails.
197
+ *
198
+ * @param sessionId - Session ID
199
+ * @param oauthIdentity - Optional OAuth provider identity
200
+ * @returns User DID (did:key format)
201
+ */
40
202
  async getUserDidForSession(sessionId, oauthIdentity) {
41
203
  // Handle null explicitly (from JSON parsing)
42
204
  const hasOAuthIdentity = oauthIdentity &&
43
- typeof oauthIdentity === 'object' &&
205
+ typeof oauthIdentity === "object" &&
44
206
  oauthIdentity.provider &&
45
207
  oauthIdentity.subject;
46
208
  // If OAuth identity provided, check for existing mapping first
@@ -108,10 +270,34 @@ export class ConsentService {
108
270
  delete: async (key) => {
109
271
  await this.env.DELEGATION_STORAGE.delete(`userDid:${key}`);
110
272
  },
273
+ // OAuth-based lookup for persistent user DID
274
+ getByOAuth: async (provider, subject) => {
275
+ try {
276
+ const oauthKey = STORAGE_KEYS.oauthIdentity(provider, subject);
277
+ const userDid = await this.env.DELEGATION_STORAGE.get(oauthKey, "text");
278
+ return userDid || null;
279
+ }
280
+ catch {
281
+ return null;
282
+ }
283
+ },
284
+ // OAuth-based storage for persistent user DID mapping
285
+ setByOAuth: async (provider, subject, did, ttl) => {
286
+ try {
287
+ const oauthKey = STORAGE_KEYS.oauthIdentity(provider, subject);
288
+ await this.env.DELEGATION_STORAGE.put(oauthKey, did, {
289
+ expirationTtl: ttl || 90 * 24 * 60 * 60, // Default 90 days for persistent mapping
290
+ });
291
+ }
292
+ catch (error) {
293
+ console.warn("[ConsentService] Failed to store OAuth mapping:", error);
294
+ throw error;
295
+ }
296
+ },
111
297
  },
112
298
  });
113
299
  }
114
- const userDid = await this.userDidManager.getOrCreateUserDid(sessionId);
300
+ const userDid = await this.userDidManager.getOrCreateUserDid(sessionId, oauthIdentity);
115
301
  // Cache in session storage
116
302
  try {
117
303
  const existingSession = (await this.env.DELEGATION_STORAGE.get(sessionKey, "json"));
@@ -136,13 +322,45 @@ export class ConsentService {
136
322
  *
137
323
  * @param projectId - Project ID to check
138
324
  * @param oauthIdentity - Optional OAuth identity from cookie
325
+ * @param toolOAuthProvider - Optional tool-specific OAuth provider (takes precedence)
139
326
  * @returns True if OAuth redirect is required
140
327
  */
141
- async isOAuthRequired(projectId, oauthIdentity) {
328
+ async isOAuthRequired(projectId, oauthIdentity, toolOAuthProvider, toolProtection) {
142
329
  // If OAuth identity is already present, OAuth is not required
143
330
  if (oauthIdentity && oauthIdentity.provider && oauthIdentity.subject) {
144
331
  return false;
145
332
  }
333
+ // If tool specifically requires an OAuth provider, it's required immediately
334
+ if (toolOAuthProvider) {
335
+ return true;
336
+ }
337
+ // Phase 2: If toolOAuthProvider is undefined but tool requires delegation,
338
+ // use ProviderResolver to check if a provider can be resolved
339
+ if (!toolOAuthProvider &&
340
+ toolProtection &&
341
+ toolProtection.requiresDelegation) {
342
+ if (this.providerResolver) {
343
+ try {
344
+ const resolvedProvider = await this.providerResolver.resolveProvider(toolProtection, projectId);
345
+ if (resolvedProvider) {
346
+ console.log("[ConsentService] OAuth required: ProviderResolver resolved provider", {
347
+ projectId,
348
+ provider: resolvedProvider,
349
+ toolRequiresDelegation: toolProtection.requiresDelegation,
350
+ hasToolOAuthProvider: !!toolOAuthProvider,
351
+ });
352
+ return true;
353
+ }
354
+ }
355
+ catch (error) {
356
+ // ProviderResolver failed - log but continue to fallback check
357
+ console.warn("[ConsentService] ProviderResolver failed to resolve provider, falling back to project config check:", {
358
+ projectId,
359
+ error: error instanceof Error ? error.message : String(error),
360
+ });
361
+ }
362
+ }
363
+ }
146
364
  // Check project config to see if OAuth is configured
147
365
  try {
148
366
  const agentShieldUrl = this.env.AGENTSHIELD_API_URL || DEFAULT_AGENTSHIELD_URL;
@@ -181,34 +399,197 @@ export class ConsentService {
181
399
  * Creates the OAuth authorization URL with proper state parameter
182
400
  * for redirecting to OAuth provider.
183
401
  *
402
+ * ✅ CSRF Protection: If oauthSecurityService is provided, state is stored securely
403
+ * in KV storage and validated on callback. Otherwise, falls back to base64-encoded
404
+ * state (less secure, but backward compatible).
405
+ *
184
406
  * @param projectId - Project ID
185
407
  * @param agentDid - Agent DID
186
408
  * @param sessionId - Session ID
187
409
  * @param scopes - Requested scopes
188
410
  * @param serverUrl - Server URL for callback
411
+ * @param oauthSecurityService - Optional OAuthSecurityService for CSRF protection
189
412
  * @returns OAuth authorization URL
190
413
  */
191
- buildOAuthUrl(projectId, agentDid, sessionId, scopes, serverUrl) {
414
+ async buildOAuthUrl(projectId, agentDid, sessionId, scopes, serverUrl, provider, // Phase 2: Optional provider name (resolved if not provided)
415
+ oauthSecurityService) {
192
416
  const agentShieldUrl = this.env.AGENTSHIELD_API_URL || DEFAULT_AGENTSHIELD_URL;
193
417
  // Generate a temporary delegation ID for state (will be created after OAuth)
194
418
  const delegationId = `temp-${Date.now()}`;
195
- // Build state parameter with required fields
196
- const state = {
419
+ // Phase 1: Generate PKCE challenge if OAuthSecurityService is available
420
+ let codeVerifier;
421
+ let codeChallenge;
422
+ if (oauthSecurityService) {
423
+ try {
424
+ const pkceChallenge = await oauthSecurityService.generatePKCEChallenge();
425
+ codeVerifier = pkceChallenge.verifier;
426
+ codeChallenge = pkceChallenge.challenge;
427
+ }
428
+ catch (error) {
429
+ console.warn("[ConsentService] Failed to generate PKCE challenge:", error);
430
+ }
431
+ }
432
+ // Build state data with required fields
433
+ const stateData = {
197
434
  project_id: projectId,
198
435
  agent_did: agentDid,
199
436
  session_id: sessionId,
200
437
  delegation_id: delegationId,
201
438
  scopes: scopes,
439
+ storedAt: Date.now(),
202
440
  };
203
- // Encode state as base64 (Cloudflare Workers compatible)
204
- const stateParam = btoa(JSON.stringify(state));
205
- // Build OAuth authorization URL
441
+ // Store PKCE code_verifier in state for token exchange
442
+ if (codeVerifier) {
443
+ stateData.code_verifier = codeVerifier;
444
+ stateData.code_challenge = codeChallenge;
445
+ stateData.redirect_uri = `${serverUrl}/oauth/callback`;
446
+ }
447
+ let stateParam;
448
+ if (oauthSecurityService && this.env.DELEGATION_STORAGE) {
449
+ // ✅ CSRF Protection: Generate secure random state value and store state data securely
450
+ const randomBytes = crypto.getRandomValues(new Uint8Array(32));
451
+ const stateValue = btoa(String.fromCharCode(...randomBytes))
452
+ .replace(/\+/g, "-")
453
+ .replace(/\//g, "_")
454
+ .replace(/=/g, "");
455
+ // Store state data securely in KV (10 minute TTL for OAuth flow)
456
+ await oauthSecurityService.storeOAuthState(stateValue, stateData, 600);
457
+ stateParam = stateValue;
458
+ console.log("[ConsentService] 🔒 SECURITY EVENT: OAuth state stored securely:", {
459
+ projectId,
460
+ agentDid: agentDid.substring(0, 20) + "...",
461
+ sessionId: sessionId.substring(0, 20) + "...",
462
+ stateValue: stateValue.substring(0, 20) + "...",
463
+ timestamp: new Date().toISOString(),
464
+ eventType: "oauth_state_stored",
465
+ ttl: 600,
466
+ });
467
+ }
468
+ else {
469
+ // Fallback: Encode state as base64 (less secure, but backward compatible)
470
+ if (!oauthSecurityService) {
471
+ console.warn("[ConsentService] ⚠️ SECURITY WARNING: OAuthSecurityService not provided, using insecure state encoding");
472
+ }
473
+ stateParam = btoa(JSON.stringify(stateData));
474
+ }
475
+ // Phase 3: Resolve provider config and extract custom parameters
476
+ let providerConfig = null;
477
+ if (provider && this.providerRegistry) {
478
+ providerConfig = this.providerRegistry.getProvider(provider);
479
+ }
480
+ // Phase 3: Check if we should use direct OAuth URL (bypass AgentShield bouncer)
481
+ // This is for custom providers that need direct OAuth URLs
482
+ if (providerConfig &&
483
+ providerConfig.proxyMode === true &&
484
+ !providerConfig.supportsPKCE) {
485
+ // Use providerConfig.clientId for custom providers, not projectId
486
+ const oauthClientId = providerConfig.clientId || projectId;
487
+ return this.buildDirectOAuthUrl(providerConfig, oauthClientId, `${serverUrl}/oauth/callback`, scopes, stateParam, codeChallenge);
488
+ }
489
+ // Phase 3: Validate custom parameters don't conflict with reserved parameters
490
+ const RESERVED_PARAMS = [
491
+ "response_type",
492
+ "client_id",
493
+ "redirect_uri",
494
+ "scope",
495
+ "state",
496
+ "code_challenge",
497
+ "code_challenge_method",
498
+ ];
499
+ if (providerConfig?.customParams) {
500
+ for (const [key, value] of Object.entries(providerConfig.customParams)) {
501
+ const normalizedKey = key.toLowerCase();
502
+ if (RESERVED_PARAMS.includes(normalizedKey)) {
503
+ throw new Error(`Custom parameter "${key}" conflicts with reserved OAuth parameter. Reserved parameters: ${RESERVED_PARAMS.join(", ")}`);
504
+ }
505
+ // Validate value is a string before calling string methods
506
+ if (typeof value !== "string") {
507
+ throw new Error(`Custom parameter "${key}" must be a string, got ${typeof value}`);
508
+ }
509
+ if (!value || value.trim().length === 0) {
510
+ throw new Error(`Custom parameter "${key}" has empty value`);
511
+ }
512
+ }
513
+ }
514
+ // Build OAuth authorization URL (AgentShield bouncer endpoint)
206
515
  const oauthUrl = new URL(`${agentShieldUrl}/bouncer/oauth/authorize`);
207
516
  oauthUrl.searchParams.set("response_type", "code");
208
517
  oauthUrl.searchParams.set("client_id", projectId); // Use projectId as client_id
209
518
  oauthUrl.searchParams.set("redirect_uri", `${serverUrl}/oauth/callback`);
210
519
  oauthUrl.searchParams.set("scope", scopes.join(" "));
211
520
  oauthUrl.searchParams.set("state", stateParam);
521
+ // ✅ Phase 1: Add PKCE challenge to authorization URL if available
522
+ if (codeChallenge) {
523
+ oauthUrl.searchParams.set("code_challenge", codeChallenge);
524
+ oauthUrl.searchParams.set("code_challenge_method", "S256");
525
+ }
526
+ // Phase 3: Inject custom parameters (after standard params, before PKCE params)
527
+ if (providerConfig?.customParams) {
528
+ for (const [key, value] of Object.entries(providerConfig.customParams)) {
529
+ oauthUrl.searchParams.set(key, value);
530
+ }
531
+ }
532
+ return oauthUrl.toString();
533
+ }
534
+ /**
535
+ * Build direct OAuth URL (bypasses AgentShield bouncer endpoint)
536
+ *
537
+ * Used for custom providers that need direct OAuth URLs (e.g., self-hosted OAuth servers).
538
+ * Triggered when providerConfig.proxyMode === true && !providerConfig.supportsPKCE
539
+ *
540
+ * @param providerConfig - Provider configuration
541
+ * @param clientId - OAuth client ID
542
+ * @param redirectUri - Redirect URI for OAuth callback
543
+ * @param scopes - Requested scopes
544
+ * @param state - OAuth state parameter
545
+ * @param codeChallenge - Optional PKCE code challenge
546
+ * @returns Direct OAuth authorization URL
547
+ */
548
+ buildDirectOAuthUrl(providerConfig, clientId, redirectUri, scopes, state, codeChallenge) {
549
+ // Validate custom parameters don't conflict with reserved parameters
550
+ const RESERVED_PARAMS = [
551
+ "response_type",
552
+ "client_id",
553
+ "redirect_uri",
554
+ "scope",
555
+ "state",
556
+ "code_challenge",
557
+ "code_challenge_method",
558
+ ];
559
+ if (providerConfig.customParams) {
560
+ for (const [key, value] of Object.entries(providerConfig.customParams)) {
561
+ const normalizedKey = key.toLowerCase();
562
+ if (RESERVED_PARAMS.includes(normalizedKey)) {
563
+ throw new Error(`Custom parameter "${key}" conflicts with reserved OAuth parameter. Reserved parameters: ${RESERVED_PARAMS.join(", ")}`);
564
+ }
565
+ // Validate value is a string before calling string methods
566
+ if (typeof value !== "string") {
567
+ throw new Error(`Custom parameter "${key}" must be a string, got ${typeof value}`);
568
+ }
569
+ if (!value || value.trim().length === 0) {
570
+ throw new Error(`Custom parameter "${key}" has empty value`);
571
+ }
572
+ }
573
+ }
574
+ // Build OAuth URL directly to provider's authorization endpoint
575
+ const oauthUrl = new URL(providerConfig.authorizationUrl);
576
+ // Include standard OAuth params
577
+ oauthUrl.searchParams.set("response_type", providerConfig.responseType || "code");
578
+ oauthUrl.searchParams.set("client_id", clientId);
579
+ oauthUrl.searchParams.set("redirect_uri", redirectUri);
580
+ oauthUrl.searchParams.set("scope", scopes.join(" "));
581
+ oauthUrl.searchParams.set("state", state);
582
+ // Include PKCE params if supported and challenge provided
583
+ if (providerConfig.supportsPKCE && codeChallenge) {
584
+ oauthUrl.searchParams.set("code_challenge", codeChallenge);
585
+ oauthUrl.searchParams.set("code_challenge_method", "S256");
586
+ }
587
+ // Include custom parameters (after standard params, before PKCE params)
588
+ if (providerConfig.customParams) {
589
+ for (const [key, value] of Object.entries(providerConfig.customParams)) {
590
+ oauthUrl.searchParams.set(key, value);
591
+ }
592
+ }
212
593
  return oauthUrl.toString();
213
594
  }
214
595
  /**
@@ -404,18 +785,85 @@ export class ConsentService {
404
785
  // Non-fatal - continue without OAuth identity
405
786
  }
406
787
  // Check if OAuth is required (after extracting OAuth identity)
407
- const oauthRequired = await this.isOAuthRequired(projectId, oauthIdentity);
788
+ // Check both project-level config AND tool-specific protection
789
+ const toolProtectionService = this.runtime?.config
790
+ ?.toolProtectionService;
791
+ let toolOAuthProvider;
792
+ let protection;
793
+ if (toolProtectionService && this.runtime) {
794
+ const agentDidObj = await this.runtime.getIdentity();
795
+ protection = await toolProtectionService.checkToolProtection(tool, agentDidObj.did);
796
+ toolOAuthProvider = protection?.oauthProvider;
797
+ }
798
+ const oauthRequired = await this.isOAuthRequired(projectId, oauthIdentity, toolOAuthProvider, protection);
799
+ // Phase 2: Resolve provider for tool if providerResolver is available
800
+ let provider;
801
+ if (this.providerResolver && this.runtime) {
802
+ try {
803
+ const agentDidObj = await this.runtime.getIdentity();
804
+ const toolProtectionService = this.runtime.config
805
+ ?.toolProtectionService;
806
+ if (toolProtectionService) {
807
+ const protection = await toolProtectionService.checkToolProtection(tool, agentDidObj.did);
808
+ if (protection) {
809
+ provider = await this.providerResolver.resolveProvider(protection, projectId);
810
+ }
811
+ }
812
+ }
813
+ catch (error) {
814
+ // Non-fatal - continue without provider info
815
+ console.warn("[ConsentService] Failed to resolve provider for consent page:", error);
816
+ }
817
+ }
818
+ let resolvedOAuthUrl;
819
+ let isOAuthRequired = false;
408
820
  if (oauthRequired) {
409
821
  // OAuth is required - redirect to OAuth provider instead of showing consent page
410
- const oauthUrl = this.buildOAuthUrl(projectId, agentDid, sessionId, scopes, serverUrl);
411
- console.log("[ConsentService] OAuth required, redirecting to OAuth provider:", {
822
+ // Note: oauthSecurityService is optional - if not provided, falls back to insecure encoding
823
+ const oauthSecurityService = this.env.DELEGATION_STORAGE
824
+ ? new (await import("./oauth-security.service")).OAuthSecurityService(this.env.DELEGATION_STORAGE, this.env.OAUTH_ENCRYPTION_SECRET)
825
+ : undefined;
826
+ // Build OAuth URL for redirection
827
+ // Note: We're building it here, but we'll pass it to the renderer
828
+ // instead of redirecting immediately, so the user sees the consent page first.
829
+ resolvedOAuthUrl = await this.buildOAuthUrl(projectId, agentDid, sessionId, scopes, serverUrl, undefined, // provider - will be resolved by ProviderResolver if available
830
+ oauthSecurityService);
831
+ isOAuthRequired = true;
832
+ console.log("[ConsentService] 🔒 SECURITY EVENT: OAuth required, preparing consent page with redirect:", {
412
833
  projectId,
413
834
  agentDid: agentDid.substring(0, 20) + "...",
414
- oauthUrl: oauthUrl.substring(0, 100) + "...",
835
+ oauthUrl: resolvedOAuthUrl.substring(0, 100) + "...",
836
+ hasSecureState: !!oauthSecurityService,
837
+ timestamp: new Date().toISOString(),
838
+ eventType: "oauth_redirect_prepared",
839
+ });
840
+ }
841
+ // ✅ Lazy initialization with projectId
842
+ const auditService = await this.getAuditService(projectId);
843
+ // Log page view event (if audit service available)
844
+ if (auditService) {
845
+ await auditService
846
+ .logConsentPageView({
847
+ sessionId,
848
+ agentDid,
849
+ targetTools: [tool], // Wrap in array
850
+ scopes,
851
+ projectId,
852
+ // oauthProvider: provider, // TODO: Enable logging of resolved provider once type is updated
853
+ })
854
+ .catch((err) => {
855
+ // Structured error logging
856
+ console.error("[ConsentService] Audit logging failed", {
857
+ eventType: "consent:page_viewed",
858
+ sessionId,
859
+ error: err instanceof Error ? err.message : String(err),
860
+ stack: err instanceof Error ? err.stack : undefined,
861
+ });
862
+ // Don't throw - audit failures shouldn't break consent flow
415
863
  });
416
- return Response.redirect(oauthUrl, 302);
417
864
  }
418
865
  // Build consent page config
866
+ // Type assertion to handle updated schema before rebuild
419
867
  const pageConfig = {
420
868
  tool,
421
869
  toolDescription,
@@ -424,10 +872,14 @@ export class ConsentService {
424
872
  sessionId,
425
873
  projectId,
426
874
  serverUrl,
875
+ provider, // Phase 2: Include provider if resolved
427
876
  branding: consentConfig.branding,
428
877
  terms: consentConfig.terms,
429
878
  customFields: consentConfig.customFields,
430
879
  autoClose: consentConfig.ui?.autoClose,
880
+ // Pass OAuth details for client-side handling
881
+ oauthRequired: isOAuthRequired,
882
+ oauthUrl: resolvedOAuthUrl,
431
883
  };
432
884
  // Render page with OAuth identity (if available)
433
885
  const html = this.renderer.render(pageConfig, oauthIdentity);
@@ -451,6 +903,1079 @@ export class ConsentService {
451
903
  });
452
904
  }
453
905
  }
906
+ /**
907
+ * Parse request body from JSON or FormData
908
+ *
909
+ * Handles both JSON and FormData/multipart requests, converting
910
+ * FormData fields to the correct format for ConsentApprovalRequest.
911
+ *
912
+ * @param request - Request to parse
913
+ * @returns Parsed body object
914
+ */
915
+ async parseRequestBody(request) {
916
+ const contentType = request.headers.get("content-type") || "";
917
+ // Helper function to parse form fields into body object
918
+ const parseFormFields = (entries) => {
919
+ const body = {};
920
+ for (const [key, value] of entries) {
921
+ // Handle special fields that need parsing
922
+ if (key === "scopes" || key === "scopes[]") {
923
+ // Scopes come as JSON string
924
+ try {
925
+ body["scopes"] = JSON.parse(value);
926
+ }
927
+ catch {
928
+ // If not JSON, treat as single scope or array
929
+ body["scopes"] = value.includes(",") ? value.split(",") : [value];
930
+ }
931
+ }
932
+ else if (key === "oauth_identity" || key === "oauth_identity_json") {
933
+ // OAuth identity comes as JSON string
934
+ try {
935
+ const parsed = JSON.parse(value);
936
+ body["oauth_identity"] = parsed || null;
937
+ }
938
+ catch {
939
+ // Invalid JSON, set to null
940
+ body["oauth_identity"] = null;
941
+ }
942
+ }
943
+ else if (key === "termsAccepted") {
944
+ // Convert checkbox values to boolean
945
+ body[key] =
946
+ value === "on" ||
947
+ value === "true" ||
948
+ value === "1" ||
949
+ value === "yes";
950
+ }
951
+ else if (key === "customFields") {
952
+ // Custom fields come as JSON string
953
+ try {
954
+ body[key] = JSON.parse(value);
955
+ }
956
+ catch {
957
+ // If not JSON, skip
958
+ }
959
+ }
960
+ else {
961
+ // Regular string fields
962
+ body[key] = value;
963
+ }
964
+ }
965
+ // Default termsAccepted to true if not provided (common for checkboxes)
966
+ if (!("termsAccepted" in body)) {
967
+ body.termsAccepted = true;
968
+ }
969
+ // Default scopes to empty array if not provided (required by schema but can be empty)
970
+ if (!("scopes" in body)) {
971
+ body.scopes = [];
972
+ }
973
+ return body;
974
+ };
975
+ // Parse URL-encoded form data (application/x-www-form-urlencoded)
976
+ // When Content-Type is URL-encoded but FormData object is passed, try FormData parsing first
977
+ if (contentType.includes("application/x-www-form-urlencoded")) {
978
+ // Try FormData parsing first (FormData object might have been passed)
979
+ try {
980
+ const clonedRequest = request.clone();
981
+ const formData = await clonedRequest.formData();
982
+ const body = {};
983
+ let hasValidFields = false;
984
+ // Check if FormData parsing returned malformed data (entire multipart body as single entry)
985
+ // Type assertion: FormData.entries() exists at runtime in Cloudflare Workers
986
+ const entriesArray = Array.from(formData.entries());
987
+ if (entriesArray.length === 1 &&
988
+ typeof entriesArray[0][0] === "string" &&
989
+ entriesArray[0][0].includes("Content-Disposition") &&
990
+ typeof entriesArray[0][1] === "string" &&
991
+ entriesArray[0][1].toString().includes("Content-Disposition")) {
992
+ // Manually parse multipart format from the value string
993
+ // The key contains the first boundary and Content-Disposition header start
994
+ // The value contains the rest of the first field and all subsequent fields
995
+ const keyPart = entriesArray[0][0];
996
+ const valuePart = entriesArray[0][1];
997
+ // Fix: If key ends with "name" and value starts with '"fieldname"', combine them
998
+ let multipartBody;
999
+ if (keyPart.trim().endsWith("name") &&
1000
+ valuePart.trim().startsWith('"')) {
1001
+ // Key ends with "name", value starts with '"fieldname"', combine with = between them
1002
+ multipartBody = keyPart + "=" + valuePart;
1003
+ }
1004
+ else {
1005
+ multipartBody = keyPart + valuePart;
1006
+ }
1007
+ // Match: Content-Disposition header with field name, then capture value until next boundary or end
1008
+ const fieldRegex = /Content-Disposition:\s*form-data;\s*name="([^"]+)"\r?\n\r?\n([\s\S]*?)(?=\r?\n------|$)/g;
1009
+ let match;
1010
+ while ((match = fieldRegex.exec(multipartBody)) !== null) {
1011
+ const fieldName = match[1];
1012
+ const fieldValue = match[2].trim(); // Remove trailing newlines
1013
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
1014
+ try {
1015
+ body["scopes"] = JSON.parse(fieldValue);
1016
+ }
1017
+ catch {
1018
+ body["scopes"] = fieldValue.includes(",")
1019
+ ? fieldValue.split(",")
1020
+ : [fieldValue];
1021
+ }
1022
+ }
1023
+ else if (fieldName === "oauth_identity" ||
1024
+ fieldName === "oauth_identity_json") {
1025
+ try {
1026
+ body["oauth_identity"] = JSON.parse(fieldValue) || null;
1027
+ }
1028
+ catch {
1029
+ body["oauth_identity"] = null;
1030
+ }
1031
+ }
1032
+ else if (fieldName === "termsAccepted") {
1033
+ body[fieldName] =
1034
+ fieldValue === "on" ||
1035
+ fieldValue === "true" ||
1036
+ fieldValue === "1" ||
1037
+ fieldValue === "yes";
1038
+ }
1039
+ else if (fieldName === "customFields") {
1040
+ try {
1041
+ body[fieldName] = JSON.parse(fieldValue);
1042
+ }
1043
+ catch {
1044
+ // Skip
1045
+ }
1046
+ }
1047
+ else {
1048
+ body[fieldName] = fieldValue;
1049
+ }
1050
+ hasValidFields = true;
1051
+ }
1052
+ }
1053
+ else {
1054
+ // Normal FormData parsing
1055
+ // Type assertion: FormData.entries() exists at runtime in Cloudflare Workers
1056
+ for (const [key, value] of formData.entries()) {
1057
+ if (value instanceof File) {
1058
+ continue;
1059
+ }
1060
+ // Extract field name from malformed keys (when FormData is passed with wrong Content-Type)
1061
+ let fieldName = key;
1062
+ if (key.includes("Content-Disposition") && key.includes('name="')) {
1063
+ // Extract field name from Content-Disposition header
1064
+ const nameMatch = key.match(/name="([^"]+)"/);
1065
+ if (nameMatch && nameMatch[1]) {
1066
+ fieldName = nameMatch[1];
1067
+ }
1068
+ else {
1069
+ // Skip if we can't extract a valid field name
1070
+ continue;
1071
+ }
1072
+ }
1073
+ else if (key.includes("------") ||
1074
+ key.includes("\r\n") ||
1075
+ key.trim() === "") {
1076
+ // Skip boundary strings and invalid keys
1077
+ continue;
1078
+ }
1079
+ hasValidFields = true;
1080
+ const stringValue = value.toString();
1081
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
1082
+ try {
1083
+ body["scopes"] = JSON.parse(stringValue);
1084
+ }
1085
+ catch {
1086
+ body["scopes"] = stringValue.includes(",")
1087
+ ? stringValue.split(",")
1088
+ : [stringValue];
1089
+ }
1090
+ }
1091
+ else if (fieldName === "oauth_identity" ||
1092
+ fieldName === "oauth_identity_json") {
1093
+ try {
1094
+ body["oauth_identity"] = JSON.parse(stringValue) || null;
1095
+ }
1096
+ catch {
1097
+ body["oauth_identity"] = null;
1098
+ }
1099
+ }
1100
+ else if (fieldName === "termsAccepted") {
1101
+ body[fieldName] =
1102
+ stringValue === "on" ||
1103
+ stringValue === "true" ||
1104
+ stringValue === "1" ||
1105
+ stringValue === "yes";
1106
+ }
1107
+ else if (fieldName === "customFields") {
1108
+ try {
1109
+ body[fieldName] = JSON.parse(stringValue);
1110
+ }
1111
+ catch {
1112
+ // Skip
1113
+ }
1114
+ }
1115
+ else {
1116
+ body[fieldName] = stringValue;
1117
+ }
1118
+ }
1119
+ }
1120
+ if (hasValidFields && Object.keys(body).length > 0) {
1121
+ if (!("termsAccepted" in body)) {
1122
+ body.termsAccepted = true;
1123
+ }
1124
+ // Default scopes to empty array if not provided
1125
+ if (!("scopes" in body)) {
1126
+ body.scopes = [];
1127
+ }
1128
+ return body;
1129
+ }
1130
+ }
1131
+ catch (formDataError) {
1132
+ // FormData parsing failed, try URL-encoded text parsing
1133
+ console.warn("[ConsentService] FormData parsing failed, trying URL-encoded text:", formDataError);
1134
+ }
1135
+ // Try URL-encoded text parsing as fallback
1136
+ try {
1137
+ const text = await request.clone().text();
1138
+ const params = new URLSearchParams(text);
1139
+ // Type assertion: URLSearchParams.entries() exists at runtime
1140
+ return parseFormFields(params.entries());
1141
+ }
1142
+ catch (urlEncodedError) {
1143
+ // Both failed, fall through to JSON parsing
1144
+ console.warn("[ConsentService] URL-encoded parsing also failed:", urlEncodedError);
1145
+ }
1146
+ }
1147
+ // Parse multipart FormData (multipart/form-data or when FormData object is passed with other Content-Type)
1148
+ // Include text/plain here to handle cases where FormData is passed with mismatched Content-Type
1149
+ if (contentType.includes("multipart/form-data") ||
1150
+ contentType.includes("form") ||
1151
+ contentType === "" ||
1152
+ contentType.includes("text/plain") ||
1153
+ contentType.includes("text")) {
1154
+ // Check if multipart/form-data Content-Type is missing boundary
1155
+ // If so, try to parse as text first (FormData might have been serialized incorrectly)
1156
+ if (contentType.includes("multipart/form-data") &&
1157
+ !contentType.includes("boundary=")) {
1158
+ try {
1159
+ const textRequest = request.clone();
1160
+ const text = await textRequest.text();
1161
+ if (text && text.length > 0) {
1162
+ // Try to manually parse multipart format from text
1163
+ const fieldRegex = /Content-Disposition:\s*form-data;\s*name="([^"]+)"\r?\n\r?\n([\s\S]*?)(?=\r?\n------|$)/g;
1164
+ const body = {};
1165
+ let match;
1166
+ let hasValidFields = false;
1167
+ while ((match = fieldRegex.exec(text)) !== null) {
1168
+ const fieldName = match[1];
1169
+ const fieldValue = match[2].trim();
1170
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
1171
+ try {
1172
+ body["scopes"] = JSON.parse(fieldValue);
1173
+ }
1174
+ catch {
1175
+ body["scopes"] = fieldValue.includes(",")
1176
+ ? fieldValue.split(",")
1177
+ : [fieldValue];
1178
+ }
1179
+ }
1180
+ else if (fieldName === "oauth_identity" ||
1181
+ fieldName === "oauth_identity_json") {
1182
+ try {
1183
+ body["oauth_identity"] = JSON.parse(fieldValue) || null;
1184
+ }
1185
+ catch {
1186
+ body["oauth_identity"] = null;
1187
+ }
1188
+ }
1189
+ else if (fieldName === "termsAccepted") {
1190
+ body[fieldName] =
1191
+ fieldValue === "on" ||
1192
+ fieldValue === "true" ||
1193
+ fieldValue === "1" ||
1194
+ fieldValue === "yes";
1195
+ }
1196
+ else if (fieldName === "customFields") {
1197
+ try {
1198
+ body[fieldName] = JSON.parse(fieldValue);
1199
+ }
1200
+ catch {
1201
+ // Skip
1202
+ }
1203
+ }
1204
+ else {
1205
+ body[fieldName] = fieldValue;
1206
+ }
1207
+ hasValidFields = true;
1208
+ }
1209
+ if (hasValidFields && Object.keys(body).length > 0) {
1210
+ if (!("termsAccepted" in body)) {
1211
+ body.termsAccepted = true;
1212
+ }
1213
+ // Default scopes to empty array if not provided
1214
+ if (!("scopes" in body)) {
1215
+ body.scopes = [];
1216
+ }
1217
+ return body;
1218
+ }
1219
+ }
1220
+ }
1221
+ catch {
1222
+ // If text parsing fails, fall through to FormData parsing
1223
+ }
1224
+ }
1225
+ try {
1226
+ const clonedRequest = request.clone();
1227
+ let formData;
1228
+ try {
1229
+ formData = await clonedRequest.formData();
1230
+ }
1231
+ catch (formDataError) {
1232
+ // Handle FormData parsing errors (missing boundary, wrong Content-Type, etc.)
1233
+ const errorMessage = formDataError instanceof Error
1234
+ ? formDataError.message
1235
+ : String(formDataError);
1236
+ const errorCause = formDataError instanceof Error && "cause" in formDataError
1237
+ ? formDataError.cause instanceof Error
1238
+ ? formDataError.cause.message
1239
+ : String(formDataError.cause)
1240
+ : "";
1241
+ if (errorMessage.includes("missing boundary") ||
1242
+ errorMessage.includes("boundary") ||
1243
+ errorMessage.includes("Content-Type was not one of") ||
1244
+ errorCause.includes("missing boundary") ||
1245
+ errorCause.includes("boundary")) {
1246
+ // When boundary is missing, try to parse as URL-encoded form data instead
1247
+ // This handles the case where FormData was passed but Content-Type doesn't include boundary
1248
+ try {
1249
+ const textRequest = request.clone();
1250
+ const text = await textRequest.text();
1251
+ // If text parsing succeeds, try URL-encoded parsing
1252
+ if (text && text.length > 0) {
1253
+ try {
1254
+ const params = new URLSearchParams(text);
1255
+ return parseFormFields(params.entries());
1256
+ }
1257
+ catch {
1258
+ // If URL-encoded parsing fails, the text might be multipart format
1259
+ // Try to manually parse multipart format from text
1260
+ const fieldRegex = /Content-Disposition:\s*form-data;\s*name="([^"]+)"\r?\n\r?\n([\s\S]*?)(?=\r?\n------|$)/g;
1261
+ const body = {};
1262
+ let match;
1263
+ let hasValidFields = false;
1264
+ while ((match = fieldRegex.exec(text)) !== null) {
1265
+ const fieldName = match[1];
1266
+ const fieldValue = match[2].trim();
1267
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
1268
+ try {
1269
+ body["scopes"] = JSON.parse(fieldValue);
1270
+ }
1271
+ catch {
1272
+ body["scopes"] = fieldValue.includes(",")
1273
+ ? fieldValue.split(",")
1274
+ : [fieldValue];
1275
+ }
1276
+ }
1277
+ else if (fieldName === "oauth_identity" ||
1278
+ fieldName === "oauth_identity_json") {
1279
+ try {
1280
+ body["oauth_identity"] = JSON.parse(fieldValue) || null;
1281
+ }
1282
+ catch {
1283
+ body["oauth_identity"] = null;
1284
+ }
1285
+ }
1286
+ else if (fieldName === "termsAccepted") {
1287
+ body[fieldName] =
1288
+ fieldValue === "on" ||
1289
+ fieldValue === "true" ||
1290
+ fieldValue === "1" ||
1291
+ fieldValue === "yes";
1292
+ }
1293
+ else if (fieldName === "customFields") {
1294
+ try {
1295
+ body[fieldName] = JSON.parse(fieldValue);
1296
+ }
1297
+ catch {
1298
+ // Skip
1299
+ }
1300
+ }
1301
+ else {
1302
+ body[fieldName] = fieldValue;
1303
+ }
1304
+ hasValidFields = true;
1305
+ }
1306
+ if (hasValidFields && Object.keys(body).length > 0) {
1307
+ if (!("termsAccepted" in body)) {
1308
+ body.termsAccepted = true;
1309
+ }
1310
+ // Default scopes to empty array if not provided
1311
+ if (!("scopes" in body)) {
1312
+ body.scopes = [];
1313
+ }
1314
+ return body;
1315
+ }
1316
+ }
1317
+ }
1318
+ }
1319
+ catch {
1320
+ // If all parsing attempts fail, rethrow the original error
1321
+ }
1322
+ }
1323
+ throw formDataError;
1324
+ }
1325
+ const body = {};
1326
+ let hasValidFields = false;
1327
+ // Check if FormData parsing returned malformed data (entire multipart body as single entry)
1328
+ // Type assertion: FormData.entries() exists at runtime in Cloudflare Workers
1329
+ const entriesArray = Array.from(formData.entries());
1330
+ if (entriesArray.length === 1 &&
1331
+ typeof entriesArray[0][0] === "string" &&
1332
+ entriesArray[0][0].includes("Content-Disposition") &&
1333
+ typeof entriesArray[0][1] === "string" &&
1334
+ entriesArray[0][1].toString().includes("Content-Disposition")) {
1335
+ // Manually parse multipart format from the value string
1336
+ const keyPart = entriesArray[0][0];
1337
+ const valuePart = entriesArray[0][1];
1338
+ // Fix: If key ends with "name" and value starts with '"fieldname"', combine them
1339
+ let multipartBody;
1340
+ if (keyPart.trim().endsWith("name") &&
1341
+ valuePart.trim().startsWith('"')) {
1342
+ multipartBody = keyPart + "=" + valuePart;
1343
+ }
1344
+ else {
1345
+ multipartBody = keyPart + valuePart;
1346
+ }
1347
+ // Match: Content-Disposition header with field name, then capture value until next boundary or end
1348
+ const fieldRegex = /Content-Disposition:\s*form-data;\s*name="([^"]+)"\r?\n\r?\n([\s\S]*?)(?=\r?\n------|$)/g;
1349
+ let match;
1350
+ while ((match = fieldRegex.exec(multipartBody)) !== null) {
1351
+ const fieldName = match[1];
1352
+ const fieldValue = match[2].trim();
1353
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
1354
+ try {
1355
+ body["scopes"] = JSON.parse(fieldValue);
1356
+ }
1357
+ catch {
1358
+ body["scopes"] = fieldValue.includes(",")
1359
+ ? fieldValue.split(",")
1360
+ : [fieldValue];
1361
+ }
1362
+ }
1363
+ else if (fieldName === "oauth_identity" ||
1364
+ fieldName === "oauth_identity_json") {
1365
+ try {
1366
+ body["oauth_identity"] = JSON.parse(fieldValue) || null;
1367
+ }
1368
+ catch {
1369
+ body["oauth_identity"] = null;
1370
+ }
1371
+ }
1372
+ else if (fieldName === "termsAccepted") {
1373
+ body[fieldName] =
1374
+ fieldValue === "on" ||
1375
+ fieldValue === "true" ||
1376
+ fieldValue === "1" ||
1377
+ fieldValue === "yes";
1378
+ }
1379
+ else if (fieldName === "customFields") {
1380
+ try {
1381
+ body[fieldName] = JSON.parse(fieldValue);
1382
+ }
1383
+ catch {
1384
+ // Skip
1385
+ }
1386
+ }
1387
+ else {
1388
+ body[fieldName] = fieldValue;
1389
+ }
1390
+ hasValidFields = true;
1391
+ }
1392
+ }
1393
+ else {
1394
+ // Normal FormData parsing
1395
+ // Type assertion: FormData.entries() exists at runtime in Cloudflare Workers
1396
+ for (const [key, value] of formData.entries()) {
1397
+ if (value instanceof File) {
1398
+ continue;
1399
+ }
1400
+ // Extract field name from malformed keys (when FormData is passed with wrong Content-Type)
1401
+ let fieldName = key;
1402
+ if (key.includes("Content-Disposition") && key.includes('name="')) {
1403
+ // Extract field name from Content-Disposition header
1404
+ const nameMatch = key.match(/name="([^"]+)"/);
1405
+ if (nameMatch && nameMatch[1]) {
1406
+ fieldName = nameMatch[1];
1407
+ }
1408
+ else {
1409
+ // Skip if we can't extract a valid field name
1410
+ continue;
1411
+ }
1412
+ }
1413
+ else if (key.includes("------") ||
1414
+ key.includes("\r\n") ||
1415
+ key.trim() === "") {
1416
+ // Skip boundary strings and invalid keys
1417
+ continue;
1418
+ }
1419
+ hasValidFields = true;
1420
+ const stringValue = value.toString();
1421
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
1422
+ try {
1423
+ body["scopes"] = JSON.parse(stringValue);
1424
+ }
1425
+ catch {
1426
+ body["scopes"] = stringValue.includes(",")
1427
+ ? stringValue.split(",")
1428
+ : [stringValue];
1429
+ }
1430
+ }
1431
+ else if (fieldName === "oauth_identity" ||
1432
+ fieldName === "oauth_identity_json") {
1433
+ try {
1434
+ body["oauth_identity"] = JSON.parse(stringValue) || null;
1435
+ }
1436
+ catch {
1437
+ body["oauth_identity"] = null;
1438
+ }
1439
+ }
1440
+ else if (fieldName === "termsAccepted") {
1441
+ body[fieldName] =
1442
+ stringValue === "on" ||
1443
+ stringValue === "true" ||
1444
+ stringValue === "1" ||
1445
+ stringValue === "yes";
1446
+ }
1447
+ else if (fieldName === "customFields") {
1448
+ try {
1449
+ body[fieldName] = JSON.parse(stringValue);
1450
+ }
1451
+ catch {
1452
+ // Skip
1453
+ }
1454
+ }
1455
+ else {
1456
+ body[fieldName] = stringValue;
1457
+ }
1458
+ }
1459
+ }
1460
+ if (hasValidFields && Object.keys(body).length > 0) {
1461
+ if (!("termsAccepted" in body)) {
1462
+ body.termsAccepted = true;
1463
+ }
1464
+ // Default scopes to empty array if not provided
1465
+ if (!("scopes" in body)) {
1466
+ body.scopes = [];
1467
+ }
1468
+ return body;
1469
+ }
1470
+ }
1471
+ catch (formDataError) {
1472
+ console.warn("[ConsentService] FormData parsing failed:", formDataError);
1473
+ // Fall through to JSON parsing
1474
+ }
1475
+ }
1476
+ // Default to JSON parsing
1477
+ try {
1478
+ return await request.json();
1479
+ }
1480
+ catch (error) {
1481
+ // If JSON parsing fails and content-type suggests form data, try FormData parsing as fallback
1482
+ // Special handling for text/plain with FormData body - try text parsing first
1483
+ if (contentType === "text/plain") {
1484
+ try {
1485
+ const textRequest = request.clone();
1486
+ const text = await textRequest.text();
1487
+ if (text && text.length > 0) {
1488
+ // Try URL-encoded parsing first
1489
+ try {
1490
+ const params = new URLSearchParams(text);
1491
+ const body = parseFormFields(params.entries());
1492
+ if (Object.keys(body).length > 0) {
1493
+ return body;
1494
+ }
1495
+ }
1496
+ catch {
1497
+ // URL-encoded parsing failed, try multipart format
1498
+ }
1499
+ // Try multipart format parsing (FormData serializes to multipart)
1500
+ const fieldRegex = /Content-Disposition:\s*form-data;\s*name="([^"]+)"\r?\n\r?\n([\s\S]*?)(?=\r?\n------|$)/g;
1501
+ const body = {};
1502
+ let match;
1503
+ let hasValidFields = false;
1504
+ while ((match = fieldRegex.exec(text)) !== null) {
1505
+ const fieldName = match[1];
1506
+ const fieldValue = match[2].trim();
1507
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
1508
+ try {
1509
+ body["scopes"] = JSON.parse(fieldValue);
1510
+ }
1511
+ catch {
1512
+ body["scopes"] = fieldValue.includes(",")
1513
+ ? fieldValue.split(",")
1514
+ : [fieldValue];
1515
+ }
1516
+ }
1517
+ else if (fieldName === "oauth_identity" ||
1518
+ fieldName === "oauth_identity_json") {
1519
+ try {
1520
+ body["oauth_identity"] = JSON.parse(fieldValue) || null;
1521
+ }
1522
+ catch {
1523
+ body["oauth_identity"] = null;
1524
+ }
1525
+ }
1526
+ else if (fieldName === "termsAccepted") {
1527
+ body[fieldName] =
1528
+ fieldValue === "on" ||
1529
+ fieldValue === "true" ||
1530
+ fieldValue === "1" ||
1531
+ fieldValue === "yes";
1532
+ }
1533
+ else if (fieldName === "customFields") {
1534
+ try {
1535
+ body[fieldName] = JSON.parse(fieldValue);
1536
+ }
1537
+ catch {
1538
+ // Skip
1539
+ }
1540
+ }
1541
+ else {
1542
+ body[fieldName] = fieldValue;
1543
+ }
1544
+ hasValidFields = true;
1545
+ }
1546
+ if (hasValidFields && Object.keys(body).length > 0) {
1547
+ if (!("termsAccepted" in body)) {
1548
+ body.termsAccepted = true;
1549
+ }
1550
+ // Default scopes to empty array if not provided
1551
+ if (!("scopes" in body)) {
1552
+ body.scopes = [];
1553
+ }
1554
+ return body;
1555
+ }
1556
+ }
1557
+ }
1558
+ catch {
1559
+ // Text parsing failed, fall through to FormData parsing
1560
+ }
1561
+ }
1562
+ if (!contentType.includes("application/json") &&
1563
+ (contentType.includes("form") ||
1564
+ contentType === "" ||
1565
+ contentType.includes("text"))) {
1566
+ try {
1567
+ // Clone request ONCE before trying any parsing, so we can reuse it if FormData parsing fails
1568
+ const fallbackRequest = request.clone();
1569
+ // Try FormData parsing as fallback (even if Content-Type doesn't match)
1570
+ let formData;
1571
+ try {
1572
+ formData = await fallbackRequest.formData();
1573
+ }
1574
+ catch (formDataParseError) {
1575
+ // If FormData parsing fails, try reading as text and parsing manually
1576
+ // This handles cases where Content-Type doesn't match (e.g., text/plain with FormData body)
1577
+ try {
1578
+ // Use a fresh clone for text parsing (body might be consumed by failed FormData attempt)
1579
+ const textRequest = request.clone();
1580
+ const text = await textRequest.text();
1581
+ if (text && text.length > 0) {
1582
+ // First try URL-encoded parsing (simpler format)
1583
+ try {
1584
+ const params = new URLSearchParams(text);
1585
+ const body = parseFormFields(params.entries());
1586
+ if (Object.keys(body).length > 0) {
1587
+ return body;
1588
+ }
1589
+ }
1590
+ catch {
1591
+ // URL-encoded parsing failed, try multipart format
1592
+ }
1593
+ // Try to manually parse multipart format from text
1594
+ const fieldRegex = /Content-Disposition:\s*form-data;\s*name="([^"]+)"\r?\n\r?\n([\s\S]*?)(?=\r?\n------|$)/g;
1595
+ const body = {};
1596
+ let match;
1597
+ let hasValidFields = false;
1598
+ while ((match = fieldRegex.exec(text)) !== null) {
1599
+ const fieldName = match[1];
1600
+ const fieldValue = match[2].trim();
1601
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
1602
+ try {
1603
+ body["scopes"] = JSON.parse(fieldValue);
1604
+ }
1605
+ catch {
1606
+ body["scopes"] = fieldValue.includes(",")
1607
+ ? fieldValue.split(",")
1608
+ : [fieldValue];
1609
+ }
1610
+ }
1611
+ else if (fieldName === "oauth_identity" ||
1612
+ fieldName === "oauth_identity_json") {
1613
+ try {
1614
+ body["oauth_identity"] = JSON.parse(fieldValue) || null;
1615
+ }
1616
+ catch {
1617
+ body["oauth_identity"] = null;
1618
+ }
1619
+ }
1620
+ else if (fieldName === "termsAccepted") {
1621
+ body[fieldName] =
1622
+ fieldValue === "on" ||
1623
+ fieldValue === "true" ||
1624
+ fieldValue === "1" ||
1625
+ fieldValue === "yes";
1626
+ }
1627
+ else if (fieldName === "customFields") {
1628
+ try {
1629
+ body[fieldName] = JSON.parse(fieldValue);
1630
+ }
1631
+ catch {
1632
+ // Skip
1633
+ }
1634
+ }
1635
+ else {
1636
+ body[fieldName] = fieldValue;
1637
+ }
1638
+ hasValidFields = true;
1639
+ }
1640
+ if (hasValidFields && Object.keys(body).length > 0) {
1641
+ if (!("termsAccepted" in body)) {
1642
+ body.termsAccepted = true;
1643
+ }
1644
+ // Default scopes to empty array if not provided
1645
+ if (!("scopes" in body)) {
1646
+ body.scopes = [];
1647
+ }
1648
+ return body;
1649
+ }
1650
+ }
1651
+ }
1652
+ catch {
1653
+ // If text parsing also fails, rethrow original FormData error
1654
+ }
1655
+ throw formDataParseError;
1656
+ }
1657
+ // Check if FormData has valid entries (might be empty if Content-Type mismatch)
1658
+ const entriesArray = Array.from(formData.entries());
1659
+ if (entriesArray.length === 0) {
1660
+ // FormData parsing succeeded but returned no entries - try text parsing
1661
+ // This handles cases where Content-Type doesn't match (e.g., text/plain with FormData body)
1662
+ try {
1663
+ const textRequest = request.clone();
1664
+ const text = await textRequest.text();
1665
+ if (text && text.length > 0) {
1666
+ // Try URL-encoded parsing first
1667
+ try {
1668
+ const params = new URLSearchParams(text);
1669
+ const body = parseFormFields(params.entries());
1670
+ if (Object.keys(body).length > 0) {
1671
+ return body;
1672
+ }
1673
+ }
1674
+ catch {
1675
+ // URL-encoded parsing failed, try multipart format
1676
+ }
1677
+ // Try multipart format parsing
1678
+ const fieldRegex = /Content-Disposition:\s*form-data;\s*name="([^"]+)"\r?\n\r?\n([\s\S]*?)(?=\r?\n------|$)/g;
1679
+ const body = {};
1680
+ let match;
1681
+ let hasValidFields = false;
1682
+ while ((match = fieldRegex.exec(text)) !== null) {
1683
+ const fieldName = match[1];
1684
+ const fieldValue = match[2].trim();
1685
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
1686
+ try {
1687
+ body["scopes"] = JSON.parse(fieldValue);
1688
+ }
1689
+ catch {
1690
+ body["scopes"] = fieldValue.includes(",")
1691
+ ? fieldValue.split(",")
1692
+ : [fieldValue];
1693
+ }
1694
+ }
1695
+ else if (fieldName === "oauth_identity" ||
1696
+ fieldName === "oauth_identity_json") {
1697
+ try {
1698
+ body["oauth_identity"] = JSON.parse(fieldValue) || null;
1699
+ }
1700
+ catch {
1701
+ body["oauth_identity"] = null;
1702
+ }
1703
+ }
1704
+ else if (fieldName === "termsAccepted") {
1705
+ body[fieldName] =
1706
+ fieldValue === "on" ||
1707
+ fieldValue === "true" ||
1708
+ fieldValue === "1" ||
1709
+ fieldValue === "yes";
1710
+ }
1711
+ else if (fieldName === "customFields") {
1712
+ try {
1713
+ body[fieldName] = JSON.parse(fieldValue);
1714
+ }
1715
+ catch {
1716
+ // Skip
1717
+ }
1718
+ }
1719
+ else {
1720
+ body[fieldName] = fieldValue;
1721
+ }
1722
+ hasValidFields = true;
1723
+ }
1724
+ if (hasValidFields && Object.keys(body).length > 0) {
1725
+ if (!("termsAccepted" in body)) {
1726
+ body.termsAccepted = true;
1727
+ }
1728
+ // Default scopes to empty array if not provided
1729
+ if (!("scopes" in body)) {
1730
+ body.scopes = [];
1731
+ }
1732
+ return body;
1733
+ }
1734
+ }
1735
+ // If text parsing failed or found no valid fields, throw error to trigger fallback
1736
+ throw new Error("FormData parsing returned empty entries and text parsing found no valid fields");
1737
+ }
1738
+ catch (textParseError) {
1739
+ // Text parsing failed or found no valid fields - throw error to trigger JSON fallback
1740
+ // This ensures we don't continue with empty FormData entries
1741
+ throw new Error(`Failed to parse FormData: ${textParseError instanceof Error ? textParseError.message : "Unknown error"}`);
1742
+ }
1743
+ }
1744
+ const body = {};
1745
+ // Type assertion: FormData.entries() exists at runtime in Cloudflare Workers
1746
+ let hasValidEntries = false;
1747
+ for (const [key, value] of formData.entries()) {
1748
+ if (value instanceof File)
1749
+ continue;
1750
+ // Extract field name from malformed keys
1751
+ let fieldName = key;
1752
+ if (key.includes("Content-Disposition") && key.includes('name="')) {
1753
+ const nameMatch = key.match(/name="([^"]+)"/);
1754
+ if (nameMatch && nameMatch[1]) {
1755
+ fieldName = nameMatch[1];
1756
+ }
1757
+ else {
1758
+ continue;
1759
+ }
1760
+ }
1761
+ else if (key.includes("------") ||
1762
+ key.includes("\r\n") ||
1763
+ key.trim() === "" ||
1764
+ key.includes("formdata-undici")) {
1765
+ // Malformed key - likely from text/plain Content-Type mismatch
1766
+ // Skip this entry and fall back to text parsing
1767
+ continue;
1768
+ }
1769
+ // If we have a valid field name, mark as having valid entries
1770
+ if (fieldName && fieldName !== key) {
1771
+ hasValidEntries = true;
1772
+ }
1773
+ else if (fieldName &&
1774
+ !key.includes("Content-Disposition") &&
1775
+ !key.includes("------") &&
1776
+ !key.includes("\r\n")) {
1777
+ hasValidEntries = true;
1778
+ }
1779
+ // Process the field value
1780
+ const stringValue = value.toString();
1781
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
1782
+ try {
1783
+ body["scopes"] = JSON.parse(stringValue);
1784
+ }
1785
+ catch {
1786
+ body["scopes"] = stringValue.includes(",")
1787
+ ? stringValue.split(",")
1788
+ : [stringValue];
1789
+ }
1790
+ }
1791
+ else if (fieldName === "oauth_identity" ||
1792
+ fieldName === "oauth_identity_json") {
1793
+ try {
1794
+ body["oauth_identity"] = JSON.parse(stringValue) || null;
1795
+ }
1796
+ catch {
1797
+ body["oauth_identity"] = null;
1798
+ }
1799
+ }
1800
+ else if (fieldName === "termsAccepted") {
1801
+ body[fieldName] =
1802
+ stringValue === "on" ||
1803
+ stringValue === "true" ||
1804
+ stringValue === "1" ||
1805
+ stringValue === "yes";
1806
+ }
1807
+ else if (fieldName === "customFields") {
1808
+ try {
1809
+ body[fieldName] = JSON.parse(stringValue);
1810
+ }
1811
+ catch {
1812
+ // Skip
1813
+ }
1814
+ }
1815
+ else {
1816
+ body[fieldName] = stringValue;
1817
+ }
1818
+ }
1819
+ // If we didn't get any valid entries (all keys were malformed), try text parsing
1820
+ if (!hasValidEntries || Object.keys(body).length === 0) {
1821
+ // Try text parsing as fallback when FormData parsing returns no valid entries
1822
+ try {
1823
+ const textRequest = request.clone();
1824
+ const text = await textRequest.text();
1825
+ if (text && text.length > 0) {
1826
+ // Try multipart format parsing from text
1827
+ const fieldRegex = /Content-Disposition:\s*form-data;\s*name="([^"]+)"\r?\n\r?\n([\s\S]*?)(?=\r?\n------|$)/g;
1828
+ const textBody = {};
1829
+ let match;
1830
+ let hasValidFields = false;
1831
+ while ((match = fieldRegex.exec(text)) !== null) {
1832
+ const fieldName = match[1];
1833
+ const fieldValue = match[2].trim();
1834
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
1835
+ try {
1836
+ textBody["scopes"] = JSON.parse(fieldValue);
1837
+ }
1838
+ catch {
1839
+ textBody["scopes"] = fieldValue.includes(",")
1840
+ ? fieldValue.split(",")
1841
+ : [fieldValue];
1842
+ }
1843
+ }
1844
+ else if (fieldName === "oauth_identity" ||
1845
+ fieldName === "oauth_identity_json") {
1846
+ try {
1847
+ textBody["oauth_identity"] =
1848
+ JSON.parse(fieldValue) || null;
1849
+ }
1850
+ catch {
1851
+ textBody["oauth_identity"] = null;
1852
+ }
1853
+ }
1854
+ else if (fieldName === "termsAccepted") {
1855
+ textBody[fieldName] =
1856
+ fieldValue === "on" ||
1857
+ fieldValue === "true" ||
1858
+ fieldValue === "1" ||
1859
+ fieldValue === "yes";
1860
+ }
1861
+ else if (fieldName === "customFields") {
1862
+ try {
1863
+ textBody[fieldName] = JSON.parse(fieldValue);
1864
+ }
1865
+ catch {
1866
+ // Skip
1867
+ }
1868
+ }
1869
+ else {
1870
+ textBody[fieldName] = fieldValue;
1871
+ }
1872
+ hasValidFields = true;
1873
+ }
1874
+ if (hasValidFields && Object.keys(textBody).length > 0) {
1875
+ if (!("termsAccepted" in textBody)) {
1876
+ textBody.termsAccepted = true;
1877
+ }
1878
+ if (!("scopes" in textBody)) {
1879
+ textBody.scopes = [];
1880
+ }
1881
+ return textBody;
1882
+ }
1883
+ }
1884
+ }
1885
+ catch {
1886
+ // Text parsing also failed, fall through to throw error
1887
+ }
1888
+ throw new Error("FormData parsing returned only malformed entries - falling back to text parsing");
1889
+ }
1890
+ if (!("termsAccepted" in body)) {
1891
+ body.termsAccepted = true;
1892
+ }
1893
+ // Default scopes to empty array if not provided
1894
+ if (!("scopes" in body)) {
1895
+ body.scopes = [];
1896
+ }
1897
+ return body;
1898
+ }
1899
+ catch (formError) {
1900
+ // FormData parsing failed - if it was due to malformed entries, try text parsing
1901
+ const errorMessage = formError instanceof Error ? formError.message : String(formError);
1902
+ if (errorMessage.includes("malformed entries") ||
1903
+ errorMessage.includes("empty entries") ||
1904
+ errorMessage.includes("falling back to text parsing")) {
1905
+ // Try text parsing as last resort
1906
+ try {
1907
+ const textRequest = request.clone();
1908
+ const text = await textRequest.text();
1909
+ if (text && text.length > 0) {
1910
+ // Try multipart format parsing
1911
+ const fieldRegex = /Content-Disposition:\s*form-data;\s*name="([^"]+)"\r?\n\r?\n([\s\S]*?)(?=\r?\n------|$)/g;
1912
+ const body = {};
1913
+ let match;
1914
+ let hasValidFields = false;
1915
+ while ((match = fieldRegex.exec(text)) !== null) {
1916
+ const fieldName = match[1];
1917
+ const fieldValue = match[2].trim();
1918
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
1919
+ try {
1920
+ body["scopes"] = JSON.parse(fieldValue);
1921
+ }
1922
+ catch {
1923
+ body["scopes"] = fieldValue.includes(",")
1924
+ ? fieldValue.split(",")
1925
+ : [fieldValue];
1926
+ }
1927
+ }
1928
+ else if (fieldName === "oauth_identity" ||
1929
+ fieldName === "oauth_identity_json") {
1930
+ try {
1931
+ body["oauth_identity"] = JSON.parse(fieldValue) || null;
1932
+ }
1933
+ catch {
1934
+ body["oauth_identity"] = null;
1935
+ }
1936
+ }
1937
+ else if (fieldName === "termsAccepted") {
1938
+ body[fieldName] =
1939
+ fieldValue === "on" ||
1940
+ fieldValue === "true" ||
1941
+ fieldValue === "1" ||
1942
+ fieldValue === "yes";
1943
+ }
1944
+ else if (fieldName === "customFields") {
1945
+ try {
1946
+ body[fieldName] = JSON.parse(fieldValue);
1947
+ }
1948
+ catch {
1949
+ // Skip
1950
+ }
1951
+ }
1952
+ else {
1953
+ body[fieldName] = fieldValue;
1954
+ }
1955
+ hasValidFields = true;
1956
+ }
1957
+ if (hasValidFields && Object.keys(body).length > 0) {
1958
+ if (!("termsAccepted" in body)) {
1959
+ body.termsAccepted = true;
1960
+ }
1961
+ // Default scopes to empty array if not provided
1962
+ if (!("scopes" in body)) {
1963
+ body.scopes = [];
1964
+ }
1965
+ return body;
1966
+ }
1967
+ }
1968
+ }
1969
+ catch {
1970
+ // Text parsing also failed
1971
+ }
1972
+ }
1973
+ // Both failed, throw original error
1974
+ }
1975
+ }
1976
+ throw new Error(`Failed to parse request body: ${error instanceof Error ? error.message : "Unknown error"}`);
1977
+ }
1978
+ }
454
1979
  /**
455
1980
  * Handle consent approval
456
1981
  *
@@ -463,13 +1988,25 @@ export class ConsentService {
463
1988
  async handleApproval(request) {
464
1989
  console.log("[ConsentService] Approval request received");
465
1990
  try {
466
- // Parse and validate request body
467
- const body = await request.json();
1991
+ // Parse and validate request body (supports both JSON and FormData)
1992
+ const body = await this.parseRequestBody(request);
468
1993
  console.log("[ConsentService] Request body parsed:", {
469
1994
  hasBody: !!body,
470
1995
  bodyKeys: Object.keys(body || {}),
471
1996
  hasOAuthIdentity: !!body?.oauth_identity,
472
1997
  });
1998
+ // Convert null oauth_identity to undefined for proper schema validation
1999
+ // Zod's .nullish() should handle null, but converting to undefined is more explicit
2000
+ // and avoids potential edge cases with FormData parsing
2001
+ if (body &&
2002
+ typeof body === "object" &&
2003
+ body !== null &&
2004
+ "oauth_identity" in body) {
2005
+ const bodyObj = body;
2006
+ if (bodyObj.oauth_identity === null) {
2007
+ bodyObj.oauth_identity = undefined;
2008
+ }
2009
+ }
473
2010
  const validation = validateConsentApprovalRequest(body);
474
2011
  if (!validation.success) {
475
2012
  console.error("[ConsentService] Approval request validation failed:", {
@@ -506,6 +2043,32 @@ export class ConsentService {
506
2043
  headers: { "Content-Type": "application/json" },
507
2044
  });
508
2045
  }
2046
+ // ✅ Extract projectId from approval request
2047
+ const projectId = approvalRequest.project_id;
2048
+ // ✅ Lazy initialization with projectId
2049
+ const auditService = await this.getAuditService(projectId);
2050
+ // Check if user needs credentials before delegation
2051
+ const needsCredentials = !approvalRequest.user_did && !approvalRequest.oauth_identity;
2052
+ if (needsCredentials && auditService) {
2053
+ await auditService
2054
+ .logCredentialRequired({
2055
+ sessionId: approvalRequest.session_id,
2056
+ agentDid: approvalRequest.agent_did,
2057
+ targetTools: [approvalRequest.tool], // Array
2058
+ scopes: approvalRequest.scopes,
2059
+ projectId,
2060
+ oauthProvider: approvalRequest.oauth_identity?.provider,
2061
+ })
2062
+ .catch((err) => {
2063
+ console.error("[ConsentService] Failed to log credential required", {
2064
+ eventType: "consent:credential_required",
2065
+ sessionId: approvalRequest.session_id,
2066
+ error: err instanceof Error ? err.message : String(err),
2067
+ });
2068
+ });
2069
+ // Note: We don't redirect here - the consent flow continues
2070
+ // The credential_required event is just for audit tracking
2071
+ }
509
2072
  // Create delegation via AgentShield API
510
2073
  console.log("[ConsentService] Creating delegation...");
511
2074
  const delegationResult = await this.createDelegation(approvalRequest);
@@ -528,6 +2091,55 @@ export class ConsentService {
528
2091
  });
529
2092
  // Store delegation token in KV
530
2093
  await this.storeDelegationToken(approvalRequest.session_id, approvalRequest.agent_did, delegationResult.delegation_token, delegationResult.delegation_id);
2094
+ // ✅ After successful delegation creation - log audit events
2095
+ if (auditService && delegationResult.success) {
2096
+ try {
2097
+ // Get userDid (may have been generated during delegation creation)
2098
+ // getUserDidForSession can work without DELEGATION_STORAGE (uses in-memory UserDidManager)
2099
+ let userDid;
2100
+ if (approvalRequest.session_id) {
2101
+ try {
2102
+ userDid = await this.getUserDidForSession(approvalRequest.session_id, approvalRequest.oauth_identity || undefined);
2103
+ }
2104
+ catch (error) {
2105
+ console.warn("[ConsentService] Failed to get userDid for audit logging:", error);
2106
+ // Continue without userDid - audit events can still be logged
2107
+ }
2108
+ }
2109
+ await auditService.logConsentApproval({
2110
+ sessionId: approvalRequest.session_id,
2111
+ userDid,
2112
+ agentDid: approvalRequest.agent_did,
2113
+ targetTools: [approvalRequest.tool], // Array
2114
+ scopes: approvalRequest.scopes,
2115
+ delegationId: delegationResult.delegation_id,
2116
+ projectId,
2117
+ termsAccepted: approvalRequest.termsAccepted || false,
2118
+ oauthIdentity: approvalRequest.oauth_identity
2119
+ ? {
2120
+ provider: approvalRequest.oauth_identity.provider,
2121
+ identifier: approvalRequest.oauth_identity.subject,
2122
+ }
2123
+ : undefined,
2124
+ });
2125
+ await auditService.logDelegationCreated({
2126
+ sessionId: approvalRequest.session_id,
2127
+ delegationId: delegationResult.delegation_id,
2128
+ agentDid: approvalRequest.agent_did,
2129
+ userDid,
2130
+ targetTools: [approvalRequest.tool], // Array
2131
+ scopes: approvalRequest.scopes,
2132
+ projectId,
2133
+ });
2134
+ }
2135
+ catch (error) {
2136
+ console.error("[ConsentService] Audit failed but continuing", {
2137
+ sessionId: approvalRequest.session_id,
2138
+ error: error instanceof Error ? error.message : String(error),
2139
+ eventTypes: ["consent:approved", "consent:delegation_created"],
2140
+ });
2141
+ }
2142
+ }
531
2143
  // Return success response
532
2144
  const response = {
533
2145
  success: true,
@@ -575,15 +2187,18 @@ export class ConsentService {
575
2187
  // Get userDID from session or generate new ephemeral DID
576
2188
  // Phase 4 PR #3: Use OAuth identity if provided in approval request
577
2189
  // CRITICAL: Must work with or without OAuth identity
2190
+ // CRITICAL: Always generate ephemeral DID if session_id is available, even without DELEGATION_STORAGE
578
2191
  let userDid;
579
- if (this.env.DELEGATION_STORAGE && request.session_id) {
2192
+ if (request.session_id) {
580
2193
  try {
581
2194
  console.log("[ConsentService] Getting User DID for session:", {
582
2195
  sessionId: request.session_id.substring(0, 20) + "...",
583
2196
  hasOAuthIdentity: !!request.oauth_identity,
584
2197
  oauthProvider: request.oauth_identity?.provider,
2198
+ hasStorage: !!this.env.DELEGATION_STORAGE,
585
2199
  });
586
2200
  // Pass OAuth identity if available in approval request (can be null/undefined)
2201
+ // getUserDidForSession can work without DELEGATION_STORAGE (uses in-memory UserDidManager)
587
2202
  userDid = await this.getUserDidForSession(request.session_id, request.oauth_identity || undefined // Explicitly handle null as undefined
588
2203
  );
589
2204
  console.log("[ConsentService] User DID retrieved:", {
@@ -594,14 +2209,12 @@ export class ConsentService {
594
2209
  catch (error) {
595
2210
  console.error("[ConsentService] Failed to get/generate userDid:", error);
596
2211
  // Continue without userDid - delegation will work without user_identifier
597
- // This is valid for non-OAuth scenarios
2212
+ // This is valid for non-OAuth scenarios, but we should log this as a warning
2213
+ console.warn("[ConsentService] Delegation will be created without user_identifier - this may affect user tracking");
598
2214
  }
599
2215
  }
600
2216
  else {
601
- console.log("[ConsentService] Skipping User DID retrieval:", {
602
- hasStorage: !!this.env.DELEGATION_STORAGE,
603
- hasSessionId: !!request.session_id,
604
- });
2217
+ console.log("[ConsentService] No session_id provided - skipping User DID generation");
605
2218
  }
606
2219
  const expiresInDays = 7; // Default to 7 days
607
2220
  // Build delegation request with error-based format detection
@@ -854,13 +2467,15 @@ export class ConsentService {
854
2467
  */
855
2468
  async buildFullFormatRequest(request, userDid, expiresInDays) {
856
2469
  const notAfter = Date.now() + expiresInDays * 24 * 60 * 60 * 1000;
2470
+ // Defensive check: ensure scopes is always defined (should be guaranteed by validation)
2471
+ const scopes = request.scopes ?? [];
857
2472
  return {
858
2473
  delegation: {
859
2474
  id: crypto.randomUUID(),
860
2475
  issuerDid: userDid || "did:key:z6MkEphemeral", // Use ephemeral if no userDid
861
2476
  subjectDid: request.agent_did,
862
2477
  constraints: {
863
- scopes: request.scopes,
2478
+ scopes,
864
2479
  notAfter,
865
2480
  notBefore: Date.now(),
866
2481
  },
@@ -895,9 +2510,11 @@ export class ConsentService {
895
2510
  */
896
2511
  buildSimplifiedFormatRequest(request, userDid, expiresInDays, fieldName) {
897
2512
  // Build request with ONLY fields that are in AgentShield's schema
2513
+ // Defensive check: ensure scopes is always defined (should be guaranteed by validation)
2514
+ const scopes = request.scopes ?? [];
898
2515
  const simplifiedRequest = {
899
2516
  agent_did: request.agent_did,
900
- scopes: request.scopes,
2517
+ scopes,
901
2518
  expires_in_days: expiresInDays,
902
2519
  };
903
2520
  // Include user_identifier if we have userDid (matches AgentShield schema)
@@ -912,7 +2529,7 @@ export class ConsentService {
912
2529
  console.log("[ConsentService] No user_identifier (no OAuth or ephemeral DID) - delegation will proceed without it");
913
2530
  }
914
2531
  // AgentShield API only accepts "custom_fields", not "metadata"
915
- // Always use "custom_fields" regardless of Day0 config
2532
+ // Always use "custom_fields" regardless of Day0 config
916
2533
  if (userDid) {
917
2534
  // Include issuer_did and subject_did in custom_fields when we have userDid
918
2535
  simplifiedRequest.custom_fields = {
@@ -971,11 +2588,11 @@ export class ConsentService {
971
2588
  // FINAL SAFEGUARD: Remove session_id and project_id if they somehow got added
972
2589
  // This provides defense-in-depth protection
973
2590
  const sanitizedBody = { ...requestBody };
974
- if ('session_id' in sanitizedBody) {
2591
+ if ("session_id" in sanitizedBody) {
975
2592
  console.warn("[ConsentService] ⚠️ session_id detected in request body - removing (not in schema)");
976
2593
  delete sanitizedBody.session_id;
977
2594
  }
978
- if ('project_id' in sanitizedBody) {
2595
+ if ("project_id" in sanitizedBody) {
979
2596
  console.warn("[ConsentService] ⚠️ project_id detected in request body - removing (not in schema)");
980
2597
  delete sanitizedBody.project_id;
981
2598
  }
@@ -998,13 +2615,15 @@ export class ConsentService {
998
2615
  }
999
2616
  // Check for validation error specifically
1000
2617
  if (response.status === 400) {
1001
- const errorMessage = responseData
1002
- ?.error?.message ||
1003
- responseData?.message ||
1004
- "Validation failed";
1005
- if (errorMessage.includes("format") ||
2618
+ const errorData = responseData;
2619
+ const errorMessage = errorData.error?.message || errorData.message || "Validation failed";
2620
+ const errorCode = errorData.error_code || errorData.error?.code;
2621
+ // Check if error_code is explicitly set to "validation_error" OR error message suggests validation error
2622
+ if (errorCode === "validation_error" ||
2623
+ errorMessage.includes("format") ||
1006
2624
  errorMessage.includes("schema") ||
1007
- errorMessage.includes("invalid")) {
2625
+ errorMessage.includes("invalid") ||
2626
+ errorMessage.includes("Validation")) {
1008
2627
  return {
1009
2628
  success: false,
1010
2629
  error: errorMessage,