@medialane/sdk 0.105.0 → 0.106.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.
package/dist/index.cjs CHANGED
@@ -1467,43 +1467,135 @@ var ALLOWED_IMAGE_CONTENT_TYPES = /* @__PURE__ */ new Set([
1467
1467
  ]);
1468
1468
  var MAX_IMAGE_REDIRECTS = 5;
1469
1469
  var MAX_IMAGE_PROXY_BYTES = 15 * 1024 * 1024;
1470
+ function parseIpv4(ip) {
1471
+ const parts = ip.split(".");
1472
+ if (parts.length !== 4) return null;
1473
+ const bytes = [];
1474
+ for (const part of parts) {
1475
+ if (!/^\d{1,3}$/.test(part)) return null;
1476
+ const n = Number(part);
1477
+ if (n > 255) return null;
1478
+ bytes.push(n);
1479
+ }
1480
+ return bytes;
1481
+ }
1482
+ function isPrivateIpv4(bytes) {
1483
+ const a = bytes[0];
1484
+ const b = bytes[1];
1485
+ const c = bytes[2];
1486
+ if (a === 0) return true;
1487
+ if (a === 10) return true;
1488
+ if (a === 100 && b >= 64 && b <= 127) return true;
1489
+ if (a === 127) return true;
1490
+ if (a === 169 && b === 254) return true;
1491
+ if (a === 172 && b >= 16 && b <= 31) return true;
1492
+ if (a === 192 && b === 0 && c === 0) return true;
1493
+ if (a === 192 && b === 168) return true;
1494
+ if (a === 198 && (b === 18 || b === 19)) return true;
1495
+ if (a >= 224) return true;
1496
+ return false;
1497
+ }
1498
+ function expandIpv6(rawIp) {
1499
+ let ip = rawIp;
1500
+ let embeddedV4 = null;
1501
+ const v4Tail = ip.match(/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
1502
+ if (v4Tail && ip.includes(":")) {
1503
+ embeddedV4 = parseIpv4(v4Tail[1]);
1504
+ if (!embeddedV4) return null;
1505
+ ip = ip.slice(0, ip.length - v4Tail[1].length) + "0:0";
1506
+ }
1507
+ const sides = ip.split("::");
1508
+ if (sides.length > 2) return null;
1509
+ const head = sides[0] ? sides[0].split(":").filter(Boolean) : [];
1510
+ const tail = sides.length === 2 && sides[1] ? sides[1].split(":").filter(Boolean) : [];
1511
+ let groups;
1512
+ if (sides.length === 1) {
1513
+ groups = head;
1514
+ if (groups.length !== 8) return null;
1515
+ } else {
1516
+ const missing = 8 - head.length - tail.length;
1517
+ if (missing < 0) return null;
1518
+ groups = [...head, ...Array(missing).fill("0"), ...tail];
1519
+ }
1520
+ if (groups.length !== 8) return null;
1521
+ const bytes = [];
1522
+ for (const group of groups) {
1523
+ if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return null;
1524
+ const n = parseInt(group, 16);
1525
+ bytes.push(n >> 8 & 255, n & 255);
1526
+ }
1527
+ if (embeddedV4) {
1528
+ bytes[12] = embeddedV4[0];
1529
+ bytes[13] = embeddedV4[1];
1530
+ bytes[14] = embeddedV4[2];
1531
+ bytes[15] = embeddedV4[3];
1532
+ }
1533
+ return bytes;
1534
+ }
1535
+ function isPrivateIpv6(bytes) {
1536
+ if (bytes.every((b) => b === 0)) return true;
1537
+ if (bytes.slice(0, 15).every((b) => b === 0) && bytes[15] === 1) return true;
1538
+ if ((bytes[0] & 254) === 252) return true;
1539
+ if (bytes[0] === 254 && (bytes[1] & 192) === 128) return true;
1540
+ if (bytes.slice(0, 10).every((b) => b === 0) && bytes[10] === 255 && bytes[11] === 255) {
1541
+ return isPrivateIpv4(bytes.slice(12));
1542
+ }
1543
+ return false;
1544
+ }
1545
+ function parseNumber(part) {
1546
+ if (/^0x[0-9a-f]+$/i.test(part)) return parseInt(part.slice(2), 16);
1547
+ if (/^0[0-7]+$/.test(part)) return parseInt(part, 8);
1548
+ if (/^\d+$/.test(part)) return parseInt(part, 10);
1549
+ return null;
1550
+ }
1551
+ function normalizeNumericHostname(host) {
1552
+ const parts = host.trim().split(".");
1553
+ if (parts.length < 1 || parts.length > 4) return null;
1554
+ const values = [];
1555
+ for (const part of parts) {
1556
+ const value = parseNumber(part);
1557
+ if (value === null || value < 0) return null;
1558
+ values.push(value);
1559
+ }
1560
+ const leading = values.slice(0, -1);
1561
+ if (leading.some((v) => v > 255)) return null;
1562
+ const tail = values[values.length - 1];
1563
+ const tailBytes = 4 - leading.length;
1564
+ if (tail > 2 ** (8 * tailBytes) - 1) return null;
1565
+ const bytes = [...leading];
1566
+ for (let i = tailBytes - 1; i >= 0; i--) bytes.push(tail >>> 8 * i & 255);
1567
+ return bytes.join(".");
1568
+ }
1569
+ var BLOCKED_HOSTNAMES = /* @__PURE__ */ new Set([
1570
+ "localhost",
1571
+ "metadata.google.internal",
1572
+ "metadata.azure.internal"
1573
+ ]);
1470
1574
  function isPrivateHost(hostname) {
1471
- const h = hostname.toLowerCase().replace(/^\[|\]$/g, "");
1472
- if (h === "localhost" || h === "127.0.0.1" || h === "0.0.0.0") return true;
1473
- if (/^\d+$/.test(h)) {
1474
- const n = parseInt(h, 10);
1475
- if (n === 2130706433 || n === 0 || n >= 2886729728 && n <= 2887778303 || n >= 3232235520 && n <= 3232301055 || n >= 167772160 && n <= 184549375 || n >= 2851995648 && n <= 2852061183) return true;
1476
- }
1477
- if (/^0x[0-9a-f]+$/i.test(h)) {
1478
- const n = parseInt(h, 16);
1479
- if (n === 2130706433 || n === 0 || n >= 2886729728 && n <= 2887778303 || n >= 3232235520 && n <= 3232301055 || n >= 167772160 && n <= 184549375 || n >= 2851995648 && n <= 2852061183) return true;
1480
- }
1481
- if (/^0\d+\.\d+\.\d+\.\d+$/.test(h)) return true;
1482
- if (h === "::1" || /^0*:0*:0*:0*:0*:0*:0*:0*1$/.test(h)) return true;
1483
- const v4mapped = h.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);
1484
- if (v4mapped) return isPrivateHost(v4mapped[1]);
1485
- if (/^10\./.test(h)) return true;
1486
- if (/^172\.(1[6-9]|2\d|3[01])\./.test(h)) return true;
1487
- if (/^192\.168\./.test(h)) return true;
1488
- if (/^169\.254\./.test(h)) return true;
1489
- if (/^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./.test(h)) return true;
1490
- if (/^fe80:/i.test(h)) return true;
1491
- if (/^f[cd][0-9a-f]{2}:/i.test(h)) return true;
1492
- if (h.endsWith(".local")) return true;
1493
- if (h === "metadata.google.internal") return true;
1494
- if (h === "metadata.azure.internal") return true;
1575
+ const host = hostname.toLowerCase().replace(/^\[|\]$/g, "");
1576
+ if (BLOCKED_HOSTNAMES.has(host)) return true;
1577
+ if (host.endsWith(".local") || host.endsWith(".internal")) return true;
1578
+ const candidate = normalizeNumericHostname(host) ?? host;
1579
+ const v4 = parseIpv4(candidate);
1580
+ if (v4) return isPrivateIpv4(v4);
1581
+ const v6 = expandIpv6(candidate);
1582
+ if (v6) return isPrivateIpv6(v6);
1495
1583
  return false;
1496
1584
  }
1497
- function validateUrl(raw) {
1585
+ function validateUrl(raw, options = {}) {
1586
+ const requireHttps = options.requireHttps ?? true;
1498
1587
  let parsed;
1499
1588
  try {
1500
1589
  parsed = new URL(raw);
1501
1590
  } catch {
1502
1591
  return { error: "Invalid url", status: 400 };
1503
1592
  }
1504
- if (parsed.protocol !== "https:") {
1593
+ if (requireHttps && parsed.protocol !== "https:") {
1505
1594
  return { error: "Only https URLs allowed", status: 400 };
1506
1595
  }
1596
+ if (!requireHttps && parsed.protocol !== "https:" && parsed.protocol !== "http:") {
1597
+ return { error: "Only http and https URLs allowed", status: 400 };
1598
+ }
1507
1599
  if (parsed.username || parsed.password) {
1508
1600
  return { error: "URL credentials not allowed", status: 400 };
1509
1601
  }
@@ -1512,6 +1604,111 @@ function validateUrl(raw) {
1512
1604
  }
1513
1605
  return { url: parsed };
1514
1606
  }
1607
+ function isPrivateOrInsecureUrl(raw, requireHttps = true) {
1608
+ return "error" in validateUrl(raw, { requireHttps });
1609
+ }
1610
+
1611
+ // src/server/image-proxy.ts
1612
+ var DEFAULT_USER_AGENT = "Mozilla/5.0 (compatible; Medialane/1.0; +https://www.medialane.io)";
1613
+ function jsonError(message, status) {
1614
+ return Response.json({ error: message }, { status });
1615
+ }
1616
+ async function readBodyWithCap(res, maxBytes) {
1617
+ const declared = Number(res.headers.get("content-length") ?? 0);
1618
+ if (declared > maxBytes) {
1619
+ return { ok: false, error: "Image too large", status: 413 };
1620
+ }
1621
+ const reader = res.body?.getReader();
1622
+ if (!reader) return { ok: false, error: "Empty response body", status: 502 };
1623
+ const chunks = [];
1624
+ let total = 0;
1625
+ for (; ; ) {
1626
+ const { done, value } = await reader.read();
1627
+ if (done) break;
1628
+ if (!value) continue;
1629
+ total += value.byteLength;
1630
+ if (total > maxBytes) {
1631
+ await reader.cancel().catch(() => {
1632
+ });
1633
+ return { ok: false, error: "Image too large", status: 413 };
1634
+ }
1635
+ chunks.push(value);
1636
+ }
1637
+ const body = new Uint8Array(total);
1638
+ let offset = 0;
1639
+ for (const chunk of chunks) {
1640
+ body.set(chunk, offset);
1641
+ offset += chunk.byteLength;
1642
+ }
1643
+ return { ok: true, body };
1644
+ }
1645
+ function createImageProxyHandler(config) {
1646
+ const doFetch = config.fetchImpl ?? fetch;
1647
+ const userAgent = config.userAgent ?? DEFAULT_USER_AGENT;
1648
+ async function resolvesToPrivateHost(hostname) {
1649
+ try {
1650
+ const addresses = await config.resolveHostname(hostname);
1651
+ if (addresses.length === 0) return true;
1652
+ return addresses.some((address) => isPrivateHost(address));
1653
+ } catch {
1654
+ return true;
1655
+ }
1656
+ }
1657
+ async function safeFetch(url, hopsLeft) {
1658
+ if (hopsLeft < 0) throw new Error("Too many redirects");
1659
+ if (await resolvesToPrivateHost(url.hostname)) {
1660
+ throw new Error("Blocked: hostname resolves to a private address");
1661
+ }
1662
+ const res = await doFetch(url.toString(), {
1663
+ redirect: "manual",
1664
+ headers: { "User-Agent": userAgent }
1665
+ });
1666
+ if (res.status >= 300 && res.status < 400) {
1667
+ const location = res.headers.get("location");
1668
+ if (!location) throw new Error("Redirect with no Location header");
1669
+ const next = new URL(location, url);
1670
+ const validated = validateUrl(next.toString());
1671
+ if ("error" in validated) throw new Error(`Redirect blocked: ${validated.error}`);
1672
+ return safeFetch(validated.url, hopsLeft - 1);
1673
+ }
1674
+ return res;
1675
+ }
1676
+ return async function handleImageProxy(req) {
1677
+ if (!config.checkRateLimit(requestIp(req))) {
1678
+ return jsonError("Too many requests", 429);
1679
+ }
1680
+ const raw = new URL(req.url).searchParams.get("url");
1681
+ if (!raw) return jsonError("Missing url", 400);
1682
+ const validated = validateUrl(raw);
1683
+ if ("error" in validated) return jsonError(validated.error, validated.status);
1684
+ let upstream;
1685
+ try {
1686
+ upstream = await safeFetch(validated.url, MAX_IMAGE_REDIRECTS);
1687
+ } catch {
1688
+ return jsonError("Failed to fetch image", 502);
1689
+ }
1690
+ if (!upstream.ok) {
1691
+ return jsonError(`Upstream returned ${upstream.status}`, upstream.status);
1692
+ }
1693
+ const contentType = upstream.headers.get("content-type") ?? "";
1694
+ const baseType = contentType.split(";")[0].trim().toLowerCase();
1695
+ if (!ALLOWED_IMAGE_CONTENT_TYPES.has(baseType)) {
1696
+ return jsonError("Not an image", 400);
1697
+ }
1698
+ const capped = await readBodyWithCap(upstream, MAX_IMAGE_PROXY_BYTES);
1699
+ if (!capped.ok) return jsonError(capped.error, capped.status);
1700
+ return new Response(capped.body, {
1701
+ status: 200,
1702
+ headers: {
1703
+ "Content-Type": contentType,
1704
+ "X-Content-Type-Options": "nosniff",
1705
+ "Content-Security-Policy": "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox",
1706
+ "Cache-Control": "public, max-age=86400, s-maxage=86400, stale-while-revalidate=604800",
1707
+ "Access-Control-Allow-Origin": "*"
1708
+ }
1709
+ });
1710
+ };
1711
+ }
1515
1712
 
1516
1713
  // src/server/backend-metadata.ts
1517
1714
  function endpoint(config, path) {
@@ -1792,6 +1989,7 @@ exports.coinHref = coinHref;
1792
1989
  exports.collectionHref = collectionHref;
1793
1990
  exports.createBackendProxyHandler = createBackendProxyHandler;
1794
1991
  exports.createFailoverFetch = createFailoverFetch;
1992
+ exports.createImageProxyHandler = createImageProxyHandler;
1795
1993
  exports.createRateLimiter = createRateLimiter;
1796
1994
  exports.createRpcProxyHandler = createRpcProxyHandler;
1797
1995
  exports.encodeU256 = encodeU256;
@@ -1808,6 +2006,7 @@ exports.getTokenBySymbol = getTokenBySymbol;
1808
2006
  exports.hasCapability = hasCapability;
1809
2007
  exports.isPolicyRefusal = isPolicyRefusal;
1810
2008
  exports.isPrivateHost = isPrivateHost;
2009
+ exports.isPrivateOrInsecureUrl = isPrivateOrInsecureUrl;
1811
2010
  exports.isSameOrigin = isSameOrigin;
1812
2011
  exports.isServiceId = isServiceId;
1813
2012
  exports.isTransientRpcError = isTransientRpcError;
@@ -1818,6 +2017,7 @@ exports.listServices = listServices;
1818
2017
  exports.normalizeAddress = normalizeAddress;
1819
2018
  exports.normalizeHash = normalizeHash;
1820
2019
  exports.parseAmount = parseAmount;
2020
+ exports.readBodyWithCap = readBodyWithCap;
1821
2021
  exports.requestIp = requestIp;
1822
2022
  exports.resolveAppFeeConfig = resolveAppFeeConfig;
1823
2023
  exports.resolveConfig = resolveConfig;