@medialane/sdk 0.104.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
@@ -3,6 +3,8 @@
3
3
  var zod = require('zod');
4
4
  var sha3_js = require('@noble/hashes/sha3.js');
5
5
  var base = require('@scure/base');
6
+ var hmac_js = require('@noble/hashes/hmac.js');
7
+ var sha2_js = require('@noble/hashes/sha2.js');
6
8
 
7
9
  // src/config.ts
8
10
 
@@ -1465,43 +1467,135 @@ var ALLOWED_IMAGE_CONTENT_TYPES = /* @__PURE__ */ new Set([
1465
1467
  ]);
1466
1468
  var MAX_IMAGE_REDIRECTS = 5;
1467
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
+ ]);
1468
1574
  function isPrivateHost(hostname) {
1469
- const h = hostname.toLowerCase().replace(/^\[|\]$/g, "");
1470
- if (h === "localhost" || h === "127.0.0.1" || h === "0.0.0.0") return true;
1471
- if (/^\d+$/.test(h)) {
1472
- const n = parseInt(h, 10);
1473
- if (n === 2130706433 || n === 0 || n >= 2886729728 && n <= 2887778303 || n >= 3232235520 && n <= 3232301055 || n >= 167772160 && n <= 184549375 || n >= 2851995648 && n <= 2852061183) return true;
1474
- }
1475
- if (/^0x[0-9a-f]+$/i.test(h)) {
1476
- const n = parseInt(h, 16);
1477
- if (n === 2130706433 || n === 0 || n >= 2886729728 && n <= 2887778303 || n >= 3232235520 && n <= 3232301055 || n >= 167772160 && n <= 184549375 || n >= 2851995648 && n <= 2852061183) return true;
1478
- }
1479
- if (/^0\d+\.\d+\.\d+\.\d+$/.test(h)) return true;
1480
- if (h === "::1" || /^0*:0*:0*:0*:0*:0*:0*:0*1$/.test(h)) return true;
1481
- const v4mapped = h.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);
1482
- if (v4mapped) return isPrivateHost(v4mapped[1]);
1483
- if (/^10\./.test(h)) return true;
1484
- if (/^172\.(1[6-9]|2\d|3[01])\./.test(h)) return true;
1485
- if (/^192\.168\./.test(h)) return true;
1486
- if (/^169\.254\./.test(h)) return true;
1487
- if (/^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./.test(h)) return true;
1488
- if (/^fe80:/i.test(h)) return true;
1489
- if (/^f[cd][0-9a-f]{2}:/i.test(h)) return true;
1490
- if (h.endsWith(".local")) return true;
1491
- if (h === "metadata.google.internal") return true;
1492
- 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);
1493
1583
  return false;
1494
1584
  }
1495
- function validateUrl(raw) {
1585
+ function validateUrl(raw, options = {}) {
1586
+ const requireHttps = options.requireHttps ?? true;
1496
1587
  let parsed;
1497
1588
  try {
1498
1589
  parsed = new URL(raw);
1499
1590
  } catch {
1500
1591
  return { error: "Invalid url", status: 400 };
1501
1592
  }
1502
- if (parsed.protocol !== "https:") {
1593
+ if (requireHttps && parsed.protocol !== "https:") {
1503
1594
  return { error: "Only https URLs allowed", status: 400 };
1504
1595
  }
1596
+ if (!requireHttps && parsed.protocol !== "https:" && parsed.protocol !== "http:") {
1597
+ return { error: "Only http and https URLs allowed", status: 400 };
1598
+ }
1505
1599
  if (parsed.username || parsed.password) {
1506
1600
  return { error: "URL credentials not allowed", status: 400 };
1507
1601
  }
@@ -1510,6 +1604,111 @@ function validateUrl(raw) {
1510
1604
  }
1511
1605
  return { url: parsed };
1512
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
+ }
1513
1712
 
1514
1713
  // src/server/backend-metadata.ts
1515
1714
  function endpoint(config, path) {
@@ -1559,6 +1758,81 @@ async function getBackendSignedUrl(config, kind = "image") {
1559
1758
  if (!res.ok || !data.data) throw new Error(data.error ?? "Failed to create upload URL");
1560
1759
  return data.data.url;
1561
1760
  }
1761
+ var IDENTITY_PREFIX = "siws_";
1762
+ var ACCOUNT_SESSION_PREFIX = "account_session_";
1763
+ var IDENTITY_DOMAIN = "siws-identity-v1";
1764
+ var ACCOUNT_SESSION_DOMAIN = "account-session-v1";
1765
+ var IDENTITY_TTL_SECONDS = 86400;
1766
+ var ACCOUNT_SESSION_TTL_SECONDS = 30 * 24 * 60 * 60;
1767
+ var CLOCK_SKEW_SECONDS = 60;
1768
+ var encoder = new TextEncoder();
1769
+ var decoder = new TextDecoder();
1770
+ function toHex(bytes) {
1771
+ let out = "";
1772
+ for (const b of bytes) out += b.toString(16).padStart(2, "0");
1773
+ return out;
1774
+ }
1775
+ function sign(secret, domain, payload) {
1776
+ const message = domain === null ? payload : `${domain}.${payload}`;
1777
+ return toHex(hmac_js.hmac(sha2_js.sha256, encoder.encode(secret), encoder.encode(message)));
1778
+ }
1779
+ function constantTimeEquals(a, b) {
1780
+ if (a.length !== b.length) return false;
1781
+ let diff = 0;
1782
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
1783
+ return diff === 0;
1784
+ }
1785
+ function signatureMatches(secret, domain, payload, provided) {
1786
+ return constantTimeEquals(provided, sign(secret, domain, payload)) || constantTimeEquals(provided, sign(secret, null, payload));
1787
+ }
1788
+ function encodePayload(value) {
1789
+ return base.base64urlnopad.encode(encoder.encode(JSON.stringify(value)));
1790
+ }
1791
+ function decodePayload(payload) {
1792
+ try {
1793
+ return JSON.parse(decoder.decode(base.base64urlnopad.decode(payload)));
1794
+ } catch {
1795
+ return null;
1796
+ }
1797
+ }
1798
+ function splitToken(raw, prefix) {
1799
+ if (!raw.startsWith(prefix)) return null;
1800
+ const inner = raw.slice(prefix.length);
1801
+ const dot = inner.lastIndexOf(".");
1802
+ if (dot === -1) return null;
1803
+ return { payload: inner.slice(0, dot), signature: inner.slice(dot + 1) };
1804
+ }
1805
+ function withinLifetime(iat, exp) {
1806
+ if (!iat || !exp) return false;
1807
+ const now = Math.floor(Date.now() / 1e3);
1808
+ return exp >= now && iat <= now + CLOCK_SKEW_SECONDS;
1809
+ }
1810
+ function issueSiwsToken(secret, chain, wallet, ttlSeconds = IDENTITY_TTL_SECONDS) {
1811
+ const iat = Math.floor(Date.now() / 1e3);
1812
+ const payload = encodePayload({ sub: wallet, chain, iat, exp: iat + ttlSeconds });
1813
+ return `${IDENTITY_PREFIX}${payload}.${sign(secret, IDENTITY_DOMAIN, payload)}`;
1814
+ }
1815
+ function verifySiwsToken(secret, raw) {
1816
+ const parts = splitToken(raw, IDENTITY_PREFIX);
1817
+ if (!parts) return null;
1818
+ if (!signatureMatches(secret, IDENTITY_DOMAIN, parts.payload, parts.signature)) return null;
1819
+ const data = decodePayload(parts.payload);
1820
+ if (!data?.sub || !withinLifetime(data.iat, data.exp)) return null;
1821
+ return { address: data.sub, chain: data.chain ?? "STARKNET" };
1822
+ }
1823
+ function issueAccountSessionToken(secret, accountId, ttlSeconds = ACCOUNT_SESSION_TTL_SECONDS) {
1824
+ const iat = Math.floor(Date.now() / 1e3);
1825
+ const payload = encodePayload({ accountId, iat, exp: iat + ttlSeconds });
1826
+ return `${ACCOUNT_SESSION_PREFIX}${payload}.${sign(secret, ACCOUNT_SESSION_DOMAIN, payload)}`;
1827
+ }
1828
+ function verifyAccountSessionToken(secret, raw) {
1829
+ const parts = splitToken(raw, ACCOUNT_SESSION_PREFIX);
1830
+ if (!parts) return null;
1831
+ if (!signatureMatches(secret, ACCOUNT_SESSION_DOMAIN, parts.payload, parts.signature)) return null;
1832
+ const data = decodePayload(parts.payload);
1833
+ if (!data?.accountId || !withinLifetime(data.iat, data.exp)) return null;
1834
+ return data.accountId;
1835
+ }
1562
1836
 
1563
1837
  // src/metadata.ts
1564
1838
  var RESERVED_TRAITS = /* @__PURE__ */ new Set([
@@ -1653,12 +1927,14 @@ function resolveSafeImageContentType(contentType) {
1653
1927
  }
1654
1928
  var MAX_IPFS_GATEWAY_RESPONSE_BYTES = 25 * 1024 * 1024;
1655
1929
 
1930
+ exports.ACCOUNT_SESSION_TTL_SECONDS = ACCOUNT_SESSION_TTL_SECONDS;
1656
1931
  exports.ALLOWED_IMAGE_CONTENT_TYPES = ALLOWED_IMAGE_CONTENT_TYPES;
1657
1932
  exports.ApiClient = ApiClient;
1658
1933
  exports.CHAINS = CHAINS;
1659
1934
  exports.DEFAULT_CHAIN = DEFAULT_CHAIN;
1660
1935
  exports.DEFAULT_CURRENCY = DEFAULT_CURRENCY;
1661
1936
  exports.FeeConfigSchema = FeeConfigSchema;
1937
+ exports.IDENTITY_TTL_SECONDS = IDENTITY_TTL_SECONDS;
1662
1938
  exports.IPFS_SAFE_CONTENT_TYPE_PREFIXES = IPFS_SAFE_CONTENT_TYPE_PREFIXES;
1663
1939
  exports.MAX_IMAGE_PROXY_BYTES = MAX_IMAGE_PROXY_BYTES;
1664
1940
  exports.MAX_IMAGE_REDIRECTS = MAX_IMAGE_REDIRECTS;
@@ -1713,6 +1989,7 @@ exports.coinHref = coinHref;
1713
1989
  exports.collectionHref = collectionHref;
1714
1990
  exports.createBackendProxyHandler = createBackendProxyHandler;
1715
1991
  exports.createFailoverFetch = createFailoverFetch;
1992
+ exports.createImageProxyHandler = createImageProxyHandler;
1716
1993
  exports.createRateLimiter = createRateLimiter;
1717
1994
  exports.createRpcProxyHandler = createRpcProxyHandler;
1718
1995
  exports.encodeU256 = encodeU256;
@@ -1729,14 +2006,18 @@ exports.getTokenBySymbol = getTokenBySymbol;
1729
2006
  exports.hasCapability = hasCapability;
1730
2007
  exports.isPolicyRefusal = isPolicyRefusal;
1731
2008
  exports.isPrivateHost = isPrivateHost;
2009
+ exports.isPrivateOrInsecureUrl = isPrivateOrInsecureUrl;
1732
2010
  exports.isSameOrigin = isSameOrigin;
1733
2011
  exports.isServiceId = isServiceId;
1734
2012
  exports.isTransientRpcError = isTransientRpcError;
1735
2013
  exports.isValidIpfsCidPath = isValidIpfsCidPath;
2014
+ exports.issueAccountSessionToken = issueAccountSessionToken;
2015
+ exports.issueSiwsToken = issueSiwsToken;
1736
2016
  exports.listServices = listServices;
1737
2017
  exports.normalizeAddress = normalizeAddress;
1738
2018
  exports.normalizeHash = normalizeHash;
1739
2019
  exports.parseAmount = parseAmount;
2020
+ exports.readBodyWithCap = readBodyWithCap;
1740
2021
  exports.requestIp = requestIp;
1741
2022
  exports.resolveAppFeeConfig = resolveAppFeeConfig;
1742
2023
  exports.resolveConfig = resolveConfig;
@@ -1750,5 +2031,7 @@ exports.uploadDirectoryToBackend = uploadDirectoryToBackend;
1750
2031
  exports.uploadFileToBackend = uploadFileToBackend;
1751
2032
  exports.uploadJsonToBackend = uploadJsonToBackend;
1752
2033
  exports.validateUrl = validateUrl;
2034
+ exports.verifyAccountSessionToken = verifyAccountSessionToken;
2035
+ exports.verifySiwsToken = verifySiwsToken;
1753
2036
  //# sourceMappingURL=index.cjs.map
1754
2037
  //# sourceMappingURL=index.cjs.map