File size: 83,476 Bytes
dbb1bf9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 | import { strict as assert } from 'node:assert';
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
import http, { createServer, request as httpRequest } from 'node:http';
import https from 'node:https';
import { createHmac } from 'node:crypto';
import { EventEmitter } from 'node:events';
import net from 'node:net';
import { brotliDecompressSync, gunzipSync } from 'node:zlib';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import { createLocalApiServer, __testing__ } from './local-api-server.mjs';
// The sidecar default-denies when LOCAL_API_TOKEN is unset (security fix:
// previously "unset" meant "auth disabled", which made any standalone run
// an open local-HTTP proxy). Set a stable test token + an authFetch helper
// so the existing test cases continue to exercise their original code
// paths instead of the new global auth gate.
const TEST_LOCAL_API_TOKEN = 'sidecar-test-token';
process.env.LOCAL_API_TOKEN = TEST_LOCAL_API_TOKEN;
function authFetch(url, options = {}) {
const headers = { ...(options.headers || {}) };
if (!headers.Authorization && !headers.authorization) {
headers.Authorization = `Bearer ${TEST_LOCAL_API_TOKEN}`;
}
return fetch(url, { ...options, headers });
}
async function listen(server, host = '127.0.0.1', port = 0) {
await new Promise((resolve, reject) => {
const onListening = () => {
server.off('error', onError);
resolve();
};
const onError = (error) => {
server.off('listening', onListening);
reject(error);
};
server.once('listening', onListening);
server.once('error', onError);
server.listen(port, host);
});
const address = server.address();
if (!address || typeof address === 'string') {
throw new Error('Failed to resolve server address');
}
return address.port;
}
async function postJsonViaHttp(url, payload, headers = {}) {
const target = new URL(url);
const body = JSON.stringify(payload);
return new Promise((resolve, reject) => {
const req = httpRequest({
hostname: target.hostname,
port: Number(target.port || 80),
path: `${target.pathname}${target.search}`,
method: 'POST',
headers: {
...headers,
'Content-Type': 'application/json',
'Content-Length': String(Buffer.byteLength(body)),
'Authorization': `Bearer ${process.env.LOCAL_API_TOKEN || ''}`,
},
}, (res) => {
const chunks = [];
res.on('data', (chunk) => chunks.push(chunk));
res.on('end', () => {
const text = Buffer.concat(chunks).toString('utf8');
let json = null;
try { json = JSON.parse(text); } catch { /* non-json response */ }
resolve({ status: res.statusCode || 0, text, json });
});
});
req.on('error', reject);
req.write(body);
req.end();
});
}
async function getJsonViaHttp(url) {
const target = new URL(url);
return new Promise((resolve, reject) => {
const req = httpRequest({
hostname: target.hostname,
port: Number(target.port || 80),
path: `${target.pathname}${target.search}`,
method: 'GET',
headers: {
'Authorization': `Bearer ${process.env.LOCAL_API_TOKEN || ''}`,
},
}, (res) => {
const chunks = [];
res.on('data', (chunk) => chunks.push(chunk));
res.on('end', () => {
const text = Buffer.concat(chunks).toString('utf8');
let json = null;
try { json = JSON.parse(text); } catch { /* non-json response */ }
resolve({ status: res.statusCode || 0, text, json });
});
});
req.on('error', reject);
req.end();
});
}
function mockHttpsRequestOnce({ statusCode, headers, body }) {
const original = https.request;
https.request = (_options, onResponse) => {
const req = new EventEmitter();
req.setTimeout = () => { };
req.write = () => { };
req.destroy = (error) => {
if (error) req.emit('error', error);
};
req.end = () => {
queueMicrotask(() => {
const res = new EventEmitter();
res.statusCode = statusCode;
res.statusMessage = '';
res.headers = headers;
onResponse(res);
if (body) res.emit('data', Buffer.from(body));
res.emit('end');
});
};
return req;
};
return () => {
https.request = original;
};
}
async function setupRemoteServer() {
const hits = [];
const origins = [];
const headers = [];
const server = createServer((req, res) => {
const url = new URL(req.url || '/', 'http://127.0.0.1');
hits.push(url.pathname);
origins.push(req.headers.origin || null);
headers.push(req.headers);
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({
source: 'remote',
path: url.pathname,
origin: req.headers.origin || null,
}));
});
const port = await listen(server);
return {
hits,
origins,
headers,
remoteBase: `http://127.0.0.1:${port}`,
async close() {
await new Promise((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
});
},
};
}
async function setupRegisterInterestRemote() {
const requests = [];
const server = createServer((req, res) => {
const chunks = [];
req.on('data', (chunk) => chunks.push(chunk));
req.on('end', () => {
const body = Buffer.concat(chunks).toString('utf8');
requests.push({
path: req.url,
headers: req.headers,
body,
json: JSON.parse(body),
});
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({ status: 'registered', referralCode: 'abc', referralCount: 0 }));
});
});
const port = await listen(server);
return {
requests,
remoteBase: `http://127.0.0.1:${port}`,
async close() {
await new Promise((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
});
},
};
}
async function setupApiDir(files) {
const tempRoot = await mkdtemp(path.join(os.tmpdir(), 'wm-sidecar-test-'));
const apiDir = path.join(tempRoot, 'api');
await mkdir(apiDir, { recursive: true });
await Promise.all(
Object.entries(files).map(async ([relativePath, source]) => {
const absolute = path.join(apiDir, relativePath);
await mkdir(path.dirname(absolute), { recursive: true });
await writeFile(absolute, source, 'utf8');
})
);
return {
apiDir,
async cleanup() {
await rm(tempRoot, { recursive: true, force: true });
},
};
}
async function setupResourceDirWithUpApi(files) {
const tempRoot = await mkdtemp(path.join(os.tmpdir(), 'wm-sidecar-resource-test-'));
const apiDir = path.join(tempRoot, '_up_', 'api');
await mkdir(apiDir, { recursive: true });
await Promise.all(
Object.entries(files).map(async ([relativePath, source]) => {
const absolute = path.join(apiDir, relativePath);
await mkdir(path.dirname(absolute), { recursive: true });
await writeFile(absolute, source, 'utf8');
})
);
return {
resourceDir: tempRoot,
apiDir,
async cleanup() {
await rm(tempRoot, { recursive: true, force: true });
},
};
}
test('returns local error directly when cloudFallback is off (default)', async () => {
const remote = await setupRemoteServer();
const localApi = await setupApiDir({
'fred-data.js': `
export default async function handler() {
return new Response(JSON.stringify({ source: 'local-error' }), {
status: 500,
headers: { 'content-type': 'application/json' }
});
}
`,
});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
remoteBase: remote.remoteBase,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/fred-data`);
assert.equal(response.status, 500);
const body = await response.json();
assert.equal(body.source, 'local-error');
assert.equal(remote.hits.length, 0);
} finally {
await app.close();
await localApi.cleanup();
await remote.close();
}
});
test('falls back to cloud when cloudFallback is enabled and local handler returns 500', async () => {
const remote = await setupRemoteServer();
const localApi = await setupApiDir({
'fred-data.js': `
export default async function handler() {
return new Response(JSON.stringify({ source: 'local-error' }), {
status: 500,
headers: { 'content-type': 'application/json' }
});
}
`,
});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
remoteBase: remote.remoteBase,
cloudFallback: 'true',
allowPrivateRemoteBase: true,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/fred-data`);
assert.equal(response.status, 200);
const body = await response.json();
assert.equal(body.source, 'remote');
assert.equal(remote.hits.includes('/api/fred-data'), true);
} finally {
await app.close();
await localApi.cleanup();
await remote.close();
}
});
test('preserves POST body when cloud fallback is triggered after local non-OK response', async () => {
const remoteBodies = [];
const remote = createServer((req, res) => {
const chunks = [];
req.on('data', (chunk) => chunks.push(chunk));
req.on('end', () => {
const body = Buffer.concat(chunks).toString('utf8');
remoteBodies.push(body);
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({ source: 'remote', body }));
});
});
const remotePort = await listen(remote);
const localApi = await setupApiDir({
'post-fail.js': `
export default async function handler(req) {
await req.text();
return new Response(JSON.stringify({ source: 'local-error' }), {
status: 500,
headers: { 'content-type': 'application/json' }
});
}
`,
});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
remoteBase: `http://127.0.0.1:${remotePort}`,
cloudFallback: 'true',
allowPrivateRemoteBase: true,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const payload = JSON.stringify({ secret: 'keep-body' });
const response = await authFetch(`http://127.0.0.1:${port}/api/post-fail`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: payload,
});
assert.equal(response.status, 200);
const body = await response.json();
assert.equal(body.source, 'remote');
assert.equal(body.body, payload);
assert.equal(remoteBodies[0], payload);
} finally {
await app.close();
await localApi.cleanup();
await new Promise((resolve, reject) => {
remote.close((error) => (error ? reject(error) : resolve()));
});
}
});
test('signs desktop register-interest cloud fallback when shared secret is configured', async () => {
const originalSecret = process.env.WM_DESKTOP_SHARED_SECRET;
const originalConvex = process.env.CONVEX_URL;
process.env.WM_DESKTOP_SHARED_SECRET = 'desktop-test-secret';
delete process.env.CONVEX_URL;
const remote = await setupRegisterInterestRemote();
const localApi = await setupApiDir({});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
remoteBase: remote.remoteBase,
allowPrivateRemoteBase: true,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await postJsonViaHttp(`http://127.0.0.1:${port}/api/register-interest`, {
email: 'desktop@example.com',
source: 'web-form',
appVersion: '2.8.0',
}, {
'Content-Encoding': 'gzip',
'X-WorldMonitor-Desktop-Timestamp': '1',
'X-WorldMonitor-Desktop-Signature': 'sha256=bad',
});
assert.equal(response.status, 200);
assert.equal(remote.requests.length, 1);
const request = remote.requests[0];
assert.equal(request.path, '/api/leads/v1/register-interest');
assert.equal(request.json.source, 'desktop-settings');
const timestamp = request.headers['x-worldmonitor-desktop-timestamp'];
const signature = request.headers['x-worldmonitor-desktop-signature'];
assert.equal(request.headers['content-encoding'], undefined);
assert.match(request.headers['user-agent'], /Chrome\/131\.0\.0\.0/);
assert.match(timestamp, /^\d+$/);
assert.match(signature, /^sha256=[a-f0-9]{64}$/);
assert.notEqual(timestamp, '1');
assert.notEqual(signature, 'sha256=bad');
const canonical = JSON.stringify({
email: 'desktop@example.com',
source: 'desktop-settings',
appVersion: '2.8.0',
referredBy: '',
website: '',
turnstileToken: '',
});
const expected = `sha256=${createHmac('sha256', process.env.WM_DESKTOP_SHARED_SECRET)
.update(`${timestamp}\n${canonical}`)
.digest('hex')}`;
assert.equal(signature, expected);
} finally {
await app.close();
await localApi.cleanup();
await remote.close();
if (originalSecret === undefined) delete process.env.WM_DESKTOP_SHARED_SECRET;
else process.env.WM_DESKTOP_SHARED_SECRET = originalSecret;
if (originalConvex === undefined) delete process.env.CONVEX_URL;
else process.env.CONVEX_URL = originalConvex;
}
});
test('uses local handler response when local handler succeeds', async () => {
const remote = await setupRemoteServer();
const localApi = await setupApiDir({
'live.js': `
export default async function handler() {
return new Response(JSON.stringify({ source: 'local-ok' }), {
status: 200,
headers: { 'content-type': 'application/json' }
});
}
`,
});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
remoteBase: remote.remoteBase,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/live`);
assert.equal(response.status, 200);
const body = await response.json();
assert.equal(body.source, 'local-ok');
assert.equal(remote.hits.length, 0);
} finally {
await app.close();
await localApi.cleanup();
await remote.close();
}
});
test('returns 404 when local route does not exist and cloudFallback is off', async () => {
const remote = await setupRemoteServer();
const localApi = await setupApiDir({});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
remoteBase: remote.remoteBase,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/not-found`);
assert.equal(response.status, 404);
const body = await response.json();
assert.equal(body.error, 'No local handler for this endpoint');
assert.equal(remote.hits.length, 0);
} finally {
await app.close();
await localApi.cleanup();
await remote.close();
}
});
test('replaces browser origin with localhost origin for local handlers', async () => {
const remote = await setupRemoteServer();
const localApi = await setupApiDir({
'origin-check.js': `
export default async function handler(req) {
const origin = req.headers.get('origin');
return new Response(JSON.stringify({
source: 'local',
originPresent: Boolean(origin),
originValue: origin || null,
}), {
status: 200,
headers: { 'content-type': 'application/json' }
});
}
`,
});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
remoteBase: remote.remoteBase,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/origin-check`, {
headers: { Origin: 'https://tauri.localhost' },
});
assert.equal(response.status, 200);
const body = await response.json();
assert.equal(body.source, 'local');
// Since e14af08f (#709) the server strips the browser Origin but
// immediately replaces it with `http://127.0.0.1:<port>`, so the
// handler does receive an Origin header — just the localhost one.
assert.equal(body.originPresent, true);
assert.equal(body.originValue, `http://127.0.0.1:${port}`);
assert.equal(remote.hits.length, 0);
} finally {
await app.close();
await localApi.cleanup();
await remote.close();
}
});
test('preserves caller Authorization while hiding the sidecar transport token', async () => {
const localApi = await setupApiDir({
'header-check.js': `
export default async function handler(req) {
return new Response(JSON.stringify({
authorization: req.headers.get('authorization'),
transportToken: req.headers.get('x-worldmonitor-local-token'),
}), {
status: 200,
headers: { 'content-type': 'application/json' },
});
}
`,
});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await fetch(`http://127.0.0.1:${port}/api/header-check`, {
headers: {
Authorization: 'Bearer caller-oauth-token',
'X-WorldMonitor-Local-Token': TEST_LOCAL_API_TOKEN,
},
});
assert.equal(response.status, 200);
assert.deepEqual(await response.json(), {
authorization: 'Bearer caller-oauth-token',
transportToken: null,
});
} finally {
await app.close();
await localApi.cleanup();
}
});
test('does not forward the sidecar transport token through Docker cloud proxy routes', async () => {
const originalConvex = process.env.CONVEX_URL;
delete process.env.CONVEX_URL;
const remote = await setupRemoteServer();
const localApi = await setupApiDir({});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
remoteBase: remote.remoteBase,
allowPrivateRemoteBase: true,
mode: 'docker',
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const headers = { 'X-WorldMonitor-Local-Token': TEST_LOCAL_API_TOKEN };
const youtubeResponse = await fetch(`http://127.0.0.1:${port}/api/youtube/live`, { headers });
assert.equal(youtubeResponse.status, 200);
const registerResponse = await fetch(`http://127.0.0.1:${port}/api/register-interest`, {
method: 'POST',
headers: { ...headers, 'Content-Type': 'application/json' },
body: JSON.stringify({ email: 'docker@example.com', source: 'web-form' }),
});
assert.equal(registerResponse.status, 200);
assert.deepEqual(remote.hits, ['/api/youtube/live', '/api/leads/v1/register-interest']);
assert.equal(remote.headers.length, 2);
for (const upstreamHeaders of remote.headers) {
assert.equal(upstreamHeaders['x-worldmonitor-local-token'], undefined);
}
} finally {
await app.close();
await localApi.cleanup();
await remote.close();
if (originalConvex === undefined) delete process.env.CONVEX_URL;
else process.env.CONVEX_URL = originalConvex;
}
});
test('preserves Request body when handler uses fetch(Request)', async () => {
// Use a DISTINCT upstream server (not the sidecar itself) so this test
// exercises real "handler proxies to external host" semantics. The upstream
// is on 127.0.0.1, so it must be opted into the SSRF allowlist via
// allowPrivateFetchOrigins — production startup has no such opt-in.
let receivedBody = '';
const upstream = createServer((req, res) => {
const chunks = [];
req.on('data', (chunk) => chunks.push(chunk));
req.on('end', () => {
receivedBody = Buffer.concat(chunks).toString('utf8');
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({ receivedBody }));
});
});
const upstreamPort = await listen(upstream);
const upstreamOrigin = `http://127.0.0.1:${upstreamPort}`;
process.env.WM_TEST_UPSTREAM = `${upstreamOrigin}/echo`;
const localApi = await setupApiDir({
'request-proxy.js': `
export default async function handler() {
const request = new Request(process.env.WM_TEST_UPSTREAM, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ secret: 'keep-body' }),
});
const upstream = await fetch(request);
const payload = await upstream.text();
return new Response(payload, {
status: upstream.status,
headers: { 'content-type': 'application/json' },
});
}
`,
});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
allowPrivateFetchOrigins: [upstreamOrigin],
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/request-proxy`);
assert.equal(response.status, 200);
const body = await response.json();
assert.equal(body.receivedBody.includes('"secret":"keep-body"'), true);
assert.equal(receivedBody.includes('"secret":"keep-body"'), true);
} finally {
delete process.env.WM_TEST_UPSTREAM;
await app.close();
await localApi.cleanup();
await new Promise((resolve, reject) => {
upstream.close((error) => (error ? reject(error) : resolve()));
});
}
});
test('returns local handler error when fetch(Request) uses a consumed body', async () => {
let upstreamHits = 0;
const upstream = createServer((_req, res) => {
upstreamHits += 1;
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({ ok: true }));
});
const upstreamPort = await listen(upstream);
const upstreamOrigin = `http://127.0.0.1:${upstreamPort}`;
process.env.WM_TEST_UPSTREAM = `${upstreamOrigin}/echo`;
const localApi = await setupApiDir({
'request-consumed.js': `
export default async function handler() {
const request = new Request(process.env.WM_TEST_UPSTREAM, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ secret: 'used-body' }),
});
await request.text();
await fetch(request);
return new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: { 'content-type': 'application/json' },
});
}
`,
});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
allowPrivateFetchOrigins: [upstreamOrigin],
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/request-consumed`);
assert.equal(response.status, 502);
const body = await response.json();
assert.equal(body.error, 'Local handler error');
assert.equal(typeof body.reason, 'string');
assert.equal(body.reason.length > 0, true);
assert.equal(upstreamHits, 0);
} finally {
delete process.env.WM_TEST_UPSTREAM;
await app.close();
await localApi.cleanup();
await new Promise((resolve, reject) => {
upstream.close((error) => (error ? reject(error) : resolve()));
});
}
});
test('blocks handler global fetches to private network targets (#3549)', async () => {
let upstreamHits = 0;
const upstream = createServer((_req, res) => {
upstreamHits += 1;
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({ ok: true }));
});
const upstreamPort = await listen(upstream);
process.env.WM_TEST_UPSTREAM = `http://127.0.0.1:${upstreamPort}/secret?token=super-secret`;
const localApi = await setupApiDir({
'private-proxy.js': `
export default async function handler() {
const upstream = await fetch(process.env.WM_TEST_UPSTREAM);
const payload = await upstream.text();
return new Response(payload, {
status: upstream.status,
headers: { 'content-type': 'application/json' },
});
}
`,
});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/private-proxy`);
assert.equal(response.status, 502);
const body = await response.json();
assert.equal(body.error, 'Local handler error');
assert.match(body.reason, /SSRF blocked/);
assert.doesNotMatch(body.reason, /super-secret/);
assert.equal(upstreamHits, 0);
} finally {
delete process.env.WM_TEST_UPSTREAM;
await app.close();
await localApi.cleanup();
await new Promise((resolve, reject) => {
upstream.close((error) => (error ? reject(error) : resolve()));
});
}
});
test('allows only Docker mode to fetch configured private Redis REST origin', async () => {
const originalRedisUrl = process.env.UPSTASH_REDIS_REST_URL;
const originalRedisToken = process.env.UPSTASH_REDIS_REST_TOKEN;
let upstreamHits = 0;
const upstream = createServer((_req, res) => {
upstreamHits += 1;
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({ ok: true }));
});
const upstreamPort = await listen(upstream);
const redisOrigin = `http://127.0.0.1:${upstreamPort}`;
const localApi = await setupApiDir({
'redis-probe.js': `
export default async function handler() {
const upstream = await fetch(process.env.UPSTASH_REDIS_REST_URL + '/ping', {
headers: { Authorization: 'Bearer ' + process.env.UPSTASH_REDIS_REST_TOKEN },
});
const payload = await upstream.text();
return new Response(payload, {
status: upstream.status,
headers: { 'content-type': 'application/json' },
});
}
`,
});
async function runProbe(mode) {
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
mode,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
return await authFetch(`http://127.0.0.1:${port}/api/redis-probe`);
} finally {
await app.close();
}
}
process.env.UPSTASH_REDIS_REST_URL = redisOrigin;
process.env.UPSTASH_REDIS_REST_TOKEN = 'test-token';
try {
const dockerResponse = await runProbe('docker');
assert.equal(dockerResponse.status, 200);
assert.deepEqual(await dockerResponse.json(), { ok: true });
assert.equal(upstreamHits, 1);
const desktopResponse = await runProbe('desktop-sidecar');
assert.equal(desktopResponse.status, 502);
const desktopBody = await desktopResponse.json();
assert.equal(desktopBody.error, 'Local handler error');
assert.match(desktopBody.reason, /SSRF blocked/);
assert.equal(upstreamHits, 1);
} finally {
if (originalRedisUrl === undefined) delete process.env.UPSTASH_REDIS_REST_URL;
else process.env.UPSTASH_REDIS_REST_URL = originalRedisUrl;
if (originalRedisToken === undefined) delete process.env.UPSTASH_REDIS_REST_TOKEN;
else process.env.UPSTASH_REDIS_REST_TOKEN = originalRedisToken;
await localApi.cleanup();
await new Promise((resolve, reject) => {
upstream.close((error) => (error ? reject(error) : resolve()));
});
}
});
test('blocks handler global fetches to non-global IPv4 special ranges', async () => {
const originalHttpRequest = http.request;
const blockedUrls = [
'http://100.64.0.1/secret',
'http://198.18.0.1/secret',
'http://192.0.0.1/secret',
'http://192.0.2.1/secret',
'http://192.88.99.1/secret',
'http://198.51.100.1/secret',
'http://203.0.113.1/secret',
'http://240.0.0.1/secret',
];
let outboundHits = 0;
http.request = (options, onResponse) => {
if (options.hostname === '127.0.0.1') {
return originalHttpRequest.call(http, options, onResponse);
}
outboundHits += 1;
const req = new EventEmitter();
req.setTimeout = () => {};
req.write = () => {};
req.destroy = (error) => {
if (error) req.emit('error', error);
};
req.end = () => {
setImmediate(() => req.emit('error', new Error(`unexpected outbound request to ${options.hostname}`)));
};
return req;
};
const localApi = await setupApiDir({
'special-range-proxy.js': `
export default async function handler(request) {
const url = new URL(request.url);
const upstream = await fetch(url.searchParams.get('target'));
const payload = await upstream.text();
return new Response(payload, {
status: upstream.status,
headers: { 'content-type': 'application/json' },
});
}
`,
});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
for (const blockedUrl of blockedUrls) {
const response = await authFetch(`http://127.0.0.1:${port}/api/special-range-proxy?target=${encodeURIComponent(blockedUrl)}`);
assert.equal(response.status, 502, blockedUrl);
const body = await response.json();
assert.equal(body.error, 'Local handler error', blockedUrl);
assert.match(body.reason, /SSRF blocked/, blockedUrl);
}
assert.equal(outboundHits, 0);
} finally {
http.request = originalHttpRequest;
await app.close();
await localApi.cleanup();
}
});
test('uses asynchronous pinned lookup callback for handler global fetches (#3549)', async () => {
const originalHttpsRequest = https.request;
const envSnapshot = {
GROQ_API_KEY: process.env.GROQ_API_KEY,
OPENROUTER_API_KEY: process.env.OPENROUTER_API_KEY,
OLLAMA_API_URL: process.env.OLLAMA_API_URL,
LLM_API_URL: process.env.LLM_API_URL,
};
let lookupCallbackWasSync = null;
delete process.env.GROQ_API_KEY;
delete process.env.OPENROUTER_API_KEY;
delete process.env.OLLAMA_API_URL;
delete process.env.LLM_API_URL;
https.request = (options, onResponse) => {
assert.equal(options.hostname, '93.184.216.34');
assert.equal(typeof options.lookup, 'function');
let sync = true;
options.lookup(options.hostname, { family: 4 }, (error, address, family) => {
assert.ifError(error);
assert.equal(address, '93.184.216.34');
assert.equal(family, 4);
lookupCallbackWasSync = sync;
});
sync = false;
const req = new EventEmitter();
req.setTimeout = () => {};
req.write = () => {};
req.destroy = (error) => {
if (error) req.emit('error', error);
};
req.end = () => {
setImmediate(() => {
const res = new EventEmitter();
res.statusCode = 200;
res.statusMessage = 'OK';
res.headers = { 'content-type': 'application/json' };
onResponse(res);
res.emit('data', Buffer.from(JSON.stringify({ ok: true })));
res.emit('end');
});
};
return req;
};
const localApi = await setupApiDir({
'public-proxy.js': `
export default async function handler() {
const upstream = await fetch('https://93.184.216.34/data');
const payload = await upstream.text();
return new Response(payload, {
status: upstream.status,
headers: { 'content-type': 'application/json' },
});
}
`,
});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/public-proxy`);
assert.equal(response.status, 200);
assert.equal(lookupCallbackWasSync, false);
} finally {
https.request = originalHttpsRequest;
for (const [key, value] of Object.entries(envSnapshot)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
await app.close();
await localApi.cleanup();
}
});
test('uses IPv4 sidecar fetch for allowed private-network LLM probes (#3549)', async () => {
const originalHttpRequest = http.request;
const envSnapshot = {
GROQ_API_KEY: process.env.GROQ_API_KEY,
OPENROUTER_API_KEY: process.env.OPENROUTER_API_KEY,
OLLAMA_API_URL: process.env.OLLAMA_API_URL,
LLM_API_URL: process.env.LLM_API_URL,
};
let sawOllamaProbe = false;
delete process.env.GROQ_API_KEY;
delete process.env.OPENROUTER_API_KEY;
delete process.env.LLM_API_URL;
process.env.OLLAMA_API_URL = 'http://ollama.test:11434';
http.request = (options, onResponse) => {
if (options.hostname !== 'ollama.test') {
return originalHttpRequest.call(http, options, onResponse);
}
sawOllamaProbe = true;
assert.equal(options.family, 4);
assert.equal(options.path, '/');
const req = new EventEmitter();
req.setTimeout = () => {};
req.write = () => {};
req.destroy = (error) => {
if (error) req.emit('error', error);
};
req.end = () => {
setImmediate(() => {
const res = new EventEmitter();
res.statusCode = 200;
res.statusMessage = 'OK';
res.headers = { 'content-type': 'application/json' };
onResponse(res);
res.emit('data', Buffer.from(JSON.stringify({ ok: true })));
res.emit('end');
});
};
return req;
};
const localApi = await setupApiDir({});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await getJsonViaHttp(`http://127.0.0.1:${port}/api/llm-health`);
assert.equal(response.status, 200);
assert.equal(response.json.available, true);
assert.deepEqual(response.json.providers, [
{ name: 'ollama', url: 'http://ollama.test:11434', available: true },
]);
assert.equal(sawOllamaProbe, true);
} finally {
http.request = originalHttpRequest;
for (const [key, value] of Object.entries(envSnapshot)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
await app.close();
await localApi.cleanup();
}
});
test('uses canonical app origin when proxying to cloud fallback (cloudFallback enabled)', async () => {
const remote = await setupRemoteServer();
const localApi = await setupApiDir({});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
remoteBase: remote.remoteBase,
cloudFallback: 'true',
allowPrivateRemoteBase: true,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/no-local-handler`, {
headers: { Origin: 'https://tauri.localhost' },
});
assert.equal(response.status, 200);
const body = await response.json();
assert.equal(body.source, 'remote');
assert.equal(body.origin, 'https://worldmonitor.app');
assert.equal(remote.origins[0], 'https://worldmonitor.app');
} finally {
await app.close();
await localApi.cleanup();
await remote.close();
}
});
test('blocks cloud fallback in Docker mode even when explicitly requested', async () => {
const remote = await setupRemoteServer();
const localApi = await setupApiDir({
'docker-test.js': `
export default async function handler() {
return new Response(JSON.stringify({ source: 'local-error' }), {
status: 500,
headers: { 'content-type': 'application/json' }
});
}
`,
});
const warnings = [];
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
remoteBase: remote.remoteBase,
cloudFallback: 'true',
mode: 'docker',
logger: { log() {}, warn(...args) { warnings.push(args.join(' ')); }, error() {} },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/docker-test`);
// Should NOT fall back to cloud; should return the local 500 directly
assert.equal(response.status, 500);
const body = await response.json();
assert.equal(body.source, 'local-error');
// Should have logged a warning about Docker mode blocking fallback
assert.ok(warnings.some(w => w.includes('Docker mode')), 'Should warn about Docker mode blocking fallback');
} finally {
await app.close();
await localApi.cleanup();
await remote.close();
}
});
test('responds to OPTIONS preflight with CORS headers', async () => {
const localApi = await setupApiDir({
'data.js': `
export default async function handler() {
return new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } });
}
`,
});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/data`, { method: 'OPTIONS' });
assert.equal(response.status, 204);
assert.equal(response.headers.get('access-control-allow-methods'), 'GET, POST, PUT, DELETE, OPTIONS');
} finally {
await app.close();
await localApi.cleanup();
}
});
test('preserves Origin in Vary when gzip compression is applied', async () => {
const localApi = await setupApiDir({
'large.js': `
export default async function handler() {
return new Response(JSON.stringify({ payload: 'x'.repeat(4096) }), {
status: 200,
headers: { 'content-type': 'application/json' }
});
}
`,
});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/large`, {
headers: {
Origin: 'https://tauri.localhost',
'Accept-Encoding': 'gzip',
},
});
assert.equal(response.status, 200);
assert.equal(response.headers.get('access-control-allow-origin'), 'https://tauri.localhost');
assert.equal(response.headers.get('content-encoding'), 'gzip');
const vary = (response.headers.get('vary') || '')
.split(',')
.map((part) => part.trim().toLowerCase())
.filter(Boolean);
assert.equal(vary.includes('origin'), true);
assert.equal(vary.includes('accept-encoding'), true);
} finally {
await app.close();
await localApi.cleanup();
}
});
test('resolves packaged tauri resource layout under _up_/api', async () => {
const remote = await setupRemoteServer();
const localResource = await setupResourceDirWithUpApi({
'live.js': `
export default async function handler() {
return new Response(JSON.stringify({ source: 'local-up' }), {
status: 200,
headers: { 'content-type': 'application/json' }
});
}
`,
});
const app = await createLocalApiServer({
port: 0,
resourceDir: localResource.resourceDir,
remoteBase: remote.remoteBase,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
assert.equal(app.context.apiDir, localResource.apiDir);
assert.equal(app.routes.length, 1);
const response = await authFetch(`http://127.0.0.1:${port}/api/live`);
assert.equal(response.status, 200);
const body = await response.json();
assert.equal(body.source, 'local-up');
assert.equal(remote.hits.length, 0);
} finally {
await app.close();
await localResource.cleanup();
await remote.close();
}
});
// ── Ollama env key allowlist + validation tests ──
test('accepts OLLAMA_API_URL via /api/local-env-update', async () => {
const localApi = await setupApiDir({});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/local-env-update`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'OLLAMA_API_URL', value: 'http://127.0.0.1:11434' }),
});
assert.equal(response.status, 200);
const body = await response.json();
assert.equal(body.ok, true);
assert.equal(body.key, 'OLLAMA_API_URL');
assert.equal(process.env.OLLAMA_API_URL, 'http://127.0.0.1:11434');
} finally {
delete process.env.OLLAMA_API_URL;
await app.close();
await localApi.cleanup();
}
});
test('accepts OLLAMA_MODEL via /api/local-env-update', async () => {
const localApi = await setupApiDir({});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/local-env-update`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'OLLAMA_MODEL', value: 'llama3.1:8b' }),
});
assert.equal(response.status, 200);
const body = await response.json();
assert.equal(body.ok, true);
assert.equal(body.key, 'OLLAMA_MODEL');
assert.equal(process.env.OLLAMA_MODEL, 'llama3.1:8b');
} finally {
delete process.env.OLLAMA_MODEL;
await app.close();
await localApi.cleanup();
}
});
test('accepts WM_DESKTOP_SHARED_SECRET via /api/local-env-update', async () => {
const originalSecret = process.env.WM_DESKTOP_SHARED_SECRET;
const localApi = await setupApiDir({});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/local-env-update`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'WM_DESKTOP_SHARED_SECRET', value: 'desktop-secret-from-runtime' }),
});
assert.equal(response.status, 200);
const body = await response.json();
assert.equal(body.ok, true);
assert.equal(body.key, 'WM_DESKTOP_SHARED_SECRET');
assert.equal(process.env.WM_DESKTOP_SHARED_SECRET, 'desktop-secret-from-runtime');
} finally {
if (originalSecret === undefined) delete process.env.WM_DESKTOP_SHARED_SECRET;
else process.env.WM_DESKTOP_SHARED_SECRET = originalSecret;
await app.close();
await localApi.cleanup();
}
});
test('validates WM_DESKTOP_SHARED_SECRET without provider probe', async () => {
const localApi = await setupApiDir({});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/local-validate-secret`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'WM_DESKTOP_SHARED_SECRET', value: 'desktop-secret-from-runtime' }),
});
assert.equal(response.status, 200);
const body = await response.json();
assert.equal(body.valid, true);
assert.equal(body.message, 'Desktop shared secret stored');
} finally {
await app.close();
await localApi.cleanup();
}
});
test('rejects unknown key via /api/local-env-update', async () => {
const localApi = await setupApiDir({});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/local-env-update`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'NOT_ALLOWED_KEY', value: 'some-value' }),
});
assert.equal(response.status, 403);
const body = await response.json();
assert.equal(body.error, 'key not in allowlist');
} finally {
await app.close();
await localApi.cleanup();
}
});
test('validates OLLAMA_API_URL via /api/local-validate-secret (reachable endpoint)', async () => {
// Stand up a mock Ollama server that responds to /v1/models
const mockOllama = createServer((req, res) => {
if (req.url === '/v1/models') {
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({ data: [{ id: 'llama3.1:8b' }] }));
} else {
res.writeHead(404);
res.end('not found');
}
});
const ollamaPort = await listen(mockOllama);
const localApi = await setupApiDir({});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/local-validate-secret`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'OLLAMA_API_URL', value: `http://127.0.0.1:${ollamaPort}` }),
});
assert.equal(response.status, 200);
const body = await response.json();
assert.equal(body.valid, true);
assert.equal(body.message, 'Ollama endpoint verified');
} finally {
await app.close();
await localApi.cleanup();
await new Promise((resolve, reject) => {
mockOllama.close((err) => (err ? reject(err) : resolve()));
});
}
});
test('validates LM Studio style /v1 base URL via /api/local-validate-secret', async () => {
const mockOpenAiCompatible = createServer((req, res) => {
if (req.url === '/v1/models') {
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({ data: [{ id: 'qwen2.5-7b-instruct' }] }));
} else {
res.writeHead(404);
res.end('not found');
}
});
const providerPort = await listen(mockOpenAiCompatible);
const localApi = await setupApiDir({});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/local-validate-secret`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'OLLAMA_API_URL', value: `http://127.0.0.1:${providerPort}/v1` }),
});
assert.equal(response.status, 200);
const body = await response.json();
assert.equal(body.valid, true);
assert.equal(body.message, 'Ollama endpoint verified');
} finally {
await app.close();
await localApi.cleanup();
await new Promise((resolve, reject) => {
mockOpenAiCompatible.close((err) => (err ? reject(err) : resolve()));
});
}
});
test('validates OLLAMA_API_URL via native /api/tags fallback', async () => {
// Mock server that only responds to /api/tags (not /v1/models)
const mockOllama = createServer((req, res) => {
if (req.url === '/api/tags') {
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({ models: [{ name: 'llama3.1:8b' }] }));
} else {
res.writeHead(404);
res.end('not found');
}
});
const ollamaPort = await listen(mockOllama);
const localApi = await setupApiDir({});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/local-validate-secret`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'OLLAMA_API_URL', value: `http://127.0.0.1:${ollamaPort}` }),
});
assert.equal(response.status, 200);
const body = await response.json();
assert.equal(body.valid, true);
assert.equal(body.message, 'Ollama endpoint verified (native API)');
} finally {
await app.close();
await localApi.cleanup();
await new Promise((resolve, reject) => {
mockOllama.close((err) => (err ? reject(err) : resolve()));
});
}
});
test('validates OLLAMA_MODEL stores model name', async () => {
const localApi = await setupApiDir({});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/local-validate-secret`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'OLLAMA_MODEL', value: 'mistral:7b' }),
});
assert.equal(response.status, 200);
const body = await response.json();
assert.equal(body.valid, true);
assert.equal(body.message, 'Model name stored');
} finally {
await app.close();
await localApi.cleanup();
}
});
test('rejects OLLAMA_API_URL with non-http protocol', async () => {
const localApi = await setupApiDir({});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/local-validate-secret`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'OLLAMA_API_URL', value: 'ftp://127.0.0.1:11434' }),
});
assert.equal(response.status, 422);
const body = await response.json();
assert.equal(body.valid, false);
assert.equal(body.message, 'Must be an http(s) URL');
} finally {
await app.close();
await localApi.cleanup();
}
});
test('treats Cloudflare challenge 403 as soft-pass during secret validation', async () => {
const localApi = await setupApiDir({});
const restoreHttps = mockHttpsRequestOnce({
statusCode: 403,
headers: {
'content-type': 'text/html; charset=utf-8',
'cf-ray': 'abc123',
},
body: '<html><title>Attention Required</title><body>Cloudflare Ray ID: 123</body></html>',
});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await postJsonViaHttp(`http://127.0.0.1:${port}/api/local-validate-secret`, {
key: 'GROQ_API_KEY',
value: 'dummy-key',
});
assert.equal(response.status, 200);
assert.equal(response.json?.valid, true);
assert.equal(response.json?.message, 'Groq key stored (Cloudflare blocked verification)');
} finally {
restoreHttps();
await app.close();
await localApi.cleanup();
}
});
test('does not soft-pass provider auth 403 JSON responses even with cf-ray header', async () => {
const localApi = await setupApiDir({});
const restoreHttps = mockHttpsRequestOnce({
statusCode: 403,
headers: {
'content-type': 'application/json',
'cf-ray': 'abc123',
},
body: JSON.stringify({ error: 'invalid api key' }),
});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await postJsonViaHttp(`http://127.0.0.1:${port}/api/local-validate-secret`, {
key: 'GROQ_API_KEY',
value: 'invalid-key',
});
assert.equal(response.status, 422);
assert.equal(response.json?.valid, false);
assert.equal(response.json?.message, 'Groq rejected this key');
} finally {
restoreHttps();
await app.close();
await localApi.cleanup();
}
});
test('auth-required behavior unchanged — rejects unauthenticated requests when token is set', async () => {
const localApi = await setupApiDir({});
const originalToken = process.env.LOCAL_API_TOKEN;
process.env.LOCAL_API_TOKEN = 'secret-token-123';
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
// Request without auth header should be rejected
const response = await fetch(`http://127.0.0.1:${port}/api/local-env-update`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'OLLAMA_API_URL', value: 'http://127.0.0.1:11434' }),
});
assert.equal(response.status, 401);
const body = await response.json();
assert.equal(body.error, 'Unauthorized');
// Request with correct auth header should succeed
const authedResponse = await authFetch(`http://127.0.0.1:${port}/api/local-env-update`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer secret-token-123',
},
body: JSON.stringify({ key: 'OLLAMA_API_URL', value: 'http://127.0.0.1:11434' }),
});
assert.equal(authedResponse.status, 200);
} finally {
if (originalToken !== undefined) {
process.env.LOCAL_API_TOKEN = originalToken;
} else {
delete process.env.LOCAL_API_TOKEN;
}
delete process.env.OLLAMA_API_URL;
await app.close();
await localApi.cleanup();
}
});
test('prefers Brotli compression for payloads larger than 1KB when supported by the client', async () => {
const remote = await setupRemoteServer();
const localApi = await setupApiDir({
'compression-check.js': `
export default async function handler() {
const payload = { value: 'x'.repeat(3000) };
return new Response(JSON.stringify(payload), {
status: 200,
headers: { 'content-type': 'application/json' }
});
}
`,
});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
remoteBase: remote.remoteBase,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/compression-check`, {
headers: { 'Accept-Encoding': 'gzip, br' },
});
assert.equal(response.status, 200);
assert.equal(response.headers.get('content-encoding'), 'br');
const compressed = Buffer.from(await response.arrayBuffer());
const decompressed = brotliDecompressSync(compressed).toString('utf8');
const body = JSON.parse(decompressed);
assert.equal(body.value.length, 3000);
assert.equal(remote.hits.length, 0);
} finally {
await app.close();
await localApi.cleanup();
await remote.close();
}
});
test('uses gzip compression when Brotli is unavailable but gzip is accepted', async () => {
const remote = await setupRemoteServer();
const localApi = await setupApiDir({
'compression-check.js': `
export default async function handler() {
const payload = { value: 'x'.repeat(3000) };
return new Response(JSON.stringify(payload), {
status: 200,
headers: { 'content-type': 'application/json' }
});
}
`,
});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
remoteBase: remote.remoteBase,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/compression-check`, {
headers: { 'Accept-Encoding': 'gzip' },
});
assert.equal(response.status, 200);
assert.equal(response.headers.get('content-encoding'), 'gzip');
const compressed = Buffer.from(await response.arrayBuffer());
const decompressed = gunzipSync(compressed).toString('utf8');
const body = JSON.parse(decompressed);
assert.equal(body.value.length, 3000);
assert.equal(remote.hits.length, 0);
} finally {
await app.close();
await localApi.cleanup();
await remote.close();
}
});
// ── Security hardening tests ────────────────────────────────────────────
test('rejects unauthenticated requests to /api/local-status when token is set', async () => {
const localApi = await setupApiDir({});
const originalToken = process.env.LOCAL_API_TOKEN;
process.env.LOCAL_API_TOKEN = 'security-test-token';
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await fetch(`http://127.0.0.1:${port}/api/local-status`);
assert.equal(response.status, 401);
const body = await response.json();
assert.equal(body.error, 'Unauthorized');
// With token should succeed
const authed = await fetch(`http://127.0.0.1:${port}/api/local-status`, {
headers: { 'Authorization': 'Bearer security-test-token' },
});
assert.equal(authed.status, 200);
} finally {
if (originalToken !== undefined) {
process.env.LOCAL_API_TOKEN = originalToken;
} else {
delete process.env.LOCAL_API_TOKEN;
}
await app.close();
await localApi.cleanup();
}
});
test('rejects unauthenticated requests to /api/local-traffic-log when token is set', async () => {
const localApi = await setupApiDir({});
const originalToken = process.env.LOCAL_API_TOKEN;
process.env.LOCAL_API_TOKEN = 'security-test-token';
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await fetch(`http://127.0.0.1:${port}/api/local-traffic-log`);
assert.equal(response.status, 401);
} finally {
if (originalToken !== undefined) {
process.env.LOCAL_API_TOKEN = originalToken;
} else {
delete process.env.LOCAL_API_TOKEN;
}
await app.close();
await localApi.cleanup();
}
});
test('rejects unauthenticated requests to /api/local-debug-toggle when token is set', async () => {
const localApi = await setupApiDir({});
const originalToken = process.env.LOCAL_API_TOKEN;
process.env.LOCAL_API_TOKEN = 'security-test-token';
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await fetch(`http://127.0.0.1:${port}/api/local-debug-toggle`);
assert.equal(response.status, 401);
} finally {
if (originalToken !== undefined) {
process.env.LOCAL_API_TOKEN = originalToken;
} else {
delete process.env.LOCAL_API_TOKEN;
}
await app.close();
await localApi.cleanup();
}
});
test('rejects unauthenticated requests to /api/rss-proxy when token is set', async () => {
const localApi = await setupApiDir({});
const originalToken = process.env.LOCAL_API_TOKEN;
process.env.LOCAL_API_TOKEN = 'security-test-token';
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await fetch(`http://127.0.0.1:${port}/api/rss-proxy?url=https://example.com/rss`);
assert.equal(response.status, 401);
} finally {
if (originalToken !== undefined) {
process.env.LOCAL_API_TOKEN = originalToken;
} else {
delete process.env.LOCAL_API_TOKEN;
}
await app.close();
await localApi.cleanup();
}
});
test('allows unauthenticated requests to /api/service-status (health check exempt)', async () => {
const localApi = await setupApiDir({});
const originalToken = process.env.LOCAL_API_TOKEN;
process.env.LOCAL_API_TOKEN = 'security-test-token';
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await fetch(`http://127.0.0.1:${port}/api/service-status`);
assert.equal(response.status, 200);
const body = await response.json();
assert.equal(body.success, true);
} finally {
if (originalToken !== undefined) {
process.env.LOCAL_API_TOKEN = originalToken;
} else {
delete process.env.LOCAL_API_TOKEN;
}
await app.close();
await localApi.cleanup();
}
});
test('allows unauthenticated requests to /api/sidecar-health (container healthcheck exempt)', async () => {
const localApi = await setupApiDir({});
const originalToken = process.env.LOCAL_API_TOKEN;
process.env.LOCAL_API_TOKEN = 'security-test-token';
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await fetch(`http://127.0.0.1:${port}/api/sidecar-health`);
assert.equal(response.status, 200);
const body = await response.json();
assert.equal(body.status, 'ok');
assert.equal(body.port, port);
} finally {
if (originalToken !== undefined) {
process.env.LOCAL_API_TOKEN = originalToken;
} else {
delete process.env.LOCAL_API_TOKEN;
}
await app.close();
await localApi.cleanup();
}
});
test('/api/health?compact=1 still dispatches to the bundled health handler', async () => {
const localApi = await setupApiDir({
'health.js': `
export default async function handler(req) {
return new Response(JSON.stringify({
source: 'bundled-health',
url: req.url,
}), { headers: { 'content-type': 'application/json' } });
}
`,
});
const originalToken = process.env.LOCAL_API_TOKEN;
process.env.LOCAL_API_TOKEN = 'security-test-token';
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await fetch(`http://127.0.0.1:${port}/api/health?compact=1`, {
headers: { Authorization: 'Bearer security-test-token' },
});
assert.equal(response.status, 200);
const body = await response.json();
assert.equal(body.source, 'bundled-health');
assert.match(body.url, /\/api\/health\?compact=1$/);
} finally {
if (originalToken !== undefined) {
process.env.LOCAL_API_TOKEN = originalToken;
} else {
delete process.env.LOCAL_API_TOKEN;
}
await app.close();
await localApi.cleanup();
}
});
test('default-deny: rejects every authenticated route when LOCAL_API_TOKEN is unset', async () => {
// Regression for the security advisory fix: previously, an unset
// LOCAL_API_TOKEN was treated as "auth disabled", which made any
// standalone sidecar (Docker, manual launch) an open local-HTTP
// proxy. The expected behaviour is now "fail closed": no token →
// every gated request returns 503.
const localApi = await setupApiDir({});
const originalToken = process.env.LOCAL_API_TOKEN;
delete process.env.LOCAL_API_TOKEN;
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
// Gated route: must 503 even when the caller would otherwise be valid.
const gated = await fetch(`http://127.0.0.1:${port}/api/local-status`, {
headers: { Authorization: 'Bearer anything' },
});
assert.equal(gated.status, 503);
const body = await gated.json();
assert.match(body.error, /LOCAL_API_TOKEN/);
// Health check is still exempt — it runs before the auth gate so
// operators can probe a misconfigured sidecar.
const health = await fetch(`http://127.0.0.1:${port}/api/sidecar-health`);
assert.equal(health.status, 200);
} finally {
if (originalToken !== undefined) {
process.env.LOCAL_API_TOKEN = originalToken;
}
await app.close();
await localApi.cleanup();
}
});
test('rss-proxy blocks requests to localhost (SSRF protection)', async () => {
const localApi = await setupApiDir({});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/rss-proxy?url=http://127.0.0.1:3000`);
assert.equal(response.status, 403);
const body = await response.json();
assert.ok(body.error.includes('private') || body.error.includes('localhost'));
} finally {
await app.close();
await localApi.cleanup();
}
});
test('rss-proxy blocks requests to private IP ranges (SSRF protection)', async () => {
const localApi = await setupApiDir({});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
// Test 192.168.x.x range
const response1 = await authFetch(`http://127.0.0.1:${port}/api/rss-proxy?url=http://192.168.1.1/`);
assert.equal(response1.status, 403);
// Test 10.x.x.x range
const response2 = await authFetch(`http://127.0.0.1:${port}/api/rss-proxy?url=http://10.0.0.1/`);
assert.equal(response2.status, 403);
// Test 172.16-31.x.x range
const response3 = await authFetch(`http://127.0.0.1:${port}/api/rss-proxy?url=http://172.16.0.1/`);
assert.equal(response3.status, 403);
} finally {
await app.close();
await localApi.cleanup();
}
});
test('rss-proxy blocks non-http protocols (SSRF protection)', async () => {
const localApi = await setupApiDir({});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/rss-proxy?url=file:///etc/passwd`);
assert.equal(response.status, 403);
const body = await response.json();
assert.ok(body.error.includes('http'));
} finally {
await app.close();
await localApi.cleanup();
}
});
test('rss-proxy blocks URLs with credentials (SSRF protection)', async () => {
const localApi = await setupApiDir({});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
const response = await authFetch(`http://127.0.0.1:${port}/api/rss-proxy?url=http://user:pass@example.com/rss`);
assert.equal(response.status, 403);
const body = await response.json();
assert.ok(body.error.includes('credentials'));
} finally {
await app.close();
await localApi.cleanup();
}
});
test('traffic log strips query strings from entries to protect privacy', async () => {
const localApi = await setupApiDir({
'test-endpoint.js': `
export default async function handler() {
return new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: { 'content-type': 'application/json' }
});
}
`,
});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
// Make a request that will be recorded in the traffic log
await authFetch(`http://127.0.0.1:${port}/api/test-endpoint?secret=value&key=data`);
// Retrieve the traffic log
const logResponse = await authFetch(`http://127.0.0.1:${port}/api/local-traffic-log`);
assert.equal(logResponse.status, 200);
const logBody = await logResponse.json();
// Verify query strings are stripped
const entry = logBody.entries.find(e => e.path.includes('test-endpoint'));
assert.ok(entry, 'Traffic log should contain the test-endpoint entry');
assert.equal(entry.path, '/api/test-endpoint');
assert.ok(!entry.path.includes('secret='), 'Query string should be stripped from traffic log');
} finally {
await app.close();
await localApi.cleanup();
}
});
test('service-status reports bound fallback port after EADDRINUSE recovery', async () => {
const blocker = createServer((_req, res) => {
res.writeHead(200, { 'content-type': 'text/plain' });
res.end('occupied');
});
await listen(blocker, '127.0.0.1', 46123);
const localApi = await setupApiDir({});
const app = await createLocalApiServer({
port: 46123,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
});
const { port } = await app.start();
try {
assert.notEqual(port, 46123);
const response = await authFetch(`http://127.0.0.1:${port}/api/service-status`);
assert.equal(response.status, 200);
const body = await response.json();
assert.equal(body.local.port, port);
const localService = body.services.find((service) => service.id === 'local-api');
assert.equal(localService.description, `Running on 127.0.0.1:${port}`);
} finally {
await app.close();
await localApi.cleanup();
await new Promise((resolve, reject) => {
blocker.close((error) => (error ? reject(error) : resolve()));
});
}
});
test('releases the upstream fetch semaphore when a response stalls mid-body (#5441)', async () => {
// Raw TCP, not http.createServer: sends valid headers with a Content-Length
// promising more body than it ever delivers, then destroys the socket
// shortly after — the "accepts connection, sends headers, stalls mid-body,
// connection eventually drops" failure mode from the issue. Node's http
// client surfaces this on `res` ('aborted'/'error'), not on `req` — which is
// exactly what the old globalThis.fetch wrapper never listened for, so the
// wrapped Promise never settled and the semaphore slot leaked permanently.
let stallConnections = 0;
const stallServer = net.createServer((socket) => {
socket.once('data', () => {
stallConnections += 1;
socket.write(
'HTTP/1.1 200 OK\r\n' +
'Content-Type: application/json\r\n' +
'Content-Length: 1000\r\n' +
'\r\n'
);
setTimeout(() => socket.destroy(), 20);
});
});
const stallPort = await listen(stallServer);
const healthy = createServer((_req, res) => {
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({ ok: true }));
});
const healthyPort = await listen(healthy);
const localApi = await setupApiDir({
'stall-proxy.js': `
export default async function handler() {
try {
await fetch('http://127.0.0.1:${stallPort}/');
return new Response(JSON.stringify({ settled: 'resolved' }), { status: 200 });
} catch (error) {
return new Response(JSON.stringify({ settled: 'rejected', message: error.message }), { status: 200 });
}
}
`,
'healthy-proxy.js': `
export default async function handler() {
const upstream = await fetch('http://127.0.0.1:${healthyPort}/');
const payload = await upstream.text();
return new Response(payload, { status: upstream.status, headers: { 'content-type': 'application/json' } });
}
`,
});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
allowPrivateFetchOrigins: [
`http://127.0.0.1:${stallPort}`,
`http://127.0.0.1:${healthyPort}`,
],
});
const { port } = await app.start();
try {
// getJsonViaHttp, NOT authFetch/global fetch: globalThis.fetch is
// monkey-patched by local-api-server.mjs and shares its 6-slot semaphore
// with the handler-side fetches this test is exercising. A real external
// client (a separate process/browser) never shares that counter — using
// the patched fetch for these outer calls too would have each one
// consume a slot just reaching the local API server, before its handler
// ever got to make its own inner request, self-deadlocking the test
// rather than reproducing the issue.
//
// MAX_CONCURRENT_UPSTREAM is 6 — fire exactly that many concurrent
// requests through the stalling upstream to exhaust every slot. Do not
// await them yet: under the pre-fix code these never settle at all, so
// awaiting here would hang the test itself, not just prove the bug.
const stallRequests = Array.from({ length: 6 }, () =>
getJsonViaHttp(`http://127.0.0.1:${port}/api/stall-proxy`)
);
// Wait until all 6 have actually reached the upstream (holding their
// semaphore slot) before touching the healthy endpoint, so the assertion
// below is exercising a genuinely exhausted semaphore, not a race.
const deadline = Date.now() + 2000;
while (stallConnections < 6 && Date.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, 10));
}
assert.equal(stallConnections, 6, 'all 6 stalling requests should have reached the upstream');
// The semaphore is now fully held by 6 in-flight stalling fetches. A 7th
// request to a completely healthy upstream must still complete quickly —
// proving the stalled slots were released rather than leaked forever.
const healthyResponse = await Promise.race([
getJsonViaHttp(`http://127.0.0.1:${port}/api/healthy-proxy`),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('healthy request did not complete — semaphore is wedged')), 3000)
),
]);
assert.equal(healthyResponse.status, 200);
assert.deepEqual(healthyResponse.json, { ok: true });
// The 6 stalling requests should also have settled (rejected) by now that
// their upstream connections were destroyed — confirm none of them hung.
const stallResults = await Promise.all(
stallRequests.map((p) =>
Promise.race([
p.then((r) => r.json),
new Promise((_, reject) => setTimeout(() => reject(new Error('stall request never settled')), 1000)),
])
)
);
for (const result of stallResults) {
assert.equal(result.settled, 'rejected');
}
} finally {
await app.close();
await localApi.cleanup();
await new Promise((resolve, reject) => {
stallServer.close((error) => (error ? reject(error) : resolve()));
});
await new Promise((resolve, reject) => {
healthy.close((error) => (error ? reject(error) : resolve()));
});
}
});
test('releases the upstream fetch semaphore when a connection goes silent forever (#5441 follow-up)', async () => {
// Accepts the connection and never writes anything, never closes -- no
// FIN/RST, no data. None of res 'error'/'aborted'/'end' or req 'error'/
// 'close' ever fire for this shape; only the new idle timeout observes it.
const openSockets = new Set();
const silentServer = net.createServer((socket) => {
// Intentionally do nothing with the data -- leave the connection open
// and silent. Track it so cleanup can force-close it: net.Server.close()
// waits for every accepted socket to end on its own, and a socket we
// never write to or read from (by design, to simulate a true silent
// stall) never will.
openSockets.add(socket);
socket.once('close', () => openSockets.delete(socket));
});
const silentPort = await listen(silentServer);
__testing__.setUpstreamIdleTimeoutMs(200);
const localApi = await setupApiDir({
'silent-proxy.js': `
export default async function handler() {
try {
await fetch('http://127.0.0.1:${silentPort}/');
return new Response(JSON.stringify({ settled: 'resolved' }), { status: 200 });
} catch (error) {
return new Response(JSON.stringify({ settled: 'rejected', message: error.message }), { status: 200 });
}
}
`,
});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
allowPrivateFetchOrigins: [`http://127.0.0.1:${silentPort}`],
});
const { port } = await app.start();
try {
const result = await Promise.race([
getJsonViaHttp(`http://127.0.0.1:${port}/api/silent-proxy`).then((r) => r.json),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('silent stall never settled -- idle timeout did not fire')), 3000)
),
]);
assert.equal(result.settled, 'rejected');
assert.match(result.message, /idle-timed out/);
// Slot must be released: a request through the SAME fetch wrapper (any
// origin) must not be blocked by the leaked silent connection.
const stallRequests = Array.from({ length: 6 }, () =>
getJsonViaHttp(`http://127.0.0.1:${port}/api/silent-proxy`).then((r) => r.json)
);
const followUp = await Promise.race([
Promise.all(stallRequests),
new Promise((_, reject) => setTimeout(() => reject(new Error('semaphore still wedged after idle timeout')), 5000)),
]);
for (const r of followUp) assert.equal(r.settled, 'rejected');
} finally {
__testing__.setUpstreamIdleTimeoutMs(12000);
await app.close();
await localApi.cleanup();
for (const socket of openSockets) socket.destroy();
await new Promise((resolve, reject) => {
silentServer.close((error) => (error ? reject(error) : resolve()));
});
}
});
test('abort-signal path: mid-flight abort rejects promptly and releases the slot (#5441 follow-up)', async () => {
// Mirrors how fetchWithTimeout drives this exact branch in production: an
// AbortController whose signal is passed into fetch(), aborted mid-flight
// against an upstream that never responds.
const openSockets = new Set();
const neverResponds = net.createServer((socket) => {
// Accepts but never writes -- the abort must fire before any other
// listener would (idle timeout stays at its default 12s here). Tracked
// so cleanup can force-close it (see the silent-stall test above for why).
openSockets.add(socket);
socket.once('close', () => openSockets.delete(socket));
});
const neverRespondsPort = await listen(neverResponds);
const localApi = await setupApiDir({
'abort-proxy.js': `
export default async function handler() {
const controller = new AbortController();
setTimeout(() => controller.abort(), 30);
try {
await fetch('http://127.0.0.1:${neverRespondsPort}/', { signal: controller.signal });
return new Response(JSON.stringify({ settled: 'resolved' }), { status: 200 });
} catch (error) {
return new Response(JSON.stringify({ settled: 'rejected', message: error.message, name: error.name }), { status: 200 });
}
}
`,
'healthy-proxy.js': `
export default async function handler() {
return new Response(JSON.stringify({ ok: true }), { status: 200 });
}
`,
});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
allowPrivateFetchOrigins: [`http://127.0.0.1:${neverRespondsPort}`],
});
const { port } = await app.start();
try {
const result = await Promise.race([
getJsonViaHttp(`http://127.0.0.1:${port}/api/abort-proxy`).then((r) => r.json),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('abort-signal path never settled -- semaphore leak reintroduced')), 2000)
),
]);
assert.equal(result.settled, 'rejected');
assert.match(result.message, /aborted by signal/);
// Slot released promptly (well under the 12s idle timeout): a healthy
// request right after must not be delayed by the aborted one.
const healthy = await Promise.race([
getJsonViaHttp(`http://127.0.0.1:${port}/api/healthy-proxy`).then((r) => r.json),
new Promise((_, reject) => setTimeout(() => reject(new Error('slot not released after abort')), 1000)),
]);
assert.deepEqual(healthy, { ok: true });
} finally {
await app.close();
await localApi.cleanup();
for (const socket of openSockets) socket.destroy();
await new Promise((resolve, reject) => {
neverResponds.close((error) => (error ? reject(error) : resolve()));
});
}
});
test('abort-signal path: an already-aborted signal rejects immediately without dispatching (#5441 follow-up)', async () => {
let connectionsReceived = 0;
const neverShouldConnect = net.createServer((_socket) => {
connectionsReceived += 1;
});
const neverShouldConnectPort = await listen(neverShouldConnect);
const localApi = await setupApiDir({
'preaborted-proxy.js': `
export default async function handler() {
const controller = new AbortController();
controller.abort();
try {
await fetch('http://127.0.0.1:${neverShouldConnectPort}/', { signal: controller.signal });
return new Response(JSON.stringify({ settled: 'resolved' }), { status: 200 });
} catch (error) {
return new Response(JSON.stringify({ settled: 'rejected', message: error.message }), { status: 200 });
}
}
`,
});
const app = await createLocalApiServer({
port: 0,
apiDir: localApi.apiDir,
logger: { log() { }, warn() { }, error() { } },
allowPrivateFetchOrigins: [`http://127.0.0.1:${neverShouldConnectPort}`],
});
const { port } = await app.start();
try {
const result = await Promise.race([
getJsonViaHttp(`http://127.0.0.1:${port}/api/preaborted-proxy`).then((r) => r.json),
new Promise((_, reject) => setTimeout(() => reject(new Error('pre-aborted fetch never settled')), 1000)),
]);
assert.equal(result.settled, 'rejected');
assert.match(result.message, /aborted by signal/);
assert.equal(connectionsReceived, 0, 'an already-aborted signal must not dispatch to the network at all');
} finally {
await app.close();
await localApi.cleanup();
await new Promise((resolve, reject) => {
neverShouldConnect.close((error) => (error ? reject(error) : resolve()));
});
}
});
|