@maskera/mcp 0.5.0 → 0.5.1

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.
package/dist/cli.js CHANGED
@@ -154,6 +154,9 @@ function unzipSafely(bytes) {
154
154
  let totalUncompressed = 0;
155
155
  const files = unzipSync(bytes, {
156
156
  filter(file) {
157
+ if (file.name.includes("\0") || file.name.startsWith("/") || file.name.startsWith("\\") || file.name.split(/[\\/]/).includes("..")) {
158
+ throw new Error(`Archive contains unsafe entry path: ${file.name}`);
159
+ }
157
160
  entryCount += 1;
158
161
  if (entryCount > MAX_ZIP_ENTRIES) {
159
162
  throw new Error(`Archive exceeds max allowed entry count (${MAX_ZIP_ENTRIES}).`);
@@ -222,62 +225,64 @@ function escapeRegexLiteral(value) {
222
225
  }
223
226
  function extractXmlTextContainers(xml, containerTag, textTags, options) {
224
227
  const escapedContainer = escapeRegexLiteral(containerTag);
225
- const containerRe = new RegExp(
226
- `<${escapedContainer}(?:\\s[^>]*)?>([\\s\\S]*?)<\\/${escapedContainer}>`,
227
- "g"
228
- );
229
228
  const sepTags = options?.separatorTags ?? {};
230
229
  const sepTagNames = Object.keys(sepTags);
231
- const allTagAlternation = [...textTags, ...sepTagNames].map(escapeRegexLiteral).join("|");
232
- const tokenRe = new RegExp(
233
- `<(${allTagAlternation})(?:\\s[^>]*)?\\/>|<(${textTags.map(escapeRegexLiteral).join("|")})(\\s[^>]*)?>([\\s\\S]*?)<\\/\\2>`,
230
+ const allSelfClosing = [...textTags, ...sepTagNames].map(escapeRegexLiteral).join("|");
231
+ const textAlt = textTags.map(escapeRegexLiteral).join("|");
232
+ const scanRe = new RegExp(
233
+ [
234
+ `<(${escapedContainer})(?:\\s[^>]*)?>`,
235
+ `<\\/(${escapedContainer})>`,
236
+ `<(${allSelfClosing})(?:\\s[^>]*)?\\/>`,
237
+ `<(${textAlt})(\\s[^>]*)?>([\\s\\S]*?)<\\/\\4>`
238
+ ].join("|"),
234
239
  "g"
235
240
  );
236
241
  const containers = [];
237
- let containerMatch = containerRe.exec(xml);
238
- while (containerMatch !== null) {
239
- const inner = containerMatch[1] ?? "";
240
- const openEndOffset = containerMatch.index + containerMatch[0].indexOf(">") + 1;
241
- const nodes = [];
242
- let combined = "";
243
- tokenRe.lastIndex = 0;
244
- let tok = tokenRe.exec(inner);
245
- while (tok !== null) {
246
- const selfClosingName = tok[1];
247
- if (selfClosingName !== void 0) {
248
- const sepChar = sepTags[selfClosingName];
249
- if (sepChar) {
250
- combined += sepChar;
251
- }
252
- tok = tokenRe.exec(inner);
253
- continue;
242
+ const stack = [];
243
+ let tok = scanRe.exec(xml);
244
+ while (tok !== null) {
245
+ if (tok[1] !== void 0) {
246
+ if (!tok[0].endsWith("/>")) {
247
+ stack.push({ nodes: [], combined: "" });
248
+ }
249
+ } else if (tok[2] !== void 0) {
250
+ const frame = stack.pop();
251
+ if (frame && frame.nodes.length > 0) {
252
+ containers.push({ text: frame.combined, nodes: frame.nodes });
253
+ }
254
+ } else if (tok[3] !== void 0) {
255
+ const top = stack[stack.length - 1];
256
+ const sepChar = sepTags[tok[3]];
257
+ if (top && sepChar) {
258
+ top.combined += sepChar;
259
+ }
260
+ } else if (tok[4] !== void 0) {
261
+ const top = stack[stack.length - 1];
262
+ if (top) {
263
+ const tagName = tok[4];
264
+ const attrs = tok[5] ?? "";
265
+ const rawContent = tok[6] ?? "";
266
+ const openTag = `<${tagName}${attrs}>`;
267
+ const unescaped = unescapeXml(rawContent);
268
+ const tagStart = tok.index;
269
+ const contentStart = tagStart + openTag.length;
270
+ const contentEnd = contentStart + rawContent.length;
271
+ const combinedStart = top.combined.length;
272
+ top.combined += unescaped;
273
+ const combinedEnd = top.combined.length;
274
+ top.nodes.push({
275
+ tagStart,
276
+ contentStart,
277
+ contentEnd,
278
+ openTag,
279
+ text: unescaped,
280
+ combinedStart,
281
+ combinedEnd
282
+ });
254
283
  }
255
- const tagName = tok[2] ?? "";
256
- const attrs = tok[3] ?? "";
257
- const rawContent = tok[4] ?? "";
258
- const openTag = `<${tagName}${attrs}>`;
259
- const unescaped = unescapeXml(rawContent);
260
- const tagStart = openEndOffset + tok.index;
261
- const contentStart = tagStart + openTag.length;
262
- const contentEnd = contentStart + rawContent.length;
263
- const combinedStart = combined.length;
264
- combined += unescaped;
265
- const combinedEnd = combined.length;
266
- nodes.push({
267
- tagStart,
268
- contentStart,
269
- contentEnd,
270
- openTag,
271
- text: unescaped,
272
- combinedStart,
273
- combinedEnd
274
- });
275
- tok = tokenRe.exec(inner);
276
284
  }
277
- if (nodes.length > 0) {
278
- containers.push({ text: combined, nodes });
279
- }
280
- containerMatch = containerRe.exec(xml);
285
+ tok = scanRe.exec(xml);
281
286
  }
282
287
  return containers;
283
288
  }
@@ -6096,14 +6101,14 @@ function renderInspectorHtml(info) {
6096
6101
  }
6097
6102
  feedEl.innerHTML = '<div class="list">' + state.items.map((it, idx) => {
6098
6103
  const time = formatLocalTime(it.timestamp);
6099
- const tags = Object.entries(it.counts || {}).map(([k, v]) => '<span class="count-tag">' + esc(k) + " \xD7" + v + "</span>").join("");
6104
+ const tags = Object.entries(it.counts || {}).map(([k, v]) => '<span class="count-tag">' + esc(k) + " \xD7" + esc(v) + "</span>").join("");
6100
6105
  const previews = (it.redactedPreview || []).map((p) => '<pre class="preview">' + highlightTokens(p) + "</pre>").join("");
6101
6106
  const errBlock = it.errorDetail ? '<p class="body-label">Svar fr\xE5n API (fel):</p><pre class="preview err-preview">' + esc(it.errorDetail) + "</pre>" : "";
6102
6107
  const statusCls = it.status >= 200 && it.status < 400 ? "" : " err";
6103
6108
  const isOpen = isExpanded(it.id, idx);
6104
6109
  return '<details class="item" data-id="' + esc(it.id) + '"' + (isOpen ? " open" : "") + '>' +
6105
- '<summary><span class="left"><span class="badge' + statusCls + '">' + it.status + '</span><span class="path">' + esc(it.method + " " + it.path) + '</span>' + tags + (it.redactions === 0 ? '<span style="color:var(--muted);font-size:12px">0 PII</span>' : "") + '</span>' +
6106
- '<span class="right"><span>' + (it.streamed ? "SSE" : "JSON") + '</span><span>' + it.durationMs + ' ms</span><span>' + esc(time) + '</span></span></summary>' +
6110
+ '<summary><span class="left"><span class="badge' + statusCls + '">' + esc(it.status) + '</span><span class="path">' + esc(it.method + " " + it.path) + '</span>' + tags + (it.redactions === 0 ? '<span style="color:var(--muted);font-size:12px">0 PII</span>' : "") + '</span>' +
6111
+ '<span class="right"><span>' + (it.streamed ? "SSE" : "JSON") + '</span><span>' + esc(it.durationMs) + ' ms</span><span>' + esc(time) + '</span></span></summary>' +
6107
6112
  '<div class="body">' + errBlock + '<p class="body-label">Skickat vidare:</p>' + (previews || '<pre class="preview">(ingen text i anropet)</pre>') + '</div></details>';
6108
6113
  }).join("") + "</div>";
6109
6114
  for (const det of feedEl.querySelectorAll("details.item")) {
@@ -6715,48 +6720,73 @@ function deriveProxySessionId(headers, body) {
6715
6720
  var TEXT_BASE64_MEDIA_RE = /^(?:text\/|application\/(?:json|xml|csv|x-ndjson|javascript|yaml|x-yaml))/i;
6716
6721
  var DATA_URI_TEXT_BASE64_RE = /^data:((?:text\/[a-z0-9.+-]+|application\/(?:json|xml|csv|x-ndjson|javascript))[^;,]*);base64,([A-Za-z0-9+/=\s]+)$/i;
6717
6722
  var DATA_URI_ANY_RE = /^data:([^;,]+);base64,([A-Za-z0-9+/=\s]+)$/i;
6723
+ var REDACTABLE_DOC_MIME_TYPES = /* @__PURE__ */ new Set([
6724
+ "application/pdf",
6725
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
6726
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
6727
+ ]);
6728
+ function isDeclaredRedactableDocument(fileName, mediaType) {
6729
+ const mime = mediaType.split(";")[0]?.trim().toLowerCase() ?? "";
6730
+ if (REDACTABLE_DOC_MIME_TYPES.has(mime)) return true;
6731
+ const lowerName = (fileName ?? "").toLowerCase();
6732
+ return lowerName.endsWith(".pdf") || lowerName.endsWith(".docx") || lowerName.endsWith(".xlsx");
6733
+ }
6718
6734
  async function tryRedactBase64Document(encoded, mediaType, fileName, redactDocument, noteBinary) {
6719
6735
  if (!redactDocument) {
6720
6736
  noteBinary(mediaType);
6721
6737
  return encoded;
6722
6738
  }
6739
+ const declaredDoc = isDeclaredRedactableDocument(fileName, mediaType);
6740
+ let bytes;
6741
+ let detected;
6723
6742
  try {
6724
6743
  const rawBuf = Buffer.from(encoded, "base64");
6725
6744
  if (rawBuf.byteLength === 0 || rawBuf.byteLength > MAX_BODY_BYTES) {
6745
+ if (declaredDoc) {
6746
+ throw new Error(`Document attachment ${mediaType} is empty or exceeds max size.`);
6747
+ }
6726
6748
  noteBinary(mediaType);
6727
6749
  return encoded;
6728
6750
  }
6729
- const bytes = new Uint8Array(rawBuf.buffer, rawBuf.byteOffset, rawBuf.byteLength);
6730
- const detected = detectFileFormat(bytes, fileName, mediaType);
6731
- if (detected.format !== "pdf" && detected.format !== "docx" && detected.format !== "xlsx") {
6732
- noteBinary(mediaType);
6733
- return encoded;
6734
- }
6735
- const res = await redactDocument(bytes, { fileName, mimeType: mediaType });
6736
- if (!res.verified) {
6737
- noteBinary(`${mediaType} (unverified)`);
6738
- return encoded;
6739
- }
6740
- if (res.scannedPages.length > 0) {
6741
- noteBinary(`${mediaType} (scanned)`);
6751
+ bytes = new Uint8Array(rawBuf.buffer, rawBuf.byteOffset, rawBuf.byteLength);
6752
+ detected = detectFileFormat(bytes, fileName, mediaType);
6753
+ } catch (err) {
6754
+ if (declaredDoc) throw err;
6755
+ noteBinary(mediaType);
6756
+ return encoded;
6757
+ }
6758
+ if (detected.format !== "pdf" && detected.format !== "docx" && detected.format !== "xlsx") {
6759
+ if (declaredDoc) {
6760
+ throw new Error(
6761
+ `Corrupt or unreadable document attachment (${mediaType}); refusing to forward unredacted bytes.`
6762
+ );
6742
6763
  }
6743
- return Buffer.from(res.bytes).toString("base64");
6744
- } catch {
6745
6764
  noteBinary(mediaType);
6746
6765
  return encoded;
6747
6766
  }
6767
+ const res = await redactDocument(bytes, { fileName, mimeType: mediaType });
6768
+ if (!res.verified) {
6769
+ throw new Error(
6770
+ `Document redaction verification failed for ${mediaType}; refusing to forward unredacted attachment.`
6771
+ );
6772
+ }
6773
+ if (res.scannedPages.length > 0) {
6774
+ noteBinary(`${mediaType} (scanned)`);
6775
+ }
6776
+ return Buffer.from(res.bytes).toString("base64");
6748
6777
  }
6749
6778
  async function redactBase64Utf8(encoded, redactString, kind) {
6779
+ let decoded;
6750
6780
  try {
6751
6781
  const rawBuf = Buffer.from(encoded, "base64");
6752
6782
  if (rawBuf.includes(0) || rawBuf.byteLength > MAX_BODY_BYTES) return encoded;
6753
- const decoded = new TextDecoder("utf-8", { fatal: true }).decode(rawBuf);
6754
- const redacted = await redactString(decoded, kind);
6755
- if (redacted === decoded) return encoded;
6756
- return Buffer.from(redacted, "utf8").toString("base64");
6783
+ decoded = new TextDecoder("utf-8", { fatal: true }).decode(rawBuf);
6757
6784
  } catch {
6758
6785
  return encoded;
6759
6786
  }
6787
+ const redacted = await redactString(decoded, kind);
6788
+ if (redacted === decoded) return encoded;
6789
+ return Buffer.from(redacted, "utf8").toString("base64");
6760
6790
  }
6761
6791
  async function redactLlmRequestBody(body, redactString, options = {}) {
6762
6792
  const clone = options.mutate ? body : structuredClone(body);