@kya-os/mcp-i-cloudflare 1.5.8-canary.3 → 1.5.8-canary.30

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 (51) hide show
  1. package/dist/__tests__/e2e/test-config.d.ts +37 -0
  2. package/dist/__tests__/e2e/test-config.d.ts.map +1 -0
  3. package/dist/__tests__/e2e/test-config.js +62 -0
  4. package/dist/__tests__/e2e/test-config.js.map +1 -0
  5. package/dist/adapter.d.ts +31 -0
  6. package/dist/adapter.d.ts.map +1 -1
  7. package/dist/adapter.js +416 -58
  8. package/dist/adapter.js.map +1 -1
  9. package/dist/agent.d.ts.map +1 -1
  10. package/dist/agent.js +87 -3
  11. package/dist/agent.js.map +1 -1
  12. package/dist/app.d.ts.map +1 -1
  13. package/dist/app.js +19 -3
  14. package/dist/app.js.map +1 -1
  15. package/dist/config.d.ts.map +1 -1
  16. package/dist/config.js +33 -4
  17. package/dist/config.js.map +1 -1
  18. package/dist/helpers/env-mapper.d.ts +60 -1
  19. package/dist/helpers/env-mapper.d.ts.map +1 -1
  20. package/dist/helpers/env-mapper.js +136 -6
  21. package/dist/helpers/env-mapper.js.map +1 -1
  22. package/dist/index.d.ts +1 -1
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +6 -2
  25. package/dist/index.js.map +1 -1
  26. package/dist/runtime/audit-logger.d.ts +96 -0
  27. package/dist/runtime/audit-logger.d.ts.map +1 -0
  28. package/dist/runtime/audit-logger.js +276 -0
  29. package/dist/runtime/audit-logger.js.map +1 -0
  30. package/dist/runtime.d.ts +12 -1
  31. package/dist/runtime.d.ts.map +1 -1
  32. package/dist/runtime.js +30 -2
  33. package/dist/runtime.js.map +1 -1
  34. package/dist/services/admin.service.d.ts.map +1 -1
  35. package/dist/services/admin.service.js +15 -1
  36. package/dist/services/admin.service.js.map +1 -1
  37. package/dist/services/consent-audit.service.d.ts +91 -0
  38. package/dist/services/consent-audit.service.d.ts.map +1 -0
  39. package/dist/services/consent-audit.service.js +243 -0
  40. package/dist/services/consent-audit.service.js.map +1 -0
  41. package/dist/services/consent.service.d.ts +43 -0
  42. package/dist/services/consent.service.d.ts.map +1 -1
  43. package/dist/services/consent.service.js +1420 -20
  44. package/dist/services/consent.service.js.map +1 -1
  45. package/dist/services/proof.service.d.ts +5 -3
  46. package/dist/services/proof.service.d.ts.map +1 -1
  47. package/dist/services/proof.service.js +19 -6
  48. package/dist/services/proof.service.js.map +1 -1
  49. package/dist/types.d.ts +28 -0
  50. package/dist/types.d.ts.map +1 -1
  51. package/package.json +13 -9
@@ -15,17 +15,163 @@ 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/config/remote-config";
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
28
+ // ✅ Audit service - lazy initialized
29
+ auditService;
30
+ auditInitPromise; // Cache promise to prevent race conditions
31
+ /**
32
+ * ✅ FIXED: Constructor takes env: CloudflareEnv, not config
33
+ */
24
34
  constructor(env, runtime) {
25
35
  this.env = env;
26
36
  this.runtime = runtime;
27
37
  this.configService = new ConsentConfigService(env);
28
38
  this.renderer = new ConsentPageRenderer();
39
+ // No initialization here - keep constructor synchronous
40
+ }
41
+ /**
42
+ * Get or initialize audit service (lazy initialization)
43
+ *
44
+ * Fetches config from remote API when projectId is available.
45
+ * Uses promise caching to prevent race conditions.
46
+ *
47
+ * @param projectId - Project ID from consent request (required for config fetch)
48
+ */
49
+ async getAuditService(projectId) {
50
+ // Already initialized
51
+ if (this.auditService) {
52
+ return this.auditService;
53
+ }
54
+ // No runtime - audit not available
55
+ if (!this.runtime) {
56
+ return undefined;
57
+ }
58
+ // Initialization in progress - wait for it
59
+ if (this.auditInitPromise) {
60
+ await this.auditInitPromise;
61
+ return this.auditService;
62
+ }
63
+ // Start initialization (with projectId for config fetch)
64
+ this.auditInitPromise = this.initializeAuditService(projectId);
65
+ try {
66
+ await this.auditInitPromise;
67
+ }
68
+ catch (error) {
69
+ console.warn("[ConsentService] Audit service initialization failed:", error);
70
+ // Don't throw - audit failures shouldn't break consent flow
71
+ }
72
+ return this.auditService;
73
+ }
74
+ /**
75
+ * Initialize audit service - fetches config from remote API
76
+ *
77
+ * ⚠️ CRITICAL: Fetches config from remote API using fetchRemoteConfig()
78
+ * This is the ONLY way to get CloudflareRuntimeConfig per requirement.
79
+ */
80
+ async initializeAuditService(projectId) {
81
+ if (!this.runtime) {
82
+ return;
83
+ }
84
+ try {
85
+ // ✅ CRITICAL: Fetch config from remote API
86
+ const config = await this.getConfigFromRemoteAPI(projectId);
87
+ if (!config?.proofing?.enabled) {
88
+ console.log("[ConsentService] Proofing not enabled in remote config");
89
+ return; // Proofing not enabled
90
+ }
91
+ // Get identity (async - requires runtime to be initialized)
92
+ const identity = await this.runtime.getIdentity();
93
+ // ✅ FIXED: CloudflareProofGenerator only takes identity, not providers
94
+ const proofGenerator = new CloudflareProofGenerator(identity);
95
+ // Get audit logger
96
+ const auditLogger = this.runtime.getAuditLogger();
97
+ if (!auditLogger) {
98
+ console.warn("[ConsentService] AuditLogger not available");
99
+ return;
100
+ }
101
+ // Create audit service with fetched config
102
+ this.auditService = new ConsentAuditService(new ProofService(config, this.runtime), auditLogger, proofGenerator, config, // ✅ Config fetched from remote API
103
+ this.runtime);
104
+ console.log("[ConsentService] Audit service initialized successfully");
105
+ }
106
+ catch (error) {
107
+ console.error("[ConsentService] Failed to initialize audit service:", error);
108
+ // Don't throw - audit failures shouldn't break consent flow
109
+ }
110
+ }
111
+ /**
112
+ * Fetch CloudflareRuntimeConfig from remote API (AgentShield)
113
+ *
114
+ * ⚠️ CRITICAL: Config MUST be fetched from remote API, not constructed from env.
115
+ *
116
+ * Uses existing `fetchRemoteConfig()` from `@kya-os/mcp-i-core/config/remote-config`
117
+ * which handles caching, error handling, and API communication.
118
+ *
119
+ * @param projectId - Project ID from consent request
120
+ * @returns Runtime config or undefined if unavailable
121
+ */
122
+ async getConfigFromRemoteAPI(projectId) {
123
+ if (!this.env.AGENTSHIELD_API_KEY) {
124
+ console.warn("[ConsentService] No API key for runtime config fetch");
125
+ return undefined;
126
+ }
127
+ try {
128
+ // Create KV cache adapter
129
+ const cache = this.env.TOOL_PROTECTION_KV
130
+ ? {
131
+ get: async (key) => {
132
+ return ((await this.env.TOOL_PROTECTION_KV.get(key, "text")) || null);
133
+ },
134
+ set: async (key, value, ttl) => {
135
+ await this.env.TOOL_PROTECTION_KV.put(key, value, {
136
+ expirationTtl: Math.floor(ttl / 1000),
137
+ });
138
+ },
139
+ }
140
+ : undefined;
141
+ const config = await fetchRemoteConfig({
142
+ apiUrl: this.env.AGENTSHIELD_API_URL || "https://kya.vouched.id",
143
+ apiKey: this.env.AGENTSHIELD_API_KEY,
144
+ projectId, // ✅ Use projectId from consent request
145
+ cacheTtl: 300000, // 5 minutes
146
+ fetchProvider: fetch,
147
+ }, cache);
148
+ // Populate serverDid from runtime identity if missing or empty
149
+ // This prevents AgentShield validation errors (serverDid must be at least 1 character)
150
+ // Note: MCPIConfig.identity is RuntimeIdentityConfig (no serverDid), but AgentShield
151
+ // may return MCPIServerConfig format (has serverDid). We need to handle both.
152
+ if (config && config.identity) {
153
+ const identityConfig = config.identity; // Type assertion for serverDid field
154
+ if (!identityConfig.serverDid || identityConfig.serverDid === "") {
155
+ try {
156
+ const runtimeIdentity = await this.runtime?.getIdentity();
157
+ if (runtimeIdentity?.did) {
158
+ identityConfig.serverDid = runtimeIdentity.did;
159
+ console.log("[ConsentService] Populated serverDid from runtime identity");
160
+ }
161
+ }
162
+ catch (error) {
163
+ console.warn("[ConsentService] Failed to get runtime identity for serverDid:", error);
164
+ }
165
+ }
166
+ }
167
+ // fetchRemoteConfig returns MCPIConfig | null
168
+ // CloudflareRuntimeConfig extends MCPIConfig, so cast is safe
169
+ return config;
170
+ }
171
+ catch (error) {
172
+ console.warn("[ConsentService] Error fetching runtime config:", error);
173
+ return undefined;
174
+ }
29
175
  }
30
176
  /**
31
177
  * Get or generate User DID for a session
@@ -38,13 +184,21 @@ export class ConsentService {
38
184
  * @returns User DID (did:key format)
39
185
  */
40
186
  async getUserDidForSession(sessionId, oauthIdentity) {
187
+ // Handle null explicitly (from JSON parsing)
188
+ const hasOAuthIdentity = oauthIdentity &&
189
+ typeof oauthIdentity === "object" &&
190
+ oauthIdentity.provider &&
191
+ oauthIdentity.subject;
41
192
  // If OAuth identity provided, check for existing mapping first
42
- if (oauthIdentity && this.env.DELEGATION_STORAGE) {
193
+ if (hasOAuthIdentity && this.env.DELEGATION_STORAGE) {
43
194
  try {
44
195
  const oauthKey = STORAGE_KEYS.oauthIdentity(oauthIdentity.provider, oauthIdentity.subject);
45
196
  const mappedUserDid = await this.env.DELEGATION_STORAGE.get(oauthKey, "text");
46
197
  if (mappedUserDid) {
47
- console.log("[ConsentService] Found persistent User DID from OAuth mapping");
198
+ console.log("[ConsentService] Found persistent User DID from OAuth mapping:", {
199
+ provider: oauthIdentity.provider,
200
+ userDid: mappedUserDid.substring(0, 20) + "...",
201
+ });
48
202
  return mappedUserDid;
49
203
  }
50
204
  }
@@ -53,6 +207,10 @@ export class ConsentService {
53
207
  // Continue with ephemeral DID generation
54
208
  }
55
209
  }
210
+ else if (oauthIdentity === null) {
211
+ // Explicitly handle null case (no OAuth)
212
+ console.log("[ConsentService] No OAuth identity provided (null), generating ephemeral DID");
213
+ }
56
214
  // Continue with existing ephemeral DID generation logic
57
215
  if (!this.env.DELEGATION_STORAGE) {
58
216
  // No storage - use cached UserDidManager instance for consistent DID generation
@@ -403,6 +561,29 @@ export class ConsentService {
403
561
  });
404
562
  return Response.redirect(oauthUrl, 302);
405
563
  }
564
+ // ✅ Lazy initialization with projectId
565
+ const auditService = await this.getAuditService(projectId);
566
+ // Log page view event (if audit service available)
567
+ if (auditService) {
568
+ await auditService
569
+ .logConsentPageView({
570
+ sessionId,
571
+ agentDid,
572
+ targetTools: [tool], // Wrap in array
573
+ scopes,
574
+ projectId,
575
+ })
576
+ .catch((err) => {
577
+ // Structured error logging
578
+ console.error("[ConsentService] Audit logging failed", {
579
+ eventType: "consent:page_viewed",
580
+ sessionId,
581
+ error: err instanceof Error ? err.message : String(err),
582
+ stack: err instanceof Error ? err.stack : undefined,
583
+ });
584
+ // Don't throw - audit failures shouldn't break consent flow
585
+ });
586
+ }
406
587
  // Build consent page config
407
588
  const pageConfig = {
408
589
  tool,
@@ -439,6 +620,1079 @@ export class ConsentService {
439
620
  });
440
621
  }
441
622
  }
623
+ /**
624
+ * Parse request body from JSON or FormData
625
+ *
626
+ * Handles both JSON and FormData/multipart requests, converting
627
+ * FormData fields to the correct format for ConsentApprovalRequest.
628
+ *
629
+ * @param request - Request to parse
630
+ * @returns Parsed body object
631
+ */
632
+ async parseRequestBody(request) {
633
+ const contentType = request.headers.get("content-type") || "";
634
+ // Helper function to parse form fields into body object
635
+ const parseFormFields = (entries) => {
636
+ const body = {};
637
+ for (const [key, value] of entries) {
638
+ // Handle special fields that need parsing
639
+ if (key === "scopes" || key === "scopes[]") {
640
+ // Scopes come as JSON string
641
+ try {
642
+ body["scopes"] = JSON.parse(value);
643
+ }
644
+ catch {
645
+ // If not JSON, treat as single scope or array
646
+ body["scopes"] = value.includes(",") ? value.split(",") : [value];
647
+ }
648
+ }
649
+ else if (key === "oauth_identity" || key === "oauth_identity_json") {
650
+ // OAuth identity comes as JSON string
651
+ try {
652
+ const parsed = JSON.parse(value);
653
+ body["oauth_identity"] = parsed || null;
654
+ }
655
+ catch {
656
+ // Invalid JSON, set to null
657
+ body["oauth_identity"] = null;
658
+ }
659
+ }
660
+ else if (key === "termsAccepted") {
661
+ // Convert checkbox values to boolean
662
+ body[key] =
663
+ value === "on" ||
664
+ value === "true" ||
665
+ value === "1" ||
666
+ value === "yes";
667
+ }
668
+ else if (key === "customFields") {
669
+ // Custom fields come as JSON string
670
+ try {
671
+ body[key] = JSON.parse(value);
672
+ }
673
+ catch {
674
+ // If not JSON, skip
675
+ }
676
+ }
677
+ else {
678
+ // Regular string fields
679
+ body[key] = value;
680
+ }
681
+ }
682
+ // Default termsAccepted to true if not provided (common for checkboxes)
683
+ if (!("termsAccepted" in body)) {
684
+ body.termsAccepted = true;
685
+ }
686
+ // Default scopes to empty array if not provided (required by schema but can be empty)
687
+ if (!("scopes" in body)) {
688
+ body.scopes = [];
689
+ }
690
+ return body;
691
+ };
692
+ // Parse URL-encoded form data (application/x-www-form-urlencoded)
693
+ // When Content-Type is URL-encoded but FormData object is passed, try FormData parsing first
694
+ if (contentType.includes("application/x-www-form-urlencoded")) {
695
+ // Try FormData parsing first (FormData object might have been passed)
696
+ try {
697
+ const clonedRequest = request.clone();
698
+ const formData = await clonedRequest.formData();
699
+ const body = {};
700
+ let hasValidFields = false;
701
+ // Check if FormData parsing returned malformed data (entire multipart body as single entry)
702
+ // Type assertion: FormData.entries() exists at runtime in Cloudflare Workers
703
+ const entriesArray = Array.from(formData.entries());
704
+ if (entriesArray.length === 1 &&
705
+ typeof entriesArray[0][0] === "string" &&
706
+ entriesArray[0][0].includes("Content-Disposition") &&
707
+ typeof entriesArray[0][1] === "string" &&
708
+ entriesArray[0][1].toString().includes("Content-Disposition")) {
709
+ // Manually parse multipart format from the value string
710
+ // The key contains the first boundary and Content-Disposition header start
711
+ // The value contains the rest of the first field and all subsequent fields
712
+ const keyPart = entriesArray[0][0];
713
+ const valuePart = entriesArray[0][1];
714
+ // Fix: If key ends with "name" and value starts with '"fieldname"', combine them
715
+ let multipartBody;
716
+ if (keyPart.trim().endsWith("name") &&
717
+ valuePart.trim().startsWith('"')) {
718
+ // Key ends with "name", value starts with '"fieldname"', combine with = between them
719
+ multipartBody = keyPart + "=" + valuePart;
720
+ }
721
+ else {
722
+ multipartBody = keyPart + valuePart;
723
+ }
724
+ // Match: Content-Disposition header with field name, then capture value until next boundary or end
725
+ const fieldRegex = /Content-Disposition:\s*form-data;\s*name="([^"]+)"\r?\n\r?\n([\s\S]*?)(?=\r?\n------|$)/g;
726
+ let match;
727
+ while ((match = fieldRegex.exec(multipartBody)) !== null) {
728
+ const fieldName = match[1];
729
+ const fieldValue = match[2].trim(); // Remove trailing newlines
730
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
731
+ try {
732
+ body["scopes"] = JSON.parse(fieldValue);
733
+ }
734
+ catch {
735
+ body["scopes"] = fieldValue.includes(",")
736
+ ? fieldValue.split(",")
737
+ : [fieldValue];
738
+ }
739
+ }
740
+ else if (fieldName === "oauth_identity" ||
741
+ fieldName === "oauth_identity_json") {
742
+ try {
743
+ body["oauth_identity"] = JSON.parse(fieldValue) || null;
744
+ }
745
+ catch {
746
+ body["oauth_identity"] = null;
747
+ }
748
+ }
749
+ else if (fieldName === "termsAccepted") {
750
+ body[fieldName] =
751
+ fieldValue === "on" ||
752
+ fieldValue === "true" ||
753
+ fieldValue === "1" ||
754
+ fieldValue === "yes";
755
+ }
756
+ else if (fieldName === "customFields") {
757
+ try {
758
+ body[fieldName] = JSON.parse(fieldValue);
759
+ }
760
+ catch {
761
+ // Skip
762
+ }
763
+ }
764
+ else {
765
+ body[fieldName] = fieldValue;
766
+ }
767
+ hasValidFields = true;
768
+ }
769
+ }
770
+ else {
771
+ // Normal FormData parsing
772
+ // Type assertion: FormData.entries() exists at runtime in Cloudflare Workers
773
+ for (const [key, value] of formData.entries()) {
774
+ if (value instanceof File) {
775
+ continue;
776
+ }
777
+ // Extract field name from malformed keys (when FormData is passed with wrong Content-Type)
778
+ let fieldName = key;
779
+ if (key.includes("Content-Disposition") && key.includes('name="')) {
780
+ // Extract field name from Content-Disposition header
781
+ const nameMatch = key.match(/name="([^"]+)"/);
782
+ if (nameMatch && nameMatch[1]) {
783
+ fieldName = nameMatch[1];
784
+ }
785
+ else {
786
+ // Skip if we can't extract a valid field name
787
+ continue;
788
+ }
789
+ }
790
+ else if (key.includes("------") ||
791
+ key.includes("\r\n") ||
792
+ key.trim() === "") {
793
+ // Skip boundary strings and invalid keys
794
+ continue;
795
+ }
796
+ hasValidFields = true;
797
+ const stringValue = value.toString();
798
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
799
+ try {
800
+ body["scopes"] = JSON.parse(stringValue);
801
+ }
802
+ catch {
803
+ body["scopes"] = stringValue.includes(",")
804
+ ? stringValue.split(",")
805
+ : [stringValue];
806
+ }
807
+ }
808
+ else if (fieldName === "oauth_identity" ||
809
+ fieldName === "oauth_identity_json") {
810
+ try {
811
+ body["oauth_identity"] = JSON.parse(stringValue) || null;
812
+ }
813
+ catch {
814
+ body["oauth_identity"] = null;
815
+ }
816
+ }
817
+ else if (fieldName === "termsAccepted") {
818
+ body[fieldName] =
819
+ stringValue === "on" ||
820
+ stringValue === "true" ||
821
+ stringValue === "1" ||
822
+ stringValue === "yes";
823
+ }
824
+ else if (fieldName === "customFields") {
825
+ try {
826
+ body[fieldName] = JSON.parse(stringValue);
827
+ }
828
+ catch {
829
+ // Skip
830
+ }
831
+ }
832
+ else {
833
+ body[fieldName] = stringValue;
834
+ }
835
+ }
836
+ }
837
+ if (hasValidFields && Object.keys(body).length > 0) {
838
+ if (!("termsAccepted" in body)) {
839
+ body.termsAccepted = true;
840
+ }
841
+ // Default scopes to empty array if not provided
842
+ if (!("scopes" in body)) {
843
+ body.scopes = [];
844
+ }
845
+ return body;
846
+ }
847
+ }
848
+ catch (formDataError) {
849
+ // FormData parsing failed, try URL-encoded text parsing
850
+ console.warn("[ConsentService] FormData parsing failed, trying URL-encoded text:", formDataError);
851
+ }
852
+ // Try URL-encoded text parsing as fallback
853
+ try {
854
+ const text = await request.clone().text();
855
+ const params = new URLSearchParams(text);
856
+ // Type assertion: URLSearchParams.entries() exists at runtime
857
+ return parseFormFields(params.entries());
858
+ }
859
+ catch (urlEncodedError) {
860
+ // Both failed, fall through to JSON parsing
861
+ console.warn("[ConsentService] URL-encoded parsing also failed:", urlEncodedError);
862
+ }
863
+ }
864
+ // Parse multipart FormData (multipart/form-data or when FormData object is passed with other Content-Type)
865
+ // Include text/plain here to handle cases where FormData is passed with mismatched Content-Type
866
+ if (contentType.includes("multipart/form-data") ||
867
+ contentType.includes("form") ||
868
+ contentType === "" ||
869
+ contentType.includes("text/plain") ||
870
+ contentType.includes("text")) {
871
+ // Check if multipart/form-data Content-Type is missing boundary
872
+ // If so, try to parse as text first (FormData might have been serialized incorrectly)
873
+ if (contentType.includes("multipart/form-data") &&
874
+ !contentType.includes("boundary=")) {
875
+ try {
876
+ const textRequest = request.clone();
877
+ const text = await textRequest.text();
878
+ if (text && text.length > 0) {
879
+ // Try to manually parse multipart format from text
880
+ const fieldRegex = /Content-Disposition:\s*form-data;\s*name="([^"]+)"\r?\n\r?\n([\s\S]*?)(?=\r?\n------|$)/g;
881
+ const body = {};
882
+ let match;
883
+ let hasValidFields = false;
884
+ while ((match = fieldRegex.exec(text)) !== null) {
885
+ const fieldName = match[1];
886
+ const fieldValue = match[2].trim();
887
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
888
+ try {
889
+ body["scopes"] = JSON.parse(fieldValue);
890
+ }
891
+ catch {
892
+ body["scopes"] = fieldValue.includes(",")
893
+ ? fieldValue.split(",")
894
+ : [fieldValue];
895
+ }
896
+ }
897
+ else if (fieldName === "oauth_identity" ||
898
+ fieldName === "oauth_identity_json") {
899
+ try {
900
+ body["oauth_identity"] = JSON.parse(fieldValue) || null;
901
+ }
902
+ catch {
903
+ body["oauth_identity"] = null;
904
+ }
905
+ }
906
+ else if (fieldName === "termsAccepted") {
907
+ body[fieldName] =
908
+ fieldValue === "on" ||
909
+ fieldValue === "true" ||
910
+ fieldValue === "1" ||
911
+ fieldValue === "yes";
912
+ }
913
+ else if (fieldName === "customFields") {
914
+ try {
915
+ body[fieldName] = JSON.parse(fieldValue);
916
+ }
917
+ catch {
918
+ // Skip
919
+ }
920
+ }
921
+ else {
922
+ body[fieldName] = fieldValue;
923
+ }
924
+ hasValidFields = true;
925
+ }
926
+ if (hasValidFields && Object.keys(body).length > 0) {
927
+ if (!("termsAccepted" in body)) {
928
+ body.termsAccepted = true;
929
+ }
930
+ // Default scopes to empty array if not provided
931
+ if (!("scopes" in body)) {
932
+ body.scopes = [];
933
+ }
934
+ return body;
935
+ }
936
+ }
937
+ }
938
+ catch {
939
+ // If text parsing fails, fall through to FormData parsing
940
+ }
941
+ }
942
+ try {
943
+ const clonedRequest = request.clone();
944
+ let formData;
945
+ try {
946
+ formData = await clonedRequest.formData();
947
+ }
948
+ catch (formDataError) {
949
+ // Handle FormData parsing errors (missing boundary, wrong Content-Type, etc.)
950
+ const errorMessage = formDataError instanceof Error
951
+ ? formDataError.message
952
+ : String(formDataError);
953
+ const errorCause = formDataError instanceof Error && "cause" in formDataError
954
+ ? formDataError.cause instanceof Error
955
+ ? formDataError.cause.message
956
+ : String(formDataError.cause)
957
+ : "";
958
+ if (errorMessage.includes("missing boundary") ||
959
+ errorMessage.includes("boundary") ||
960
+ errorMessage.includes("Content-Type was not one of") ||
961
+ errorCause.includes("missing boundary") ||
962
+ errorCause.includes("boundary")) {
963
+ // When boundary is missing, try to parse as URL-encoded form data instead
964
+ // This handles the case where FormData was passed but Content-Type doesn't include boundary
965
+ try {
966
+ const textRequest = request.clone();
967
+ const text = await textRequest.text();
968
+ // If text parsing succeeds, try URL-encoded parsing
969
+ if (text && text.length > 0) {
970
+ try {
971
+ const params = new URLSearchParams(text);
972
+ return parseFormFields(params.entries());
973
+ }
974
+ catch {
975
+ // If URL-encoded parsing fails, the text might be multipart format
976
+ // Try to manually parse multipart format from text
977
+ const fieldRegex = /Content-Disposition:\s*form-data;\s*name="([^"]+)"\r?\n\r?\n([\s\S]*?)(?=\r?\n------|$)/g;
978
+ const body = {};
979
+ let match;
980
+ let hasValidFields = false;
981
+ while ((match = fieldRegex.exec(text)) !== null) {
982
+ const fieldName = match[1];
983
+ const fieldValue = match[2].trim();
984
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
985
+ try {
986
+ body["scopes"] = JSON.parse(fieldValue);
987
+ }
988
+ catch {
989
+ body["scopes"] = fieldValue.includes(",")
990
+ ? fieldValue.split(",")
991
+ : [fieldValue];
992
+ }
993
+ }
994
+ else if (fieldName === "oauth_identity" ||
995
+ fieldName === "oauth_identity_json") {
996
+ try {
997
+ body["oauth_identity"] = JSON.parse(fieldValue) || null;
998
+ }
999
+ catch {
1000
+ body["oauth_identity"] = null;
1001
+ }
1002
+ }
1003
+ else if (fieldName === "termsAccepted") {
1004
+ body[fieldName] =
1005
+ fieldValue === "on" ||
1006
+ fieldValue === "true" ||
1007
+ fieldValue === "1" ||
1008
+ fieldValue === "yes";
1009
+ }
1010
+ else if (fieldName === "customFields") {
1011
+ try {
1012
+ body[fieldName] = JSON.parse(fieldValue);
1013
+ }
1014
+ catch {
1015
+ // Skip
1016
+ }
1017
+ }
1018
+ else {
1019
+ body[fieldName] = fieldValue;
1020
+ }
1021
+ hasValidFields = true;
1022
+ }
1023
+ if (hasValidFields && Object.keys(body).length > 0) {
1024
+ if (!("termsAccepted" in body)) {
1025
+ body.termsAccepted = true;
1026
+ }
1027
+ // Default scopes to empty array if not provided
1028
+ if (!("scopes" in body)) {
1029
+ body.scopes = [];
1030
+ }
1031
+ return body;
1032
+ }
1033
+ }
1034
+ }
1035
+ }
1036
+ catch {
1037
+ // If all parsing attempts fail, rethrow the original error
1038
+ }
1039
+ }
1040
+ throw formDataError;
1041
+ }
1042
+ const body = {};
1043
+ let hasValidFields = false;
1044
+ // Check if FormData parsing returned malformed data (entire multipart body as single entry)
1045
+ // Type assertion: FormData.entries() exists at runtime in Cloudflare Workers
1046
+ const entriesArray = Array.from(formData.entries());
1047
+ if (entriesArray.length === 1 &&
1048
+ typeof entriesArray[0][0] === "string" &&
1049
+ entriesArray[0][0].includes("Content-Disposition") &&
1050
+ typeof entriesArray[0][1] === "string" &&
1051
+ entriesArray[0][1].toString().includes("Content-Disposition")) {
1052
+ // Manually parse multipart format from the value string
1053
+ const keyPart = entriesArray[0][0];
1054
+ const valuePart = entriesArray[0][1];
1055
+ // Fix: If key ends with "name" and value starts with '"fieldname"', combine them
1056
+ let multipartBody;
1057
+ if (keyPart.trim().endsWith("name") &&
1058
+ valuePart.trim().startsWith('"')) {
1059
+ multipartBody = keyPart + "=" + valuePart;
1060
+ }
1061
+ else {
1062
+ multipartBody = keyPart + valuePart;
1063
+ }
1064
+ // Match: Content-Disposition header with field name, then capture value until next boundary or end
1065
+ const fieldRegex = /Content-Disposition:\s*form-data;\s*name="([^"]+)"\r?\n\r?\n([\s\S]*?)(?=\r?\n------|$)/g;
1066
+ let match;
1067
+ while ((match = fieldRegex.exec(multipartBody)) !== null) {
1068
+ const fieldName = match[1];
1069
+ const fieldValue = match[2].trim();
1070
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
1071
+ try {
1072
+ body["scopes"] = JSON.parse(fieldValue);
1073
+ }
1074
+ catch {
1075
+ body["scopes"] = fieldValue.includes(",")
1076
+ ? fieldValue.split(",")
1077
+ : [fieldValue];
1078
+ }
1079
+ }
1080
+ else if (fieldName === "oauth_identity" ||
1081
+ fieldName === "oauth_identity_json") {
1082
+ try {
1083
+ body["oauth_identity"] = JSON.parse(fieldValue) || null;
1084
+ }
1085
+ catch {
1086
+ body["oauth_identity"] = null;
1087
+ }
1088
+ }
1089
+ else if (fieldName === "termsAccepted") {
1090
+ body[fieldName] =
1091
+ fieldValue === "on" ||
1092
+ fieldValue === "true" ||
1093
+ fieldValue === "1" ||
1094
+ fieldValue === "yes";
1095
+ }
1096
+ else if (fieldName === "customFields") {
1097
+ try {
1098
+ body[fieldName] = JSON.parse(fieldValue);
1099
+ }
1100
+ catch {
1101
+ // Skip
1102
+ }
1103
+ }
1104
+ else {
1105
+ body[fieldName] = fieldValue;
1106
+ }
1107
+ hasValidFields = true;
1108
+ }
1109
+ }
1110
+ else {
1111
+ // Normal FormData parsing
1112
+ // Type assertion: FormData.entries() exists at runtime in Cloudflare Workers
1113
+ for (const [key, value] of formData.entries()) {
1114
+ if (value instanceof File) {
1115
+ continue;
1116
+ }
1117
+ // Extract field name from malformed keys (when FormData is passed with wrong Content-Type)
1118
+ let fieldName = key;
1119
+ if (key.includes("Content-Disposition") && key.includes('name="')) {
1120
+ // Extract field name from Content-Disposition header
1121
+ const nameMatch = key.match(/name="([^"]+)"/);
1122
+ if (nameMatch && nameMatch[1]) {
1123
+ fieldName = nameMatch[1];
1124
+ }
1125
+ else {
1126
+ // Skip if we can't extract a valid field name
1127
+ continue;
1128
+ }
1129
+ }
1130
+ else if (key.includes("------") ||
1131
+ key.includes("\r\n") ||
1132
+ key.trim() === "") {
1133
+ // Skip boundary strings and invalid keys
1134
+ continue;
1135
+ }
1136
+ hasValidFields = true;
1137
+ const stringValue = value.toString();
1138
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
1139
+ try {
1140
+ body["scopes"] = JSON.parse(stringValue);
1141
+ }
1142
+ catch {
1143
+ body["scopes"] = stringValue.includes(",")
1144
+ ? stringValue.split(",")
1145
+ : [stringValue];
1146
+ }
1147
+ }
1148
+ else if (fieldName === "oauth_identity" ||
1149
+ fieldName === "oauth_identity_json") {
1150
+ try {
1151
+ body["oauth_identity"] = JSON.parse(stringValue) || null;
1152
+ }
1153
+ catch {
1154
+ body["oauth_identity"] = null;
1155
+ }
1156
+ }
1157
+ else if (fieldName === "termsAccepted") {
1158
+ body[fieldName] =
1159
+ stringValue === "on" ||
1160
+ stringValue === "true" ||
1161
+ stringValue === "1" ||
1162
+ stringValue === "yes";
1163
+ }
1164
+ else if (fieldName === "customFields") {
1165
+ try {
1166
+ body[fieldName] = JSON.parse(stringValue);
1167
+ }
1168
+ catch {
1169
+ // Skip
1170
+ }
1171
+ }
1172
+ else {
1173
+ body[fieldName] = stringValue;
1174
+ }
1175
+ }
1176
+ }
1177
+ if (hasValidFields && Object.keys(body).length > 0) {
1178
+ if (!("termsAccepted" in body)) {
1179
+ body.termsAccepted = true;
1180
+ }
1181
+ // Default scopes to empty array if not provided
1182
+ if (!("scopes" in body)) {
1183
+ body.scopes = [];
1184
+ }
1185
+ return body;
1186
+ }
1187
+ }
1188
+ catch (formDataError) {
1189
+ console.warn("[ConsentService] FormData parsing failed:", formDataError);
1190
+ // Fall through to JSON parsing
1191
+ }
1192
+ }
1193
+ // Default to JSON parsing
1194
+ try {
1195
+ return await request.json();
1196
+ }
1197
+ catch (error) {
1198
+ // If JSON parsing fails and content-type suggests form data, try FormData parsing as fallback
1199
+ // Special handling for text/plain with FormData body - try text parsing first
1200
+ if (contentType === "text/plain") {
1201
+ try {
1202
+ const textRequest = request.clone();
1203
+ const text = await textRequest.text();
1204
+ if (text && text.length > 0) {
1205
+ // Try URL-encoded parsing first
1206
+ try {
1207
+ const params = new URLSearchParams(text);
1208
+ const body = parseFormFields(params.entries());
1209
+ if (Object.keys(body).length > 0) {
1210
+ return body;
1211
+ }
1212
+ }
1213
+ catch {
1214
+ // URL-encoded parsing failed, try multipart format
1215
+ }
1216
+ // Try multipart format parsing (FormData serializes to multipart)
1217
+ const fieldRegex = /Content-Disposition:\s*form-data;\s*name="([^"]+)"\r?\n\r?\n([\s\S]*?)(?=\r?\n------|$)/g;
1218
+ const body = {};
1219
+ let match;
1220
+ let hasValidFields = false;
1221
+ while ((match = fieldRegex.exec(text)) !== null) {
1222
+ const fieldName = match[1];
1223
+ const fieldValue = match[2].trim();
1224
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
1225
+ try {
1226
+ body["scopes"] = JSON.parse(fieldValue);
1227
+ }
1228
+ catch {
1229
+ body["scopes"] = fieldValue.includes(",")
1230
+ ? fieldValue.split(",")
1231
+ : [fieldValue];
1232
+ }
1233
+ }
1234
+ else if (fieldName === "oauth_identity" ||
1235
+ fieldName === "oauth_identity_json") {
1236
+ try {
1237
+ body["oauth_identity"] = JSON.parse(fieldValue) || null;
1238
+ }
1239
+ catch {
1240
+ body["oauth_identity"] = null;
1241
+ }
1242
+ }
1243
+ else if (fieldName === "termsAccepted") {
1244
+ body[fieldName] =
1245
+ fieldValue === "on" ||
1246
+ fieldValue === "true" ||
1247
+ fieldValue === "1" ||
1248
+ fieldValue === "yes";
1249
+ }
1250
+ else if (fieldName === "customFields") {
1251
+ try {
1252
+ body[fieldName] = JSON.parse(fieldValue);
1253
+ }
1254
+ catch {
1255
+ // Skip
1256
+ }
1257
+ }
1258
+ else {
1259
+ body[fieldName] = fieldValue;
1260
+ }
1261
+ hasValidFields = true;
1262
+ }
1263
+ if (hasValidFields && Object.keys(body).length > 0) {
1264
+ if (!("termsAccepted" in body)) {
1265
+ body.termsAccepted = true;
1266
+ }
1267
+ // Default scopes to empty array if not provided
1268
+ if (!("scopes" in body)) {
1269
+ body.scopes = [];
1270
+ }
1271
+ return body;
1272
+ }
1273
+ }
1274
+ }
1275
+ catch {
1276
+ // Text parsing failed, fall through to FormData parsing
1277
+ }
1278
+ }
1279
+ if (!contentType.includes("application/json") &&
1280
+ (contentType.includes("form") ||
1281
+ contentType === "" ||
1282
+ contentType.includes("text"))) {
1283
+ try {
1284
+ // Clone request ONCE before trying any parsing, so we can reuse it if FormData parsing fails
1285
+ const fallbackRequest = request.clone();
1286
+ // Try FormData parsing as fallback (even if Content-Type doesn't match)
1287
+ let formData;
1288
+ try {
1289
+ formData = await fallbackRequest.formData();
1290
+ }
1291
+ catch (formDataParseError) {
1292
+ // If FormData parsing fails, try reading as text and parsing manually
1293
+ // This handles cases where Content-Type doesn't match (e.g., text/plain with FormData body)
1294
+ try {
1295
+ // Use a fresh clone for text parsing (body might be consumed by failed FormData attempt)
1296
+ const textRequest = request.clone();
1297
+ const text = await textRequest.text();
1298
+ if (text && text.length > 0) {
1299
+ // First try URL-encoded parsing (simpler format)
1300
+ try {
1301
+ const params = new URLSearchParams(text);
1302
+ const body = parseFormFields(params.entries());
1303
+ if (Object.keys(body).length > 0) {
1304
+ return body;
1305
+ }
1306
+ }
1307
+ catch {
1308
+ // URL-encoded parsing failed, try multipart format
1309
+ }
1310
+ // Try to manually parse multipart format from text
1311
+ const fieldRegex = /Content-Disposition:\s*form-data;\s*name="([^"]+)"\r?\n\r?\n([\s\S]*?)(?=\r?\n------|$)/g;
1312
+ const body = {};
1313
+ let match;
1314
+ let hasValidFields = false;
1315
+ while ((match = fieldRegex.exec(text)) !== null) {
1316
+ const fieldName = match[1];
1317
+ const fieldValue = match[2].trim();
1318
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
1319
+ try {
1320
+ body["scopes"] = JSON.parse(fieldValue);
1321
+ }
1322
+ catch {
1323
+ body["scopes"] = fieldValue.includes(",")
1324
+ ? fieldValue.split(",")
1325
+ : [fieldValue];
1326
+ }
1327
+ }
1328
+ else if (fieldName === "oauth_identity" ||
1329
+ fieldName === "oauth_identity_json") {
1330
+ try {
1331
+ body["oauth_identity"] = JSON.parse(fieldValue) || null;
1332
+ }
1333
+ catch {
1334
+ body["oauth_identity"] = null;
1335
+ }
1336
+ }
1337
+ else if (fieldName === "termsAccepted") {
1338
+ body[fieldName] =
1339
+ fieldValue === "on" ||
1340
+ fieldValue === "true" ||
1341
+ fieldValue === "1" ||
1342
+ fieldValue === "yes";
1343
+ }
1344
+ else if (fieldName === "customFields") {
1345
+ try {
1346
+ body[fieldName] = JSON.parse(fieldValue);
1347
+ }
1348
+ catch {
1349
+ // Skip
1350
+ }
1351
+ }
1352
+ else {
1353
+ body[fieldName] = fieldValue;
1354
+ }
1355
+ hasValidFields = true;
1356
+ }
1357
+ if (hasValidFields && Object.keys(body).length > 0) {
1358
+ if (!("termsAccepted" in body)) {
1359
+ body.termsAccepted = true;
1360
+ }
1361
+ // Default scopes to empty array if not provided
1362
+ if (!("scopes" in body)) {
1363
+ body.scopes = [];
1364
+ }
1365
+ return body;
1366
+ }
1367
+ }
1368
+ }
1369
+ catch {
1370
+ // If text parsing also fails, rethrow original FormData error
1371
+ }
1372
+ throw formDataParseError;
1373
+ }
1374
+ // Check if FormData has valid entries (might be empty if Content-Type mismatch)
1375
+ const entriesArray = Array.from(formData.entries());
1376
+ if (entriesArray.length === 0) {
1377
+ // FormData parsing succeeded but returned no entries - try text parsing
1378
+ // This handles cases where Content-Type doesn't match (e.g., text/plain with FormData body)
1379
+ try {
1380
+ const textRequest = request.clone();
1381
+ const text = await textRequest.text();
1382
+ if (text && text.length > 0) {
1383
+ // Try URL-encoded parsing first
1384
+ try {
1385
+ const params = new URLSearchParams(text);
1386
+ const body = parseFormFields(params.entries());
1387
+ if (Object.keys(body).length > 0) {
1388
+ return body;
1389
+ }
1390
+ }
1391
+ catch {
1392
+ // URL-encoded parsing failed, try multipart format
1393
+ }
1394
+ // Try multipart format parsing
1395
+ const fieldRegex = /Content-Disposition:\s*form-data;\s*name="([^"]+)"\r?\n\r?\n([\s\S]*?)(?=\r?\n------|$)/g;
1396
+ const body = {};
1397
+ let match;
1398
+ let hasValidFields = false;
1399
+ while ((match = fieldRegex.exec(text)) !== null) {
1400
+ const fieldName = match[1];
1401
+ const fieldValue = match[2].trim();
1402
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
1403
+ try {
1404
+ body["scopes"] = JSON.parse(fieldValue);
1405
+ }
1406
+ catch {
1407
+ body["scopes"] = fieldValue.includes(",")
1408
+ ? fieldValue.split(",")
1409
+ : [fieldValue];
1410
+ }
1411
+ }
1412
+ else if (fieldName === "oauth_identity" ||
1413
+ fieldName === "oauth_identity_json") {
1414
+ try {
1415
+ body["oauth_identity"] = JSON.parse(fieldValue) || null;
1416
+ }
1417
+ catch {
1418
+ body["oauth_identity"] = null;
1419
+ }
1420
+ }
1421
+ else if (fieldName === "termsAccepted") {
1422
+ body[fieldName] =
1423
+ fieldValue === "on" ||
1424
+ fieldValue === "true" ||
1425
+ fieldValue === "1" ||
1426
+ fieldValue === "yes";
1427
+ }
1428
+ else if (fieldName === "customFields") {
1429
+ try {
1430
+ body[fieldName] = JSON.parse(fieldValue);
1431
+ }
1432
+ catch {
1433
+ // Skip
1434
+ }
1435
+ }
1436
+ else {
1437
+ body[fieldName] = fieldValue;
1438
+ }
1439
+ hasValidFields = true;
1440
+ }
1441
+ if (hasValidFields && Object.keys(body).length > 0) {
1442
+ if (!("termsAccepted" in body)) {
1443
+ body.termsAccepted = true;
1444
+ }
1445
+ // Default scopes to empty array if not provided
1446
+ if (!("scopes" in body)) {
1447
+ body.scopes = [];
1448
+ }
1449
+ return body;
1450
+ }
1451
+ }
1452
+ // If text parsing failed or found no valid fields, throw error to trigger fallback
1453
+ throw new Error("FormData parsing returned empty entries and text parsing found no valid fields");
1454
+ }
1455
+ catch (textParseError) {
1456
+ // Text parsing failed or found no valid fields - throw error to trigger JSON fallback
1457
+ // This ensures we don't continue with empty FormData entries
1458
+ throw new Error(`Failed to parse FormData: ${textParseError instanceof Error ? textParseError.message : "Unknown error"}`);
1459
+ }
1460
+ }
1461
+ const body = {};
1462
+ // Type assertion: FormData.entries() exists at runtime in Cloudflare Workers
1463
+ let hasValidEntries = false;
1464
+ for (const [key, value] of formData.entries()) {
1465
+ if (value instanceof File)
1466
+ continue;
1467
+ // Extract field name from malformed keys
1468
+ let fieldName = key;
1469
+ if (key.includes("Content-Disposition") && key.includes('name="')) {
1470
+ const nameMatch = key.match(/name="([^"]+)"/);
1471
+ if (nameMatch && nameMatch[1]) {
1472
+ fieldName = nameMatch[1];
1473
+ }
1474
+ else {
1475
+ continue;
1476
+ }
1477
+ }
1478
+ else if (key.includes("------") ||
1479
+ key.includes("\r\n") ||
1480
+ key.trim() === "" ||
1481
+ key.includes("formdata-undici")) {
1482
+ // Malformed key - likely from text/plain Content-Type mismatch
1483
+ // Skip this entry and fall back to text parsing
1484
+ continue;
1485
+ }
1486
+ // If we have a valid field name, mark as having valid entries
1487
+ if (fieldName && fieldName !== key) {
1488
+ hasValidEntries = true;
1489
+ }
1490
+ else if (fieldName &&
1491
+ !key.includes("Content-Disposition") &&
1492
+ !key.includes("------") &&
1493
+ !key.includes("\r\n")) {
1494
+ hasValidEntries = true;
1495
+ }
1496
+ // Process the field value
1497
+ const stringValue = value.toString();
1498
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
1499
+ try {
1500
+ body["scopes"] = JSON.parse(stringValue);
1501
+ }
1502
+ catch {
1503
+ body["scopes"] = stringValue.includes(",")
1504
+ ? stringValue.split(",")
1505
+ : [stringValue];
1506
+ }
1507
+ }
1508
+ else if (fieldName === "oauth_identity" ||
1509
+ fieldName === "oauth_identity_json") {
1510
+ try {
1511
+ body["oauth_identity"] = JSON.parse(stringValue) || null;
1512
+ }
1513
+ catch {
1514
+ body["oauth_identity"] = null;
1515
+ }
1516
+ }
1517
+ else if (fieldName === "termsAccepted") {
1518
+ body[fieldName] =
1519
+ stringValue === "on" ||
1520
+ stringValue === "true" ||
1521
+ stringValue === "1" ||
1522
+ stringValue === "yes";
1523
+ }
1524
+ else if (fieldName === "customFields") {
1525
+ try {
1526
+ body[fieldName] = JSON.parse(stringValue);
1527
+ }
1528
+ catch {
1529
+ // Skip
1530
+ }
1531
+ }
1532
+ else {
1533
+ body[fieldName] = stringValue;
1534
+ }
1535
+ }
1536
+ // If we didn't get any valid entries (all keys were malformed), try text parsing
1537
+ if (!hasValidEntries || Object.keys(body).length === 0) {
1538
+ // Try text parsing as fallback when FormData parsing returns no valid entries
1539
+ try {
1540
+ const textRequest = request.clone();
1541
+ const text = await textRequest.text();
1542
+ if (text && text.length > 0) {
1543
+ // Try multipart format parsing from text
1544
+ const fieldRegex = /Content-Disposition:\s*form-data;\s*name="([^"]+)"\r?\n\r?\n([\s\S]*?)(?=\r?\n------|$)/g;
1545
+ const textBody = {};
1546
+ let match;
1547
+ let hasValidFields = false;
1548
+ while ((match = fieldRegex.exec(text)) !== null) {
1549
+ const fieldName = match[1];
1550
+ const fieldValue = match[2].trim();
1551
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
1552
+ try {
1553
+ textBody["scopes"] = JSON.parse(fieldValue);
1554
+ }
1555
+ catch {
1556
+ textBody["scopes"] = fieldValue.includes(",")
1557
+ ? fieldValue.split(",")
1558
+ : [fieldValue];
1559
+ }
1560
+ }
1561
+ else if (fieldName === "oauth_identity" ||
1562
+ fieldName === "oauth_identity_json") {
1563
+ try {
1564
+ textBody["oauth_identity"] =
1565
+ JSON.parse(fieldValue) || null;
1566
+ }
1567
+ catch {
1568
+ textBody["oauth_identity"] = null;
1569
+ }
1570
+ }
1571
+ else if (fieldName === "termsAccepted") {
1572
+ textBody[fieldName] =
1573
+ fieldValue === "on" ||
1574
+ fieldValue === "true" ||
1575
+ fieldValue === "1" ||
1576
+ fieldValue === "yes";
1577
+ }
1578
+ else if (fieldName === "customFields") {
1579
+ try {
1580
+ textBody[fieldName] = JSON.parse(fieldValue);
1581
+ }
1582
+ catch {
1583
+ // Skip
1584
+ }
1585
+ }
1586
+ else {
1587
+ textBody[fieldName] = fieldValue;
1588
+ }
1589
+ hasValidFields = true;
1590
+ }
1591
+ if (hasValidFields && Object.keys(textBody).length > 0) {
1592
+ if (!("termsAccepted" in textBody)) {
1593
+ textBody.termsAccepted = true;
1594
+ }
1595
+ if (!("scopes" in textBody)) {
1596
+ textBody.scopes = [];
1597
+ }
1598
+ return textBody;
1599
+ }
1600
+ }
1601
+ }
1602
+ catch {
1603
+ // Text parsing also failed, fall through to throw error
1604
+ }
1605
+ throw new Error("FormData parsing returned only malformed entries - falling back to text parsing");
1606
+ }
1607
+ if (!("termsAccepted" in body)) {
1608
+ body.termsAccepted = true;
1609
+ }
1610
+ // Default scopes to empty array if not provided
1611
+ if (!("scopes" in body)) {
1612
+ body.scopes = [];
1613
+ }
1614
+ return body;
1615
+ }
1616
+ catch (formError) {
1617
+ // FormData parsing failed - if it was due to malformed entries, try text parsing
1618
+ const errorMessage = formError instanceof Error ? formError.message : String(formError);
1619
+ if (errorMessage.includes("malformed entries") ||
1620
+ errorMessage.includes("empty entries") ||
1621
+ errorMessage.includes("falling back to text parsing")) {
1622
+ // Try text parsing as last resort
1623
+ try {
1624
+ const textRequest = request.clone();
1625
+ const text = await textRequest.text();
1626
+ if (text && text.length > 0) {
1627
+ // Try multipart format parsing
1628
+ const fieldRegex = /Content-Disposition:\s*form-data;\s*name="([^"]+)"\r?\n\r?\n([\s\S]*?)(?=\r?\n------|$)/g;
1629
+ const body = {};
1630
+ let match;
1631
+ let hasValidFields = false;
1632
+ while ((match = fieldRegex.exec(text)) !== null) {
1633
+ const fieldName = match[1];
1634
+ const fieldValue = match[2].trim();
1635
+ if (fieldName === "scopes" || fieldName === "scopes[]") {
1636
+ try {
1637
+ body["scopes"] = JSON.parse(fieldValue);
1638
+ }
1639
+ catch {
1640
+ body["scopes"] = fieldValue.includes(",")
1641
+ ? fieldValue.split(",")
1642
+ : [fieldValue];
1643
+ }
1644
+ }
1645
+ else if (fieldName === "oauth_identity" ||
1646
+ fieldName === "oauth_identity_json") {
1647
+ try {
1648
+ body["oauth_identity"] = JSON.parse(fieldValue) || null;
1649
+ }
1650
+ catch {
1651
+ body["oauth_identity"] = null;
1652
+ }
1653
+ }
1654
+ else if (fieldName === "termsAccepted") {
1655
+ body[fieldName] =
1656
+ fieldValue === "on" ||
1657
+ fieldValue === "true" ||
1658
+ fieldValue === "1" ||
1659
+ fieldValue === "yes";
1660
+ }
1661
+ else if (fieldName === "customFields") {
1662
+ try {
1663
+ body[fieldName] = JSON.parse(fieldValue);
1664
+ }
1665
+ catch {
1666
+ // Skip
1667
+ }
1668
+ }
1669
+ else {
1670
+ body[fieldName] = fieldValue;
1671
+ }
1672
+ hasValidFields = true;
1673
+ }
1674
+ if (hasValidFields && Object.keys(body).length > 0) {
1675
+ if (!("termsAccepted" in body)) {
1676
+ body.termsAccepted = true;
1677
+ }
1678
+ // Default scopes to empty array if not provided
1679
+ if (!("scopes" in body)) {
1680
+ body.scopes = [];
1681
+ }
1682
+ return body;
1683
+ }
1684
+ }
1685
+ }
1686
+ catch {
1687
+ // Text parsing also failed
1688
+ }
1689
+ }
1690
+ // Both failed, throw original error
1691
+ }
1692
+ }
1693
+ throw new Error(`Failed to parse request body: ${error instanceof Error ? error.message : "Unknown error"}`);
1694
+ }
1695
+ }
442
1696
  /**
443
1697
  * Handle consent approval
444
1698
  *
@@ -449,11 +1703,33 @@ export class ConsentService {
449
1703
  * @returns JSON response
450
1704
  */
451
1705
  async handleApproval(request) {
1706
+ console.log("[ConsentService] Approval request received");
452
1707
  try {
453
- // Parse and validate request body
454
- const body = await request.json();
1708
+ // Parse and validate request body (supports both JSON and FormData)
1709
+ const body = await this.parseRequestBody(request);
1710
+ console.log("[ConsentService] Request body parsed:", {
1711
+ hasBody: !!body,
1712
+ bodyKeys: Object.keys(body || {}),
1713
+ hasOAuthIdentity: !!body?.oauth_identity,
1714
+ });
1715
+ // Convert null oauth_identity to undefined for proper schema validation
1716
+ // Zod's .nullish() should handle null, but converting to undefined is more explicit
1717
+ // and avoids potential edge cases with FormData parsing
1718
+ if (body &&
1719
+ typeof body === "object" &&
1720
+ body !== null &&
1721
+ "oauth_identity" in body) {
1722
+ const bodyObj = body;
1723
+ if (bodyObj.oauth_identity === null) {
1724
+ bodyObj.oauth_identity = undefined;
1725
+ }
1726
+ }
455
1727
  const validation = validateConsentApprovalRequest(body);
456
1728
  if (!validation.success) {
1729
+ console.error("[ConsentService] Approval request validation failed:", {
1730
+ errors: validation.error.errors,
1731
+ receivedBody: body,
1732
+ });
457
1733
  return new Response(JSON.stringify({
458
1734
  success: false,
459
1735
  error: "Invalid request",
@@ -465,6 +1741,13 @@ export class ConsentService {
465
1741
  });
466
1742
  }
467
1743
  const approvalRequest = validation.data;
1744
+ console.log("[ConsentService] Approval request validated:", {
1745
+ agentDid: approvalRequest.agent_did?.substring(0, 20) + "...",
1746
+ sessionId: approvalRequest.session_id?.substring(0, 20) + "...",
1747
+ scopes: approvalRequest.scopes,
1748
+ hasOAuthIdentity: !!approvalRequest.oauth_identity,
1749
+ oauthProvider: approvalRequest.oauth_identity?.provider,
1750
+ });
468
1751
  // Validate terms acceptance if required
469
1752
  const consentConfig = await this.configService.getConsentConfig(approvalRequest.project_id);
470
1753
  if (consentConfig.terms?.required && !approvalRequest.termsAccepted) {
@@ -477,9 +1760,40 @@ export class ConsentService {
477
1760
  headers: { "Content-Type": "application/json" },
478
1761
  });
479
1762
  }
1763
+ // ✅ Extract projectId from approval request
1764
+ const projectId = approvalRequest.project_id;
1765
+ // ✅ Lazy initialization with projectId
1766
+ const auditService = await this.getAuditService(projectId);
1767
+ // Check if user needs credentials before delegation
1768
+ const needsCredentials = !approvalRequest.user_did && !approvalRequest.oauth_identity;
1769
+ if (needsCredentials && auditService) {
1770
+ await auditService
1771
+ .logCredentialRequired({
1772
+ sessionId: approvalRequest.session_id,
1773
+ agentDid: approvalRequest.agent_did,
1774
+ targetTools: [approvalRequest.tool], // Array
1775
+ scopes: approvalRequest.scopes,
1776
+ projectId,
1777
+ oauthProvider: approvalRequest.oauth_identity?.provider,
1778
+ })
1779
+ .catch((err) => {
1780
+ console.error("[ConsentService] Failed to log credential required", {
1781
+ eventType: "consent:credential_required",
1782
+ sessionId: approvalRequest.session_id,
1783
+ error: err instanceof Error ? err.message : String(err),
1784
+ });
1785
+ });
1786
+ // Note: We don't redirect here - the consent flow continues
1787
+ // The credential_required event is just for audit tracking
1788
+ }
480
1789
  // Create delegation via AgentShield API
1790
+ console.log("[ConsentService] Creating delegation...");
481
1791
  const delegationResult = await this.createDelegation(approvalRequest);
482
1792
  if (!delegationResult.success) {
1793
+ console.error("[ConsentService] Delegation creation failed:", {
1794
+ error: delegationResult.error,
1795
+ error_code: delegationResult.error_code,
1796
+ });
483
1797
  return new Response(JSON.stringify({
484
1798
  success: false,
485
1799
  error: delegationResult.error || "Failed to create delegation",
@@ -489,8 +1803,60 @@ export class ConsentService {
489
1803
  headers: { "Content-Type": "application/json" },
490
1804
  });
491
1805
  }
1806
+ console.log("[ConsentService] ✅ Delegation created successfully:", {
1807
+ delegationId: delegationResult.delegation_id?.substring(0, 20) + "...",
1808
+ });
492
1809
  // Store delegation token in KV
493
1810
  await this.storeDelegationToken(approvalRequest.session_id, approvalRequest.agent_did, delegationResult.delegation_token, delegationResult.delegation_id);
1811
+ // ✅ After successful delegation creation - log audit events
1812
+ if (auditService && delegationResult.success) {
1813
+ try {
1814
+ // Get userDid (may have been generated during delegation creation)
1815
+ // getUserDidForSession can work without DELEGATION_STORAGE (uses in-memory UserDidManager)
1816
+ let userDid;
1817
+ if (approvalRequest.session_id) {
1818
+ try {
1819
+ userDid = await this.getUserDidForSession(approvalRequest.session_id, approvalRequest.oauth_identity || undefined);
1820
+ }
1821
+ catch (error) {
1822
+ console.warn("[ConsentService] Failed to get userDid for audit logging:", error);
1823
+ // Continue without userDid - audit events can still be logged
1824
+ }
1825
+ }
1826
+ await auditService.logConsentApproval({
1827
+ sessionId: approvalRequest.session_id,
1828
+ userDid,
1829
+ agentDid: approvalRequest.agent_did,
1830
+ targetTools: [approvalRequest.tool], // Array
1831
+ scopes: approvalRequest.scopes,
1832
+ delegationId: delegationResult.delegation_id,
1833
+ projectId,
1834
+ termsAccepted: approvalRequest.termsAccepted || false,
1835
+ oauthIdentity: approvalRequest.oauth_identity
1836
+ ? {
1837
+ provider: approvalRequest.oauth_identity.provider,
1838
+ identifier: approvalRequest.oauth_identity.subject,
1839
+ }
1840
+ : undefined,
1841
+ });
1842
+ await auditService.logDelegationCreated({
1843
+ sessionId: approvalRequest.session_id,
1844
+ delegationId: delegationResult.delegation_id,
1845
+ agentDid: approvalRequest.agent_did,
1846
+ userDid,
1847
+ targetTools: [approvalRequest.tool], // Array
1848
+ scopes: approvalRequest.scopes,
1849
+ projectId,
1850
+ });
1851
+ }
1852
+ catch (error) {
1853
+ console.error("[ConsentService] Audit failed but continuing", {
1854
+ sessionId: approvalRequest.session_id,
1855
+ error: error instanceof Error ? error.message : String(error),
1856
+ eventTypes: ["consent:approved", "consent:delegation_created"],
1857
+ });
1858
+ }
1859
+ }
494
1860
  // Return success response
495
1861
  const response = {
496
1862
  success: true,
@@ -537,17 +1903,36 @@ export class ConsentService {
537
1903
  const fieldName = await getDelegationFieldName(this.env.DELEGATION_STORAGE);
538
1904
  // Get userDID from session or generate new ephemeral DID
539
1905
  // Phase 4 PR #3: Use OAuth identity if provided in approval request
1906
+ // CRITICAL: Must work with or without OAuth identity
1907
+ // CRITICAL: Always generate ephemeral DID if session_id is available, even without DELEGATION_STORAGE
540
1908
  let userDid;
541
- if (this.env.DELEGATION_STORAGE && request.session_id) {
1909
+ if (request.session_id) {
542
1910
  try {
543
- // Pass OAuth identity if available in approval request
544
- userDid = await this.getUserDidForSession(request.session_id, request.oauth_identity);
1911
+ console.log("[ConsentService] Getting User DID for session:", {
1912
+ sessionId: request.session_id.substring(0, 20) + "...",
1913
+ hasOAuthIdentity: !!request.oauth_identity,
1914
+ oauthProvider: request.oauth_identity?.provider,
1915
+ hasStorage: !!this.env.DELEGATION_STORAGE,
1916
+ });
1917
+ // Pass OAuth identity if available in approval request (can be null/undefined)
1918
+ // getUserDidForSession can work without DELEGATION_STORAGE (uses in-memory UserDidManager)
1919
+ userDid = await this.getUserDidForSession(request.session_id, request.oauth_identity || undefined // Explicitly handle null as undefined
1920
+ );
1921
+ console.log("[ConsentService] User DID retrieved:", {
1922
+ userDid: userDid?.substring(0, 20) + "...",
1923
+ hasUserDid: !!userDid,
1924
+ });
545
1925
  }
546
1926
  catch (error) {
547
- console.warn("[ConsentService] Failed to get/generate userDid:", error);
548
- // Continue without userDid - delegation will use ephemeral placeholder
1927
+ console.error("[ConsentService] Failed to get/generate userDid:", error);
1928
+ // Continue without userDid - delegation will work without user_identifier
1929
+ // This is valid for non-OAuth scenarios, but we should log this as a warning
1930
+ console.warn("[ConsentService] Delegation will be created without user_identifier - this may affect user tracking");
549
1931
  }
550
1932
  }
1933
+ else {
1934
+ console.log("[ConsentService] No session_id provided - skipping User DID generation");
1935
+ }
551
1936
  const expiresInDays = 7; // Default to 7 days
552
1937
  // Build delegation request with error-based format detection
553
1938
  // Try full format first, fallback to simplified format on error
@@ -799,13 +2184,15 @@ export class ConsentService {
799
2184
  */
800
2185
  async buildFullFormatRequest(request, userDid, expiresInDays) {
801
2186
  const notAfter = Date.now() + expiresInDays * 24 * 60 * 60 * 1000;
2187
+ // Defensive check: ensure scopes is always defined (should be guaranteed by validation)
2188
+ const scopes = request.scopes ?? [];
802
2189
  return {
803
2190
  delegation: {
804
2191
  id: crypto.randomUUID(),
805
2192
  issuerDid: userDid || "did:key:z6MkEphemeral", // Use ephemeral if no userDid
806
2193
  subjectDid: request.agent_did,
807
2194
  constraints: {
808
- scopes: request.scopes,
2195
+ scopes,
809
2196
  notAfter,
810
2197
  notBefore: Date.now(),
811
2198
  },
@@ -840,18 +2227,28 @@ export class ConsentService {
840
2227
  */
841
2228
  buildSimplifiedFormatRequest(request, userDid, expiresInDays, fieldName) {
842
2229
  // Build request with ONLY fields that are in AgentShield's schema
2230
+ // Defensive check: ensure scopes is always defined (should be guaranteed by validation)
2231
+ const scopes = request.scopes ?? [];
843
2232
  const simplifiedRequest = {
844
2233
  agent_did: request.agent_did,
845
- scopes: request.scopes,
2234
+ scopes,
846
2235
  expires_in_days: expiresInDays,
847
2236
  };
848
2237
  // Include user_identifier if we have userDid (matches AgentShield schema)
2238
+ // CRITICAL: user_identifier is optional - delegation works without it
849
2239
  if (userDid) {
850
2240
  simplifiedRequest.user_identifier = userDid;
2241
+ console.log("[ConsentService] Including user_identifier in delegation request:", {
2242
+ userDid: userDid.substring(0, 20) + "...",
2243
+ });
2244
+ }
2245
+ else {
2246
+ console.log("[ConsentService] No user_identifier (no OAuth or ephemeral DID) - delegation will proceed without it");
851
2247
  }
852
2248
  // AgentShield API only accepts "custom_fields", not "metadata"
853
- // Always use "custom_fields" regardless of Day0 config
2249
+ // Always use "custom_fields" regardless of Day0 config
854
2250
  if (userDid) {
2251
+ // Include issuer_did and subject_did in custom_fields when we have userDid
855
2252
  simplifiedRequest.custom_fields = {
856
2253
  issuer_did: userDid,
857
2254
  subject_did: request.agent_did,
@@ -865,6 +2262,7 @@ export class ConsentService {
865
2262
  // Include custom_fields from request even if no userDid
866
2263
  simplifiedRequest.custom_fields = request.customFields;
867
2264
  }
2265
+ // If no userDid and no customFields, custom_fields is omitted (valid)
868
2266
  // EXPLICIT SAFEGUARD: Remove session_id and project_id if they somehow got added
869
2267
  // This should never happen, but provides defense-in-depth
870
2268
  delete simplifiedRequest.session_id;
@@ -907,11 +2305,11 @@ export class ConsentService {
907
2305
  // FINAL SAFEGUARD: Remove session_id and project_id if they somehow got added
908
2306
  // This provides defense-in-depth protection
909
2307
  const sanitizedBody = { ...requestBody };
910
- if ('session_id' in sanitizedBody) {
2308
+ if ("session_id" in sanitizedBody) {
911
2309
  console.warn("[ConsentService] ⚠️ session_id detected in request body - removing (not in schema)");
912
2310
  delete sanitizedBody.session_id;
913
2311
  }
914
- if ('project_id' in sanitizedBody) {
2312
+ if ("project_id" in sanitizedBody) {
915
2313
  console.warn("[ConsentService] ⚠️ project_id detected in request body - removing (not in schema)");
916
2314
  delete sanitizedBody.project_id;
917
2315
  }
@@ -934,13 +2332,15 @@ export class ConsentService {
934
2332
  }
935
2333
  // Check for validation error specifically
936
2334
  if (response.status === 400) {
937
- const errorMessage = responseData
938
- ?.error?.message ||
939
- responseData?.message ||
940
- "Validation failed";
941
- if (errorMessage.includes("format") ||
2335
+ const errorData = responseData;
2336
+ const errorMessage = errorData.error?.message || errorData.message || "Validation failed";
2337
+ const errorCode = errorData.error_code || errorData.error?.code;
2338
+ // Check if error_code is explicitly set to "validation_error" OR error message suggests validation error
2339
+ if (errorCode === "validation_error" ||
2340
+ errorMessage.includes("format") ||
942
2341
  errorMessage.includes("schema") ||
943
- errorMessage.includes("invalid")) {
2342
+ errorMessage.includes("invalid") ||
2343
+ errorMessage.includes("Validation")) {
944
2344
  return {
945
2345
  success: false,
946
2346
  error: errorMessage,