@testsmith/api-spector-agent 0.9.11 → 0.9.13

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 (2) hide show
  1. package/dist/index.cjs +115 -18
  2. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -58924,7 +58924,7 @@ var require_websocket2 = __commonJS({
58924
58924
  var http = require("http");
58925
58925
  var net = require("net");
58926
58926
  var tls = require("tls");
58927
- var { randomBytes, createHash: createHash2 } = require("crypto");
58927
+ var { randomBytes: randomBytes2, createHash: createHash2 } = require("crypto");
58928
58928
  var { Duplex, Readable } = require("stream");
58929
58929
  var { URL: URL2 } = require("url");
58930
58930
  var PerMessageDeflate2 = require_permessage_deflate2();
@@ -59462,7 +59462,7 @@ var require_websocket2 = __commonJS({
59462
59462
  }
59463
59463
  }
59464
59464
  const defaultPort = isSecure ? 443 : 80;
59465
- const key = randomBytes(16).toString("base64");
59465
+ const key = randomBytes2(16).toString("base64");
59466
59466
  const request = isSecure ? https.request : http.request;
59467
59467
  const protocolSet = /* @__PURE__ */ new Set();
59468
59468
  let perMessageDeflate;
@@ -73401,6 +73401,8 @@ var import_xmldom = __toESM(require_lib());
73401
73401
  // src/main/request-exec.ts
73402
73402
  var import_undici = __toESM(require_undici());
73403
73403
  var import_promises2 = require("fs/promises");
73404
+ var import_path = require("path");
73405
+ var import_crypto = require("crypto");
73404
73406
  var nodeTls = __toESM(require("tls"));
73405
73407
 
73406
73408
  // src/main/stream/parse.ts
@@ -73669,6 +73671,10 @@ function getSecretsConfig() {
73669
73671
  }
73670
73672
 
73671
73673
  // src/main/secrets/providers/vault.ts
73674
+ function applyVars(str, vars) {
73675
+ if (!vars || !str.includes("{{")) return str;
73676
+ return str.replace(/\{\{\s*([\w.$-]+)\s*\}\}/g, (m6, name) => name in vars ? vars[name] : m6);
73677
+ }
73672
73678
  function env(...names) {
73673
73679
  for (const n5 of names) {
73674
73680
  const v3 = process.env[n5];
@@ -73700,6 +73706,7 @@ function resolveConn() {
73700
73706
  return {
73701
73707
  address: address.replace(/\/+$/, ""),
73702
73708
  namespace: env("VAULT_NAMESPACE", "BAO_NAMESPACE", "API_SPECTOR_VAULT_NAMESPACE") ?? cfg.namespace,
73709
+ pathPrefix: env("VAULT_PATH_PREFIX", "BAO_PATH_PREFIX", "API_SPECTOR_VAULT_PATH_PREFIX") ?? cfg.pathPrefix,
73703
73710
  authMethod,
73704
73711
  token,
73705
73712
  roleId,
@@ -73783,17 +73790,22 @@ async function clientToken(conn) {
73783
73790
  cachedToken = { value: token, expiresAt: ttl > 0 ? now + ttl * 1e3 : now + 5 * 6e4 };
73784
73791
  return token;
73785
73792
  }
73786
- async function readSecret(refBody, scheme) {
73793
+ async function readSecret(refBody, scheme, ctx = {}) {
73787
73794
  const hash = refBody.lastIndexOf("#");
73788
73795
  if (hash < 0) {
73789
73796
  throw new Error(`${scheme} reference must be '${scheme}:<path>#<key>' (got '${scheme}:${refBody}')`);
73790
73797
  }
73791
- const path = refBody.slice(0, hash).replace(/^\/+/, "");
73798
+ const rawPath = refBody.slice(0, hash);
73792
73799
  const key = refBody.slice(hash + 1);
73793
- if (!path || !key) {
73800
+ const absolute = /^\//.test(rawPath);
73801
+ const relPath = rawPath.replace(/^\/+/, "");
73802
+ if (!relPath || !key) {
73794
73803
  throw new Error(`${scheme} reference must be '${scheme}:<path>#<key>' (got '${scheme}:${refBody}')`);
73795
73804
  }
73796
73805
  const conn = resolveConn();
73806
+ const relResolved = applyVars(relPath, ctx.vars);
73807
+ const prefix = applyVars(conn.pathPrefix ?? "", ctx.vars).replace(/^\/+|\/+$/g, "");
73808
+ const path = !absolute && prefix ? `${prefix}/${relResolved}` : relResolved;
73797
73809
  const cacheKey = `${conn.address}|${conn.namespace ?? ""}|${path}`;
73798
73810
  const now = Date.now();
73799
73811
  let bag;
@@ -73816,11 +73828,11 @@ async function readSecret(refBody, scheme) {
73816
73828
  }
73817
73829
  var vaultProvider = {
73818
73830
  scheme: "vault",
73819
- resolve: (refBody) => readSecret(refBody, "vault")
73831
+ resolve: (refBody, ctx) => readSecret(refBody, "vault", ctx)
73820
73832
  };
73821
73833
  var openBaoProvider = {
73822
73834
  scheme: "bao",
73823
- resolve: (refBody) => readSecret(refBody, "bao")
73835
+ resolve: (refBody, ctx) => readSecret(refBody, "bao", ctx)
73824
73836
  };
73825
73837
 
73826
73838
  // src/main/secrets/providers/sigv4.ts
@@ -74381,7 +74393,7 @@ function buildUrl(baseUrl, params, vars) {
74381
74393
  const qs = queryRows.map((p6) => `${encodeURIComponent(interpolate(p6.key, vars))}=${encodeURIComponent(interpolate(p6.value, vars))}`).join("&");
74382
74394
  return url2 + sep + qs;
74383
74395
  }
74384
- async function resolveInlineSecretRefs(text) {
74396
+ async function resolveInlineSecretRefs(text, vars) {
74385
74397
  const refs = /* @__PURE__ */ new Set();
74386
74398
  for (const m6 of text.matchAll(/\{\{\s*([^}]+?)\s*\}\}/g)) {
74387
74399
  const inner = m6[1].trim();
@@ -74390,7 +74402,7 @@ async function resolveInlineSecretRefs(text) {
74390
74402
  if (refs.size === 0) return {};
74391
74403
  const out = {};
74392
74404
  await Promise.all([...refs].map(async (ref) => {
74393
- const value2 = await resolveExternalSecret(ref);
74405
+ const value2 = await resolveExternalSecret(ref, { vars });
74394
74406
  if (value2 !== null) out[ref] = value2;
74395
74407
  }));
74396
74408
  return out;
@@ -80951,6 +80963,81 @@ async function buildDispatcher(proxy, tls) {
80951
80963
  _dispatcherCache.set(key, dispatcher);
80952
80964
  return dispatcher;
80953
80965
  }
80966
+ var MIME_BY_EXT = {
80967
+ ".json": "application/json",
80968
+ ".xml": "application/xml",
80969
+ ".txt": "text/plain",
80970
+ ".csv": "text/csv",
80971
+ ".html": "text/html",
80972
+ ".pdf": "application/pdf",
80973
+ ".png": "image/png",
80974
+ ".jpg": "image/jpeg",
80975
+ ".jpeg": "image/jpeg",
80976
+ ".gif": "image/gif",
80977
+ ".webp": "image/webp",
80978
+ ".svg": "image/svg+xml",
80979
+ ".zip": "application/zip",
80980
+ ".gz": "application/gzip",
80981
+ ".mp4": "video/mp4",
80982
+ ".mp3": "audio/mpeg",
80983
+ ".wav": "audio/wav",
80984
+ ".doc": "application/msword",
80985
+ ".xls": "application/vnd.ms-excel",
80986
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
80987
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
80988
+ ".bin": "application/octet-stream"
80989
+ };
80990
+ function guessMultipartContentType(name) {
80991
+ return MIME_BY_EXT[(0, import_path.extname)(name).toLowerCase()] ?? "application/octet-stream";
80992
+ }
80993
+ function sanitizeFormName(s8) {
80994
+ return s8.replace(/"/g, "%22").replace(/[\r\n]/g, "");
80995
+ }
80996
+ async function buildMultipartBody(parts2, vars) {
80997
+ const boundary = `----APISpectorFormBoundary${(0, import_crypto.randomBytes)(16).toString("hex")}`;
80998
+ const chunks = [];
80999
+ const previewLines = [];
81000
+ for (const p6 of parts2) {
81001
+ if (!p6.enabled || !p6.key.trim()) continue;
81002
+ const name = sanitizeFormName(interpolate(p6.key, vars));
81003
+ chunks.push(Buffer.from(`--${boundary}\r
81004
+ `));
81005
+ if (p6.type === "file") {
81006
+ const path = interpolate(p6.filePath ?? "", vars).trim();
81007
+ let bytes;
81008
+ try {
81009
+ bytes = await (0, import_promises2.readFile)(path);
81010
+ } catch {
81011
+ throw new Error(`Multipart file not found or unreadable: ${path || "(no path set)"}`);
81012
+ }
81013
+ const filename = sanitizeFormName(interpolate(p6.fileName?.trim() || (0, import_path.basename)(path), vars));
81014
+ const ct2 = p6.contentType?.trim() || guessMultipartContentType(filename);
81015
+ chunks.push(Buffer.from(
81016
+ `Content-Disposition: form-data; name="${name}"; filename="${filename}"\r
81017
+ Content-Type: ${ct2}\r
81018
+ \r
81019
+ `
81020
+ ));
81021
+ chunks.push(bytes);
81022
+ chunks.push(Buffer.from("\r\n"));
81023
+ previewLines.push(`${name}: <file ${path} (${ct2}, ${bytes.length} bytes)>`);
81024
+ } else {
81025
+ const value2 = interpolate(p6.value ?? "", vars);
81026
+ chunks.push(Buffer.from(`Content-Disposition: form-data; name="${name}"\r
81027
+ \r
81028
+ ${value2}\r
81029
+ `));
81030
+ previewLines.push(`${name}: ${value2}`);
81031
+ }
81032
+ }
81033
+ chunks.push(Buffer.from(`--${boundary}--\r
81034
+ `));
81035
+ return {
81036
+ body: Buffer.concat(chunks),
81037
+ contentType: `multipart/form-data; boundary=${boundary}`,
81038
+ preview: previewLines.join("\n")
81039
+ };
81040
+ }
80954
81041
  function buildBodyAndApplyHeaders(req, vars, headers) {
80955
81042
  let body;
80956
81043
  if (req.body.mode === "json" && req.body.json) {
@@ -80987,7 +81074,7 @@ function buildBodyAndApplyHeaders(req, vars, headers) {
80987
81074
  async function performHttpExchange(opts) {
80988
81075
  const { req, resolvedUrl, dispatcher, proxy, tls, onSent } = opts;
80989
81076
  let vars = opts.vars;
80990
- const inlineSecrets = await resolveInlineSecrets(req);
81077
+ const inlineSecrets = await resolveInlineSecrets(req, vars);
80991
81078
  if (Object.keys(inlineSecrets).length) vars = { ...vars, ...inlineSecrets };
80992
81079
  const start = Date.now();
80993
81080
  if (req.auth.type === "oauth2") {
@@ -81012,15 +81099,25 @@ async function performHttpExchange(opts) {
81012
81099
  if (h6.enabled && h6.key) headers.set(interpolate(h6.key, vars), interpolate(h6.value, vars));
81013
81100
  }
81014
81101
  for (const [k2, v3] of Object.entries(authHeaders2)) headers.set(k2, v3);
81015
- const body = buildBodyAndApplyHeaders(req, vars, headers);
81016
81102
  const methodHasBody = !["GET", "HEAD"].includes(req.method);
81017
- const effectiveBody = methodHasBody ? body : void 0;
81103
+ let effectiveBody;
81104
+ let previewBody;
81105
+ if (methodHasBody && req.body.mode === "multipart" && req.body.multipart?.length) {
81106
+ const mp = await buildMultipartBody(req.body.multipart, vars);
81107
+ effectiveBody = mp.body;
81108
+ previewBody = mp.preview;
81109
+ if (!headers.has("content-type")) headers.set("Content-Type", mp.contentType);
81110
+ } else {
81111
+ const body = buildBodyAndApplyHeaders(req, vars, headers);
81112
+ effectiveBody = methodHasBody ? body : void 0;
81113
+ previewBody = typeof effectiveBody === "string" ? effectiveBody : void 0;
81114
+ }
81018
81115
  const captureSent = (h6) => {
81019
81116
  const captured = {};
81020
81117
  h6.forEach((value2, key) => {
81021
81118
  captured[key] = value2;
81022
81119
  });
81023
- onSent?.({ method: req.method, url: finalUrl, headers: captured, body: effectiveBody });
81120
+ onSent?.({ method: req.method, url: finalUrl, headers: captured, body: previewBody });
81024
81121
  return captured;
81025
81122
  };
81026
81123
  const doFetch = (h6) => (0, import_undici.fetch)(finalUrl, {
@@ -81084,7 +81181,7 @@ async function performHttpExchange(opts) {
81084
81181
  responseBody,
81085
81182
  durationMs: Date.now() - start,
81086
81183
  sentHeaders,
81087
- sentBody: effectiveBody,
81184
+ sentBody: previewBody,
81088
81185
  finalUrl,
81089
81186
  ...streamFields
81090
81187
  };
@@ -81102,7 +81199,7 @@ function syntheticHttpFailure(status, statusText) {
81102
81199
  error: `Request returned ${status} - no assertion was defined to verify the status code.`
81103
81200
  };
81104
81201
  }
81105
- async function resolveInlineSecrets(req) {
81202
+ async function resolveInlineSecrets(req, vars) {
81106
81203
  const haystack = [
81107
81204
  req.url ?? "",
81108
81205
  JSON.stringify(req.params ?? []),
@@ -81112,7 +81209,7 @@ async function resolveInlineSecrets(req) {
81112
81209
  req.preRequestScript ?? "",
81113
81210
  req.postRequestScript ?? ""
81114
81211
  ].join("\n");
81115
- return resolveInlineSecretRefs(haystack);
81212
+ return resolveInlineSecretRefs(haystack, vars);
81116
81213
  }
81117
81214
  async function executeRunnerRequest(opts) {
81118
81215
  const { req, collectionVars, envVars, globals, dispatcher, piiMaskPatterns, proxy, tls, onScriptOutput } = opts;
@@ -81226,7 +81323,7 @@ async function executeRunnerRequest(opts) {
81226
81323
  }
81227
81324
  let inlineSecrets = {};
81228
81325
  try {
81229
- inlineSecrets = await resolveInlineSecrets(req);
81326
+ inlineSecrets = await resolveInlineSecrets(req, vars);
81230
81327
  } catch (err) {
81231
81328
  return {
81232
81329
  result: {
@@ -81535,7 +81632,7 @@ var APP_URL = (process.env.APP_URL || "").replace(/\/+$/, "");
81535
81632
  var AGENT_TOKEN = process.env.AGENT_TOKEN || "";
81536
81633
  var RUNTIME_TOKEN = process.env.RUNTIME_TOKEN || "";
81537
81634
  var POLL_MS = Number(process.env.POLL_INTERVAL_MS || 5e3);
81538
- var VERSION = true ? "0.9.11" : "";
81635
+ var VERSION = true ? "0.9.13" : "";
81539
81636
  var authHeaders = AGENT_TOKEN ? { Authorization: `Bearer ${AGENT_TOKEN}` } : RUNTIME_TOKEN ? { "X-Runtime-Token": RUNTIME_TOKEN } : {};
81540
81637
  async function postResult(m6, fields) {
81541
81638
  await fetch(`${APP_URL}/api/monitor-runtime/${m6.id}/result`, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@testsmith/api-spector-agent",
3
- "version": "0.9.11",
3
+ "version": "0.9.13",
4
4
  "description": "API Spector private runner: monitor internal/local APIs the cloud cannot reach, with no inbound connections.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://api-spector.dev",