@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/index.js CHANGED
@@ -313,6 +313,9 @@ function unzipSafely(bytes) {
313
313
  let totalUncompressed = 0;
314
314
  const files = unzipSync(bytes, {
315
315
  filter(file) {
316
+ if (file.name.includes("\0") || file.name.startsWith("/") || file.name.startsWith("\\") || file.name.split(/[\\/]/).includes("..")) {
317
+ throw new Error(`Archive contains unsafe entry path: ${file.name}`);
318
+ }
316
319
  entryCount += 1;
317
320
  if (entryCount > MAX_ZIP_ENTRIES) {
318
321
  throw new Error(`Archive exceeds max allowed entry count (${MAX_ZIP_ENTRIES}).`);
@@ -381,62 +384,64 @@ function escapeRegexLiteral(value) {
381
384
  }
382
385
  function extractXmlTextContainers(xml, containerTag, textTags, options) {
383
386
  const escapedContainer = escapeRegexLiteral(containerTag);
384
- const containerRe = new RegExp(
385
- `<${escapedContainer}(?:\\s[^>]*)?>([\\s\\S]*?)<\\/${escapedContainer}>`,
386
- "g"
387
- );
388
387
  const sepTags = options?.separatorTags ?? {};
389
388
  const sepTagNames = Object.keys(sepTags);
390
- const allTagAlternation = [...textTags, ...sepTagNames].map(escapeRegexLiteral).join("|");
391
- const tokenRe = new RegExp(
392
- `<(${allTagAlternation})(?:\\s[^>]*)?\\/>|<(${textTags.map(escapeRegexLiteral).join("|")})(\\s[^>]*)?>([\\s\\S]*?)<\\/\\2>`,
389
+ const allSelfClosing = [...textTags, ...sepTagNames].map(escapeRegexLiteral).join("|");
390
+ const textAlt = textTags.map(escapeRegexLiteral).join("|");
391
+ const scanRe = new RegExp(
392
+ [
393
+ `<(${escapedContainer})(?:\\s[^>]*)?>`,
394
+ `<\\/(${escapedContainer})>`,
395
+ `<(${allSelfClosing})(?:\\s[^>]*)?\\/>`,
396
+ `<(${textAlt})(\\s[^>]*)?>([\\s\\S]*?)<\\/\\4>`
397
+ ].join("|"),
393
398
  "g"
394
399
  );
395
400
  const containers = [];
396
- let containerMatch = containerRe.exec(xml);
397
- while (containerMatch !== null) {
398
- const inner = containerMatch[1] ?? "";
399
- const openEndOffset = containerMatch.index + containerMatch[0].indexOf(">") + 1;
400
- const nodes = [];
401
- let combined = "";
402
- tokenRe.lastIndex = 0;
403
- let tok = tokenRe.exec(inner);
404
- while (tok !== null) {
405
- const selfClosingName = tok[1];
406
- if (selfClosingName !== void 0) {
407
- const sepChar = sepTags[selfClosingName];
408
- if (sepChar) {
409
- combined += sepChar;
410
- }
411
- tok = tokenRe.exec(inner);
412
- continue;
401
+ const stack = [];
402
+ let tok = scanRe.exec(xml);
403
+ while (tok !== null) {
404
+ if (tok[1] !== void 0) {
405
+ if (!tok[0].endsWith("/>")) {
406
+ stack.push({ nodes: [], combined: "" });
407
+ }
408
+ } else if (tok[2] !== void 0) {
409
+ const frame = stack.pop();
410
+ if (frame && frame.nodes.length > 0) {
411
+ containers.push({ text: frame.combined, nodes: frame.nodes });
412
+ }
413
+ } else if (tok[3] !== void 0) {
414
+ const top = stack[stack.length - 1];
415
+ const sepChar = sepTags[tok[3]];
416
+ if (top && sepChar) {
417
+ top.combined += sepChar;
418
+ }
419
+ } else if (tok[4] !== void 0) {
420
+ const top = stack[stack.length - 1];
421
+ if (top) {
422
+ const tagName = tok[4];
423
+ const attrs = tok[5] ?? "";
424
+ const rawContent = tok[6] ?? "";
425
+ const openTag = `<${tagName}${attrs}>`;
426
+ const unescaped = unescapeXml(rawContent);
427
+ const tagStart = tok.index;
428
+ const contentStart = tagStart + openTag.length;
429
+ const contentEnd = contentStart + rawContent.length;
430
+ const combinedStart = top.combined.length;
431
+ top.combined += unescaped;
432
+ const combinedEnd = top.combined.length;
433
+ top.nodes.push({
434
+ tagStart,
435
+ contentStart,
436
+ contentEnd,
437
+ openTag,
438
+ text: unescaped,
439
+ combinedStart,
440
+ combinedEnd
441
+ });
413
442
  }
414
- const tagName = tok[2] ?? "";
415
- const attrs = tok[3] ?? "";
416
- const rawContent = tok[4] ?? "";
417
- const openTag = `<${tagName}${attrs}>`;
418
- const unescaped = unescapeXml(rawContent);
419
- const tagStart = openEndOffset + tok.index;
420
- const contentStart = tagStart + openTag.length;
421
- const contentEnd = contentStart + rawContent.length;
422
- const combinedStart = combined.length;
423
- combined += unescaped;
424
- const combinedEnd = combined.length;
425
- nodes.push({
426
- tagStart,
427
- contentStart,
428
- contentEnd,
429
- openTag,
430
- text: unescaped,
431
- combinedStart,
432
- combinedEnd
433
- });
434
- tok = tokenRe.exec(inner);
435
443
  }
436
- if (nodes.length > 0) {
437
- containers.push({ text: combined, nodes });
438
- }
439
- containerMatch = containerRe.exec(xml);
444
+ tok = scanRe.exec(xml);
440
445
  }
441
446
  return containers;
442
447
  }
@@ -5712,14 +5717,14 @@ function renderInspectorHtml(info) {
5712
5717
  }
5713
5718
  feedEl.innerHTML = '<div class="list">' + state.items.map((it, idx) => {
5714
5719
  const time = formatLocalTime(it.timestamp);
5715
- const tags = Object.entries(it.counts || {}).map(([k, v]) => '<span class="count-tag">' + esc(k) + " \xD7" + v + "</span>").join("");
5720
+ const tags = Object.entries(it.counts || {}).map(([k, v]) => '<span class="count-tag">' + esc(k) + " \xD7" + esc(v) + "</span>").join("");
5716
5721
  const previews = (it.redactedPreview || []).map((p) => '<pre class="preview">' + highlightTokens(p) + "</pre>").join("");
5717
5722
  const errBlock = it.errorDetail ? '<p class="body-label">Svar fr\xE5n API (fel):</p><pre class="preview err-preview">' + esc(it.errorDetail) + "</pre>" : "";
5718
5723
  const statusCls = it.status >= 200 && it.status < 400 ? "" : " err";
5719
5724
  const isOpen = isExpanded(it.id, idx);
5720
5725
  return '<details class="item" data-id="' + esc(it.id) + '"' + (isOpen ? " open" : "") + '>' +
5721
- '<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>' +
5722
- '<span class="right"><span>' + (it.streamed ? "SSE" : "JSON") + '</span><span>' + it.durationMs + ' ms</span><span>' + esc(time) + '</span></span></summary>' +
5726
+ '<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>' +
5727
+ '<span class="right"><span>' + (it.streamed ? "SSE" : "JSON") + '</span><span>' + esc(it.durationMs) + ' ms</span><span>' + esc(time) + '</span></span></summary>' +
5723
5728
  '<div class="body">' + errBlock + '<p class="body-label">Skickat vidare:</p>' + (previews || '<pre class="preview">(ingen text i anropet)</pre>') + '</div></details>';
5724
5729
  }).join("") + "</div>";
5725
5730
  for (const det of feedEl.querySelectorAll("details.item")) {
@@ -6711,48 +6716,73 @@ function deriveProxySessionId(headers, body) {
6711
6716
  var TEXT_BASE64_MEDIA_RE = /^(?:text\/|application\/(?:json|xml|csv|x-ndjson|javascript|yaml|x-yaml))/i;
6712
6717
  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;
6713
6718
  var DATA_URI_ANY_RE = /^data:([^;,]+);base64,([A-Za-z0-9+/=\s]+)$/i;
6719
+ var REDACTABLE_DOC_MIME_TYPES = /* @__PURE__ */ new Set([
6720
+ "application/pdf",
6721
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
6722
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
6723
+ ]);
6724
+ function isDeclaredRedactableDocument(fileName, mediaType) {
6725
+ const mime = mediaType.split(";")[0]?.trim().toLowerCase() ?? "";
6726
+ if (REDACTABLE_DOC_MIME_TYPES.has(mime)) return true;
6727
+ const lowerName = (fileName ?? "").toLowerCase();
6728
+ return lowerName.endsWith(".pdf") || lowerName.endsWith(".docx") || lowerName.endsWith(".xlsx");
6729
+ }
6714
6730
  async function tryRedactBase64Document(encoded, mediaType, fileName, redactDocument, noteBinary) {
6715
6731
  if (!redactDocument) {
6716
6732
  noteBinary(mediaType);
6717
6733
  return encoded;
6718
6734
  }
6735
+ const declaredDoc = isDeclaredRedactableDocument(fileName, mediaType);
6736
+ let bytes;
6737
+ let detected;
6719
6738
  try {
6720
6739
  const rawBuf = Buffer.from(encoded, "base64");
6721
6740
  if (rawBuf.byteLength === 0 || rawBuf.byteLength > MAX_BODY_BYTES) {
6741
+ if (declaredDoc) {
6742
+ throw new Error(`Document attachment ${mediaType} is empty or exceeds max size.`);
6743
+ }
6722
6744
  noteBinary(mediaType);
6723
6745
  return encoded;
6724
6746
  }
6725
- const bytes = new Uint8Array(rawBuf.buffer, rawBuf.byteOffset, rawBuf.byteLength);
6726
- const detected = detectFileFormat(bytes, fileName, mediaType);
6727
- if (detected.format !== "pdf" && detected.format !== "docx" && detected.format !== "xlsx") {
6728
- noteBinary(mediaType);
6729
- return encoded;
6730
- }
6731
- const res = await redactDocument(bytes, { fileName, mimeType: mediaType });
6732
- if (!res.verified) {
6733
- noteBinary(`${mediaType} (unverified)`);
6734
- return encoded;
6735
- }
6736
- if (res.scannedPages.length > 0) {
6737
- noteBinary(`${mediaType} (scanned)`);
6747
+ bytes = new Uint8Array(rawBuf.buffer, rawBuf.byteOffset, rawBuf.byteLength);
6748
+ detected = detectFileFormat(bytes, fileName, mediaType);
6749
+ } catch (err) {
6750
+ if (declaredDoc) throw err;
6751
+ noteBinary(mediaType);
6752
+ return encoded;
6753
+ }
6754
+ if (detected.format !== "pdf" && detected.format !== "docx" && detected.format !== "xlsx") {
6755
+ if (declaredDoc) {
6756
+ throw new Error(
6757
+ `Corrupt or unreadable document attachment (${mediaType}); refusing to forward unredacted bytes.`
6758
+ );
6738
6759
  }
6739
- return Buffer.from(res.bytes).toString("base64");
6740
- } catch {
6741
6760
  noteBinary(mediaType);
6742
6761
  return encoded;
6743
6762
  }
6763
+ const res = await redactDocument(bytes, { fileName, mimeType: mediaType });
6764
+ if (!res.verified) {
6765
+ throw new Error(
6766
+ `Document redaction verification failed for ${mediaType}; refusing to forward unredacted attachment.`
6767
+ );
6768
+ }
6769
+ if (res.scannedPages.length > 0) {
6770
+ noteBinary(`${mediaType} (scanned)`);
6771
+ }
6772
+ return Buffer.from(res.bytes).toString("base64");
6744
6773
  }
6745
6774
  async function redactBase64Utf8(encoded, redactString, kind) {
6775
+ let decoded;
6746
6776
  try {
6747
6777
  const rawBuf = Buffer.from(encoded, "base64");
6748
6778
  if (rawBuf.includes(0) || rawBuf.byteLength > MAX_BODY_BYTES) return encoded;
6749
- const decoded = new TextDecoder("utf-8", { fatal: true }).decode(rawBuf);
6750
- const redacted = await redactString(decoded, kind);
6751
- if (redacted === decoded) return encoded;
6752
- return Buffer.from(redacted, "utf8").toString("base64");
6779
+ decoded = new TextDecoder("utf-8", { fatal: true }).decode(rawBuf);
6753
6780
  } catch {
6754
6781
  return encoded;
6755
6782
  }
6783
+ const redacted = await redactString(decoded, kind);
6784
+ if (redacted === decoded) return encoded;
6785
+ return Buffer.from(redacted, "utf8").toString("base64");
6756
6786
  }
6757
6787
  async function redactLlmRequestBody(body, redactString, options = {}) {
6758
6788
  const clone = options.mutate ? body : structuredClone(body);