@didit-protocol/mcp-server 4.0.0 → 5.1.34

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 (170) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +583 -227
  3. package/dist/audit-log.d.ts +22 -0
  4. package/dist/audit-log.d.ts.map +1 -0
  5. package/dist/audit-log.js +77 -0
  6. package/dist/audit-log.js.map +1 -0
  7. package/dist/auth/introspection-verifier.d.ts +16 -0
  8. package/dist/auth/introspection-verifier.d.ts.map +1 -0
  9. package/dist/auth/introspection-verifier.js +77 -0
  10. package/dist/auth/introspection-verifier.js.map +1 -0
  11. package/dist/auth/verifier.d.ts +19 -0
  12. package/dist/auth/verifier.d.ts.map +1 -0
  13. package/dist/auth/verifier.js +88 -0
  14. package/dist/auth/verifier.js.map +1 -0
  15. package/dist/blank-args.d.ts +10 -0
  16. package/dist/blank-args.d.ts.map +1 -0
  17. package/dist/blank-args.js +34 -0
  18. package/dist/blank-args.js.map +1 -0
  19. package/dist/chatgpt-app.d.ts +44 -0
  20. package/dist/chatgpt-app.d.ts.map +1 -0
  21. package/dist/chatgpt-app.js +52 -0
  22. package/dist/chatgpt-app.js.map +1 -0
  23. package/dist/config.d.ts +93 -5
  24. package/dist/config.d.ts.map +1 -1
  25. package/dist/config.js +198 -27
  26. package/dist/config.js.map +1 -1
  27. package/dist/dates.d.ts +2 -0
  28. package/dist/dates.d.ts.map +1 -0
  29. package/dist/dates.js +23 -0
  30. package/dist/dates.js.map +1 -0
  31. package/dist/feature-config-schema.d.ts +66 -0
  32. package/dist/feature-config-schema.d.ts.map +1 -0
  33. package/dist/feature-config-schema.js +192 -0
  34. package/dist/feature-config-schema.js.map +1 -0
  35. package/dist/http.d.ts +4 -0
  36. package/dist/http.d.ts.map +1 -0
  37. package/dist/http.js +230 -0
  38. package/dist/http.js.map +1 -0
  39. package/dist/index.d.ts +20 -1
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +2397 -510
  42. package/dist/index.js.map +1 -1
  43. package/dist/internal-tools.d.ts +17 -0
  44. package/dist/internal-tools.d.ts.map +1 -0
  45. package/dist/internal-tools.js +26 -0
  46. package/dist/internal-tools.js.map +1 -0
  47. package/dist/mcp-modern.d.ts +36 -0
  48. package/dist/mcp-modern.d.ts.map +1 -0
  49. package/dist/mcp-modern.js +152 -0
  50. package/dist/mcp-modern.js.map +1 -0
  51. package/dist/orgapp.d.ts +34 -0
  52. package/dist/orgapp.d.ts.map +1 -0
  53. package/dist/orgapp.js +93 -0
  54. package/dist/orgapp.js.map +1 -0
  55. package/dist/permissions.d.ts +24 -0
  56. package/dist/permissions.d.ts.map +1 -0
  57. package/dist/permissions.js +210 -0
  58. package/dist/permissions.js.map +1 -0
  59. package/dist/privileged-tools.d.ts +14 -0
  60. package/dist/privileged-tools.d.ts.map +1 -0
  61. package/dist/privileged-tools.js +21 -0
  62. package/dist/privileged-tools.js.map +1 -0
  63. package/dist/schema/feature-config-schema.json +4446 -0
  64. package/dist/security.d.ts +168 -0
  65. package/dist/security.d.ts.map +1 -0
  66. package/dist/security.js +858 -0
  67. package/dist/security.js.map +1 -0
  68. package/dist/session-pdf-download.d.ts +8 -0
  69. package/dist/session-pdf-download.d.ts.map +1 -0
  70. package/dist/session-pdf-download.js +91 -0
  71. package/dist/session-pdf-download.js.map +1 -0
  72. package/dist/tools/analytics.d.ts +13 -0
  73. package/dist/tools/analytics.d.ts.map +1 -0
  74. package/dist/tools/analytics.js +171 -0
  75. package/dist/tools/analytics.js.map +1 -0
  76. package/dist/tools/auth.d.ts +10 -3
  77. package/dist/tools/auth.d.ts.map +1 -1
  78. package/dist/tools/auth.js +68 -11
  79. package/dist/tools/auth.js.map +1 -1
  80. package/dist/tools/billing.d.ts +2 -2
  81. package/dist/tools/billing.d.ts.map +1 -1
  82. package/dist/tools/billing.js +37 -4
  83. package/dist/tools/billing.js.map +1 -1
  84. package/dist/tools/blocklist.d.ts +5 -0
  85. package/dist/tools/blocklist.d.ts.map +1 -0
  86. package/dist/tools/blocklist.js +21 -0
  87. package/dist/tools/blocklist.js.map +1 -0
  88. package/dist/tools/businesses.d.ts +1 -1
  89. package/dist/tools/businesses.d.ts.map +1 -1
  90. package/dist/tools/businesses.js +31 -9
  91. package/dist/tools/businesses.js.map +1 -1
  92. package/dist/tools/cases.d.ts +6 -0
  93. package/dist/tools/cases.d.ts.map +1 -0
  94. package/dist/tools/cases.js +63 -0
  95. package/dist/tools/cases.js.map +1 -0
  96. package/dist/tools/compliance.d.ts +8 -0
  97. package/dist/tools/compliance.d.ts.map +1 -0
  98. package/dist/tools/compliance.js +95 -0
  99. package/dist/tools/compliance.js.map +1 -0
  100. package/dist/tools/context.d.ts +2 -0
  101. package/dist/tools/context.d.ts.map +1 -0
  102. package/dist/tools/context.js +37 -0
  103. package/dist/tools/context.js.map +1 -0
  104. package/dist/tools/customization.d.ts +10 -4
  105. package/dist/tools/customization.d.ts.map +1 -1
  106. package/dist/tools/customization.js +21 -11
  107. package/dist/tools/customization.js.map +1 -1
  108. package/dist/tools/feature-config.d.ts +53 -0
  109. package/dist/tools/feature-config.d.ts.map +1 -0
  110. package/dist/tools/feature-config.js +432 -0
  111. package/dist/tools/feature-config.js.map +1 -0
  112. package/dist/tools/lists.d.ts.map +1 -1
  113. package/dist/tools/lists.js +17 -16
  114. package/dist/tools/lists.js.map +1 -1
  115. package/dist/tools/members.d.ts +7 -0
  116. package/dist/tools/members.d.ts.map +1 -0
  117. package/dist/tools/members.js +60 -0
  118. package/dist/tools/members.js.map +1 -0
  119. package/dist/tools/observability.d.ts +4 -0
  120. package/dist/tools/observability.d.ts.map +1 -0
  121. package/dist/tools/observability.js +17 -0
  122. package/dist/tools/observability.js.map +1 -0
  123. package/dist/tools/questionnaires.d.ts +62 -3
  124. package/dist/tools/questionnaires.d.ts.map +1 -1
  125. package/dist/tools/questionnaires.js +131 -6
  126. package/dist/tools/questionnaires.js.map +1 -1
  127. package/dist/tools/reports.d.ts +5 -0
  128. package/dist/tools/reports.d.ts.map +1 -0
  129. package/dist/tools/reports.js +89 -0
  130. package/dist/tools/reports.js.map +1 -0
  131. package/dist/tools/search.d.ts +30 -0
  132. package/dist/tools/search.d.ts.map +1 -0
  133. package/dist/tools/search.js +317 -0
  134. package/dist/tools/search.js.map +1 -0
  135. package/dist/tools/session-explain-levers.d.ts +17 -0
  136. package/dist/tools/session-explain-levers.d.ts.map +1 -0
  137. package/dist/tools/session-explain-levers.js +139 -0
  138. package/dist/tools/session-explain-levers.js.map +1 -0
  139. package/dist/tools/session-explain.d.ts +3 -0
  140. package/dist/tools/session-explain.d.ts.map +1 -0
  141. package/dist/tools/session-explain.js +180 -0
  142. package/dist/tools/session-explain.js.map +1 -0
  143. package/dist/tools/sessions.d.ts +9 -2
  144. package/dist/tools/sessions.d.ts.map +1 -1
  145. package/dist/tools/sessions.js +131 -22
  146. package/dist/tools/sessions.js.map +1 -1
  147. package/dist/tools/settings.d.ts +15 -1
  148. package/dist/tools/settings.d.ts.map +1 -1
  149. package/dist/tools/settings.js +143 -6
  150. package/dist/tools/settings.js.map +1 -1
  151. package/dist/tools/standalone.d.ts +7 -6
  152. package/dist/tools/standalone.d.ts.map +1 -1
  153. package/dist/tools/standalone.js +41 -26
  154. package/dist/tools/standalone.js.map +1 -1
  155. package/dist/tools/transactions.d.ts +9 -0
  156. package/dist/tools/transactions.d.ts.map +1 -1
  157. package/dist/tools/transactions.js +77 -4
  158. package/dist/tools/transactions.js.map +1 -1
  159. package/dist/tools/users.d.ts +1 -1
  160. package/dist/tools/users.d.ts.map +1 -1
  161. package/dist/tools/users.js +30 -9
  162. package/dist/tools/users.js.map +1 -1
  163. package/dist/tools/webhooks.d.ts.map +1 -1
  164. package/dist/tools/webhooks.js +22 -5
  165. package/dist/tools/webhooks.js.map +1 -1
  166. package/dist/tools/workflow-graph.d.ts +65 -0
  167. package/dist/tools/workflow-graph.d.ts.map +1 -0
  168. package/dist/tools/workflow-graph.js +686 -0
  169. package/dist/tools/workflow-graph.js.map +1 -0
  170. package/package.json +23 -6
@@ -0,0 +1,858 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MAX_UPLOAD_BYTES = exports.MAX_BATCH_IDS = exports.DiditError = void 0;
4
+ exports.pathSegment = pathSegment;
5
+ exports.assertBoolean = assertBoolean;
6
+ exports.validateLocalFile = validateLocalFile;
7
+ exports.validateUploadBuffer = validateUploadBuffer;
8
+ exports.requireFileSource = requireFileSource;
9
+ exports.resolveFileSource = resolveFileSource;
10
+ exports.assertSafeWebhookUrl = assertSafeWebhookUrl;
11
+ exports.sanitizeText = sanitizeText;
12
+ exports.redactDeep = redactDeep;
13
+ exports.sanitizeErrorShape = sanitizeErrorShape;
14
+ exports.toSafeErrorShape = toSafeErrorShape;
15
+ exports.statusToCode = statusToCode;
16
+ exports.statusToHint = statusToHint;
17
+ exports.extractDrfFieldError = extractDrfFieldError;
18
+ exports.parseErrorBody = parseErrorBody;
19
+ exports.maskSecret = maskSecret;
20
+ exports.redactApplication = redactApplication;
21
+ exports.redactWebhookDestination = redactWebhookDestination;
22
+ exports.redactApiKey = redactApiKey;
23
+ exports.redactCollection = redactCollection;
24
+ // Ported verbatim from the audited mcp-server-v2-public hardening core (config.ts).
25
+ // Surface-agnostic security/correctness helpers: structured errors, DRF error parsing,
26
+ // sanitization, secret redaction, path-segment + SSRF + file-upload guards.
27
+ const fs_1 = require("fs");
28
+ const path_1 = require("path");
29
+ /**
30
+ * A typed error carrying the structured shape. On an MCP error result the
31
+ * dispatch renders this as a TEXT block only — `Error [code]: message` plus an
32
+ * optional `Hint:`/`Allowed:` line — and OMITS `structuredContent` entirely, so a
33
+ * strict client never validates an error against a tool's success `outputSchema`.
34
+ * The `[code]` tag keeps the text machine-parseable. Never embeds the internal HTTP path.
35
+ */
36
+ class DiditError extends Error {
37
+ constructor(shape) {
38
+ super(shape.message);
39
+ this.name = "DiditError";
40
+ this.shape = shape;
41
+ }
42
+ }
43
+ exports.DiditError = DiditError;
44
+ // ── Path-segment safety (WS-E security) ───────────────────────────────────────
45
+ //
46
+ // EVERY user-controlled value interpolated into a request path MUST go through
47
+ // pathSegment(). `new URL()` normalizes `..`, so a raw value like
48
+ // "../billing/balance" would silently target a DIFFERENT endpoint. We reject the
49
+ // routing/traversal metacharacters outright AND percent-encode the rest.
50
+ function pathSegment(value, field) {
51
+ // A value that never ARRIVED and a value of the wrong SHAPE are different bugs, and
52
+ // collapsing them sends the caller to the wrong place. the dispatcher was
53
+ // stripping the routing ids out of a handler's args before the handler read them, so
54
+ // `organization_id` reached here as `undefined`, and the caller was told its perfectly
55
+ // good UUID "must be a string ... with no path separators", a hint describing a condition
56
+ // the input already satisfied. 18 production calls across 10 traces dead-ended on that
57
+ // wording because it blamed the value the caller sent instead of reporting that nothing
58
+ // was received. Report the missing case as missing, and name the type we DID get.
59
+ if (value === undefined || value === null) {
60
+ throw new DiditError({
61
+ code: "bad_request",
62
+ message: `${field} is required but no value was received.`,
63
+ field,
64
+ hint: `Pass ${field} in the tool arguments. If you did pass it, the value was dropped before it reached the handler - report this rather than retrying.`,
65
+ });
66
+ }
67
+ if (typeof value !== "string") {
68
+ const received = Array.isArray(value) ? "array" : typeof value;
69
+ throw new DiditError({
70
+ code: "bad_request",
71
+ message: `${field} must be a string (received ${/^[aeiou]/.test(received) ? "an" : "a"} ${received}).`,
72
+ field,
73
+ hint: "Provide a single id/value with no path separators.",
74
+ });
75
+ }
76
+ const trimmed = value.trim();
77
+ if (!trimmed) {
78
+ throw new DiditError({
79
+ code: "bad_request",
80
+ message: `${field} must not be empty.`,
81
+ field,
82
+ });
83
+ }
84
+ // Reject routing/path-separator metacharacters BEFORE encoding so the value can
85
+ // never escape its slot. NOTE: we reject only path-ESCAPING traversal — a bare
86
+ // "." or ".." segment (which `new URL()` would resolve as the current/parent
87
+ // dir) — NOT every "..". A dotted run *inside* a segment (e.g. a valid
88
+ // vendor_data like "customer..prod") is safe: `/` is already rejected, and
89
+ // encodeURIComponent leaves the dots literal so it can't be re-read as traversal.
90
+ if (/[\/?#]/.test(trimmed)) {
91
+ throw new DiditError({
92
+ code: "bad_request",
93
+ message: `${field} contains illegal path characters.`,
94
+ field,
95
+ hint: "Path identifiers must not contain '/', '?', or '#'.",
96
+ });
97
+ }
98
+ if (trimmed === "." || trimmed === "..") {
99
+ throw new DiditError({
100
+ code: "bad_request",
101
+ message: `${field} must not be a path-traversal segment.`,
102
+ field,
103
+ hint: "A bare '.' or '..' segment is not a valid identifier.",
104
+ });
105
+ }
106
+ return encodeURIComponent(trimmed);
107
+ }
108
+ /**
109
+ * Require a value to be a real boolean (true/false) — NOT a truthy string such as
110
+ * "false". Used for safety flags (delete_all, confirm) where a coerced string is a
111
+ * security bug (a truthy "false" would otherwise pass a `truthy` check).
112
+ */
113
+ function assertBoolean(value, field) {
114
+ if (value !== undefined && value !== null && typeof value !== "boolean") {
115
+ throw new DiditError({
116
+ code: "bad_request",
117
+ message: `${field} must be a boolean (true or false), not a string or number.`,
118
+ field,
119
+ hint: `Pass ${field}:true or ${field}:false — the string "true"/"false" is rejected.`,
120
+ });
121
+ }
122
+ }
123
+ /** Hard cap on the number of ids accepted in a single batch operation. */
124
+ exports.MAX_BATCH_IDS = 1000;
125
+ // ── Local-file upload safety (WS-E security) ──────────────────────────────────
126
+ /** Maximum size (bytes) accepted for a local image/branding upload. */
127
+ exports.MAX_UPLOAD_BYTES = 15 * 1024 * 1024; // 15 MB
128
+ const RESTRICTED_PATH_PREFIXES = [
129
+ "/etc/", "/proc/", "/sys/", "/dev/", "/root/", "/run/", "/var/run/", "/boot/",
130
+ ];
131
+ /** Allowed upload file extensions (lower-case, with the dot). */
132
+ const ALLOWED_UPLOAD_EXTENSIONS = new Set([
133
+ ".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".ico", ".pdf",
134
+ ]);
135
+ /**
136
+ * Basenames we refuse to read even if they somehow carried an image extension —
137
+ * secret/credential files + manifests. Defense in depth on top of the
138
+ * magic-bytes allow-list (a `.env` would also fail the sniff). Matched
139
+ * case-insensitively against the FILE NAME (not directory components).
140
+ */
141
+ const BLOCKED_UPLOAD_BASENAMES = new Set([
142
+ ".env", ".env.local", ".env.development", ".env.production", ".env.test",
143
+ "id_rsa", "id_dsa", "id_ecdsa", "id_ed25519",
144
+ ".netrc", ".npmrc", ".pgpass", ".git-credentials", ".htpasswd",
145
+ "credentials", "package.json", "package-lock.json", "yarn.lock", "pnpm-lock.yaml",
146
+ ]);
147
+ /**
148
+ * Sniff the leading bytes of an upload and return a known image/document type,
149
+ * or null if the magic bytes don't match an allowed format.
150
+ */
151
+ function sniffMagicBytes(buf) {
152
+ // PNG 89 50 4E 47 0D 0A 1A 0A
153
+ if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47 &&
154
+ buf[4] === 0x0d && buf[5] === 0x0a && buf[6] === 0x1a && buf[7] === 0x0a)
155
+ return "png";
156
+ // JPEG FF D8 FF
157
+ if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff)
158
+ return "jpeg";
159
+ // GIF "GIF87a" / "GIF89a"
160
+ if (buf.slice(0, 4).toString("latin1") === "GIF8")
161
+ return "gif";
162
+ // WEBP "RIFF"...."WEBP"
163
+ if (buf.slice(0, 4).toString("latin1") === "RIFF" && buf.slice(8, 12).toString("latin1") === "WEBP")
164
+ return "webp";
165
+ // BMP "BM"
166
+ if (buf[0] === 0x42 && buf[1] === 0x4d)
167
+ return "bmp";
168
+ // ICO 00 00 01 00
169
+ if (buf[0] === 0x00 && buf[1] === 0x00 && buf[2] === 0x01 && buf[3] === 0x00)
170
+ return "ico";
171
+ // PDF "%PDF-"
172
+ if (buf.slice(0, 5).toString("latin1") === "%PDF-")
173
+ return "pdf";
174
+ return null;
175
+ }
176
+ /**
177
+ * Sniff the leading bytes of a file. Reads only the header so a non-image file
178
+ * is rejected BEFORE the (potentially large) full read.
179
+ */
180
+ function sniffFileType(filePath) {
181
+ let fd;
182
+ const buf = Buffer.alloc(16);
183
+ try {
184
+ fd = (0, fs_1.openSync)(filePath, "r");
185
+ (0, fs_1.readSync)(fd, buf, 0, 16, 0);
186
+ }
187
+ catch {
188
+ return null;
189
+ }
190
+ finally {
191
+ if (fd !== undefined)
192
+ (0, fs_1.closeSync)(fd);
193
+ }
194
+ return sniffMagicBytes(buf);
195
+ }
196
+ /**
197
+ * Validate that a path points to a readable, regular, sanely-sized image/document
198
+ * file before we read it for an upload. Requires an ABSOLUTE path; rejects
199
+ * non-strings, directories, symlinks, restricted system paths, dotfiles + known
200
+ * secret/manifest filenames, disallowed extensions, empty + oversized files, and
201
+ * — crucially — any content whose MAGIC BYTES are not a recognised image/PDF
202
+ * (so `.env`, `package.json`, source, archives, executables can never be read).
203
+ * Never echoes the path back (no leak).
204
+ */
205
+ function validateLocalFile(filePath, field = "image_path") {
206
+ if (typeof filePath !== "string" || !filePath.trim()) {
207
+ throw new DiditError({
208
+ code: "bad_request",
209
+ message: `${field} must be a non-empty file-path string.`,
210
+ field,
211
+ hint: "Provide an absolute path to a readable image (png/jpg/jpeg/webp/gif/bmp/ico) or PDF file.",
212
+ });
213
+ }
214
+ if (!(0, path_1.isAbsolute)(filePath)) {
215
+ throw new DiditError({
216
+ code: "bad_request",
217
+ message: `${field} must be an absolute path.`,
218
+ field,
219
+ hint: "Provide an absolute path (starting with '/'), not a relative one.",
220
+ });
221
+ }
222
+ const lower = filePath.toLowerCase();
223
+ for (const bad of RESTRICTED_PATH_PREFIXES) {
224
+ if (lower === bad.slice(0, -1) || lower.startsWith(bad)) {
225
+ throw new DiditError({
226
+ code: "bad_request",
227
+ message: `${field} points to a restricted system path.`,
228
+ field,
229
+ });
230
+ }
231
+ }
232
+ const name = (0, path_1.basename)(filePath);
233
+ // Dotfiles (e.g. `.env`, `.npmrc`) are never uploadable images.
234
+ if (name.startsWith(".") && !ALLOWED_UPLOAD_EXTENSIONS.has((0, path_1.extname)(name).toLowerCase())) {
235
+ throw new DiditError({
236
+ code: "bad_request",
237
+ message: `${field} must not be a dotfile.`,
238
+ field,
239
+ });
240
+ }
241
+ if (BLOCKED_UPLOAD_BASENAMES.has(name.toLowerCase())) {
242
+ throw new DiditError({
243
+ code: "bad_request",
244
+ message: `${field} points to a blocked secret/configuration file.`,
245
+ field,
246
+ });
247
+ }
248
+ const ext = (0, path_1.extname)(name).toLowerCase();
249
+ if (!ALLOWED_UPLOAD_EXTENSIONS.has(ext)) {
250
+ throw new DiditError({
251
+ code: "bad_request",
252
+ message: `${field} has an unsupported file extension.`,
253
+ field,
254
+ hint: "Allowed extensions: png, jpg, jpeg, webp, gif, bmp, ico, pdf.",
255
+ });
256
+ }
257
+ let st;
258
+ try {
259
+ // lstat (NOT stat) so a symlink is detected rather than followed.
260
+ st = (0, fs_1.lstatSync)(filePath);
261
+ }
262
+ catch {
263
+ throw new DiditError({
264
+ code: "bad_request",
265
+ message: `${field}: file not found or not readable.`,
266
+ field,
267
+ hint: "Provide an absolute path to a readable image/PDF file.",
268
+ });
269
+ }
270
+ if (st.isSymbolicLink()) {
271
+ throw new DiditError({ code: "bad_request", message: `${field} must not be a symbolic link.`, field });
272
+ }
273
+ if (!st.isFile()) {
274
+ throw new DiditError({ code: "bad_request", message: `${field} must be a regular file.`, field });
275
+ }
276
+ if (st.size <= 0) {
277
+ throw new DiditError({ code: "bad_request", message: `${field} is empty (0 bytes).`, field });
278
+ }
279
+ if (st.size > exports.MAX_UPLOAD_BYTES) {
280
+ throw new DiditError({
281
+ code: "bad_request",
282
+ message: `${field} exceeds the ${Math.round(exports.MAX_UPLOAD_BYTES / 1024 / 1024)}MB upload limit.`,
283
+ field,
284
+ });
285
+ }
286
+ // Content sniff LAST (after the cheap rejects) but BEFORE any full read by the
287
+ // caller: the magic bytes must match a recognised image/PDF format.
288
+ const sniffed = sniffFileType(filePath);
289
+ if (!sniffed) {
290
+ throw new DiditError({
291
+ code: "bad_request",
292
+ message: `${field} is not a recognised image or PDF (content check failed).`,
293
+ field,
294
+ hint: "Upload a real png/jpg/jpeg/webp/gif/bmp/ico image or a PDF.",
295
+ });
296
+ }
297
+ return filePath;
298
+ }
299
+ // ── Base64 upload safety (hosted transport) ───────────────────────────────────
300
+ const DATA_URL_PREFIX = /^data:[^;,]+;base64,/;
301
+ /**
302
+ * Validate an upload supplied as base64 content (raw base64 or a data URL) —
303
+ * the remote-caller counterpart of validateLocalFile for the hosted HTTP
304
+ * transport, where the caller has no filesystem on this machine. Enforces the
305
+ * same size cap and magic-bytes allow-list, and returns the decoded bytes.
306
+ */
307
+ function validateUploadBuffer(value, field = "image_base64") {
308
+ if (typeof value !== "string" || !value.trim()) {
309
+ throw new DiditError({
310
+ code: "bad_request",
311
+ message: `${field} must be a non-empty base64 string.`,
312
+ field,
313
+ hint: "Provide the file content as base64 (raw or a data: URL).",
314
+ });
315
+ }
316
+ const base64 = value.replace(DATA_URL_PREFIX, "").trim();
317
+ if (!/^[A-Za-z0-9+/]+=*$/.test(base64)) {
318
+ throw new DiditError({
319
+ code: "bad_request",
320
+ message: `${field} is not valid base64.`,
321
+ field,
322
+ hint: "Provide the file content as base64 (raw or a data: URL).",
323
+ });
324
+ }
325
+ // Reject on the encoded length first so we never materialise an oversized buffer.
326
+ if ((base64.length * 3) / 4 > exports.MAX_UPLOAD_BYTES) {
327
+ throw new DiditError({
328
+ code: "bad_request",
329
+ message: `${field} exceeds the ${Math.round(exports.MAX_UPLOAD_BYTES / 1024 / 1024)}MB upload limit.`,
330
+ field,
331
+ });
332
+ }
333
+ const buffer = Buffer.from(base64, "base64");
334
+ if (buffer.length === 0) {
335
+ throw new DiditError({ code: "bad_request", message: `${field} is empty.`, field });
336
+ }
337
+ const type = sniffMagicBytes(buffer.subarray(0, 16));
338
+ if (!type) {
339
+ throw new DiditError({
340
+ code: "bad_request",
341
+ message: `${field} is not a recognised image or PDF (content check failed).`,
342
+ field,
343
+ hint: "Upload a real png/jpg/jpeg/webp/gif/bmp/ico image or a PDF.",
344
+ });
345
+ }
346
+ return { buffer, type };
347
+ }
348
+ /**
349
+ * Assert that a required tool file input was actually supplied (either form).
350
+ * Throws the canonical "file is required" error with the local-vs-hosted hint.
351
+ */
352
+ function requireFileSource(source, fieldBase) {
353
+ if (!source?.path && !source?.base64) {
354
+ throw new DiditError({
355
+ code: "bad_request",
356
+ message: `A file is required: provide ${fieldBase}_path or ${fieldBase}_base64.`,
357
+ field: `${fieldBase}_path`,
358
+ hint: `${fieldBase}_path is an absolute path on the machine running the MCP server (local/stdio runs). ` +
359
+ `${fieldBase}_base64 is the file content as base64 or a data: URL — use it when calling the hosted MCP ` +
360
+ `(the Didit Copilot resolves attachment references like "att_1" into it automatically).`,
361
+ });
362
+ }
363
+ return source;
364
+ }
365
+ /**
366
+ * Resolve a tool file input to bytes + a filename for multipart upload.
367
+ * Exactly one of `path`/`base64` must be set when `required`; both set is
368
+ * always an error. `fieldBase` is the parameter stem (e.g. "front_image" for
369
+ * front_image_path / front_image_base64) used in error messages.
370
+ */
371
+ function resolveFileSource(source, fieldBase, { required = false } = {}) {
372
+ const path = source?.path;
373
+ const base64 = source?.base64;
374
+ if (path && base64) {
375
+ throw new DiditError({
376
+ code: "bad_request",
377
+ message: `Provide only one of ${fieldBase}_path or ${fieldBase}_base64, not both.`,
378
+ field: `${fieldBase}_path`,
379
+ });
380
+ }
381
+ if (!path && !base64) {
382
+ if (!required)
383
+ return undefined;
384
+ requireFileSource(source, fieldBase);
385
+ }
386
+ if (path) {
387
+ const safePath = validateLocalFile(path, `${fieldBase}_path`);
388
+ return { buffer: (0, fs_1.readFileSync)(safePath), filename: (0, path_1.basename)(safePath) };
389
+ }
390
+ const { buffer, type } = validateUploadBuffer(base64, `${fieldBase}_base64`);
391
+ const ext = type === "jpeg" ? "jpg" : type;
392
+ return { buffer, filename: `${fieldBase}.${ext}` };
393
+ }
394
+ // ── Webhook SSRF guard (WS-E security) ────────────────────────────────────────
395
+ function ipv4IsInternal(host) {
396
+ const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
397
+ if (!m)
398
+ return false;
399
+ const o = m.slice(1).map(Number);
400
+ if (o.some((n) => n > 255))
401
+ return true; // malformed → treat as unsafe
402
+ const [a, b] = o;
403
+ if (a === 0 || a === 127)
404
+ return true; // 0.0.0.0/8, loopback
405
+ if (a === 10)
406
+ return true; // RFC-1918
407
+ if (a === 169 && b === 254)
408
+ return true; // link-local incl. 169.254.169.254 metadata
409
+ if (a === 172 && b >= 16 && b <= 31)
410
+ return true; // RFC-1918
411
+ if (a === 192 && b === 168)
412
+ return true; // RFC-1918
413
+ if (a === 100 && b >= 64 && b <= 127)
414
+ return true; // CGNAT
415
+ return false;
416
+ }
417
+ function isInternalHost(rawHost) {
418
+ // Canonicalize: lower-case, strip IPv6 brackets, and drop FQDN trailing dots
419
+ // (e.g. `localhost.` / `evil.com.`) so a trailing-dot variant can't dodge the
420
+ // name checks below.
421
+ let host = rawHost.toLowerCase().replace(/^\[/, "").replace(/\]$/, "");
422
+ host = host.replace(/\.+$/, "");
423
+ if (!host)
424
+ return true;
425
+ if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host === "ip6-localhost")
426
+ return true;
427
+ if (host === "::1" || host === "::" || host === "0:0:0:0:0:0:0:1")
428
+ return true;
429
+ // IPv6 unique-local (fc00::/7) + link-local (fe80::/10)
430
+ if (/^f[cd][0-9a-f]*:/.test(host) || /^fe[89ab][0-9a-f]*:/.test(host))
431
+ return true;
432
+ // IPv4-mapped IPv6, DOTTED tail (::ffff:127.0.0.1) — extract the v4 tail.
433
+ const mappedDotted = /(?:^|:)((?:\d{1,3}\.){3}\d{1,3})$/.exec(host);
434
+ if (mappedDotted && ipv4IsInternal(mappedDotted[1]))
435
+ return true;
436
+ // IPv4-mapped IPv6, HEX tail (::ffff:7f00:1). The WHATWG URL parser canonicalizes
437
+ // `[::ffff:127.0.0.1]` to this hex form, so we MUST decode it back to dotted
438
+ // quad and run it through the same internal-range check.
439
+ const mappedHex = /^(?:0*:)*:?0*ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(host);
440
+ if (mappedHex) {
441
+ const hi = parseInt(mappedHex[1], 16);
442
+ const lo = parseInt(mappedHex[2], 16);
443
+ const dotted = `${(hi >> 8) & 0xff}.${hi & 0xff}.${(lo >> 8) & 0xff}.${lo & 0xff}`;
444
+ if (ipv4IsInternal(dotted))
445
+ return true;
446
+ }
447
+ // Best-effort alias guard: reject a hostname that EMBEDS an internal IPv4 literal
448
+ // as a dotted label (e.g. 127.0.0.1.nip.io, 10.0.0.1.sslip.io) — wildcard-DNS
449
+ // services that resolve straight back to the embedded internal address. This is
450
+ // NOT a complete rebinding defense (see the note on assertSafeWebhookUrl): a host
451
+ // can still resolve to an internal IP at request time without revealing it in the
452
+ // name, so the BACKEND must re-validate the resolved IP at delivery time.
453
+ const embedded = /(?:^|\.)((?:\d{1,3}\.){3}\d{1,3})(?:$|\.)/.exec(host);
454
+ if (embedded && ipv4IsInternal(embedded[1]))
455
+ return true;
456
+ return ipv4IsInternal(host);
457
+ }
458
+ /**
459
+ * Reject a URL that the BACKEND will fetch or call (webhook destination, KYB
460
+ * webhook_url, session-import source_file_url, URL-form portrait_image…) when it
461
+ * points at an internal / loopback / cloud-metadata / RFC-1918 host. This is the
462
+ * single client-side SSRF guard; returns the URL when it is a public http(s) endpoint.
463
+ *
464
+ * ⚠️ CLIENT-SIDE ONLY — NOT a complete DNS-rebinding / TOCTOU defense. The MCP only
465
+ * FORWARDS the URL; the OUTBOUND fetch happens on the Didit BACKEND. A hostname that
466
+ * passes this check can still resolve to an internal IP at delivery time (rebinding),
467
+ * or redirect (3xx) to an internal target after the fact. The BACKEND MUST therefore
468
+ * re-validate at delivery time: resolve the host and re-check the ACTUAL IP against
469
+ * the same internal ranges, disable/restrict following redirects, and pin/re-validate
470
+ * the post-redirect target. This function rejects literal internal hosts and obviously
471
+ * suspicious embedded-internal-IP aliases (e.g. 127.0.0.1.nip.io) — it cannot see DNS.
472
+ */
473
+ function assertSafeWebhookUrl(rawUrl, field = "url") {
474
+ if (typeof rawUrl !== "string" || !rawUrl.trim()) {
475
+ throw new DiditError({ code: "bad_request", message: `${field} must be a non-empty URL string.`, field });
476
+ }
477
+ let u;
478
+ try {
479
+ u = new URL(rawUrl.trim());
480
+ }
481
+ catch {
482
+ throw new DiditError({ code: "bad_request", message: `${field} must be a valid absolute URL.`, field });
483
+ }
484
+ if (u.protocol !== "https:" && u.protocol !== "http:") {
485
+ throw new DiditError({
486
+ code: "bad_request",
487
+ message: `${field} must use http or https.`,
488
+ field,
489
+ });
490
+ }
491
+ if (isInternalHost(u.hostname)) {
492
+ throw new DiditError({
493
+ code: "unsafe_operation",
494
+ message: `${field} targets an internal, loopback, or cloud-metadata address.`,
495
+ field,
496
+ hint: "Use a public HTTPS endpoint. Internal hosts (localhost, 127.0.0.0/8, 169.254.169.254, 10/172.16/192.168 RFC-1918) are refused.",
497
+ });
498
+ }
499
+ return rawUrl.trim();
500
+ }
501
+ // ── Error sanitization (WS-G security) ────────────────────────────────────────
502
+ const SENSITIVE_KEY_RE = /(api[_-]?key|secret|token|password|passwd|pwd|authorization|bearer|refresh[_-]?token|client[_-]?secret|signing[_-]?secret)/i;
503
+ /** Canonical RFC-4122 UUID (8-4-4-4-12 hex). A legitimate resource id. */
504
+ const UUID_RE = /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi;
505
+ /**
506
+ * Strip secrets / PII / local-environment detail out of a free-text string:
507
+ * URLs + hosts, absolute file paths (INCLUDING spaces, e.g. "Application Support"),
508
+ * emails, known secret-token shapes, JWTs, long opaque mixed blobs, and
509
+ * phone-number-like digit runs. Canonical UUIDs are PRESERVED — they are legit
510
+ * resource ids that the 24+ mixed-token rule and the phone digit-run rule would
511
+ * otherwise mangle — so we stash them behind a sentinel before redacting and
512
+ * restore them at the end.
513
+ */
514
+ function sanitizeText(input) {
515
+ let s = typeof input === "string" ? input : String(input ?? "");
516
+ // Redact secret-shaped tokens FIRST — BEFORE UUID preservation — so a secret like
517
+ // "didit-<uuid>" / "sk_live_…" is redacted whole instead of having its UUID tail
518
+ // preserved (which would shrink it below the match threshold and let it slip).
519
+ // Exempt tool names (didit_ + lowercase words, e.g. "didit_context_get"): error
520
+ // hints reference them so the model knows which tool to call next, and real keys
521
+ // always carry digits/uppercase, which the exemption pattern cannot match.
522
+ s = s.replace(/\b(?:didit|sk|pk|rk|whsec|key)[_-][A-Za-z0-9_\-]{6,}/gi, (m) => /^didit_[a-z_]+$/.test(m) ? m : "[redacted-secret]");
523
+ // Stash canonical UUIDs so no downstream rule can touch them, then restore.
524
+ const uuids = [];
525
+ s = s.replace(UUID_RE, (m) => {
526
+ uuids.push(m);
527
+ return `UUID${uuids.length - 1}`;
528
+ });
529
+ s = s.replace(/\bhttps?:\/\/[^\s"'<>]+/gi, "[redacted-url]");
530
+ s = s.replace(/\b[A-Za-z]:\\[^\s"'<>]+/g, "[redacted-path]"); // Windows abs paths
531
+ // Unix abs paths (>=2 segments). A space is allowed INSIDE a segment only when
532
+ // that segment is followed by another '/', so we consume a directory name like
533
+ // "Application Support" in full but never run off the end of the path into prose.
534
+ s = s.replace(/(?:\/[A-Za-z0-9._@%+\-]+(?: +[A-Za-z0-9._@%+\-]+)*(?=\/))+\/?[A-Za-z0-9._@%+\-]*/g, "[redacted-path]");
535
+ s = s.replace(/\b[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}\b/g, "[redacted-email]");
536
+ s = s.replace(/\beyJ[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+/g, "[redacted-token]");
537
+ s = s.replace(/\b[A-Za-z0-9_\-]{24,}\b/g, (m) => (/[A-Za-z]/.test(m) && /\d/.test(m) ? "[redacted-token]" : m));
538
+ s = s.replace(/(?<!\w)\+?\d[\d\s().\-]{6,}\d(?!\w)/g, "[redacted-phone]");
539
+ // Restore the preserved UUIDs.
540
+ s = s.replace(/UUID(\d+)/g, (_m, i) => uuids[Number(i)] ?? "");
541
+ return s;
542
+ }
543
+ /** Recursively redact sensitive-keyed values and sanitize string leaves. */
544
+ function redactDeep(value) {
545
+ if (typeof value === "string")
546
+ return sanitizeText(value);
547
+ if (Array.isArray(value))
548
+ return value.map(redactDeep);
549
+ if (value && typeof value === "object") {
550
+ const out = {};
551
+ for (const [k, v] of Object.entries(value)) {
552
+ out[k] = SENSITIVE_KEY_RE.test(k) ? "[redacted]" : redactDeep(v);
553
+ }
554
+ return out;
555
+ }
556
+ return value;
557
+ }
558
+ /**
559
+ * Sanitize a structured error shape. `code`, `field`, and `hint` are MCP-authored
560
+ * (trusted) — they legitimately name env vars (e.g. DIDIT_DEFAULT_ORG_ID) and tools,
561
+ * so they are NOT value-sanitized (that would mangle remediation hints). `message`
562
+ * and `allowed[]` can carry BACKEND-origin text (a 422 body's enum list could leak a
563
+ * URL / email / token), so each is run through sanitizeText. Any other nested fields
564
+ * go through redactDeep.
565
+ */
566
+ function sanitizeErrorShape(shape) {
567
+ const { code, field, allowed, hint, message, ...rest } = shape;
568
+ return {
569
+ ...redactDeep(rest),
570
+ ...(code !== undefined ? { code } : {}),
571
+ ...(field !== undefined ? { field } : {}),
572
+ ...(allowed !== undefined
573
+ ? { allowed: Array.isArray(allowed) ? allowed.map((a) => sanitizeText(a)) : sanitizeText(allowed) }
574
+ : {}),
575
+ ...(hint !== undefined ? { hint } : {}),
576
+ ...(message !== undefined ? { message: sanitizeText(message) } : {}),
577
+ };
578
+ }
579
+ /**
580
+ * Convert ANY thrown value into a safe DiditErrorShape: DiditError shapes are
581
+ * sanitized; transport failures (undici `fetch failed`, ECONNREFUSED, DNS, TLS…)
582
+ * become a clean `network_error`; everything else is sanitized + wrapped.
583
+ */
584
+ function toSafeErrorShape(error) {
585
+ if (error instanceof DiditError)
586
+ return sanitizeErrorShape(error.shape);
587
+ const raw = error && error.message ? String(error.message) : String(error);
588
+ const isTransport = /fetch failed|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ECONNRESET|EPIPE|socket hang up|network|getaddrinfo|\bTLS\b|certificate|self[- ]signed/i.test(raw) ||
589
+ (error && (error.name === "FetchError" || error.code === "ECONNREFUSED" || error.code === "ENOTFOUND"));
590
+ if (isTransport) {
591
+ return {
592
+ code: "network_error",
593
+ message: "Could not reach the Didit API (network/transport error).",
594
+ hint: "Check connectivity and retry. If it persists, the API may be temporarily unavailable.",
595
+ };
596
+ }
597
+ return { code: "error", message: sanitizeText(raw) };
598
+ }
599
+ /** Map an HTTP status to a stable machine-readable error code. */
600
+ function statusToCode(status) {
601
+ switch (status) {
602
+ case 400:
603
+ return "bad_request";
604
+ case 401:
605
+ return "unauthorized";
606
+ case 402:
607
+ return "payment_required";
608
+ case 403:
609
+ return "forbidden";
610
+ case 404:
611
+ return "not_found";
612
+ case 409:
613
+ return "conflict";
614
+ case 422:
615
+ return "unprocessable";
616
+ case 429:
617
+ return "rate_limited";
618
+ default:
619
+ return status >= 500 ? "server_error" : "error";
620
+ }
621
+ }
622
+ /** Per-status remediation hint so the model knows what to do next. */
623
+ function statusToHint(status, body) {
624
+ switch (status) {
625
+ case 402:
626
+ return "Insufficient balance. Use didit_top_up to add credits (minimum $50), then retry.";
627
+ case 404:
628
+ return "The referenced id was not found. List the parent collection first (e.g. didit_list_sessions / didit_list_workflows) to get a valid id.";
629
+ case 422:
630
+ return body && Array.isArray(body.allowed)
631
+ ? "Invalid enum value — choose one of the values in `allowed`."
632
+ : "A field value was rejected. Check the field constraints and retry.";
633
+ case 403:
634
+ return "This action is not permitted with the current credentials (it may require a different role).";
635
+ case 401:
636
+ return "Authentication failed. Check the api key / access token.";
637
+ case 409:
638
+ return "Conflict — the resource is in a state that blocks this action (e.g. transaction monitoring not configured). Configure the prerequisite first.";
639
+ case 429:
640
+ return "Rate limited. Back off and retry after a short delay.";
641
+ case 400:
642
+ // Cheap presence check (no second full DRF traversal — parseErrorBody already extracts the detail).
643
+ return body && (typeof body === "object" || typeof body === "string") ? "Fix the indicated field and retry." : undefined;
644
+ default:
645
+ return undefined;
646
+ }
647
+ }
648
+ // ── DRF (Django REST Framework) error-body extraction (WS-G explainability) ───
649
+ //
650
+ // The REAL Didit backend returns validation errors as FIELD-KEYED objects or BARE
651
+ // ARRAYS, NOT the {detail:"..."} shape. Without parsing these we would surface the
652
+ // opaque "Request failed with status N" and lose the backend's field-level detail.
653
+ // Captured real 400 bodies:
654
+ // (a) field-error object { "list_type": ["..."], "entry_type": ["\"x\" is not a valid choice."] }
655
+ // (b) NESTED field-error { "features": [["Each workflow feature must be an object."]] }
656
+ // { "form_elements": [{ "element_type": ["This field is required."] }] }
657
+ // (c) bare array ["Provide vendor_data_list or set delete_all=true."]
658
+ // flattenDrfError() turns any nested array/object value into a readable line;
659
+ // extractDrfFieldError() picks the FIRST offending field and assembles the message.
660
+ // Bounds so a hostile / huge / cyclic backend error body can't overflow the stack,
661
+ // burn CPU, or produce oversized user-facing text (DoS-safe).
662
+ const DRF_MAX_DEPTH = 8;
663
+ const DRF_MAX_PARTS = 40;
664
+ const DRF_MAX_LEAF = 400;
665
+ const DRF_MAX_MSG = 2000;
666
+ /** Flatten a DRF error value (string | nested arrays | nested {field:...} objects) into one readable
667
+ * line. Depth/breadth/leaf/total-length bounded, with a cycle guard. */
668
+ function flattenDrfError(value, depth = 0, seen) {
669
+ if (value === null || value === undefined)
670
+ return "";
671
+ if (typeof value === "string")
672
+ return value.trim().slice(0, DRF_MAX_LEAF);
673
+ if (typeof value === "number" || typeof value === "boolean")
674
+ return String(value);
675
+ if (typeof value !== "object" || depth >= DRF_MAX_DEPTH)
676
+ return "";
677
+ const visited = seen || new Set();
678
+ if (visited.has(value))
679
+ return ""; // cycle guard
680
+ visited.add(value);
681
+ let parts;
682
+ if (Array.isArray(value)) {
683
+ parts = value.slice(0, DRF_MAX_PARTS).map((v) => flattenDrfError(v, depth + 1, visited)).filter(Boolean);
684
+ }
685
+ else {
686
+ // Bounded lazy scan — a for…in stops after DRF_MAX_PARTS without allocating the
687
+ // full key array (DoS-safe on a pathologically wide object).
688
+ parts = [];
689
+ let n = 0;
690
+ for (const k in value) {
691
+ if (!Object.prototype.hasOwnProperty.call(value, k))
692
+ continue;
693
+ if (n++ >= DRF_MAX_PARTS)
694
+ break;
695
+ const inner = flattenDrfError(value[k], depth + 1, visited);
696
+ if (inner)
697
+ parts.push(`${k}: ${inner}`);
698
+ }
699
+ }
700
+ visited.delete(value);
701
+ return parts.join("; ").slice(0, DRF_MAX_MSG);
702
+ }
703
+ /** A backend error KEY is rendered as the remediation `field` ONLY when it looks like a real field
704
+ * path (identifier / dots / brackets, ≤64 chars). Anything else (an email, an absolute path, a
705
+ * secret) is dropped so a hostile/odd backend body can't leak it via the `Field:` line. */
706
+ function safeFieldName(field) {
707
+ if (typeof field !== "string" || !/^[A-Za-z0-9_.\-[\]]{1,64}$/.test(field))
708
+ return undefined;
709
+ // Reject secret-SHAPED keys. The explicit prefix check is order-independent (sanitizeText
710
+ // stashes UUIDs before its secret regex, so "didit_<uuid>" would otherwise slip through);
711
+ // the sanitizeText comparison then catches anything else redactable.
712
+ if (/^(didit|sk|pk|rk|whsec|key)[_-]/i.test(field))
713
+ return undefined;
714
+ return sanitizeText(field) === field ? field : undefined;
715
+ }
716
+ /**
717
+ * Detect + extract a DRF field-error body. Returns { message, field? } — `field`
718
+ * is the FIRST offending key (undefined for a bare array). Returns null when the
719
+ * body is NOT a field-error shape (so the {detail}/{message}/{error} path handles it).
720
+ * The flattened message keeps the original backend text (e.g. `"x" is not a valid choice`).
721
+ */
722
+ function extractDrfFieldError(body) {
723
+ // (c) bare array — ["Provide vendor_data_list or set delete_all=true."]
724
+ if (Array.isArray(body)) {
725
+ const message = flattenDrfError(body);
726
+ return message ? { message } : null;
727
+ }
728
+ if (!body || typeof body !== "object")
729
+ return null;
730
+ // Single BOUNDED lazy pass (≤ DRF_MAX_PARTS keys; no full-width allocation).
731
+ // Treat as a field-error MAP only when at least one value is an array/object — a
732
+ // {detail:"..."} string body is NOT a field map (handled by the standard path).
733
+ let firstFieldKey;
734
+ const parts = [];
735
+ let scanned = 0;
736
+ for (const k in body) {
737
+ if (!Object.prototype.hasOwnProperty.call(body, k))
738
+ continue;
739
+ if (scanned++ >= DRF_MAX_PARTS)
740
+ break;
741
+ const v = body[k];
742
+ if (firstFieldKey === undefined && (Array.isArray(v) || (v !== null && typeof v === "object")))
743
+ firstFieldKey = k;
744
+ const inner = flattenDrfError(v);
745
+ if (inner)
746
+ parts.push(`${k}: ${inner}`);
747
+ }
748
+ if (firstFieldKey === undefined)
749
+ return null;
750
+ const message = parts.join("; ").slice(0, DRF_MAX_MSG);
751
+ return message ? { message, field: safeFieldName(firstFieldKey) } : null;
752
+ }
753
+ /**
754
+ * Pull the clearest human message + offending field + allowed-enum list out of ANY
755
+ * backend error body. Priority: the standard {detail}/{message}/{error} STRING
756
+ * shapes first, then DRF field-error objects / nested arrays / bare arrays.
757
+ * The returned `message` is sanitized at RENDER time (sanitizeErrorShape runs
758
+ * sanitizeText over message + allowed); `field` is a backend KEY name and is
759
+ * PRESERVED (never value-sanitized) so the remediation field stays intact.
760
+ * `message` is undefined when nothing usable was found (caller falls back to a status line).
761
+ */
762
+ function parseErrorBody(body) {
763
+ const isPlainObject = body && typeof body === "object" && !Array.isArray(body);
764
+ const allowed = isPlainObject && Array.isArray(body.allowed) ? body.allowed.map((a) => String(a)) : undefined;
765
+ // 1) Standard {detail}/{message}/{error} STRING shapes (highest priority).
766
+ if (isPlainObject) {
767
+ const standard = body.detail ?? body.message ?? body.error;
768
+ if (typeof standard === "string" && standard.trim()) {
769
+ const field = (typeof body.field === "string" && body.field) ||
770
+ /^(\w+) is required$/.exec(standard)?.[1] ||
771
+ undefined;
772
+ return { message: standard, field: safeFieldName(field), allowed };
773
+ }
774
+ }
775
+ // 2) DRF field-error object / nested / bare array.
776
+ const drf = extractDrfFieldError(body);
777
+ if (drf) {
778
+ const explicitField = isPlainObject && typeof body.field === "string" && body.field ? body.field : undefined;
779
+ return { message: drf.message, field: safeFieldName(explicitField) || drf.field, allowed };
780
+ }
781
+ return { allowed };
782
+ }
783
+ /**
784
+ * Mask a secret to a short preview that shows it exists without leaking the value.
785
+ */
786
+ function maskSecret(secret) {
787
+ if (secret === null || secret === undefined)
788
+ return null;
789
+ const s = String(secret);
790
+ if (s.length <= 8)
791
+ return "••••••••";
792
+ return `${s.slice(0, 4)}…${s.slice(-4)} (${s.length} chars, hidden)`;
793
+ }
794
+ /**
795
+ * Redact known secret-bearing fields on an application object. Replaces the raw
796
+ * value with a masked preview and adds *_set booleans. Returns a shallow copy.
797
+ */
798
+ function redactApplication(app) {
799
+ if (!app || typeof app !== "object")
800
+ return app;
801
+ const out = { ...app };
802
+ if ("api_key" in out) {
803
+ out.api_key_set = out.api_key !== null && out.api_key !== undefined && out.api_key !== "";
804
+ out.api_key_preview = maskSecret(out.api_key);
805
+ delete out.api_key;
806
+ }
807
+ if ("client_secret" in out) {
808
+ out.client_secret_set = !!out.client_secret;
809
+ out.client_secret_preview = maskSecret(out.client_secret);
810
+ delete out.client_secret;
811
+ }
812
+ if ("secret" in out) {
813
+ out.secret_set = !!out.secret;
814
+ out.secret_preview = maskSecret(out.secret);
815
+ delete out.secret;
816
+ }
817
+ return out;
818
+ }
819
+ /** Redact the signing secret on a webhook destination. */
820
+ function redactWebhookDestination(dest) {
821
+ if (!dest || typeof dest !== "object")
822
+ return dest;
823
+ const out = { ...dest };
824
+ for (const key of ["secret_shared_key", "signing_secret", "secret"]) {
825
+ if (key in out) {
826
+ out.secret_set = out[key] !== null && out[key] !== undefined && out[key] !== "";
827
+ delete out[key];
828
+ }
829
+ }
830
+ return out;
831
+ }
832
+ /** Redact api_key fields on an API-key object (list_api_keys). */
833
+ function redactApiKey(key) {
834
+ if (!key || typeof key !== "object")
835
+ return key;
836
+ const out = { ...key };
837
+ for (const field of ["api_key", "key", "secret", "token", "value"]) {
838
+ if (field in out) {
839
+ out[`${field}_set`] = out[field] !== null && out[field] !== undefined && out[field] !== "";
840
+ out[`${field}_preview`] = maskSecret(out[field]);
841
+ delete out[field];
842
+ }
843
+ }
844
+ return out;
845
+ }
846
+ /**
847
+ * Apply redaction across a list-envelope or a bare array/object of the given
848
+ * shape, using the provided per-item redactor.
849
+ */
850
+ function redactCollection(payload, redactor) {
851
+ if (Array.isArray(payload))
852
+ return payload.map(redactor);
853
+ if (payload && Array.isArray(payload.results)) {
854
+ return { ...payload, results: payload.results.map(redactor) };
855
+ }
856
+ return redactor(payload);
857
+ }
858
+ //# sourceMappingURL=security.js.map