@layervai/qurl-mcp 0.4.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/README.md +798 -50
  2. package/assets/fonts/NotoSansSC-Regular.ttf +0 -0
  3. package/assets/fonts/OFL.txt +93 -0
  4. package/assets/fonts/README.md +18 -0
  5. package/dist/auth/request-context.d.ts +13 -0
  6. package/dist/auth/request-context.d.ts.map +1 -0
  7. package/dist/auth/request-context.js +21 -0
  8. package/dist/auth/request-context.js.map +1 -0
  9. package/dist/auth/static-bearer.d.ts +12 -0
  10. package/dist/auth/static-bearer.d.ts.map +1 -0
  11. package/dist/auth/static-bearer.js +47 -0
  12. package/dist/auth/static-bearer.js.map +1 -0
  13. package/dist/client.d.ts +66 -11
  14. package/dist/client.d.ts.map +1 -1
  15. package/dist/client.js +116 -7
  16. package/dist/client.js.map +1 -1
  17. package/dist/config.d.ts +98 -0
  18. package/dist/config.d.ts.map +1 -0
  19. package/dist/config.js +543 -0
  20. package/dist/config.js.map +1 -0
  21. package/dist/credential-rate-limit-store.d.ts +38 -0
  22. package/dist/credential-rate-limit-store.d.ts.map +1 -0
  23. package/dist/credential-rate-limit-store.js +135 -0
  24. package/dist/credential-rate-limit-store.js.map +1 -0
  25. package/dist/email-addresses.d.ts +7 -0
  26. package/dist/email-addresses.d.ts.map +1 -0
  27. package/dist/email-addresses.js +36 -0
  28. package/dist/email-addresses.js.map +1 -0
  29. package/dist/email-types.d.ts +33 -0
  30. package/dist/email-types.d.ts.map +1 -0
  31. package/dist/email-types.js +28 -0
  32. package/dist/email-types.js.map +1 -0
  33. package/dist/emf-metrics.d.ts +25 -0
  34. package/dist/emf-metrics.d.ts.map +1 -0
  35. package/dist/emf-metrics.js +87 -0
  36. package/dist/emf-metrics.js.map +1 -0
  37. package/dist/http-config.d.ts +38 -0
  38. package/dist/http-config.d.ts.map +1 -0
  39. package/dist/http-config.js +243 -0
  40. package/dist/http-config.js.map +1 -0
  41. package/dist/http-routes.d.ts +5 -0
  42. package/dist/http-routes.d.ts.map +1 -0
  43. package/dist/http-routes.js +12 -0
  44. package/dist/http-routes.js.map +1 -0
  45. package/dist/http.d.ts +33 -0
  46. package/dist/http.d.ts.map +1 -0
  47. package/dist/http.js +1116 -0
  48. package/dist/http.js.map +1 -0
  49. package/dist/index.d.ts +1 -1
  50. package/dist/index.d.ts.map +1 -1
  51. package/dist/index.js +42 -26
  52. package/dist/index.js.map +1 -1
  53. package/dist/logging.d.ts +7 -0
  54. package/dist/logging.d.ts.map +1 -0
  55. package/dist/logging.js +110 -0
  56. package/dist/logging.js.map +1 -0
  57. package/dist/prompts/audit-links.js +1 -1
  58. package/dist/prompts/audit-links.js.map +1 -1
  59. package/dist/server.d.ts +14 -4
  60. package/dist/server.d.ts.map +1 -1
  61. package/dist/server.js +38 -8
  62. package/dist/server.js.map +1 -1
  63. package/dist/services/email.d.ts +17 -0
  64. package/dist/services/email.d.ts.map +1 -0
  65. package/dist/services/email.js +351 -0
  66. package/dist/services/email.js.map +1 -0
  67. package/dist/services/html.d.ts +5 -0
  68. package/dist/services/html.d.ts.map +1 -0
  69. package/dist/services/html.js +28 -0
  70. package/dist/services/html.js.map +1 -0
  71. package/dist/services/legal-pages.d.ts +12 -0
  72. package/dist/services/legal-pages.d.ts.map +1 -0
  73. package/dist/services/legal-pages.js +588 -0
  74. package/dist/services/legal-pages.js.map +1 -0
  75. package/dist/services/text-pdf.d.ts +16 -0
  76. package/dist/services/text-pdf.d.ts.map +1 -0
  77. package/dist/services/text-pdf.js +141 -0
  78. package/dist/services/text-pdf.js.map +1 -0
  79. package/dist/services/video-page.d.ts +4 -0
  80. package/dist/services/video-page.d.ts.map +1 -0
  81. package/dist/services/video-page.js +311 -0
  82. package/dist/services/video-page.js.map +1 -0
  83. package/dist/text.d.ts +4 -0
  84. package/dist/text.d.ts.map +1 -0
  85. package/dist/text.js +16 -0
  86. package/dist/text.js.map +1 -0
  87. package/dist/tools/_shared.d.ts +10 -1
  88. package/dist/tools/_shared.d.ts.map +1 -1
  89. package/dist/tools/_shared.js +25 -8
  90. package/dist/tools/_shared.js.map +1 -1
  91. package/dist/tools/batch-create.d.ts +12 -11
  92. package/dist/tools/batch-create.d.ts.map +1 -1
  93. package/dist/tools/batch-create.js +6 -4
  94. package/dist/tools/batch-create.js.map +1 -1
  95. package/dist/tools/consumer-access.d.ts +235 -0
  96. package/dist/tools/consumer-access.d.ts.map +1 -0
  97. package/dist/tools/consumer-access.js +231 -0
  98. package/dist/tools/consumer-access.js.map +1 -0
  99. package/dist/tools/create-qurl.d.ts +43 -4
  100. package/dist/tools/create-qurl.d.ts.map +1 -1
  101. package/dist/tools/create-qurl.js +69 -32
  102. package/dist/tools/create-qurl.js.map +1 -1
  103. package/dist/tools/delete-qurl.d.ts +3 -2
  104. package/dist/tools/delete-qurl.d.ts.map +1 -1
  105. package/dist/tools/delete-qurl.js +9 -13
  106. package/dist/tools/delete-qurl.js.map +1 -1
  107. package/dist/tools/duration.d.ts +13 -0
  108. package/dist/tools/duration.d.ts.map +1 -0
  109. package/dist/tools/duration.js +71 -0
  110. package/dist/tools/duration.js.map +1 -0
  111. package/dist/tools/email-delivery.d.ts +36 -0
  112. package/dist/tools/email-delivery.d.ts.map +1 -0
  113. package/dist/tools/email-delivery.js +114 -0
  114. package/dist/tools/email-delivery.js.map +1 -0
  115. package/dist/tools/extend-qurl.d.ts +20 -6
  116. package/dist/tools/extend-qurl.d.ts.map +1 -1
  117. package/dist/tools/extend-qurl.js +180 -19
  118. package/dist/tools/extend-qurl.js.map +1 -1
  119. package/dist/tools/get-qurl.d.ts +13 -5
  120. package/dist/tools/get-qurl.d.ts.map +1 -1
  121. package/dist/tools/get-qurl.js +5 -3
  122. package/dist/tools/get-qurl.js.map +1 -1
  123. package/dist/tools/list-qurl-sessions.d.ts +5 -4
  124. package/dist/tools/list-qurl-sessions.d.ts.map +1 -1
  125. package/dist/tools/list-qurl-sessions.js +2 -2
  126. package/dist/tools/list-qurl-sessions.js.map +1 -1
  127. package/dist/tools/list-qurls.d.ts +15 -7
  128. package/dist/tools/list-qurls.d.ts.map +1 -1
  129. package/dist/tools/list-qurls.js +9 -7
  130. package/dist/tools/list-qurls.js.map +1 -1
  131. package/dist/tools/mint-link.d.ts +39 -3
  132. package/dist/tools/mint-link.d.ts.map +1 -1
  133. package/dist/tools/mint-link.js +26 -14
  134. package/dist/tools/mint-link.js.map +1 -1
  135. package/dist/tools/output-schemas.d.ts +154 -45
  136. package/dist/tools/output-schemas.d.ts.map +1 -1
  137. package/dist/tools/output-schemas.js +106 -30
  138. package/dist/tools/output-schemas.js.map +1 -1
  139. package/dist/tools/resolve-qurl.d.ts +4 -3
  140. package/dist/tools/resolve-qurl.d.ts.map +1 -1
  141. package/dist/tools/resolve-qurl.js +3 -3
  142. package/dist/tools/resolve-qurl.js.map +1 -1
  143. package/dist/tools/revoke-qurl-token.d.ts +3 -2
  144. package/dist/tools/revoke-qurl-token.d.ts.map +1 -1
  145. package/dist/tools/revoke-qurl-token.js +2 -2
  146. package/dist/tools/revoke-qurl-token.js.map +1 -1
  147. package/dist/tools/share-by-crid.d.ts +50 -0
  148. package/dist/tools/share-by-crid.d.ts.map +1 -0
  149. package/dist/tools/share-by-crid.js +114 -0
  150. package/dist/tools/share-by-crid.js.map +1 -0
  151. package/dist/tools/terminate-qurl-sessions.d.ts +3 -2
  152. package/dist/tools/terminate-qurl-sessions.d.ts.map +1 -1
  153. package/dist/tools/terminate-qurl-sessions.js +7 -3
  154. package/dist/tools/terminate-qurl-sessions.js.map +1 -1
  155. package/dist/tools/update-qurl-token.d.ts +5 -4
  156. package/dist/tools/update-qurl-token.d.ts.map +1 -1
  157. package/dist/tools/update-qurl-token.js +8 -9
  158. package/dist/tools/update-qurl-token.js.map +1 -1
  159. package/dist/tools/update-qurl.d.ts +13 -5
  160. package/dist/tools/update-qurl.d.ts.map +1 -1
  161. package/dist/tools/update-qurl.js +10 -11
  162. package/dist/tools/update-qurl.js.map +1 -1
  163. package/dist/tools/upload-file-data-qurl.d.ts +138 -0
  164. package/dist/tools/upload-file-data-qurl.d.ts.map +1 -0
  165. package/dist/tools/upload-file-data-qurl.js +207 -0
  166. package/dist/tools/upload-file-data-qurl.js.map +1 -0
  167. package/dist/tools/upload-file-qurl.d.ts +134 -0
  168. package/dist/tools/upload-file-qurl.d.ts.map +1 -0
  169. package/dist/tools/upload-file-qurl.js +174 -0
  170. package/dist/tools/upload-file-qurl.js.map +1 -0
  171. package/dist/tools/upload-file-shared.d.ts +53 -0
  172. package/dist/tools/upload-file-shared.d.ts.map +1 -0
  173. package/dist/tools/upload-file-shared.js +617 -0
  174. package/dist/tools/upload-file-shared.js.map +1 -0
  175. package/dist/tools/upload-mint-options.d.ts +22 -0
  176. package/dist/tools/upload-mint-options.d.ts.map +1 -0
  177. package/dist/tools/upload-mint-options.js +47 -0
  178. package/dist/tools/upload-mint-options.js.map +1 -0
  179. package/dist/tools/upload-text-qurl.d.ts +112 -0
  180. package/dist/tools/upload-text-qurl.d.ts.map +1 -0
  181. package/dist/tools/upload-text-qurl.js +106 -0
  182. package/dist/tools/upload-text-qurl.js.map +1 -0
  183. package/package.json +26 -8
@@ -0,0 +1,617 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { basename, extname } from "node:path";
3
+ import { getRequestMaxUploadFileDataBytes, getRequestQurlApiKey, getRequestQurlConnectorUrl, markRequestCredentialValidated, } from "../auth/request-context.js";
4
+ import { MISSING_API_KEY_MESSAGE, QURLAPIError } from "../client.js";
5
+ import { isLoopbackHostname, loadRuntimeConfig, normalizeServiceBaseUrl } from "../config.js";
6
+ import { formatErrorForLog } from "../logging.js";
7
+ import { flattenControlCharacters, isControlCodePoint } from "../text.js";
8
+ import { RESOURCE_ID_PATTERN } from "./_shared.js";
9
+ import { MAX_EXPIRY_MS, MAX_SESSION_MS, MIN_EXPIRY_MS, MIN_SESSION_MS, parseDurationMs, } from "./duration.js";
10
+ import { DEFAULT_UPLOAD_EXPIRES_IN } from "./upload-mint-options.js";
11
+ export const supportedMimeTypes = [
12
+ "application/pdf",
13
+ "image/gif",
14
+ "image/jpeg",
15
+ "image/png",
16
+ "image/webp",
17
+ ];
18
+ const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
19
+ const PNG_IEND_CHUNK = Buffer.from([0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130]);
20
+ const PDF_EOF_MARKER = Buffer.from("%%EOF", "ascii");
21
+ export const mimeTypeByExtension = new Map([
22
+ [".gif", "image/gif"],
23
+ [".jpeg", "image/jpeg"],
24
+ [".jpg", "image/jpeg"],
25
+ [".pdf", "application/pdf"],
26
+ [".png", "image/png"],
27
+ [".webp", "image/webp"],
28
+ ]);
29
+ export function getConnectorConfig(allowServerApiKeyFallback = false) {
30
+ let runtimeConfig;
31
+ const getRuntimeConfig = () => (runtimeConfig ??= loadRuntimeConfig());
32
+ const serverApiKey = allowServerApiKeyFallback
33
+ ? (process.env.QURL_API_KEY?.trim() ?? getRuntimeConfig().qurlApiKey)
34
+ : undefined;
35
+ const apiKey = getRequestQurlApiKey() ?? serverApiKey ?? "";
36
+ if (!apiKey) {
37
+ throw new QURLAPIError(0, "missing_api_key", MISSING_API_KEY_MESSAGE);
38
+ }
39
+ const connectorURL = getRequestQurlConnectorUrl() ??
40
+ process.env.QURL_CONNECTOR_URL?.trim() ??
41
+ getRuntimeConfig().defaultQurlConnectorUrl ??
42
+ "";
43
+ if (!connectorURL) {
44
+ throw new QURLAPIError(0, "missing_connector_url", "QURL_CONNECTOR_URL is not set. Set it in the MCP server environment or runtime config to enable file uploads.");
45
+ }
46
+ // Validate operator configuration during preflight, before callers decode
47
+ // or read a potentially large upload payload. getConnectorUploadUrl already
48
+ // guarantees the /api/upload suffix the mint route derives from.
49
+ const uploadUrl = getConnectorUploadUrl(connectorURL);
50
+ return { apiKey, uploadUrl };
51
+ }
52
+ export function getConnectorUploadUrl(connectorURL) {
53
+ let connectorBaseUrl;
54
+ try {
55
+ connectorBaseUrl = new URL(normalizeServiceBaseUrl(connectorURL, "QURL_CONNECTOR_URL", true));
56
+ }
57
+ catch (error) {
58
+ throw new QURLAPIError(0, "invalid_connector_url", error instanceof Error ? error.message : "QURL_CONNECTOR_URL must be a valid absolute URL.");
59
+ }
60
+ const basePath = connectorBaseUrl.pathname.replace(/\/$/, "");
61
+ const containsAmbiguousUploadRoute = /(?:^|\/)(?:api\/)?upload(?:\/|$)/.test(basePath) && !basePath.endsWith("/api/upload");
62
+ if (containsAmbiguousUploadRoute) {
63
+ throw new QURLAPIError(0, "invalid_connector_url", "QURL_CONNECTOR_URL must be a connector service base URL or end exactly with /api/upload.");
64
+ }
65
+ connectorBaseUrl.pathname = basePath.endsWith("/api/upload")
66
+ ? basePath
67
+ : `${basePath}/api/upload`;
68
+ return connectorBaseUrl.toString();
69
+ }
70
+ export function normalizeFileName(input) {
71
+ const name = basename(input.replaceAll("\\", "/")).trim();
72
+ if (!name || name === "." || name === "..") {
73
+ throw new Error("file_name must not be empty");
74
+ }
75
+ const hasControlCharacter = [...name].some((character) => {
76
+ const codePoint = character.codePointAt(0) ?? 0;
77
+ return isControlCodePoint(codePoint);
78
+ });
79
+ if (Buffer.byteLength(name, "utf8") > 255 || hasControlCharacter) {
80
+ throw new Error("file_name must be at most 255 UTF-8 bytes and contain no control characters");
81
+ }
82
+ return name;
83
+ }
84
+ export function inferContentType(filePath) {
85
+ return mimeTypeByExtension.get(extname(filePath).toLowerCase());
86
+ }
87
+ export function getMaxUploadFileBytes() {
88
+ const requestScoped = getRequestMaxUploadFileDataBytes();
89
+ if (requestScoped !== undefined)
90
+ return requestScoped;
91
+ return loadRuntimeConfig().maxUploadFileDataBytes;
92
+ }
93
+ export function validateFileNameContentType(fileName, contentType) {
94
+ const inferred = inferContentType(fileName);
95
+ if (!inferred) {
96
+ throw new Error("file_name must include a basename and supported PDF or raster image extension (for example, image.png); content_type does not replace the required filename extension.");
97
+ }
98
+ if (inferred !== contentType) {
99
+ throw new Error(`content_type ${contentType} does not match the filename extension.`);
100
+ }
101
+ }
102
+ export function validateFileSignature(fileData, contentType) {
103
+ const bytes = fileData.buffer instanceof ArrayBuffer
104
+ ? Buffer.from(fileData.buffer, fileData.byteOffset, fileData.byteLength)
105
+ : Buffer.from(fileData);
106
+ // latin1 preserves byte values exactly; Node's ascii decoder masks the high
107
+ // bit and would let non-ASCII bytes impersonate an ASCII magic header.
108
+ // These are bounded type-confusion guards rather than full decoders. Start
109
+ // and end framing rejects bytes appended after a terminal marker, but JPEG
110
+ // and GIF internals and PNG chunk integrity are not parsed; downstream
111
+ // connector validation and nosniff delivery remain the authoritative content
112
+ // boundary.
113
+ const ascii = (start, end) => bytes.subarray(start, end).toString("latin1");
114
+ const hasPdfTrailer = () => {
115
+ const pdfEofIndex = bytes.lastIndexOf(PDF_EOF_MARKER);
116
+ return (pdfEofIndex >= 0 &&
117
+ bytes
118
+ .subarray(pdfEofIndex + PDF_EOF_MARKER.length)
119
+ .every((byte) => byte === 9 || byte === 10 || byte === 12 || byte === 13 || byte === 32));
120
+ };
121
+ const valid = (contentType === "application/pdf" && ascii(0, 5) === "%PDF-" && hasPdfTrailer()) ||
122
+ (contentType === "image/png" &&
123
+ bytes.length >= PNG_SIGNATURE.length + PNG_IEND_CHUNK.length &&
124
+ bytes.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE) &&
125
+ bytes.subarray(-PNG_IEND_CHUNK.length).equals(PNG_IEND_CHUNK)) ||
126
+ (contentType === "image/jpeg" &&
127
+ bytes.length >= 6 &&
128
+ bytes[0] === 0xff &&
129
+ bytes[1] === 0xd8 &&
130
+ bytes[2] === 0xff &&
131
+ bytes[bytes.length - 2] === 0xff &&
132
+ bytes[bytes.length - 1] === 0xd9) ||
133
+ (contentType === "image/gif" &&
134
+ ["GIF87a", "GIF89a"].includes(ascii(0, 6)) &&
135
+ bytes[bytes.length - 1] === 0x3b) ||
136
+ (contentType === "image/webp" &&
137
+ bytes.length >= 16 &&
138
+ ascii(0, 4) === "RIFF" &&
139
+ // WebP requires RIFF size + 8 to equal the complete file size. Reject
140
+ // trailing bytes deliberately so a valid prefix cannot bless a polyglot.
141
+ bytes.readUInt32LE(4) + 8 === bytes.length &&
142
+ ascii(8, 12) === "WEBP" &&
143
+ ["VP8 ", "VP8L", "VP8X"].includes(ascii(12, 16)));
144
+ if (!valid) {
145
+ throw new Error(`File content does not match declared content_type ${contentType}.`);
146
+ }
147
+ }
148
+ /**
149
+ * Parse JSON response body safely, returning undefined on parse failure.
150
+ */
151
+ function parseJsonBody(raw) {
152
+ try {
153
+ return raw ? JSON.parse(raw) : undefined;
154
+ }
155
+ catch {
156
+ return undefined;
157
+ }
158
+ }
159
+ function extractConnectorError(parsed, defaultCode) {
160
+ const body = typeof parsed === "object" && parsed !== null ? parsed : {};
161
+ const nestedError = typeof body.error === "object" && body.error !== null
162
+ ? body.error
163
+ : {};
164
+ const stringField = (record, field) => {
165
+ const value = record[field];
166
+ return typeof value === "string" ? value : undefined;
167
+ };
168
+ return {
169
+ code: stringField(nestedError, "code") ?? stringField(body, "code") ?? defaultCode,
170
+ detail: stringField(nestedError, "detail") ??
171
+ stringField(nestedError, "message") ??
172
+ stringField(body, "detail") ??
173
+ stringField(body, "message") ??
174
+ // The connector's gin handlers answer {"error": "<text>"}. On the upload
175
+ // path this bounded, flattened text reaches the caller on purpose (the
176
+ // operator-run connector's reason, e.g. a size limit); the mint path keeps
177
+ // it in the operator log because its caller message is rebuilt.
178
+ stringField(body, "error"),
179
+ type: stringField(nestedError, "type"),
180
+ instance: stringField(nestedError, "instance"),
181
+ };
182
+ }
183
+ /**
184
+ * Throw a QURLAPIError from a failed connector response.
185
+ */
186
+ function throwConnectorError(response, parsed, requestId, defaultCode = "connector_upload_failed") {
187
+ const { code, detail, type, instance } = extractConnectorError(parsed, defaultCode);
188
+ const safeDetail = detail ? sanitizeConnectorDetail(detail) : undefined;
189
+ throw new QURLAPIError(response.status,
190
+ // Namespaced so a connector cannot pose as a local condition (e.g. its own
191
+ // "missing_api_key" being rendered as this server's missing-key guidance).
192
+ code.startsWith("connector_") ? code : `connector_${code}`,
193
+ // Quoted and attributed: this text is third-party data in the caller's context.
194
+ safeDetail
195
+ ? `Connector reported (HTTP ${response.status}): "${safeDetail}"`
196
+ : `Connector request failed with HTTP ${response.status}`, type, instance, requestId);
197
+ }
198
+ /**
199
+ * Extract the raw resource_id field from a connector success response.
200
+ * Handles both `{ resource_id }` and `{ data: { resource_id } }` shapes.
201
+ */
202
+ function extractResourceId(parsed) {
203
+ if (typeof parsed !== "object" || parsed === null) {
204
+ return undefined;
205
+ }
206
+ // Direct shape: { resource_id: string }
207
+ if ("resource_id" in parsed) {
208
+ return parsed.resource_id;
209
+ }
210
+ // Wrapped shape: { data: { resource_id: string } }
211
+ if ("data" in parsed &&
212
+ typeof parsed.data === "object" &&
213
+ parsed.data !== null &&
214
+ "resource_id" in parsed.data) {
215
+ return parsed.data.resource_id;
216
+ }
217
+ return undefined;
218
+ }
219
+ async function readConnectorResponseBody(response) {
220
+ if (!response.body)
221
+ return "";
222
+ const reader = response.body.getReader();
223
+ const chunks = [];
224
+ let totalBytes = 0;
225
+ while (true) {
226
+ const { done, value } = await reader.read();
227
+ if (done)
228
+ break;
229
+ totalBytes += value.byteLength;
230
+ if (totalBytes > 64 * 1024) {
231
+ await reader.cancel();
232
+ // Keep an error status (e.g. a proxy's HTML 502) so it is still reported.
233
+ throw new QURLAPIError(response.ok ? 0 : response.status, "connector_response_too_large", "Connector response exceeded the 64 KiB limit.");
234
+ }
235
+ chunks.push(Buffer.from(value));
236
+ }
237
+ return Buffer.concat(chunks).toString("utf8");
238
+ }
239
+ /**
240
+ * Process connector response and extract resource_id.
241
+ * Throws QURLAPIError on failure or missing resource_id.
242
+ */
243
+ async function processConnectorResponse(response) {
244
+ const requestId = response.headers.get("x-request-id") ?? undefined;
245
+ const raw = await readConnectorResponseBody(response);
246
+ const contentType = response.headers.get("content-type")?.toLowerCase();
247
+ if (response.ok && contentType && !contentType.includes("json")) {
248
+ throw new QURLAPIError(0, "unexpected_response", "Connector upload succeeded with a non-JSON response.", undefined, undefined, requestId);
249
+ }
250
+ const parsed = parseJsonBody(raw);
251
+ if (!response.ok) {
252
+ throwConnectorError(response, parsed, requestId);
253
+ }
254
+ const resourceId = extractResourceId(parsed);
255
+ if (resourceId === undefined) {
256
+ throw new QURLAPIError(0, "unexpected_response", "Connector upload succeeded but did not return a resource_id.", undefined, undefined, requestId);
257
+ }
258
+ if (typeof resourceId !== "string" || !RESOURCE_ID_PATTERN.test(resourceId)) {
259
+ throw new QURLAPIError(0, "invalid_resource_id", "Connector upload returned a resource_id with an invalid format.", undefined, undefined, requestId);
260
+ }
261
+ return { resource_id: resourceId };
262
+ }
263
+ // getConnectorUploadUrl guarantees the /api/upload suffix; the mint route is
264
+ // its sibling. Fail loudly rather than POST a mint body at the upload route.
265
+ function assertConnectorMintable(uploadUrl) {
266
+ if (!new URL(uploadUrl).pathname.endsWith("/api/upload")) {
267
+ throw new QURLAPIError(0, "invalid_connector_url", "Connector upload URL must end with /api/upload.");
268
+ }
269
+ }
270
+ function connectorMintUrl(uploadUrl, resourceId) {
271
+ assertConnectorMintable(uploadUrl);
272
+ const url = new URL(uploadUrl);
273
+ url.pathname = `${url.pathname.slice(0, -"/api/upload".length)}/api/mint_link/${encodeURIComponent(resourceId)}`;
274
+ return url.toString();
275
+ }
276
+ const MAX_LINK_LENGTH = 8192;
277
+ // Why a minted link cannot be returned, or undefined when it can. The link
278
+ // carries an access token and may be emailed, so never plain HTTP, except from
279
+ // a loopback development connector: the same exception the connector URL
280
+ // itself gets in normalizeServiceBaseUrl. The host is deliberately not pinned:
281
+ // connector-minted links are served from the qURL link domain, not the
282
+ // connector's own host, and the operator-configured connector is already
283
+ // trusted with the file and the bearer.
284
+ function linkProblem(entry, connectorIsLoopback) {
285
+ const value = entry.qurl_link;
286
+ if (typeof value !== "string")
287
+ return "no usable link";
288
+ if (value.length > MAX_LINK_LENGTH)
289
+ return "an oversized link";
290
+ // The URL parser silently strips tab/CR/LF, so control characters are
291
+ // refused here rather than returned inside a link that parsed cleanly.
292
+ // eslint-disable-next-line no-control-regex
293
+ if (/[\u0000-\u001f\u007f]/.test(value))
294
+ return "a link with control characters";
295
+ let url;
296
+ try {
297
+ url = new URL(value);
298
+ }
299
+ catch {
300
+ return "an unparsable link";
301
+ }
302
+ const deliverable = url.protocol === "https:" ||
303
+ (url.protocol === "http:" && connectorIsLoopback && isLoopbackHostname(url.hostname));
304
+ if (!deliverable) {
305
+ return url.protocol === "http:" ? "a non-HTTPS link" : "a non-HTTP(S) link";
306
+ }
307
+ // An expiry already past by this host's clock is not refused: if this clock
308
+ // runs ahead, the link is still good, and refusing would discard the only
309
+ // handle to a file that cannot be deleted. It is returned with a flag.
310
+ return undefined;
311
+ }
312
+ // Every link in a mint response is live and cannot be revoked from this server,
313
+ // so operator logs name all of them (bounded and flattened; the IDs are untrusted).
314
+ // Operator-log only (never the caller), so the cap is generous: these links
315
+ // are live and unrevocable here, and the log is where cleanup starts.
316
+ const LOGGED_LINK_LIMIT = 100;
317
+ function sanitizeConnectorDetail(detail) {
318
+ // Slice first: flattening the whole (up to 64 KiB) body only to keep 1 KiB is waste.
319
+ return flattenControlCharacters(detail.slice(0, 4096)).replace(/\s+/g, " ").trim().slice(0, 1024);
320
+ }
321
+ function describeLinks(links) {
322
+ if (!Array.isArray(links) || links.length === 0)
323
+ return "none";
324
+ const shown = links
325
+ .slice(0, LOGGED_LINK_LIMIT)
326
+ .map((entry) => {
327
+ const id = entry?.qurl_id;
328
+ return typeof id === "string"
329
+ ? flattenControlCharacters(id.slice(0, 256)).slice(0, 64)
330
+ : "(no qurl_id)";
331
+ })
332
+ .join(", ");
333
+ return links.length > LOGGED_LINK_LIMIT
334
+ ? `${shown} (+${links.length - LOGGED_LINK_LIMIT} more)`
335
+ : shown;
336
+ }
337
+ function reportedLinkIds(links) {
338
+ return (Array.isArray(links) ? links : [])
339
+ .map((entry) => entry?.qurl_id)
340
+ .filter((id) => typeof id === "string" && id.length > 0)
341
+ .map((id) => flattenControlCharacters(id.slice(0, 256)).slice(0, 64));
342
+ }
343
+ /** The single link the connector minted, or why its response is unusable. */
344
+ function isPastExpiry(expiresAt) {
345
+ return typeof expiresAt === "string" && Date.parse(expiresAt) <= Date.now();
346
+ }
347
+ // Clock skew can make a live link look expired. Count every link-shaped entry.
348
+ function isPossiblyLiveLink(entry) {
349
+ const link = entry;
350
+ const parsable = (value) => typeof value === "string" && value.length <= MAX_LINK_LENGTH && URL.canParse(value);
351
+ // Real evidence of a minted token: a non-empty ID, or a link that parses.
352
+ const hasId = typeof link?.qurl_id === "string" && link.qurl_id.length > 0;
353
+ return hasId || parsable(link?.qurl_link);
354
+ }
355
+ function mintedLinkFrom(parsed, connectorUploadUrl) {
356
+ const links = parsed?.links;
357
+ const entries = (Array.isArray(links) ? links : []).map((entry) => (typeof entry === "object" && entry !== null ? entry : {}));
358
+ // Use the first deliverable link rather than strictly index 0: a malformed
359
+ // first entry must not discard a good one, since the file cannot be re-linked.
360
+ // The qurl_id is informational here (it may belong to the connector's
361
+ // resource), so an unexpected or missing ID does not make a working link unusable.
362
+ const connectorIsLoopback = isLoopbackHostname(new URL(connectorUploadUrl).hostname);
363
+ const reasonFor = (entry) => linkProblem(entry, connectorIsLoopback);
364
+ const problems = entries.map(reasonFor);
365
+ // Prefer a deliverable link that is not already past; fall back to any.
366
+ const firstDeliverable = problems.indexOf(undefined);
367
+ const unexpired = entries.findIndex((entry, i) => problems[i] === undefined && !isPastExpiry(entry.expires_at));
368
+ const index = unexpired === -1 ? firstDeliverable : unexpired;
369
+ if (index === -1) {
370
+ const reasons = [...new Set(problems)].join(", ");
371
+ const reason = reasons || "no usable link";
372
+ return {
373
+ problem: `Connector mint returned ${reason} (links: ${describeLinks(links)}).`,
374
+ };
375
+ }
376
+ const chosen = entries[index];
377
+ // Count all possibly live extras; the local clock cannot prove expiry.
378
+ const others = entries.filter((entry, other) => other !== index && isPossiblyLiveLink(entry));
379
+ return {
380
+ link: {
381
+ // Untrusted: bounded and flattened before it reaches the caller or email.
382
+ ...(typeof chosen.qurl_id === "string" && chosen.qurl_id
383
+ ? { qurl_id: flattenControlCharacters(chosen.qurl_id).slice(0, 64) }
384
+ : {}),
385
+ qurl_link: chosen.qurl_link,
386
+ expires_at: chosen.expires_at,
387
+ },
388
+ others,
389
+ extraCount: others.length,
390
+ extraQurlIds: reportedLinkIds(others).slice(0, 10),
391
+ };
392
+ }
393
+ /**
394
+ * Contract: qurl-s3-connector internal/handler/handler.go MintLink (route in
395
+ * main.go's uploader mode) takes { n, one_time_use, expires_at, session_duration }
396
+ * and passes one_time_use and session_duration to qurl-service's mint in both
397
+ * legacy and render-at-mint modes. Drift is tracked with #282.
398
+ *
399
+ * Mint the recipient link through the connector's `/api/mint_link`, the only
400
+ * link the connector serves for an upload. The upload resource's own target is
401
+ * not a viewable page in the connector's tunnel mode (its per-upload qURL is
402
+ * never shared there), so minting on it with qurl-service yields a link that
403
+ * opens to a 404.
404
+ */
405
+ export async function mintUploadedFile(connectorConfig, resourceId, file, input) {
406
+ let requestedExpiresAt;
407
+ let requestSent = false;
408
+ let minted;
409
+ let extraCount = 0;
410
+ let liveQurlIds = [];
411
+ let liveLinkCount = 0;
412
+ let extraQurlIds = [];
413
+ try {
414
+ // Upload links cannot be revoked from here (#281), so never leave the
415
+ // lifetime to the connector's default: 24h, as create_qurl's API default.
416
+ const expiresIn = input.expires_in || DEFAULT_UPLOAD_EXPIRES_IN;
417
+ const expiresInMs = parseDurationMs(expiresIn);
418
+ if (expiresInMs === undefined || expiresInMs < MIN_EXPIRY_MS || expiresInMs > MAX_EXPIRY_MS) {
419
+ throw new QURLAPIError(0, "invalid_expires_in", `Unsupported duration: ${expiresIn}`);
420
+ }
421
+ // The connector requires whole seconds in Go duration syntax (no d/w units).
422
+ // Check direct callers too, then normalize accepted day/week input below.
423
+ const sessionMs = input.session_duration ? parseDurationMs(input.session_duration) : undefined;
424
+ if (input.session_duration &&
425
+ (sessionMs === undefined ||
426
+ sessionMs < MIN_SESSION_MS ||
427
+ sessionMs > MAX_SESSION_MS ||
428
+ sessionMs % 1000 !== 0)) {
429
+ throw new QURLAPIError(0, "invalid_session_duration", `Unsupported duration: ${input.session_duration}`);
430
+ }
431
+ // The connector's mint contract takes an absolute expires_at, so the
432
+ // relative expires_in is anchored to this host's clock.
433
+ requestedExpiresAt = new Date(Date.now() + expiresInMs).toISOString();
434
+ const body = {
435
+ n: 1,
436
+ one_time_use: input.one_time_use ?? true,
437
+ expires_at: requestedExpiresAt,
438
+ ...(sessionMs !== undefined ? { session_duration: `${sessionMs / 1000}s` } : {}),
439
+ };
440
+ const mintUrl = connectorMintUrl(connectorConfig.uploadUrl, resourceId);
441
+ requestSent = true;
442
+ const response = await fetchConnector(mintUrl, {
443
+ method: "POST",
444
+ headers: {
445
+ Authorization: `Bearer ${connectorConfig.apiKey}`,
446
+ Accept: "application/json",
447
+ "Content-Type": "application/json",
448
+ },
449
+ body: JSON.stringify(body),
450
+ });
451
+ const requestId = response.headers.get("x-request-id") ?? undefined;
452
+ const raw = await readConnectorResponseBody(response);
453
+ const contentType = response.headers.get("content-type")?.toLowerCase();
454
+ const unexpected = (message) => new QURLAPIError(0, "unexpected_response", message, undefined, undefined, requestId);
455
+ // Same predicate as processConnectorResponse: a missing Content-Type is tolerated.
456
+ if (response.ok && contentType && !contentType.includes("json")) {
457
+ throw unexpected("Connector mint returned a non-JSON response.");
458
+ }
459
+ const parsed = parseJsonBody(raw);
460
+ // Any link in a failed response is live and unrevocable here; report it.
461
+ const responseLinks = parsed?.links;
462
+ // Counted apart from IDs (a live link may come back without a qurl_id),
463
+ // and both over live entries only, so the IDs never outnumber the count.
464
+ const liveEntries = (Array.isArray(responseLinks) ? responseLinks : []).filter(isPossiblyLiveLink);
465
+ liveQurlIds = reportedLinkIds(liveEntries).slice(0, 10);
466
+ liveLinkCount = liveEntries.length;
467
+ if (!response.ok)
468
+ throwConnectorError(response, parsed, requestId, "connector_mint_failed");
469
+ if (parsed?.success === false) {
470
+ const { detail } = extractConnectorError(parsed, "connector_mint_failed");
471
+ const reason = detail ? `: ${sanitizeConnectorDetail(detail)}` : "";
472
+ throw unexpected(`Connector mint reported failure${reason}.`);
473
+ }
474
+ const result = mintedLinkFrom(parsed, connectorConfig.uploadUrl);
475
+ if ("problem" in result)
476
+ throw unexpected(result.problem);
477
+ // A deliverable mint means qurl-service accepted the forwarded bearer via
478
+ // the operator-configured connector: the same evidence, under the same
479
+ // trust assumption, as a successful direct API call (see QURLClient.call).
480
+ // The connector checks a non-empty caller bearer against qurl-service
481
+ // before minting (ConfirmResourceAccess in tunnel mode, the caller's own
482
+ // mint in legacy mode). The upload alone does not promote: it is the mint
483
+ // that provably reaches qURL.
484
+ markRequestCredentialValidated();
485
+ if (result.extraCount > 0) {
486
+ // n: 1 was requested; extra links are live, so report them, not just log.
487
+ console.error(`Connector returned ${result.extraCount} additional possibly live links for ${resourceId}; returning one ` +
488
+ `(links: ${describeLinks([result.link, ...result.others])})`);
489
+ }
490
+ minted = result.link;
491
+ extraCount = result.extraCount;
492
+ extraQurlIds = result.extraQurlIds;
493
+ }
494
+ catch (error) {
495
+ if (error?.neverConnected)
496
+ requestSent = false;
497
+ // The connector API exposes upload but no delete endpoint. Keep the mint
498
+ // error primary and log the orphan resource for operator cleanup.
499
+ console.error(`Connector resource ${resourceId} remains after link minting failed ` +
500
+ `(requested expires_at=${requestedExpiresAt ?? "connector default"}; ${formatErrorForLog(error)})`);
501
+ throw new QURLAPIError(error instanceof QURLAPIError ? error.statusCode : 0, "upload_mint_failed", `Upload succeeded but link creation failed` +
502
+ (error instanceof QURLAPIError && error.statusCode > 0
503
+ ? ` (connector responded HTTP ${error.statusCode})`
504
+ : "") +
505
+ `. Resource ID: ${resourceId}. ` +
506
+ "The stored file remains on the connector and cannot be deleted or re-linked from this tool; " +
507
+ "do not retry automatically, since each retry stores another copy; tell the user and ask." +
508
+ (liveLinkCount > 0
509
+ ? ` The connector reported ${liveLinkCount} possibly live link(s) this server refused to return` +
510
+ (liveQurlIds.length > 0
511
+ ? `: ${liveQurlIds.join(", ")}` +
512
+ (liveLinkCount > liveQurlIds.length ? " (IDs listed may be incomplete)" : "")
513
+ : " (the connector reported no IDs for them)") +
514
+ "; tell the user."
515
+ : requestSent
516
+ ? " If the request failed after reaching the connector, a link may already have been minted; check the connector before sharing a replacement."
517
+ : ""));
518
+ }
519
+ // Normalized so the reported (and emailed) expiry is always ISO 8601 or absent.
520
+ const confirmedExpiresAt = typeof minted.expires_at === "string" && !Number.isNaN(Date.parse(minted.expires_at))
521
+ ? new Date(minted.expires_at).toISOString()
522
+ : undefined;
523
+ // Small fixed tolerance for the connector's whole-second rounding and the
524
+ // round trip; any real clamp, even of a 1m link, is flagged.
525
+ const driftMs = confirmedExpiresAt
526
+ ? Date.parse(confirmedExpiresAt) - Date.parse(requestedExpiresAt)
527
+ : 0;
528
+ const driftsFromRequest = Math.abs(driftMs) > 5_000;
529
+ // The dangerous direction for a link that cannot be revoked here: it lives longer.
530
+ const outlivesRequest = driftMs > 5_000;
531
+ if (driftsFromRequest) {
532
+ // A clamp or host clock skew changed the link's lifetime; make it visible.
533
+ console.error(`Connector link ${minted.qurl_id ?? "(no qurl_id)"} expires at ${confirmedExpiresAt}, not the requested ${requestedExpiresAt}`);
534
+ }
535
+ return {
536
+ resource_id: resourceId,
537
+ ...(minted.qurl_id ? { qurl_id: minted.qurl_id } : {}),
538
+ qurl_link: minted.qurl_link,
539
+ // Only a connector-confirmed expiry is reported as expires_at; the request
540
+ // may have been clamped, and expires_at reaches recipients in email.
541
+ ...(confirmedExpiresAt ? { expires_at: confirmedExpiresAt } : {}),
542
+ requested_expires_at: requestedExpiresAt,
543
+ ...(driftsFromRequest ? { expires_at_differs_from_request: true } : {}),
544
+ ...(outlivesRequest ? { expires_at_later_than_requested: true } : {}),
545
+ ...(isPastExpiry(confirmedExpiresAt) ? { expires_at_already_past: true } : {}),
546
+ ...(!confirmedExpiresAt ? { expires_at_unconfirmed: true } : {}),
547
+ ...(extraCount > 0
548
+ ? {
549
+ unexpected_extra_link_count: extraCount,
550
+ ...(extraQurlIds.length > 0 ? { unexpected_extra_qurl_ids: extraQurlIds } : {}),
551
+ }
552
+ : {}),
553
+ file_name: file.name,
554
+ content_type: file.contentType,
555
+ size_bytes: file.sizeBytes,
556
+ };
557
+ }
558
+ // Failures that prove no request reached the connector (the name or the
559
+ // connection never resolved), unlike a reset or timeout, which is ambiguous.
560
+ const NEVER_CONNECTED_CODES = new Set(["ENOTFOUND", "EAI_AGAIN", "ECONNREFUSED"]);
561
+ function connectorTransportError(error) {
562
+ const code = error instanceof Error && ["AbortError", "TimeoutError"].includes(error.name)
563
+ ? "connector_timeout"
564
+ : "connector_unreachable";
565
+ const causeCode = (error?.cause?.code ?? "");
566
+ return Object.assign(new QURLAPIError(0, code, code === "connector_timeout" ? "Connector request timed out." : "Connector request failed."), { neverConnected: NEVER_CONNECTED_CODES.has(causeCode) });
567
+ }
568
+ async function fetchConnector(uploadUrl, init) {
569
+ try {
570
+ return await fetch(uploadUrl, {
571
+ ...init,
572
+ redirect: "error",
573
+ signal: globalThis.AbortSignal.timeout(60_000),
574
+ });
575
+ }
576
+ catch (error) {
577
+ throw connectorTransportError(error);
578
+ }
579
+ }
580
+ export async function uploadToConnector(fileData, fileName, contentType, connectorConfig) {
581
+ // Security boundary: uploadUrl comes only from operator configuration.
582
+ // Never accept a per-request connector destination here; doing so would
583
+ // turn the caller's forwarded qURL credential into an SSRF disclosure.
584
+ const { apiKey, uploadUrl } = connectorConfig;
585
+ const form = new globalThis.FormData();
586
+ // BlobPart's DOM type excludes SharedArrayBuffer-backed views. Reuse the
587
+ // normal ArrayBuffer view without copying; only copy the theoretical shared
588
+ // buffer case into an ordinary Uint8Array.
589
+ const blobData = fileData.buffer instanceof ArrayBuffer
590
+ ? new Uint8Array(fileData.buffer, fileData.byteOffset, fileData.byteLength)
591
+ : new Uint8Array(fileData);
592
+ form.append("file",
593
+ // lgtm[js/file-access-to-http] This tool explicitly uploads caller-provided bytes to the operator-configured connector.
594
+ new globalThis.Blob([blobData], { type: contentType }), fileName);
595
+ // The standards-based FormData serializer owns Content-Disposition filename
596
+ // quoting/escaping; never interpolate this value into a raw header.
597
+ // lgtm[js/file-access-to-http] The validated destination and upload are the explicit behavior of this MCP tool.
598
+ const response = await fetchConnector(uploadUrl, {
599
+ method: "POST",
600
+ headers: {
601
+ Authorization: `Bearer ${apiKey}`,
602
+ Accept: "application/json",
603
+ },
604
+ body: form, // lgtm[js/file-access-to-http]
605
+ });
606
+ // fetchConnector's signal remains attached while this reads the response
607
+ // body, so a connector that stalls after sending headers is still bounded.
608
+ try {
609
+ return await processConnectorResponse(response);
610
+ }
611
+ catch (error) {
612
+ if (error instanceof QURLAPIError)
613
+ throw error;
614
+ throw connectorTransportError(error);
615
+ }
616
+ }
617
+ //# sourceMappingURL=upload-file-shared.js.map