File size: 225,821 Bytes
d939dd0 | 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 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 | from __future__ import annotations
import argparse
import base64
import binascii
import hashlib
import hmac
import ipaddress
import json
import mimetypes
import os
import re
import secrets
import signal
import sys
import threading
from dataclasses import replace
from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any, Mapping
from urllib.parse import parse_qs, parse_qsl, unquote, urlencode, urlsplit
import auth_views
import render as views
import specialty_store as specialty
import specialty_views
import wishlist_store as wishlist
import wishlist_views
from browse_breadth import load_browse_breadth
from deals_catalog import build_deals_view, load_deals_catalog
from external_verification import (
ExternalRegistrationVerification,
VerificationConfigurationError,
VerificationRateLimited,
VerificationUnavailable,
load_external_registration_verification,
registration_frontend_script,
)
from home_catalog import load_home_product_catalog
from home_category_catalog import load_home_category_groups, load_home_category_offers
from mail_transport import (
SMTPConfig,
load_local_inbox_url,
load_smtp_config,
send_smtp_message,
smtp_error_summary,
smtp_public_summary,
)
from product_options import UNAVAILABLE_SELECTION_COPY
from review_catalog import render_reviews_section
from review_store import (
ReviewAuthenticationRequired,
ReviewNotFound,
ReviewPermissionDenied,
ReviewValidationError,
)
from search_catalog import (
SearchRequest,
SearchValidationError,
build_search_hit,
candidate_search_hits,
is_portable_ssd_contract_query,
normalize_search_query,
parse_search_request,
refine_search_hits,
source_department_for_query,
)
from search_suggestions import (
SearchSuggestionValidationError,
build_suggestion_corpus,
parse_suggestion_request,
suggest_search_terms,
)
from stripe_gateway import (
PAYMENT_MODE_STRIPE_TEST,
STRIPE_PROVIDER_SESSION_PATTERN,
STRIPE_WEBHOOK_MAX_BYTES,
STRIPE_WEBHOOK_PATH,
PaymentConfig,
StripeAPIError,
StripeConfigurationError,
StripeGateway,
StripeSignatureError,
load_payment_config,
verify_stripe_signature,
)
from store import (
AddressInUse,
AddressNotFound,
AddressRevisionConflict,
BEST_SELLERS_PATH,
CART_LINE_ID_PATTERN,
COMPARE_LINE_ID_PATTERN,
MAIL_LOCAL_ONLY,
MAIL_SMTP_PENDING,
PDP_PATH,
SUPPORTED_DELIVERY_COUNTRIES,
SUPPORTED_DELIVERY_COUNTRY_CODES,
TARGET_ASIN,
TERMINAL_PATHS,
CheckoutReconciliationRequired,
ContractError,
OrderActionTokenInvalid,
OrderNotFound,
OrderStateConflict,
ReturnNotFound,
Store,
normalize_email,
)
ROOT = Path(__file__).resolve().parent
STATIC_ROOT = (ROOT / "static").resolve()
FIXTURE_ROOT = (ROOT / "fixtures").resolve()
SCHEMA_PATH = ROOT / "schema.sql"
DEFAULT_DB = ROOT / "runtime" / "websitebench" / "amazon.sqlite3"
SESSION_COOKIE = "__Host-websitebench-amazon-session"
FLOW_COOKIE = "amazon_clone_flow"
SESSION_BYTES = 32
TRUE_ENV_VALUES = frozenset({"1", "true", "yes", "on"})
# A 10,000-character review body is a supported domain value. URL-encoded
# non-ASCII text can use up to twelve bytes per Unicode scalar (four UTF-8
# bytes, each percent-encoded), so keep the transport limit above that bound.
MAX_FORM_BYTES = 128 * 1024
MAX_ADMIN_BYTES = 64 * 1024
MAX_AUTH_JSON_BYTES = 4 * 1024
PDP_ROUTE = re.compile(r"^/([^/]+)/dp/([A-Z0-9]{10})$")
BARE_PDP_ROUTE = re.compile(r"^/dp/([A-Z0-9]{10})$")
HOME_COLLECTION_ROUTE = re.compile(
r"^/gp/home-collection/([a-z0-9-]+)(?:/([1-4]))?$"
)
PRODUCT_REVIEWS_ROUTE = re.compile(r"^/product-reviews/([A-Z0-9]{10})$")
PRODUCT_REVIEW_HELPFUL_ROUTE = re.compile(
r"^/product-reviews/([A-Z0-9]{10})/helpful$"
)
HOME_PRODUCT_CATALOG = load_home_product_catalog(FIXTURE_ROOT)
SEARCH_SUGGESTION_CORPUS = build_suggestion_corpus(HOME_PRODUCT_CATALOG)
BROWSE_BREADTH = load_browse_breadth(FIXTURE_ROOT)
SEARCH_DEPARTMENT_SUPPLEMENTS = (
*BROWSE_BREADTH["department_commerce_supplements"],
*BROWSE_BREADTH["search_commerce_cards"],
)
SEARCH_COMMERCE_PRODUCT_CATALOG = {
str(product["asin"]): product
for product in BROWSE_BREADTH["search_commerce_cards"]
}
FROZEN_SEARCH_QUERIES = frozenset(
normalize_search_query(str(query))
for product in BROWSE_BREADTH["search_commerce_cards"]
for query in product.get("captured_queries", ())
if isinstance(query, str) and query.strip()
)
HOME_CATEGORY_PRODUCT_CATALOG = {
str(product["asin"]): product
for product in load_home_category_offers(FIXTURE_ROOT)
}
HOME_CATEGORY_GROUPS = load_home_category_groups(FIXTURE_ROOT)
HOME_CATEGORY_QUERY_TILES: dict[str, dict[str, Any]] = {}
for _home_category_group in HOME_CATEGORY_GROUPS.values():
HOME_CATEGORY_QUERY_TILES[
normalize_search_query(str(_home_category_group["title"]))
] = {
"collection_key": str(_home_category_group["key"]),
"tile_index": None,
"products": tuple(
dict(product)
for tile in _home_category_group["tiles"]
for product in tile["products"]
),
}
for _home_category_tile in _home_category_group["tiles"]:
HOME_CATEGORY_QUERY_TILES[
normalize_search_query(str(_home_category_tile["query"]))
] = {
"collection_key": str(_home_category_group["key"]),
"tile_index": int(_home_category_tile["index"]),
"products": tuple(
dict(product) for product in _home_category_tile["products"]
),
}
PORTABLE_SEARCH_ORDER = (
"B08HN37XC1",
"B08GTYFC37",
"B0F6NKYDTY",
"B0BGKXX9TK",
"B0874XN4D8",
"B0C5JQ68FY",
"B08GV9M64L",
"B09VLK9W3S",
"B0CHFSWM2P",
)
DEALS_CATALOG = load_deals_catalog(
FIXTURE_ROOT, BROWSE_BREADTH["verified_offers"]
)
DEALS_PRODUCT_CATALOG = {
str(product["asin"]): product for product in DEALS_CATALOG
}
AUTH_PATHS = frozenset({"/ap/signin", "/ap/register", "/ap/forgotpassword", "/ap/cvf/verify"})
AUTH_SIGNOUT_PATH = "/ap/signout"
AUTH_SEND_CODE_PATH = "/api/auth/send-code"
AUTH_VERIFY_CODE_PATH = "/api/auth/verify-code"
EXTERNAL_AUTH_API_PATHS = frozenset(
{AUTH_SEND_CODE_PATH, AUTH_VERIFY_CODE_PATH}
)
ADDRESS_BOOK_PATH = "/a/addresses"
ADDRESS_ADD_PATH = "/a/addresses/add"
ADDRESS_EDIT_PATH = "/a/addresses/edit"
ADDRESS_CREATE_PATH = "/a/addresses/create"
ADDRESS_UPDATE_PATH = "/a/addresses/update"
ADDRESS_DELETE_PATH = "/a/addresses/delete"
ADDRESS_DEFAULT_PATH = "/a/addresses/set-default"
ADDRESS_BOOK_POST_PATHS = frozenset(
{
ADDRESS_CREATE_PATH,
ADDRESS_UPDATE_PATH,
ADDRESS_DELETE_PATH,
ADDRESS_DEFAULT_PATH,
}
)
ADDRESS_FORM_NAMES = frozenset(
{
"fullName",
"addressLine1",
"addressLine2",
"city",
"state",
"postalCode",
"countryCode",
"phoneNumber",
}
)
CART_MUTATION_PATHS = frozenset(
{
"/gp/buy/now",
"/gp/cart/add.html",
"/gp/cart/update.html",
"/gp/cart/delete.html",
"/gp/cart/save-for-later.html",
"/gp/cart/move-to-cart.html",
}
)
# Ordinary cart mutations are account-owned. Buy Now is kept separate because
# its existing pending-intent flow already redirects anonymous shoppers before
# creating the authenticated checkout.
AUTHENTICATED_CART_MUTATION_PATHS = frozenset(
CART_MUTATION_PATHS - {"/gp/buy/now"}
)
BUY_NOW_PATH = "/gp/buy/now"
ADD_TO_CART_CONFIRMATION_PATH = "/gp/cart/added"
BUY_NOW_CONTINUE_PATH = "/gp/buy/now/continue"
CHECKOUT_START_PATH = "/gp/buy/spc/handlers/display.html"
CHECKOUT_ADDRESS_PATH = "/gp/buy/addressselect/handlers/display.html"
CHECKOUT_DELIVERY_PATH = "/gp/buy/shipoptionselect/handlers/display.html"
CHECKOUT_PAYMENT_PATH = "/gp/buy/payselect/handlers/display.html"
PLACE_ORDER_PATH = "/gp/buy/place-order"
STRIPE_CHECKOUT_PATH = "/gp/buy/stripe-checkout"
STRIPE_RETURN_PATH = "/gp/buy/stripe-return"
STRIPE_CANCEL_PATH = "/gp/buy/stripe-cancel"
ORDER_DETAIL_PATH = "/gp/your-account/order-details"
ORDER_EMAIL_RETRY_PATH = "/gp/your-account/order-email/retry"
ORDER_CANCEL_PATH = "/gp/your-account/order-cancel"
RETURN_CREATE_PATH = "/gp/your-account/returns/create"
RETURN_DETAIL_PATH = "/gp/your-account/returns/details"
COMPARE_PATH = "/gp/compare"
COMPARE_MUTATION_PATHS = frozenset(
{"/gp/compare/add", "/gp/compare/remove", "/gp/compare/clear"}
)
CHECKOUT_STAGE_ORDER = {
"CART_READY": 0,
"ADDRESS_SELECTED": 1,
"DELIVERY_SELECTED": 2,
"PAYMENT_SELECTED": 3,
"PAYMENT_PENDING": 3,
"PLACED": 4,
}
ASIN_PATTERN = re.compile(r"^[A-Z0-9]{10}$")
PROTECTED_ACCOUNT_PATHS = frozenset(
{"/gp/css/homepage.html", "/gp/css/order-history"}
)
WISHLIST_POST_PATHS = frozenset(
{
wishlist_views.WISHLIST_CREATE_PATH,
wishlist_views.WISHLIST_RENAME_PATH,
wishlist_views.WISHLIST_DELETE_PATH,
wishlist_views.WISHLIST_ADD_ITEM_PATH,
wishlist_views.WISHLIST_REMOVE_ITEM_PATH,
wishlist_views.WISHLIST_MOVE_TO_CART_PATH,
}
)
WISHLIST_FRIENDS_PATH = "/hz/wishlist/your-friends"
SITE_DIRECTORY_PATH = "/gp/site-directory"
DELIVERY_PREFERENCE_PATH = "/gp/delivery/ajax/address-change.html"
DELIVERY_SELECTIONS_PATH = "/gp/delivery/ajax/address-selections"
SEARCH_SUGGESTIONS_PATH = "/search/suggestions"
LANGUAGE_PREFERENCE_PATH = "/customer-preferences/edit"
CUSTOMER_SERVICE_PATH = "/gp/help/customer/display.html"
CUSTOMER_SERVICE_NODE = "508510"
SHIPPING_POLICIES_NODE = "468520"
RETURNS_REPLACEMENTS_NODE = "201819200"
CONDITIONS_OF_USE_NODE = "508088"
PRIVACY_NOTICE_NODE = "468496"
GIFT_CARDS_PATH = specialty.GIFT_CARDS_PATH
SPECIALTY_POST_PATHS = frozenset(
{
specialty.GIFT_CARD_PREVIEW_PATH,
specialty.GIFT_CARD_REDEEM_PATH,
specialty.SELL_DRAFT_PATH,
specialty.REGISTRY_CREATE_PATH,
}
)
def env_flag(name: str) -> bool:
return os.environ.get(name, "").strip().casefold() in TRUE_ENV_VALUES
def cloudflare_review_profile() -> bool:
profile = os.environ.get("WEBSITEBENCH_BACKEND_PROFILE")
if profile is None:
# Compatibility only for old standalone launchers.
profile = os.environ.get("CLAWBENCH_BACKEND_PROFILE", "")
return profile.strip() == "cloudflare-review"
def browser_cookie(name: str, value: str, *, max_age: int | None = None) -> str:
attributes = [f"{name}={value}", "Path=/", "HttpOnly", "SameSite=Lax"]
if (
name == SESSION_COOKIE
or env_flag("AMAZON_COOKIE_SECURE")
or cloudflare_review_profile()
):
attributes.append("Secure")
if max_age is not None:
attributes.append(f"Max-Age={max_age}")
return "; ".join(attributes)
def public_basic_auth_credentials() -> tuple[str, str] | None:
username = os.environ.get("AMAZON_BASIC_AUTH_USERNAME", "")
password = os.environ.get("AMAZON_BASIC_AUTH_PASSWORD", "")
if not username and not password:
return None
if not username or not password:
raise ValueError(
"AMAZON_BASIC_AUTH_USERNAME and AMAZON_BASIC_AUTH_PASSWORD "
"must be configured together"
)
return username, password
PUBLIC_NAVIGATION_LANDINGS: dict[
str, tuple[str, str, tuple[tuple[str, str], ...]]
] = {
LANGUAGE_PREFERENCE_PATH: (
"Language preferences",
"This local snapshot is available in English (United States). Continue browsing or visit customer service.",
(
("Continue in English", "/"),
("Browse books", "/s?k=books"),
("Visit Customer Service", "/gp/help/customer/display.html?nodeId=508510"),
),
),
"/gp/navigation/amazon-business": (
"Amazon Business",
"Business accounts are a separate registration programme and are not modelled by this storefront. A personal account can be created from the sign-in page and used for the whole shopping journey.",
(
("Create an account", "/ap/register"),
("Sign in", "/ap/signin"),
("Return to Amazon home", "/"),
),
),
"/gp/navigation/amazon-music": (
"Amazon Music",
"Browse music-related picks available in this offline storefront.",
(("Browse featured products", "/s?k=music"), ("Return to Amazon home", "/")),
),
"/gp/navigation/kindle": (
"Kindle E-readers & Books",
"Browse the captured Books department and reading-related products.",
(("Browse Books", "/s?i=books"), ("Return to Amazon home", "/")),
),
"/gp/navigation/appstore": (
"Amazon Appstore",
"App downloads are outside this offline shopping clone.",
(("Browse Computers", "/s?i=computers"), ("Return to Amazon home", "/")),
),
"/gp/navigation/automotive": (
"Automotive",
"Browse products in the local catalog while the Automotive department remains an offline boundary.",
(("Browse all products", "/s?k=products"), ("Return to Amazon home", "/")),
),
"/gp/navigation/baby": (
"Baby",
"Browse products in the local catalog while the Baby department remains an offline boundary.",
(("Browse Home & Kitchen", "/s?i=home-kitchen"), ("Return to Amazon home", "/")),
),
"/gp/navigation/shop-by-interest": (
"Shop By Interest",
"Continue into the captured Amazon shopping departments.",
(("Browse Today's Deals", "/gp/goldbox/"), ("Browse all departments", "/gp/site-directory")),
),
"/gp/navigation/amazon-live": (
"Amazon Live",
"Live video streams are outside this offline shopping clone.",
(("Browse Today's Deals", "/gp/goldbox/"), ("Return to Amazon home", "/")),
),
"/gp/navigation/international-shopping": (
"International Shopping",
"The local storefront is showing USD offers for delivery to Singapore.",
(("Browse all products", "/s?k=products"), ("Choose delivery location", DELIVERY_PREFERENCE_PATH)),
),
"/gp/navigation/second-chance": (
"Amazon Second Chance",
"Refurbishment services are outside this offline shopping clone.",
(("Browse Today's Deals", "/gp/goldbox/"), ("Return to Amazon home", "/")),
),
}
# Footer subjects this storefront deliberately does not model. Each gets its own
# destination so a visitor lands on a page that names what they clicked and says
# plainly that it is out of scope, instead of a link that goes nowhere.
_BOUNDARY_LANDINGS: tuple[tuple[str, str, str], ...] = (
("careers", "Careers", "Recruitment is outside this shopping storefront."),
("blog", "About Amazon Blog", "Editorial content is outside this shopping storefront."),
("about", "About Amazon", "Corporate information is outside this shopping storefront."),
("investor-relations", "Investor Relations", "Investor material is outside this shopping storefront."),
("amazon-science", "Amazon Science", "Research publications are outside this shopping storefront."),
("amazon-devices", "Amazon Devices", "This storefront's captured catalog stocks no Amazon-branded devices, so there is no local department to browse."),
("sell-business", "Sell on Amazon Business", "Seller registration is outside this shopping storefront."),
("sell-apps", "Sell apps on Amazon", "Developer programmes are outside this shopping storefront."),
("affiliate", "Become an Affiliate", "The affiliate programme is outside this shopping storefront."),
("advertise", "Advertise Your Products", "Advertising services are outside this shopping storefront."),
("self-publish", "Self-Publish with Us", "Publishing services are outside this shopping storefront."),
("amazon-hub", "Host an Amazon Hub", "Pickup-location hosting is outside this shopping storefront."),
("business-card", "Amazon Business Card", "Credit products are outside this shopping storefront. Checkout here uses a local sandbox gateway and charges nothing."),
("shop-with-points", "Shop with Points", "Rewards-point redemption is not modelled by this storefront."),
("reload-balance", "Reload Your Balance", "Gift-card balance reloads are not modelled by this storefront."),
("currency-converter", "Amazon Currency Converter", "This storefront prices every offer in USD and does not convert currencies."),
("covid-19", "Amazon and COVID-19", "This announcement page is outside this shopping storefront."),
("content-and-devices", "Manage Your Content and Devices", "Digital content libraries are outside this shopping storefront."),
("recalls", "Recalls and Product Safety Alerts", "Safety notices are outside this shopping storefront."),
("health-data-privacy", "Consumer Health Data Privacy Disclosure", "This storefront collects no health data. The Privacy Notice lists everything it does store."),
("ads-privacy", "Your Ads Privacy Choices", "This storefront runs no advertising, sets no advertising cookies, and makes no third-party requests."),
("new-releases", "New Releases", "This storefront freezes one Best Sellers ranking. New Releases is not modelled."),
("internal-hard-drives", "Internal Hard Drives", "This storefront's captured catalog does not stock Internal Hard Drives. The frozen Best Sellers ranking covers external solid state drives."),
("usb-flash-drives", "USB Flash Drives", "This storefront's captured catalog does not stock USB Flash Drives. The frozen Best Sellers ranking covers external solid state drives."),
("network-attached-storage", "Network Attached Storage", "This storefront's captured catalog does not stock Network Attached Storage. The frozen Best Sellers ranking covers external solid state drives."),
("internal-solid-state-drives", "Internal Solid State Drives", "This storefront's captured catalog does not stock Internal Solid State Drives. The frozen Best Sellers ranking covers external solid state drives."),
("tape-libraries", "Tape Libraries", "This storefront's captured catalog does not stock Tape Libraries. The frozen Best Sellers ranking covers external solid state drives."),
("tape-drives", "Floppy & Tape Drives", "This storefront's captured catalog does not stock Floppy & Tape Drives. The frozen Best Sellers ranking covers external solid state drives."),
("external-zip-drives", "External Zip Drives", "This storefront's captured catalog does not stock External Zip Drives. The frozen Best Sellers ranking covers external solid state drives."),
("crypto-hardware-wallets", "Crypto Hardware Wallets", "This storefront's captured catalog does not stock Crypto Hardware Wallets. The frozen Best Sellers ranking covers external solid state drives."),
("movers-shakers", "Movers & Shakers", "This storefront freezes one Best Sellers ranking. Movers & Shakers is not modelled."),
)
# Separate Amazon products and companies linked from the footer grid.
_BRAND_LANDINGS: tuple[tuple[str, str], ...] = (
("amazon-music", "Amazon Music"), ("amazon-ads", "Amazon Ads"), ("6pm", "6pm"),
("abebooks", "AbeBooks"), ("acx", "ACX"), ("veeqo", "Veeqo"),
("amazonglobal", "AmazonGlobal"), ("aws", "Amazon Web Services"),
("audible", "Audible"), ("box-office-mojo", "Box Office Mojo"),
("goodreads", "Goodreads"), ("imdb", "IMDb"), ("imdbpro", "IMDbPro"),
("kindle-direct-publishing", "Kindle Direct Publishing"),
("prime-video-direct", "Prime Video Direct"), ("shopbop", "Shopbop"),
("woot", "Woot!"), ("zappos", "Zappos"), ("ring", "Ring"),
("eero", "eero WiFi"), ("blink", "Blink"),
("neighbors-app", "Neighbors App"), ("pillpack", "PillPack"),
)
_BOUNDARY_ACTIONS = (
("Return to Amazon home", "/"),
("Browse all departments", "/gp/site-directory"),
("Visit Customer Service", "/gp/help/customer/display.html?nodeId=508510"),
)
for _slug, _title, _copy in _BOUNDARY_LANDINGS:
PUBLIC_NAVIGATION_LANDINGS.setdefault(
f"/gp/navigation/{_slug}", (_title, _copy, _BOUNDARY_ACTIONS)
)
for _slug, _name in _BRAND_LANDINGS:
PUBLIC_NAVIGATION_LANDINGS.setdefault(
f"/gp/navigation/{_slug}",
(
_name,
f"{_name} is a separate service. This storefront reproduces the "
f"Amazon.com shopping journey only, and makes no request to any "
f"other site while you browse.",
_BOUNDARY_ACTIONS,
),
)
def digest(value: str) -> str:
return hashlib.sha256(value.encode("utf-8")).hexdigest()
def delivery_location_token(session_digest: str) -> str:
"""Per-session token for the delivery-location form.
The source storefront carries a `glow-validation-token` on the same form.
This is a real one: it is derived from the browser session, so a form
harvested from one session cannot be replayed against another. It is
checked in addition to, not instead of, the same-origin POST check every
other mutation in this clone performs.
"""
return digest(f"delivery-location:{session_digest}")[:32]
def json_bytes(payload: Any) -> bytes:
return json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
def compare_entry_product(
store: Store,
product: dict[str, Any] | Mapping[str, Any],
*,
eligible_asins: frozenset[str] | None = None,
) -> dict[str, Any]:
"""Annotate a rendered product from the server-owned compare registry."""
rendered = dict(product)
asin = str(rendered.get("asin") or "")
eligible = asin in (
eligible_asins
if eligible_asins is not None
else store.compare_eligible_asins()
)
rendered["compare_eligible"] = eligible
if eligible:
rendered["default_selected_options"] = store.default_product_options(asin)
return rendered
def product_for_pdp(store: Store, asin: str) -> dict[str, Any] | None:
"""Return the unified display record while keeping its offer authoritative."""
product = store.display_product(asin)
return compare_entry_product(store, product) if product is not None else None
def compare_product_for_view(
store: Store, compare_item: dict[str, Any]
) -> dict[str, Any]:
"""Keep rich presentation while making the resolved line quote authoritative."""
asin = str(compare_item.get("asin") or "")
presentation = product_for_pdp(store, asin) or {}
return {**presentation, **compare_item, "compare_eligible": True}
def review_product_source_scope(store: Store, asin: str) -> str | None:
"""Return the server-owned product scope that authorizes local reviews."""
if store.display_product(asin) is None:
return None
if asin in HOME_PRODUCT_CATALOG:
return "home_snapshot"
if store.product(asin) is not None:
return "catalog_product"
if store.commerce_offer(asin) is not None:
return "commerce_offer"
return None
def valid_account_email(value: str) -> str | None:
normalized = normalize_email(value)
if not normalized or len(normalized) > 254 or normalized.count("@") != 1:
return None
local, domain = normalized.split("@", 1)
if not local or not domain or any(character.isspace() or ord(character) < 32 for character in normalized):
return None
return normalized
def clean_display_name(value: str) -> str | None:
cleaned = " ".join(value.strip().split())
if not cleaned or len(cleaned) > 128 or any(ord(character) < 32 for character in cleaned):
return None
return cleaned
def clean_checkout_text(
value: str, *, maximum: int, required: bool = True
) -> str | None:
cleaned = " ".join(value.strip().split())
if required and not cleaned:
return None
if len(cleaned) > maximum or any(ord(character) < 32 for character in cleaned):
return None
return cleaned
def normalized_address_fields(fields: dict[str, str]) -> dict[str, str] | None:
"""Map one strict browser address form to the store's canonical fields."""
if not ADDRESS_FORM_NAMES.issubset(fields):
return None
address = {
"full_name": clean_checkout_text(fields["fullName"], maximum=128),
"address_line1": clean_checkout_text(
fields["addressLine1"], maximum=200
),
"address_line2": clean_checkout_text(
fields["addressLine2"], maximum=200, required=False
),
"city": clean_checkout_text(fields["city"], maximum=100),
"state_region": clean_checkout_text(fields["state"], maximum=100),
"postal_code": clean_checkout_text(fields["postalCode"], maximum=32),
"country_code": fields["countryCode"].strip().upper(),
"phone": clean_checkout_text(
fields["phoneNumber"], maximum=32, required=False
),
}
if (
any(value is None for value in address.values())
or str(address["country_code"]) not in SUPPORTED_DELIVERY_COUNTRY_CODES
):
return None
return {name: str(value) for name, value in address.items()}
def review_query_parameters(query: dict[str, list[str]]) -> tuple[int | None, str]:
"""Parse the two public review controls without accepting ambiguous values."""
star_values = query.get("reviewStar", [])
sort_values = query.get("reviewSort", [])
if len(star_values) > 1 or len(sort_values) > 1:
raise ReviewValidationError("review filters must have one value")
star: int | None = None
if star_values:
if re.fullmatch(r"[1-5]", star_values[0]) is None:
raise ReviewValidationError("reviewStar must be 1 through 5")
star = int(star_values[0])
sort = sort_values[0] if sort_values else "recent"
if sort not in {"recent", "helpful"}:
raise ReviewValidationError("reviewSort must be recent or helpful")
return star, sort
class ReusableThreadingHTTPServer(ThreadingHTTPServer):
allow_reuse_address = True
daemon_threads = True
def handle_error(self, request: Any, client_address: Any) -> None:
"""Do not log tracebacks for ordinary clients closing keep-alive sockets."""
error = sys.exc_info()[1]
if isinstance(
error, (BrokenPipeError, ConnectionAbortedError, ConnectionResetError)
):
return
super().handle_error(request, client_address)
def dispatch_mail_delivery(
store: Store,
config: SMTPConfig,
delivery: dict[str, Any],
) -> bool:
"""Atomically claim and asynchronously deliver one durable SMTP job."""
kind = str(delivery["kind"])
email_id = int(delivery["email_id"])
claim_token = store.claim_mail_delivery(kind, email_id)
if claim_token is None:
return False
def deliver() -> None:
try:
send_smtp_message(
config,
recipient=str(delivery["recipient"]),
subject=str(delivery["subject"]),
body=str(delivery["body"]),
)
except Exception as exc:
store.mark_mail_delivery(
kind,
email_id,
claim_token=claim_token,
sent=False,
error_summary=smtp_error_summary(exc),
)
else:
store.mark_mail_delivery(
kind,
email_id,
claim_token=claim_token,
sent=True,
)
worker = threading.Thread(
target=deliver,
name=f"amazon-clone-mail-{kind}-{email_id}",
daemon=True,
)
try:
worker.start()
except RuntimeError as exc:
store.mark_mail_delivery(
kind,
email_id,
claim_token=claim_token,
sent=False,
error_summary=smtp_error_summary(exc),
)
return False
return True
def wishlist_selection_query(
query: dict[str, list[str]],
) -> tuple[str, dict[str, str]] | None:
"""Parse one strict, duplicate-free ASIN plus complete option selection."""
if not query or len(query) > 16 or "ASIN" not in query:
return None
fields: dict[str, str] = {}
for name, values in query.items():
if len(values) != 1:
return None
if name != "ASIN" and (
not name.startswith("option.") or not name.removeprefix("option.")
):
return None
fields[name] = values[0]
asin = fields.pop("ASIN", "")
if ASIN_PATTERN.fullmatch(asin) is None:
return None
return asin, {
name.removeprefix("option."): value
for name, value in fields.items()
}
class PublicHandler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
store: Store
smtp_config: SMTPConfig | None = None
local_inbox_url: str | None = None
external_registration_verification: ExternalRegistrationVerification | None = None
payment_config = PaymentConfig(mode="local-sandbox")
stripe_gateway: StripeGateway | None = None
server_version = "AmazonClone/0.1"
def log_message(self, format_string: str, *args: Any) -> None:
safe_path = self.path
if urlsplit(self.path).path.startswith("/ap/"):
safe_path = urlsplit(self.path).path
message = format_string % args
if safe_path != self.path:
message = message.replace(self.path, safe_path)
sys.stdout.write(
json.dumps(
{
"stream": "public",
"client": self.client_address[0],
"method": self.command,
"path": safe_path,
"message": message,
},
ensure_ascii=False,
)
+ "\n"
)
sys.stdout.flush()
def _security_headers(self) -> dict[str, str]:
headers = {
"Content-Security-Policy": (
"default-src 'self'; img-src 'self' data:; style-src 'self'; "
"script-src 'self'; connect-src 'self'; form-action 'self'; "
"frame-ancestors 'none'; base-uri 'self'"
),
"Referrer-Policy": "strict-origin-when-cross-origin",
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"Cache-Control": "no-store",
}
if env_flag("AMAZON_HSTS") or cloudflare_review_profile():
headers["Strict-Transport-Security"] = "max-age=31536000"
if env_flag("AMAZON_NOINDEX") or cloudflare_review_profile():
headers["X-Robots-Tag"] = "noindex, nofollow, noarchive"
return headers
def _public_basic_auth_is_valid(self) -> bool:
try:
expected = public_basic_auth_credentials()
except ValueError:
return False
if expected is None:
return True
header = self.headers.get("Authorization", "")
scheme, separator, encoded = header.partition(" ")
if not separator or scheme.casefold() != "basic":
return False
try:
decoded = base64.b64decode(encoded, validate=True)
except binascii.Error:
return False
username, separator, password = decoded.partition(b":")
if not separator:
return False
expected_username, expected_password = expected
return hmac.compare_digest(
username, expected_username.encode("utf-8")
) and hmac.compare_digest(
password, expected_password.encode("utf-8")
)
def _require_public_basic_auth(self) -> bool:
if self._public_basic_auth_is_valid():
return True
self.close_connection = True
self._send(
401,
b"Authentication required.",
content_type="text/plain; charset=utf-8",
headers={
"Connection": "close",
"WWW-Authenticate": 'Basic realm="WebsiteBench Amazon", charset="UTF-8"',
},
)
return False
def _send(
self,
status: int,
body: bytes = b"",
*,
content_type: str = "text/html; charset=utf-8",
headers: dict[str, str] | None = None,
cookies: list[str] | None = None,
) -> None:
self.send_response(status)
all_headers = self._security_headers()
if headers:
all_headers.update(headers)
all_headers["Content-Type"] = content_type
all_headers["Content-Length"] = str(len(body))
for key, value in all_headers.items():
self.send_header(key, value)
for cookie in cookies or []:
self.send_header("Set-Cookie", cookie)
self.end_headers()
if self.command != "HEAD" and body:
try:
self.wfile.write(body)
except (BrokenPipeError, ConnectionAbortedError, ConnectionResetError):
# Browsers routinely cancel in-flight static responses when a
# tab navigates or closes. The response is already committed,
# so treat that peer disconnect as a normal end of connection
# instead of letting socketserver print a misleading traceback.
self.close_connection = True
def _send_html(
self,
status: int,
html: str,
*,
cookies: list[str] | None = None,
headers: dict[str, str] | None = None,
) -> None:
self._send(status, html.encode("utf-8"), cookies=cookies, headers=headers)
def _send_json(
self,
status: int,
payload: Mapping[str, Any],
*,
cookies: list[str] | None = None,
headers: dict[str, str] | None = None,
) -> None:
self._send(
status,
json_bytes(payload),
content_type="application/json; charset=utf-8",
cookies=cookies,
headers=headers,
)
def _request_cookies(self) -> SimpleCookie[str]:
jar: SimpleCookie[str] = SimpleCookie()
raw = self.headers.get("Cookie", "")
if raw:
try:
jar.load(raw)
except Exception:
pass
return jar
def _session(self) -> tuple[str, str, list[str]]:
jar = self._request_cookies()
morsel = jar.get(SESSION_COOKIE)
token = morsel.value if morsel and len(morsel.value) >= 32 else secrets.token_urlsafe(SESSION_BYTES)
session_digest = digest(token)
self.store.ensure_session(session_digest)
# Publish this browser's storefront delivery location so the header,
# the mobile notice and the PDP buy box all render the same choice
# without threading it through every view signature.
views.set_delivery_context(
self.store.delivery_country(session_digest),
delivery_location_token(session_digest),
)
cookies: list[str] = []
if morsel is None or morsel.value != token:
cookies.append(browser_cookie(SESSION_COOKIE, token))
return token, session_digest, cookies
def _rotate_authenticated_session(
self, session_digest: str, cookies: list[str]
) -> str:
token = secrets.token_urlsafe(SESSION_BYTES)
new_session_digest = digest(token)
self.store.rotate_authenticated_session(session_digest, new_session_digest)
cookies[:] = [browser_cookie(SESSION_COOKIE, token)]
return new_session_digest
def _mail_mode(self) -> str:
return MAIL_SMTP_PENDING if self.smtp_config is not None else MAIL_LOCAL_ONLY
def _auth_mail_status(
self, session_digest: str, purpose: str
) -> dict[str, Any] | None:
if purpose == "password-reset":
pending = self.store.pending_password_reset(session_digest)
if pending is not None and pending.get("verified"):
status = self.store.password_reset_mail_status(session_digest)
if (
self.smtp_config is None
and status is not None
and status.get("status") in {"SMTP_PENDING", "SMTP_FAILED"}
):
return {
"status": MAIL_LOCAL_ONLY,
"delivery_attempts": status.get("delivery_attempts", 0),
"can_retry": False,
}
return status
# Before OTP verification, known and unknown identifiers expose
# exactly the same neutral surface. SMTP outcome and Retry are
# intentionally unavailable until identity ownership is proven.
return {
"status": "QUEUED",
"delivery_attempts": 0,
"can_retry": False,
}
status = self.store.registration_mail_status(session_digest)
if (
self.smtp_config is None
and status is not None
and status.get("status") in {"SMTP_PENDING", "SMTP_FAILED"}
):
return {
"status": MAIL_LOCAL_ONLY,
"delivery_attempts": status.get("delivery_attempts", 0),
"can_retry": False,
}
return status
def _public_order_mail_state(self, order: dict[str, Any]) -> dict[str, Any]:
email = order.get("email")
if (
self.smtp_config is None
and isinstance(email, dict)
and email.get("status") in {"SMTP_PENDING", "SMTP_FAILED"}
):
return {
**order,
"email": {
**email,
"status": MAIL_LOCAL_ONLY,
"is_simulation": True,
"can_retry": False,
},
}
return order
def _dispatch_mail(self, delivery: dict[str, Any] | None) -> None:
"""Attempt configured SMTP asynchronously so reset responses stay uniform."""
config = self.smtp_config
if delivery is None or config is None:
return
dispatch_mail_delivery(self.store, config, delivery)
def _flow_digest(self) -> str:
morsel = self._request_cookies().get(FLOW_COOKIE)
return digest(morsel.value) if morsel else ""
def _referer(self) -> str:
return self.headers.get("Referer", "")
def _signin_location_for_cart_mutation(self) -> str:
referer = urlsplit(self._referer())
return_candidate = ""
if (
referer.scheme in {"http", "https"}
and referer.netloc.casefold() == self.headers.get("Host", "").casefold()
and referer.path.startswith("/")
):
return_candidate = referer.path
if referer.query:
return_candidate += "?" + referer.query
return_to = auth_views.safe_return_target(
{"openid.return_to": [return_candidate]}
) or "/gp/cart/view.html"
return "/ap/signin?" + urlencode({"openid.return_to": return_to})
def _same_origin_path(self, raw_url: str, expected_path: str) -> bool:
parsed = urlsplit(raw_url)
return bool(
parsed.scheme in {"http", "https"}
and parsed.netloc == self.headers.get("Host", "")
and parsed.path == expected_path
)
def _terminal_source_is_canonical(self) -> bool:
referer_ok = self._same_origin_path(self._referer(), PDP_PATH)
origin = self.headers.get("Origin", "")
if not origin:
return referer_ok
parsed = urlsplit(origin)
return referer_ok and parsed.scheme in {"http", "https"} and parsed.netloc == self.headers.get("Host", "")
def _form_fields(self, raw_body: bytes) -> dict[str, str] | None:
media_type = self.headers.get("Content-Type", "").split(";", 1)[0].strip().lower()
if media_type != "application/x-www-form-urlencoded":
return None
try:
pairs = parse_qsl(
raw_body.decode("utf-8"),
keep_blank_values=True,
strict_parsing=True,
max_num_fields=16,
)
except (UnicodeDecodeError, ValueError):
return None
fields: dict[str, str] = {}
for name, value in pairs:
if name in fields:
return None
fields[name] = value
return fields
def _json_fields(
self, raw_body: bytes, expected_fields: frozenset[str]
) -> dict[str, str] | None:
media_type = (
self.headers.get("Content-Type", "")
.split(";", 1)[0]
.strip()
.lower()
)
if (
media_type != "application/json"
or not raw_body
or len(raw_body) > MAX_AUTH_JSON_BYTES
):
return None
try:
payload = json.loads(raw_body.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError):
return None
if (
not isinstance(payload, dict)
or set(payload) != expected_fields
or any(not isinstance(payload[name], str) for name in expected_fields)
):
return None
return {name: payload[name] for name in expected_fields}
def _external_client_address(self) -> str:
candidate = self.client_address[0]
if env_flag("AMAZON_TRUST_PROXY_HEADERS") or cloudflare_review_profile():
candidate = self.headers.get(
"X-WebsiteBench-Client-IP", ""
).strip()
try:
return str(ipaddress.ip_address(candidate))
except ValueError:
# One shared fallback budget fails safely when a trusted proxy did
# not provide a parseable address.
return "unknown"
def _expected_request_authority(self) -> tuple[str, str]:
scheme = (
"https"
if env_flag("AMAZON_COOKIE_SECURE") or cloudflare_review_profile()
else "http"
)
authority = self.headers.get("Host", "")
if env_flag("AMAZON_TRUST_PROXY_HEADERS") or cloudflare_review_profile():
forwarded_scheme = self.headers.get("X-Forwarded-Proto", "").strip()
forwarded_authority = self.headers.get(
"X-Forwarded-Host", ""
).strip()
if forwarded_scheme in {"http", "https"}:
scheme = forwarded_scheme
if forwarded_authority:
authority = forwarded_authority
return scheme, authority.casefold()
def _auth_post_origin_is_safe(self) -> bool:
origin = self.headers.get("Origin", "")
candidate = origin or self.headers.get("Referer", "")
if not candidate:
return False
parsed = urlsplit(candidate)
expected_scheme, expected_authority = self._expected_request_authority()
return (
parsed.scheme == expected_scheme
and parsed.netloc.casefold() == expected_authority
)
def _delivery_return_location(self, *, error: bool) -> str:
"""Where to send the browser after a delivery-location submission.
The source storefront re-renders whatever page the picker was opened
from. Only the path and query of a same-authority Referer are reused,
so this can never become an open redirect.
"""
target = "/"
referer = self.headers.get("Referer", "")
if referer:
parsed = urlsplit(referer)
expected_scheme, expected_authority = self._expected_request_authority()
same_origin = (
parsed.scheme == expected_scheme
and parsed.netloc.casefold() == expected_authority
)
if same_origin and parsed.path.startswith("/"):
target = parsed.path
retained = [
(name, value)
for name, value in parse_qsl(parsed.query, keep_blank_values=True)
if name != "locationError"
]
if retained:
target += "?" + urlencode(retained)
if error:
target += "&" if "?" in target else "?"
target += "locationError=1"
return target
def _stripe_return_urls(self) -> tuple[str, str]:
scheme, authority = self._expected_request_authority()
if not authority:
raise ContractError("checkout request authority is unavailable")
root = f"{scheme}://{authority}"
placeholder = "{CHECKOUT_SESSION_ID}"
success = (
root
+ STRIPE_RETURN_PATH
+ "?session_id="
+ placeholder
)
cancel = (
root
+ STRIPE_RETURN_PATH
+ "?cancelled=1&session_id="
+ placeholder
)
return success, cancel
def _handle_stripe_webhook(self) -> None:
config = self.payment_config
gateway = self.stripe_gateway
if not config.stripe_enabled or gateway is None:
self._send(
404,
b"Not Found",
content_type="text/plain; charset=utf-8",
)
return
try:
content_length = int(
self.headers.get("Content-Length", "0") or "0"
)
except ValueError:
self._send(
400,
b"Invalid Content-Length",
content_type="text/plain; charset=utf-8",
)
return
if (
content_length <= 0
or content_length > STRIPE_WEBHOOK_MAX_BYTES
):
self.close_connection = True
self._send(
413,
b"Webhook body is too large",
content_type="text/plain; charset=utf-8",
headers={"Connection": "close"},
)
return
raw_body = self.rfile.read(content_length)
try:
if config.trust_edge_webhook:
if (
self.headers.get("X-WebsiteBench-Stripe-Verified", "")
!= "1"
):
raise StripeSignatureError(
"edge webhook verification is required"
)
else:
assert config.webhook_secret is not None
verify_stripe_signature(
raw_body,
self.headers.get("Stripe-Signature", ""),
config.webhook_secret,
)
event = json.loads(raw_body.decode("utf-8"))
if not isinstance(event, dict):
raise ValueError("webhook event must be an object")
data = event.get("data")
provider_object = (
data.get("object")
if isinstance(data, dict)
else None
)
if (
not isinstance(provider_object, dict)
or not isinstance(event.get("id"), str)
or not isinstance(event.get("type"), str)
or isinstance(event.get("created"), bool)
or not isinstance(event.get("created"), int)
):
raise ValueError("webhook event shape is invalid")
session_id = str(provider_object.get("id") or "")
if STRIPE_PROVIDER_SESSION_PATTERN.fullmatch(session_id) is None:
raise ValueError("webhook Session ID is invalid")
except (
UnicodeDecodeError,
json.JSONDecodeError,
StripeSignatureError,
ValueError,
):
self._send_json(400, {"ok": False, "error": "invalid-webhook"})
return
try:
provider_session = gateway.retrieve_checkout_session(session_id)
result = self.store.process_stripe_event(
str(event["id"]),
str(event["type"]),
int(event["created"]),
provider_session,
mail_mode=self._mail_mode(),
)
except StripeAPIError:
self._send_json(
503,
{"ok": False, "error": "stripe-temporarily-unavailable"},
)
return
except ContractError:
self._send_json(
400, {"ok": False, "error": "invalid-webhook-event"}
)
return
order_id = result.get("order_id")
if isinstance(order_id, int):
self._dispatch_mail(self.store.order_mail_delivery(order_id))
self._send_json(
200,
{
"ok": True,
"duplicate": bool(result.get("duplicate")),
"status": str(result.get("event_status") or "PROCESSED"),
},
)
def _serve_static(self, path: str) -> None:
relative = unquote(path.removeprefix("/static/"))
if relative == "auth-verification.js":
self._send(
200,
registration_frontend_script(),
content_type="text/javascript; charset=utf-8",
headers={"Cache-Control": "no-cache"},
)
return
candidate = (STATIC_ROOT / relative).resolve()
if STATIC_ROOT not in candidate.parents or not candidate.is_file():
self._send(404, b"Not Found", content_type="text/plain; charset=utf-8")
return
content_type = mimetypes.guess_type(candidate.name)[0] or "application/octet-stream"
self._send(
200,
candidate.read_bytes(),
content_type=content_type,
headers={"Cache-Control": "no-cache"},
)
def _send_product_page(
self,
product: dict[str, Any],
*,
cart_count: int,
flow_ready: bool,
account_name: str | None,
session_digest: str,
query: dict[str, list[str]],
path: str,
cookies: list[str],
) -> None:
asin = str(product["asin"])
default_options = self.store.default_product_options(asin)
option_quotes = self.store.product_option_quotes(asin)
default_quote = next(
(
quote
for quote in option_quotes
if quote.get("selected_options") == default_options
),
None,
)
product = {
**compare_entry_product(self.store, product),
"default_selected_options": default_options,
"option_spec": self.store.product_option_spec(asin),
"option_quote_matrix": option_quotes,
"option_unavailable_copy": UNAVAILABLE_SELECTION_COPY,
"recommendations": self.store.product_recommendations(asin),
}
if default_quote is not None:
product.update(
{
"price_minor": int(default_quote["price_minor"]),
"currency": str(default_quote["currency"]),
"image_path": str(default_quote["image_path"]),
"availability": str(default_quote["display_availability"]),
}
)
try:
review_star, review_sort = review_query_parameters(query)
except ReviewValidationError as exc:
self._send_html(
400,
views.error_page(str(exc), cart_count, 400),
cookies=cookies,
)
return
review_kwargs: dict[str, Any] = {
"local_reviews": self.store.reviews_for_session(
session_digest, product["asin"], sort=review_sort
),
"review_star": review_star,
"review_sort": review_sort,
"review_base_path": path,
}
page = views.product_page(
product,
cart_count,
flow_ready,
account_name,
**review_kwargs,
)
self._send_html(200, page, cookies=cookies)
def _render_search_view(
self,
search_request: SearchRequest,
cart_count: int,
account_name: str | None,
) -> str:
"""Build one deterministic page-family search model."""
display_catalog = self.store.display_products()
display_by_asin = {
str(product["asin"]): product for product in display_catalog
}
category_tile = HOME_CATEGORY_QUERY_TILES.get(
normalize_search_query(search_request.query)
)
if category_tile is not None:
products = []
for source_index, category_product in enumerate(category_tile["products"]):
asin = str(category_product["asin"])
offer = self.store.commerce_offer(asin)
if offer is None:
raise ContractError(
f"home category product has no server quote: {asin}"
)
product = {
**dict(category_product),
**display_by_asin[asin],
**offer,
"category_key": category_product["category_key"],
"category_index": category_product["category_index"],
"category_label": category_product["category_label"],
"category_query": category_product["category_query"],
"source_search_url": category_product["source_search_url"],
}
default_options = self.store.default_product_options(asin)
product["default_selected_options"] = default_options
products.append(
build_search_hit(
product,
relevance=len(category_tile["products"]) - source_index,
source_index=source_index,
)
)
candidates = products
elif is_portable_ssd_contract_query(search_request.query):
products: list[dict[str, Any]] = []
source_products: list[dict[str, Any]] = []
frozen_by_asin = {
str(product["asin"]): product for product in self.store.products()
}
for asin in PORTABLE_SEARCH_ORDER:
source_product = frozen_by_asin[asin]
product = {
**dict(source_product),
**display_by_asin[str(source_product["asin"])],
}
# The frozen products come from the directly observed External
# SSD ranking/search surface, so Computers is an evidenced
# department identity rather than a title-based inference.
product["placements"] = [
{
"railKey": "best-sellers-computers-accessories",
"railTitle": "Computers & Accessories",
}
]
default_options = self.store.default_product_options(product["asin"])
product["default_selected_options"] = default_options
for quote in self.store.product_option_quotes(product["asin"]):
if quote.get("selected_options") == default_options:
product["availability"] = quote.get("display_availability")
break
products.append(product)
source_products.append(dict(source_product))
for source_product in BROWSE_BREADTH["portable_ssd_supplement"]:
products.append(
{
**dict(source_product),
**display_by_asin[str(source_product["asin"])],
}
)
source_products.append(dict(source_product))
total_candidates = len(products)
candidates = [
replace(
build_search_hit(
product,
relevance=total_candidates - index,
source_index=index,
),
# Display enrichment must not create new membership in a
# frozen source facet. Supplemental cards without a
# captured brand remain outside Brand filtering even if a
# later PDP capture established their manufacturer.
brand=(
str(source_products[index]["brand"])
if isinstance(source_products[index].get("brand"), str)
and str(source_products[index]["brand"]).strip()
else None
),
)
for index, product in enumerate(products)
]
elif (
search_request.department != "aps"
or source_department_for_query(search_request.query) is not None
or normalize_search_query(search_request.query) in FROZEN_SEARCH_QUERIES
):
candidates = candidate_search_hits(
search_request,
HOME_PRODUCT_CATALOG,
SEARCH_DEPARTMENT_SUPPLEMENTS,
)
enriched_candidates = []
for hit in candidates:
enriched = build_search_hit(
{
**dict(hit.product),
**display_by_asin[hit.asin],
},
relevance=hit.relevance,
source_index=hit.source_index,
)
# Frozen query/department membership comes from the captured
# result set. Enrichment may fill shopping facts, but it must
# not rewrite that source ordering or membership.
enriched_candidates.append(
replace(enriched, departments=hit.departments)
)
candidates = enriched_candidates
else:
candidates = candidate_search_hits(
search_request,
{str(product["asin"]): product for product in display_catalog},
)
eligible_asins = self.store.compare_eligible_asins()
candidates = [
replace(
hit,
product=compare_entry_product(
self.store,
hit.product,
eligible_asins=eligible_asins,
),
)
for hit in candidates
]
search_page = refine_search_hits(search_request, candidates, page_size=16)
visible_candidates = [
hit
for hit in candidates
if search_request.department == "aps"
or search_request.department in hit.departments
]
available_brands = tuple(
dict.fromkeys(
hit.brand for hit in visible_candidates if hit.brand is not None
)
)
price_ranges = (
(None, 2499),
(2500, 4999),
(5000, 9999),
(10000, 19999),
(20000, None),
)
available_facets = {
"departments": tuple(
dict.fromkeys(
department
for hit in candidates
for department in hit.departments
)
),
"brand": bool(available_brands),
"price_ranges": tuple(
(minimum, maximum)
for minimum, maximum in price_ranges
if any(
hit.price_minor is not None
and (minimum is None or hit.price_minor >= minimum)
and (maximum is None or hit.price_minor <= maximum)
for hit in visible_candidates
)
),
"rating": any(
hit.rating_value is not None and hit.rating_value >= 4
for hit in visible_candidates
),
"availability": any(
hit.availability == "in-stock" for hit in visible_candidates
),
}
return views.search_results_page(
search_page,
cart_count,
account_name,
available_brands=available_brands,
available_facets=available_facets,
result_layout="grid" if category_tile is not None else "list",
department_rail_products=(
[
product
for product in display_catalog
if search_request.department == "computers"
and str(product.get("brand") or "").casefold() == "sandisk"
]
if not search_request.query
else []
),
)
def do_HEAD(self) -> None:
self.do_GET()
def do_GET(self) -> None:
request = urlsplit(self.path)
path = request.path or "/"
if path == "/healthz":
try:
self.store.meta()
except Exception:
self._send(
503,
json_bytes({"ok": False}),
content_type="application/json; charset=utf-8",
)
return
build_id = os.environ.get("DEPLOYMENT_BUILD_ID", "")
build_headers = (
{"X-WebsiteBench-Container-Build-ID": build_id}
if re.fullmatch(r"[0-9a-f]{40}", build_id)
else None
)
self._send(
200,
json_bytes({"ok": True}),
content_type="application/json; charset=utf-8",
headers=build_headers,
)
return
if not self._require_public_basic_auth():
return
try:
query = parse_qs(
request.query, keep_blank_values=True, max_num_fields=64
)
except ValueError:
self._send(
400,
b"Too many query parameters.",
content_type="text/plain; charset=utf-8",
)
return
if path.startswith("/static/"):
self._serve_static(path)
return
if path.startswith("/__bench/"):
self._send(404, b"Not Found", content_type="text/plain; charset=utf-8")
return
if path == "/robots.txt":
self._send(200, b"User-agent: *\nDisallow: /__bench/\n", content_type="text/plain; charset=utf-8")
return
_, session_digest, cookies = self._session()
cart_count = self.store.cart_count(session_digest)
current_account = self.store.account_for_session(session_digest)
account_name = (
str(current_account["display_name"]) if current_account is not None else None
)
referer = self._referer()
if path == STRIPE_RETURN_PATH:
if (
not self.payment_config.stripe_enabled
or self.stripe_gateway is None
):
self._send_html(
404, views.not_found_page(cart_count), cookies=cookies
)
return
if current_account is None:
location = "/ap/signin?" + urlencode(
{"openid.return_to": STRIPE_RETURN_PATH}
)
self._send(
303,
b"",
headers={"Location": location},
cookies=cookies,
)
return
session_values = query.get("session_id", [])
session_id = (
session_values[0]
if len(session_values) == 1
and STRIPE_PROVIDER_SESSION_PATTERN.fullmatch(
session_values[0]
)
else ""
)
mapping = (
self.store.stripe_checkout_for_session(
session_digest, session_id
)
if session_id
else None
)
if mapping is None:
self._send_html(
404, views.not_found_page(cart_count), cookies=cookies
)
return
try:
provider_session = (
self.stripe_gateway.retrieve_checkout_session(session_id)
)
order = self.store.confirm_stripe_return(
session_digest,
session_id,
provider_session,
mail_mode=self._mail_mode(),
)
except StripeAPIError:
self._send_html(
503,
views.stripe_payment_status_page(
mapping,
cart_count,
account_name or "Customer",
session_id=session_id,
state="unavailable",
cancelled=False,
),
cookies=cookies,
)
return
except ContractError:
self._send_html(
409,
views.stripe_payment_status_page(
mapping,
cart_count,
account_name or "Customer",
session_id=session_id,
state="mismatch",
cancelled=False,
),
cookies=cookies,
)
return
if order is not None:
self._dispatch_mail(
self.store.order_mail_delivery(order["order_id"])
)
location = ORDER_DETAIL_PATH + "?" + urlencode(
{"orderID": order["order_id"]}
)
self._send(
303,
b"",
headers={"Location": location},
cookies=cookies,
)
return
cancelled = query.get("cancelled", []) == ["1"]
self._send_html(
200,
views.stripe_payment_status_page(
mapping,
cart_count,
account_name or "Customer",
session_id=session_id,
state=str(
provider_session.get("payment_status") or "unpaid"
),
cancelled=cancelled,
),
cookies=cookies,
)
return
if path == SEARCH_SUGGESTIONS_PATH:
try:
suggestion_request = parse_suggestion_request(request.query)
suggestions = suggest_search_terms(
suggestion_request, SEARCH_SUGGESTION_CORPUS
)
except SearchSuggestionValidationError as exc:
self.store.record_read_route(
session_digest,
"SEARCH_SUGGESTIONS",
path,
referer,
status=400,
)
self._send(
400,
json_bytes({"error": str(exc)}),
content_type="application/json; charset=utf-8",
cookies=cookies,
)
return
self.store.record_read_route(
session_digest, "SEARCH_SUGGESTIONS", path, referer
)
self._send(
200,
json_bytes(
{
"department": suggestion_request.department,
"query": suggestion_request.query,
"suggestions": [
{
"department": suggestion.department,
"kind": suggestion.kind,
"value": suggestion.value,
}
for suggestion in suggestions
],
}
),
content_type="application/json; charset=utf-8",
cookies=cookies,
)
return
if path == AUTH_SIGNOUT_PATH:
self._send(
405,
b"Sign out requires POST.",
content_type="text/plain; charset=utf-8",
headers={"Allow": "POST"},
cookies=cookies,
)
return
if path in {"/", "/ref=nav_logo"}:
self.store.record_read_route(session_digest, "HOME", path, referer)
page = views.home_page(self.store.products(), cart_count, account_name)
self._send_html(200, page, cookies=cookies)
return
home_collection_match = HOME_COLLECTION_ROUTE.fullmatch(path)
if home_collection_match:
collection_key, tile_value = home_collection_match.groups()
tile_index = int(tile_value) if tile_value is not None else None
group = HOME_CATEGORY_GROUPS.get(collection_key)
if group is None or (
tile_index is not None and tile_index not in range(1, 5)
):
self.store.record_read_route(
session_digest,
"HOME_COLLECTION_NOT_FOUND",
path,
referer,
status=404,
)
self._send_html(
404, views.not_found_page(cart_count), cookies=cookies
)
return
destination = views.home_collection_href(collection_key, tile_index)
self.store.record_read_route(
session_digest, "HOME_COLLECTION_REDIRECT", path, referer
)
self._send(
302,
b"",
headers={"Location": destination},
cookies=cookies,
)
return
if path == "/Best-Sellers/zgbs":
self.store.record_read_route(session_digest, "BEST_SELLERS_ROOT", path, referer)
page = views.best_sellers_root(self.store.products(), cart_count, account_name)
self._send_html(200, page, cookies=cookies)
return
if path == BEST_SELLERS_PATH:
self.store.record_best_sellers(session_digest, path, referer)
page = views.external_ssd_best_sellers(self.store.ranking(), cart_count, account_name)
self._send_html(200, page, cookies=cookies)
return
if path == PDP_PATH:
capability = secrets.token_urlsafe(SESSION_BYTES)
flow_ready = self.store.record_pdp(
session_digest,
path,
referer,
digest(capability),
self._same_origin_path(referer, BEST_SELLERS_PATH),
)
if flow_ready:
cookies.append(browser_cookie(FLOW_COOKIE, capability))
product = product_for_pdp(self.store, TARGET_ASIN)
assert product is not None
self._send_product_page(
product,
cart_count=cart_count,
flow_ready=flow_ready,
account_name=account_name,
session_digest=session_digest,
query=query,
path=path,
cookies=cookies,
)
return
if path == f"/gp/aw/d/{TARGET_ASIN}":
self.store.record_read_route(session_digest, "TARGET_PDP_MOBILE_ALIAS", path, referer)
product = product_for_pdp(self.store, TARGET_ASIN)
assert product is not None
self._send_product_page(
product,
cart_count=cart_count,
flow_ready=False,
account_name=account_name,
session_digest=session_digest,
query=query,
path=path,
cookies=cookies,
)
return
bare_product_match = BARE_PDP_ROUTE.fullmatch(path)
if bare_product_match:
asin = bare_product_match.group(1)
product = product_for_pdp(self.store, asin)
if product is not None:
self.store.record_read_route(session_digest, "HOME_PRODUCT_DETAIL", path, referer)
self._send_product_page(
product,
cart_count=cart_count,
flow_ready=False,
account_name=account_name,
session_digest=session_digest,
query=query,
path=path,
cookies=cookies,
)
return
product_match = PDP_ROUTE.fullmatch(path)
if product_match:
slug, asin = product_match.groups()
product = product_for_pdp(self.store, asin)
if product is not None and product["slug"] == slug:
self.store.record_read_route(session_digest, "PRODUCT_DETAIL", path, referer)
self._send_product_page(
product,
cart_count=cart_count,
flow_ready=False,
account_name=account_name,
session_digest=session_digest,
query=query,
path=path,
cookies=cookies,
)
return
product_reviews_match = PRODUCT_REVIEWS_ROUTE.fullmatch(path)
if product_reviews_match:
asin = product_reviews_match.group(1)
product = product_for_pdp(self.store, asin)
if product is None:
self.store.record_read_route(
session_digest, "PRODUCT_REVIEWS_NOT_FOUND", path, referer, status=404
)
self._send_html(404, views.not_found_page(cart_count), cookies=cookies)
return
try:
review_star, review_sort = review_query_parameters(query)
local_reviews = self.store.reviews_for_session(
session_digest, asin, sort=review_sort
)
except ReviewValidationError as exc:
self._send_html(
400,
views.error_page(str(exc), cart_count, 400),
cookies=cookies,
)
return
review_html = render_reviews_section(
asin,
local_reviews,
star=review_star,
sort=review_sort,
account_name=account_name,
base_path=path,
product_label=str(product["title"]),
)
self.store.record_read_route(
session_digest, "PRODUCT_REVIEWS", path, referer
)
self._send_html(
200,
views.product_reviews_page(
product, review_html, cart_count, account_name
),
cookies=cookies,
)
return
if path in {"/s", "/s/ref=nb_sb_noss"}:
try:
search_request = parse_search_request(request.query)
page = self._render_search_view(
search_request, cart_count, account_name
)
except SearchValidationError as exc:
self.store.record_read_route(
session_digest, "SEARCH", path, referer, status=400
)
self._send_html(
400,
views.error_page(str(exc), cart_count, 400),
cookies=cookies,
)
return
self.store.record_read_route(session_digest, "SEARCH", path, referer)
self._send_html(200, page, cookies=cookies)
return
if path == "/gp/cart/view.html":
self.store.record_read_route(session_digest, "CART", path, referer)
lines = self.store.cart(session_digest)
saved_lines = self.store.saved_cart(session_digest)
page = views.cart_page(
lines,
self.store.cart_count(session_digest),
account_name,
saved_lines=saved_lines,
recommendation_products=self.store.product_recommendations(
"B0874XN4D8"
),
)
self._send_html(200, page, cookies=cookies)
return
if path == ADD_TO_CART_CONFIRMATION_PATH:
line_id_values = query.get("lineID", [])
if set(query) != {"lineID"} or len(line_id_values) != 1:
self._send_html(
400,
views.error_page("The added item could not be identified.", cart_count, 400),
cookies=cookies,
)
return
line_id = line_id_values[0]
if CART_LINE_ID_PATTERN.fullmatch(line_id) is None:
self._send_html(
400,
views.error_page("The added cart line is invalid.", cart_count, 400),
cookies=cookies,
)
return
matching_lines = [
line
for line in self.store.cart(session_digest)
if line["line_id"] == line_id
]
line = matching_lines[0] if matching_lines else None
product = (
product_for_pdp(self.store, str(line["asin"]))
if line is not None
else None
)
if product is None or line is None:
self._send_html(
404, views.not_found_page(cart_count), cookies=cookies
)
return
self.store.record_read_route(
session_digest, "ADD_TO_CART_CONFIRMATION", path, referer
)
self._send_html(
200,
views.cart_added_page(
{**product, **line},
self.store.cart(session_digest),
self.store.cart_count(session_digest),
account_name,
recommendation_products=self.store.product_recommendations(
str(product["asin"])
),
),
cookies=cookies,
)
return
if path == COMPARE_PATH:
compare_products = [
compare_product_for_view(self.store, item)
for item in self.store.compare_items(session_digest)
]
error = (query.get("error") or [None])[0]
self.store.record_read_route(session_digest, "COMPARE", path, referer)
self._send_html(
200,
views.compare_page(compare_products, cart_count, account_name, error),
cookies=cookies,
)
return
if path == SITE_DIRECTORY_PATH:
self.store.record_read_route(session_digest, "SITE_DIRECTORY", path, referer)
directory_sections = []
for raw_section in BROWSE_BREADTH["rail_sections"]:
section = dict(raw_section)
section["products"] = [
display
for product in raw_section.get("products", ())
if (display := self.store.display_product(str(product["asin"])))
is not None
]
directory_sections.append(section)
page = views.site_directory_page(
directory_sections,
cart_count,
account_name,
)
self._send_html(200, page, cookies=cookies)
return
if path == "/gp/goldbox/":
self.store.record_read_route(session_digest, "TODAYS_DEALS", path, referer)
self._send_html(
200,
views.deals_page(
build_deals_view(DEALS_CATALOG, query),
cart_count,
account_name,
),
cookies=cookies,
)
return
if path == GIFT_CARDS_PATH:
self.store.record_read_route(session_digest, "GIFT_CARDS", path, referer)
self._send_html(
200,
specialty_views.gift_cards_page(cart_count, account_name),
cookies=cookies,
)
return
if path == specialty.GIFT_CARD_PREVIEW_PATH:
preview_values = query.get("previewID")
preview = (
specialty.gift_card_preview(
self.store, session_digest, preview_values[0]
)
if set(query) == {"previewID"}
and preview_values is not None
and len(preview_values) == 1
else None
)
if preview is None:
self.store.record_read_route(
session_digest, "GIFT_CARD_PREVIEW_NOT_FOUND", path, referer, status=404
)
self._send_html(404, views.not_found_page(cart_count), cookies=cookies)
return
self.store.record_read_route(
session_digest, "GIFT_CARD_PREVIEW", path, referer
)
self._send_html(
200,
specialty_views.gift_card_preview_page(
preview, cart_count, account_name
),
cookies=cookies,
)
return
if path in {
specialty.GIFT_CARD_BALANCE_PATH,
specialty.GIFT_CARD_REDEEM_PATH,
}:
status_values = query.get("status")
if query and not (
set(query) == {"status"} and status_values == ["not-applied"]
):
self.store.record_read_route(
session_digest, "GIFT_CARD_BALANCE_INVALID", path, referer, status=400
)
self._send_html(
400,
views.error_page("Check the request and try again.", cart_count, 400),
cookies=cookies,
)
return
balance = specialty.gift_card_balance(self.store, session_digest)
self.store.record_read_route(
session_digest, "GIFT_CARD_BALANCE", path, referer
)
self._send_html(
200,
specialty_views.gift_card_balance_page(
balance,
cart_count,
account_name,
redemption_result=status_values == ["not-applied"],
),
cookies=cookies,
)
return
if path == specialty.SELL_PATH:
drafts = specialty.seller_drafts(self.store, session_digest)
self.store.record_read_route(session_digest, "SELL", path, referer)
self._send_html(
200,
specialty_views.sell_page(drafts, cart_count, account_name),
cookies=cookies,
)
return
if path == specialty.SELL_DRAFT_PATH:
draft_values = query.get("draftID")
draft = (
specialty.seller_draft(self.store, session_digest, draft_values[0])
if set(query) == {"draftID"}
and draft_values is not None
and len(draft_values) == 1
else None
)
if draft is None:
self.store.record_read_route(
session_digest, "SELL_DRAFT_NOT_FOUND", path, referer, status=404
)
self._send_html(404, views.not_found_page(cart_count), cookies=cookies)
return
self.store.record_read_route(session_digest, "SELL_DRAFT", path, referer)
self._send_html(
200,
specialty_views.seller_draft_page(draft, cart_count, account_name),
cookies=cookies,
)
return
if path == specialty.REGISTRY_PATH:
own_registries = specialty.registries(self.store, session_digest)
self.store.record_read_route(session_digest, "REGISTRY", path, referer)
self._send_html(
200,
specialty_views.registry_page(
own_registries, cart_count, account_name
),
cookies=cookies,
)
return
if path == specialty.REGISTRY_SEARCH_PATH:
search_values = query.get("query")
if not (
set(query) == {"query"}
and search_values is not None
and len(search_values) == 1
):
self.store.record_read_route(
session_digest, "REGISTRY_SEARCH_INVALID", path, referer, status=400
)
self._send_html(
400,
views.error_page("Check the search and try again.", cart_count, 400),
cookies=cookies,
)
return
try:
normalized_query, results = specialty.search_registries(
self.store, session_digest, search_values[0]
)
except specialty.SpecialtyValidationError:
self.store.record_read_route(
session_digest, "REGISTRY_SEARCH_INVALID", path, referer, status=400
)
self._send_html(
400,
views.error_page("Check the search and try again.", cart_count, 400),
cookies=cookies,
)
return
self.store.record_read_route(session_digest, "REGISTRY_SEARCH", path, referer)
self._send_html(
200,
specialty_views.registry_search_page(
normalized_query, results, cart_count, account_name
),
cookies=cookies,
)
return
if path == specialty.REGISTRY_DETAIL_PATH:
registry_values = query.get("registryID")
registry = (
specialty.registry(self.store, session_digest, registry_values[0])
if set(query) == {"registryID"}
and registry_values is not None
and len(registry_values) == 1
else None
)
if registry is None:
self.store.record_read_route(
session_digest, "REGISTRY_DETAIL_NOT_FOUND", path, referer, status=404
)
self._send_html(404, views.not_found_page(cart_count), cookies=cookies)
return
self.store.record_read_route(
session_digest, "REGISTRY_DETAIL", path, referer
)
self._send_html(
200,
specialty_views.registry_detail_page(
registry, cart_count, account_name
),
cookies=cookies,
)
return
if path == specialty.PRIME_VIDEO_PATH:
self.store.record_read_route(
session_digest, "PRIME_VIDEO_PLACEHOLDER", path, referer
)
self._send_html(
200,
specialty_views.prime_video_page(cart_count, account_name),
cookies=cookies,
)
return
if path == CUSTOMER_SERVICE_PATH:
node_id = (query.get("nodeId") or [CUSTOMER_SERVICE_NODE])[0].strip()
if node_id == SHIPPING_POLICIES_NODE:
route_key = "SHIPPING_POLICIES"
page = views.shipping_policies_page(cart_count, account_name)
elif node_id == RETURNS_REPLACEMENTS_NODE:
route_key = "RETURNS_REPLACEMENTS"
page = views.returns_replacements_page(cart_count, account_name)
elif node_id == CONDITIONS_OF_USE_NODE:
route_key = "CONDITIONS_OF_USE"
page = views.conditions_of_use_page(cart_count, account_name)
elif node_id == PRIVACY_NOTICE_NODE:
route_key = "PRIVACY_NOTICE"
page = views.privacy_notice_page(cart_count, account_name)
else:
route_key = "CUSTOMER_SERVICE"
help_query = (query.get("help_keywords") or [""])[0].strip()
page = views.customer_service_page(
cart_count,
account_name,
help_query=help_query,
)
self.store.record_read_route(session_digest, route_key, path, referer)
self._send_html(200, page, cookies=cookies)
return
if path == DELIVERY_PREFERENCE_PATH:
self.store.record_read_route(
session_digest, "DELIVERY_LOCATION", path, referer
)
self._send_html(
200,
views.delivery_location_page(
cart_count,
account_name,
error=bool(query.get("locationError")),
),
cookies=cookies,
)
return
if path == DELIVERY_SELECTIONS_PATH:
selected_code, selected_label = self.store.delivery_country(session_digest)
self.store.record_read_route(
session_digest, "DELIVERY_SELECTIONS", path, referer
)
self._send_json(
200,
{
"header": "Choose your location",
"destinationType": "COUNTRY",
"action": DELIVERY_PREFERENCE_PATH,
"token": delivery_location_token(session_digest),
"selected": selected_code,
"selectedLabel": selected_label,
"options": [
{"code": code, "label": label}
for code, label in SUPPORTED_DELIVERY_COUNTRIES
],
},
cookies=cookies,
)
return
if path in PUBLIC_NAVIGATION_LANDINGS:
title, copy, links = PUBLIC_NAVIGATION_LANDINGS[path]
self.store.record_read_route(session_digest, "PUBLIC_NAVIGATION", path, referer)
self._send_html(
200,
views.navigation_landing_page(
title,
copy,
links,
cart_count,
account_name,
),
cookies=cookies,
)
return
if path in AUTH_PATHS:
self.store.record_read_route(session_digest, "AUTH_FRONTEND", path, referer)
if path == "/ap/cvf/verify":
purpose = (query.get("purpose") or ["registration"])[0]
pending = (
self.store.pending_password_reset(session_digest)
if purpose == "password-reset"
else self.store.pending_registration(session_digest)
)
self._send_html(
200,
auth_views.verification_page(
query,
masked_destination=(pending or {}).get("masked_email"),
mail_delivery_mode=(
"SMTP" if self.smtp_config is not None else "LOCAL_ONLY"
),
mail_delivery=self._auth_mail_status(
session_digest, purpose
),
local_inbox_url=self.local_inbox_url,
),
cookies=cookies,
)
return
if path == "/ap/forgotpassword" and (
(query.get("stage") or [""])[0].lower() == "reset-password"
):
pending_reset = self.store.pending_password_reset(session_digest)
if not pending_reset or not pending_reset["verified"]:
self._send(
303,
b"",
headers={"Location": "/ap/forgotpassword"},
cookies=cookies,
)
return
if (
path == "/ap/register"
and self.external_registration_verification is not None
):
page = auth_views.register_page(
query, external_verification=True
)
else:
page = auth_views.page_for(path, query)
self._send_html(200, page, cookies=cookies)
return
if path in {ADDRESS_BOOK_PATH, ADDRESS_ADD_PATH, ADDRESS_EDIT_PATH}:
if current_account is None:
return_target = path
if path == ADDRESS_EDIT_PATH and request.query:
return_target += "?" + request.query
location = "/ap/signin?" + urlencode(
{"openid.return_to": return_target}
)
self._send(303, b"", headers={"Location": location}, cookies=cookies)
return
if path == ADDRESS_BOOK_PATH:
status_values = query.get("status", [])
status = (
status_values[0]
if len(status_values) == 1
and status_values[0]
in {"added", "updated", "deleted", "default"}
else None
)
self.store.record_read_route(
session_digest, "ADDRESS_BOOK", path, referer
)
self._send_html(
200,
views.address_book_page(
self.store.addresses_for_session(session_digest),
cart_count,
account_name or "Customer",
status=status,
),
cookies=cookies,
)
return
if path == ADDRESS_ADD_PATH:
self._send_html(
200,
views.address_form_page(
None, cart_count, account_name or "Customer"
),
cookies=cookies,
)
return
address_values = query.get("addressID", [])
address = (
self.store.address_for_session(
session_digest, address_values[0]
)
if len(address_values) == 1
else None
)
if address is None:
self._send_html(
404, views.not_found_page(cart_count), cookies=cookies
)
return
self._send_html(
200,
views.address_form_page(
address, cart_count, account_name or "Customer"
),
cookies=cookies,
)
return
if path == BUY_NOW_CONTINUE_PATH:
if current_account is None:
location = "/ap/signin?" + urlencode(
{"openid.return_to": BUY_NOW_CONTINUE_PATH}
)
self._send(303, b"", headers={"Location": location}, cookies=cookies)
return
try:
checkout = self.store.resume_buy_now(session_digest)
except ContractError:
self._send_html(
409,
views.error_page(
"This Buy Now offer is no longer available. Return to the product page and choose it again.",
cart_count,
409,
),
cookies=cookies,
)
return
if checkout is None:
self._send(
303,
b"",
headers={"Location": "/gp/cart/view.html"},
cookies=cookies,
)
return
self._send(
303,
b"",
headers={"Location": CHECKOUT_ADDRESS_PATH},
cookies=cookies,
)
return
if path in {
CHECKOUT_ADDRESS_PATH,
CHECKOUT_DELIVERY_PATH,
CHECKOUT_PAYMENT_PATH,
CHECKOUT_START_PATH,
}:
if current_account is None:
location = "/ap/signin?" + urlencode({"openid.return_to": path})
self._send(303, b"", headers={"Location": location}, cookies=cookies)
return
checkout = self.store.reconcile_checkout(session_digest)
if path == CHECKOUT_ADDRESS_PATH and checkout is None:
try:
checkout = self.store.start_checkout(session_digest)
except ContractError:
self._send(303, b"", headers={"Location": "/gp/cart/view.html"}, cookies=cookies)
return
if checkout is None:
self._send(303, b"", headers={"Location": CHECKOUT_ADDRESS_PATH}, cookies=cookies)
return
stage = CHECKOUT_STAGE_ORDER.get(str(checkout.get("status")), -1)
if str(checkout.get("status")) == "PLACED" and checkout.get("order_id"):
location = ORDER_DETAIL_PATH + "?" + urlencode({"orderID": checkout["order_id"]})
self._send(303, b"", headers={"Location": location}, cookies=cookies)
return
reconciliation_reason = str(
checkout.get("reconciliation_reason") or ""
)
notice_values = query.get("notice", [])
notice = (
notice_values[0]
if len(notice_values) == 1
and notice_values[0]
in {
"cart-changed",
"unsupported-delivery-country",
"payment-declined",
"payment-cancelled",
}
else ""
)
if (
path == CHECKOUT_START_PATH
and reconciliation_reason == "cart-changed"
and stage >= CHECKOUT_STAGE_ORDER["DELIVERY_SELECTED"]
):
location = CHECKOUT_PAYMENT_PATH + "?" + urlencode(
{"notice": "cart-changed"}
)
self._send(
303, b"", headers={"Location": location}, cookies=cookies
)
return
if (
reconciliation_reason == "unsupported-delivery-country"
and path != CHECKOUT_ADDRESS_PATH
):
location = CHECKOUT_ADDRESS_PATH + "?" + urlencode(
{"notice": "unsupported-delivery-country"}
)
self._send(
303, b"", headers={"Location": location}, cookies=cookies
)
return
if reconciliation_reason:
checkout = {**checkout, "notice": reconciliation_reason}
elif notice:
checkout = {**checkout, "notice": notice}
checkout_item_count = sum(
int(item.get("quantity", 0))
for item in checkout.get("items", [])
if isinstance(item, dict)
)
if path == CHECKOUT_ADDRESS_PATH:
page = views.checkout_address_page(checkout, checkout_item_count, account_name or "Customer")
elif path == CHECKOUT_DELIVERY_PATH:
if stage < CHECKOUT_STAGE_ORDER["ADDRESS_SELECTED"]:
self._send(303, b"", headers={"Location": CHECKOUT_ADDRESS_PATH}, cookies=cookies)
return
page = views.checkout_delivery_page(checkout, checkout_item_count, account_name or "Customer")
elif path == CHECKOUT_PAYMENT_PATH:
if stage < CHECKOUT_STAGE_ORDER["DELIVERY_SELECTED"]:
self._send(303, b"", headers={"Location": CHECKOUT_DELIVERY_PATH}, cookies=cookies)
return
page = views.checkout_payment_page(
checkout,
checkout_item_count,
account_name or "Customer",
payment_mode=self.payment_config.mode,
)
else:
if stage < CHECKOUT_STAGE_ORDER["PAYMENT_SELECTED"]:
fallback = (
CHECKOUT_PAYMENT_PATH
if stage >= CHECKOUT_STAGE_ORDER["DELIVERY_SELECTED"]
else CHECKOUT_DELIVERY_PATH
if stage >= CHECKOUT_STAGE_ORDER["ADDRESS_SELECTED"]
else CHECKOUT_ADDRESS_PATH
)
self._send(303, b"", headers={"Location": fallback}, cookies=cookies)
return
page = views.checkout_review_page(
checkout,
checkout_item_count,
account_name or "Customer",
payment_mode=self.payment_config.mode,
)
self._send_html(200, page, cookies=cookies)
return
if path == ORDER_DETAIL_PATH:
if current_account is None:
location = "/ap/signin?" + urlencode({"openid.return_to": path})
self._send(303, b"", headers={"Location": location}, cookies=cookies)
return
order_values = query.get("orderID", [])
order = (
self.store.order_for_session(session_digest, order_values[0])
if len(order_values) == 1
else None
)
if order is None:
self._send_html(404, views.not_found_page(cart_count), cookies=cookies)
return
order = self._public_order_mail_state(order)
self._send_html(
200,
views.order_confirmation_page(order, cart_count, account_name or "Customer"),
cookies=cookies,
)
return
if path in {RETURN_CREATE_PATH, RETURN_DETAIL_PATH}:
if current_account is None:
return_target = path + ("?" + request.query if request.query else "")
location = "/ap/signin?" + urlencode(
{"openid.return_to": return_target}
)
self._send(303, b"", headers={"Location": location}, cookies=cookies)
return
if path == RETURN_CREATE_PATH:
order_values = query.get("orderID", [])
order = (
self.store.order_for_session(session_digest, order_values[0])
if len(order_values) == 1
else None
)
if order is None:
self._send_html(
404, views.not_found_page(cart_count), cookies=cookies
)
return
existing_return = order.get("return_request")
if isinstance(existing_return, dict):
location = RETURN_DETAIL_PATH + "?" + urlencode(
{"returnID": existing_return["return_request_id"]}
)
self._send(303, b"", headers={"Location": location}, cookies=cookies)
return
if not order.get("can_return"):
self._send_html(
409,
views.error_page(
"This simulated order is not eligible for a return request in its current state.",
cart_count,
409,
),
cookies=cookies,
)
return
self._send_html(
200,
views.return_request_page(
order, cart_count, account_name or "Customer"
),
cookies=cookies,
)
return
return_values = query.get("returnID", [])
order = (
self.store.return_for_session(session_digest, return_values[0])
if len(return_values) == 1
else None
)
if order is None:
self._send_html(
404, views.not_found_page(cart_count), cookies=cookies
)
return
self._send_html(
200,
views.return_details_page(
order, cart_count, account_name or "Customer"
),
cookies=cookies,
)
return
if path == wishlist_views.WISHLIST_INTRO_PATH:
if current_account is not None:
self._send(
303,
b"",
headers={"Location": wishlist_views.WISHLIST_INDEX_PATH},
cookies=cookies,
)
return
self.store.record_read_route(
session_digest, "WISHLIST_INTRO", path, referer
)
self._send_html(
200,
wishlist_views.wishlist_intro_page(cart_count),
cookies=cookies,
)
return
if path == WISHLIST_FRIENDS_PATH:
if current_account is None:
location = "/ap/signin?" + urlencode(
{"openid.return_to": WISHLIST_FRIENDS_PATH}
)
self._send(
303, b"", headers={"Location": location}, cookies=cookies
)
return
self.store.record_read_route(
session_digest, "WISHLIST_FRIENDS_BOUNDARY", path, referer
)
self._send_html(
200,
views.navigation_landing_page(
"Your Friends' Lists",
"Shared-list invitations are outside this local shopping clone. Your private Lists and Registry shopping remain available.",
(
("Open Your Lists", wishlist_views.WISHLIST_INDEX_PATH),
("Open Gift Registries", "/gp/browse.html?node=16115931011"),
),
cart_count,
account_name,
),
cookies=cookies,
)
return
if path in {
wishlist_views.WISHLIST_INDEX_PATH,
wishlist_views.WISHLIST_ADD_CHOOSER_PATH,
}:
if current_account is None:
return_target = path + (f"?{request.query}" if request.query else "")
location = "/ap/signin?" + urlencode(
{"openid.return_to": return_target}
)
self._send(
303, b"", headers={"Location": location}, cookies=cookies
)
return
if path == wishlist_views.WISHLIST_ADD_CHOOSER_PATH:
selection_query = wishlist_selection_query(query)
if selection_query is None:
self._send(
400,
b"Malformed Add to List request",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
asin, requested_options = selection_query
try:
product, selected_options = (
wishlist.product_selection_for_wishlist(
self.store, asin, requested_options
)
)
wishlists = wishlist.lists_for_session(
self.store, session_digest
)
except wishlist.WishlistAuthenticationRequired:
return_target = path + (
f"?{request.query}" if request.query else ""
)
location = "/ap/signin?" + urlencode(
{"openid.return_to": return_target}
)
self._send(
303,
b"",
headers={"Location": location},
cookies=cookies,
)
return
except wishlist.WishlistNotFound:
self._send_html(
404, views.not_found_page(cart_count), cookies=cookies
)
return
except wishlist.WishlistValidationError as exc:
self._send_html(
400,
views.error_page(str(exc), cart_count, 400),
cookies=cookies,
)
return
self.store.record_read_route(
session_digest, "WISHLIST_ADD_CHOOSER", path, referer
)
self._send_html(
200,
wishlist_views.wishlist_add_chooser_page(
product,
selected_options,
wishlists,
cart_count,
account_name or "Customer",
),
cookies=cookies,
)
return
if set(query) - {"listID", "status"} or any(
len(values) != 1 for values in query.values()
):
self._send(
400,
b"Malformed Wishlist request",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
status_messages = {
"created": "List created.",
"renamed": "List renamed.",
"deleted": "List deleted.",
"added": "Added to List.",
"already-added": "This item was already on the List.",
"removed": "Item removed from List.",
}
status_values = query.get("status", [])
status_token = status_values[0] if status_values else ""
if status_token and status_token not in status_messages:
self._send(
400,
b"Malformed Wishlist status",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
try:
wishlists = wishlist.lists_for_session(
self.store, session_digest
)
list_values = query.get("listID", [])
if list_values:
selected_list = wishlist.list_for_session(
self.store, session_digest, list_values[0]
)
page = wishlist_views.wishlist_detail_page(
selected_list,
wishlists,
cart_count,
account_name or "Customer",
status=status_messages.get(status_token, ""),
)
route_kind = "WISHLIST_DETAIL"
else:
page = wishlist_views.wishlist_index_page(
wishlists,
cart_count,
account_name or "Customer",
status=status_messages.get(status_token, ""),
)
route_kind = "WISHLIST_INDEX"
except wishlist.WishlistAuthenticationRequired:
location = "/ap/signin?" + urlencode(
{"openid.return_to": wishlist_views.WISHLIST_INDEX_PATH}
)
self._send(
303, b"", headers={"Location": location}, cookies=cookies
)
return
except wishlist.WishlistNotFound:
self._send_html(
404, views.not_found_page(cart_count), cookies=cookies
)
return
except wishlist.WishlistValidationError as exc:
self._send_html(
400,
views.error_page(str(exc), cart_count, 400),
cookies=cookies,
)
return
self.store.record_read_route(
session_digest, route_kind, path, referer
)
self._send_html(200, page, cookies=cookies)
return
if path == "/gp/css/order-history" and current_account is not None:
orders = [
self._public_order_mail_state(order)
for order in self.store.orders_for_session(session_digest)
]
self.store.record_read_route(session_digest, "ORDERS", path, referer)
self._send_html(
200,
views.order_history_page(orders, cart_count, account_name or "Customer"),
cookies=cookies,
)
return
if path in PROTECTED_ACCOUNT_PATHS:
if current_account is None:
location = "/ap/signin?" + urlencode({"openid.return_to": path})
self._send(303, b"", headers={"Location": location}, cookies=cookies)
return
self.store.record_read_route(session_digest, "ACCOUNT", path, referer)
self._send_html(200, views.account_page(current_account, cart_count), cookies=cookies)
return
if path.startswith(("/electronics-store/", "/computer-pc-", "/External-Solid-State-Drives/")):
self.store.record_read_route(session_digest, "CATEGORY", path, referer)
page = self._render_search_view(
parse_search_request("k=portable+ssd&i=computers"),
cart_count,
account_name,
)
self._send_html(200, page, cookies=cookies)
return
self.store.record_read_route(session_digest, "NOT_FOUND", path, referer, status=404)
self._send_html(404, views.not_found_page(cart_count), cookies=cookies)
def do_POST(self) -> None:
request = urlsplit(self.path)
path = request.path
if path == STRIPE_WEBHOOK_PATH:
self._handle_stripe_webhook()
return
if not self._require_public_basic_auth():
return
query = parse_qs(request.query, keep_blank_values=True)
_, session_digest, cookies = self._session()
try:
content_length = int(self.headers.get("Content-Length", "0") or "0")
except ValueError:
self._send(400, b"Invalid Content-Length", content_type="text/plain; charset=utf-8", cookies=cookies)
return
if content_length < 0 or content_length > MAX_FORM_BYTES:
# The request body has deliberately not been consumed. Close this
# HTTP/1.1 connection so those bytes cannot be parsed as a second
# request after the 413 response.
self.close_connection = True
self._send_html(
413,
views.error_page("The form submission was too large.", self.store.cart_count(session_digest), 413),
cookies=cookies,
headers={"Connection": "close"},
)
return
raw_body = self.rfile.read(content_length)
if path in EXTERNAL_AUTH_API_PATHS:
verification = self.external_registration_verification
if verification is None:
self._send_json(
404,
{"ok": False, "error": "not_found"},
cookies=cookies,
)
return
if not self._auth_post_origin_is_safe():
self._send_json(
403,
{"ok": False, "error": "forbidden"},
cookies=cookies,
)
return
expected_fields = (
frozenset({"email"})
if path == AUTH_SEND_CODE_PATH
else frozenset({"email", "code"})
)
fields = (
self._json_fields(raw_body, expected_fields)
if not request.query
else None
)
email = valid_account_email((fields or {}).get("email", ""))
code = (fields or {}).get("code", "")
if (
fields is None
or email is None
or (
path == AUTH_VERIFY_CODE_PATH
and re.fullmatch(r"[0-9]{6}", code) is None
)
):
self._send_json(
400,
{"ok": False, "error": "invalid_request"},
cookies=cookies,
)
return
try:
if path == AUTH_SEND_CODE_PATH:
# Keep account existence private. Existing accounts receive
# the same accepted response without a registration email.
if not self.store.account_exists(email):
issue = verification.issue(
session_digest,
email,
self._external_client_address(),
)
expires_in = issue.expires_in
else:
expires_in = 5 * 60
self._send_json(
202,
{"ok": True, "expires_in": expires_in},
cookies=cookies,
)
return
result = verification.verify(session_digest, email, code)
except VerificationRateLimited as exc:
self._send_json(
429,
{
"ok": False,
"error": "rate_limited",
"retry_after": exc.retry_after,
},
cookies=cookies,
headers={"Retry-After": str(exc.retry_after)},
)
return
except VerificationUnavailable:
self._send_json(
503,
{"ok": False, "error": "verification_unavailable"},
cookies=cookies,
headers={"Retry-After": "30"},
)
return
status_codes = {
"verified": 200,
"invalid": 400,
"expired": 410,
"locked": 423,
}
self._send_json(
status_codes.get(result, 503),
{"ok": result == "verified", "status": result},
cookies=cookies,
)
return
if path == AUTH_SIGNOUT_PATH:
if not self._auth_post_origin_is_safe():
self._send(403, b"Forbidden", content_type="text/plain; charset=utf-8", cookies=cookies)
return
self.store.sign_out(session_digest)
cookies.append(browser_cookie(SESSION_COOKIE, "", max_age=0))
self._send(
303,
b"",
headers={"Location": "/"},
cookies=cookies,
)
return
if path in SPECIALTY_POST_PATHS:
if not self._auth_post_origin_is_safe():
self._send(
403,
b"Forbidden",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
fields = self._form_fields(raw_body)
expected_fields = {
specialty.GIFT_CARD_PREVIEW_PATH: {
"design",
"amount",
"recipientKind",
},
specialty.GIFT_CARD_REDEEM_PATH: {"claimCode"},
specialty.SELL_DRAFT_PATH: {
"title",
"category",
"condition",
"price",
"quantity",
"description",
},
specialty.REGISTRY_CREATE_PATH: {
"registryType",
"ownerName",
"registryName",
"eventDate",
},
}[path]
if query or fields is None or set(fields) != expected_fields:
self._send_html(
400,
views.error_page("Check the fields and try again.", self.store.cart_count(session_digest), 400),
cookies=cookies,
)
return
try:
if path == specialty.GIFT_CARD_PREVIEW_PATH:
result = specialty.create_gift_card_preview(
self.store,
session_digest,
fields["design"],
fields["amount"],
fields["recipientKind"],
)
location = specialty.GIFT_CARD_PREVIEW_PATH + "?" + urlencode(
{"previewID": int(result["preview_id"])}
)
elif path == specialty.GIFT_CARD_REDEEM_PATH:
specialty.redeem_gift_card(
self.store, session_digest, fields["claimCode"]
)
location = specialty.GIFT_CARD_BALANCE_PATH + "?" + urlencode(
{"status": "not-applied"}
)
elif path == specialty.SELL_DRAFT_PATH:
result = specialty.save_seller_draft(
self.store, session_digest, fields
)
location = specialty.SELL_DRAFT_PATH + "?" + urlencode(
{"draftID": int(result["draft_id"])}
)
else:
result = specialty.create_registry(
self.store, session_digest, fields
)
location = specialty.REGISTRY_DETAIL_PATH + "?" + urlencode(
{"registryID": int(result["registry_id"])}
)
except specialty.SpecialtyValidationError:
self._send_html(
400,
views.error_page("Check the fields and try again.", self.store.cart_count(session_digest), 400),
cookies=cookies,
)
return
self._send(303, b"", headers={"Location": location}, cookies=cookies)
return
if path in AUTH_PATHS:
fields = self._form_fields(raw_body)
if not self._auth_post_origin_is_safe():
self._send(403, b"Forbidden", content_type="text/plain; charset=utf-8", cookies=cookies)
return
if path == "/ap/signin":
if fields is not None and "email" in fields and "password" not in fields:
email = valid_account_email(fields["email"])
if email is None:
self._send_html(
400,
auth_views.signin_page(
query, "There was a problem with your sign-in. Please try again."
),
cookies=cookies,
)
return
return_to = auth_views.safe_return_target(
{"openid.return_to": [fields.get("openid.return_to", "")]}
)
if not self.store.account_exists(email):
registration_query = {"email": email}
if return_to:
registration_query["openid.return_to"] = return_to
self._send(
303,
b"",
headers={
"Location": "/ap/register?"
+ urlencode(registration_query)
},
cookies=cookies,
)
return
self.store.begin_signin(session_digest, email, return_to)
self._send(
303,
b"",
headers={"Location": "/ap/signin?stage=password"},
cookies=cookies,
)
return
if fields is not None and "password" in fields and "email" not in fields:
password = fields["password"]
if 1 <= len(password) <= 1024:
authenticated, return_to = self.store.authenticate_session(
session_digest, password
)
else:
authenticated, return_to = False, None
if authenticated:
self._rotate_authenticated_session(session_digest, cookies)
self._send(
303,
b"",
headers={"Location": return_to or "/"},
cookies=cookies,
)
return
self._send_html(
401,
auth_views.signin_page(
{"stage": ["password"]},
"Your email or password is incorrect.",
),
cookies=cookies,
)
return
self._send_html(
400,
auth_views.signin_page(
query, "There was a problem with your sign-in. Please try again."
),
cookies=cookies,
)
return
if path == "/ap/register":
return_to = auth_views.safe_return_target(
{"openid.return_to": [(fields or {}).get("openid.return_to", "")]}
)
email = valid_account_email((fields or {}).get("email", ""))
display_name = clean_display_name((fields or {}).get("customerName", ""))
password = (fields or {}).get("password", "")
password_check = (fields or {}).get("passwordCheck", "")
passwords_mismatch = password != password_check
expected_registration_fields = {
"customerName",
"email",
"password",
"passwordCheck",
}
supplied_registration_fields = (
frozenset(fields) if fields is not None else frozenset()
)
valid = bool(
fields is not None
and supplied_registration_fields
in {
frozenset(expected_registration_fields),
frozenset(
{*expected_registration_fields, "openid.return_to"}
),
}
and email is not None
and display_name is not None
and 6 <= len(password) <= 1024
and password == password_check
)
external_verification = (
self.external_registration_verification
)
if external_verification is not None:
verified_ticket = False
if valid:
try:
verified_ticket = (
external_verification.consume_verified(
session_digest, email or ""
)
)
except VerificationUnavailable:
self._send_html(
503,
auth_views.register_page(
query,
"Email verification is temporarily unavailable. Please try again.",
external_verification=True,
),
cookies=cookies,
headers={"Retry-After": "30"},
)
return
created = bool(
valid
and verified_ticket
and self.store.create_externally_verified_account(
session_digest,
email or "",
display_name or "",
password,
)
)
if created:
self._rotate_authenticated_session(
session_digest, cookies
)
self._send(
303,
b"",
headers={"Location": return_to or "/"},
cookies=cookies,
)
return
page_query: dict[str, list[str]] = {}
if return_to:
page_query["openid.return_to"] = [return_to]
if email is not None:
page_query["email"] = [email]
self._send_html(
400,
auth_views.register_page(
page_query,
(
"Passwords do not match."
if passwords_mismatch
else (
"Verify this email address, then check your "
"details and try again."
)
),
external_verification=True,
),
cookies=cookies,
)
return
pending = bool(
valid
and self.store.begin_registration(
session_digest,
email or "",
display_name or "",
password,
return_to,
mail_mode=self._mail_mode(),
)
)
if pending:
self._dispatch_mail(
self.store.registration_delivery(session_digest)
)
self._send(
303,
b"",
headers={"Location": "/ap/cvf/verify?purpose=registration"},
cookies=cookies,
)
return
page_query: dict[str, list[str]] = {}
if return_to:
page_query["openid.return_to"] = [return_to]
if email is not None and not valid:
page_query["email"] = [email]
self._send_html(
400,
auth_views.register_page(
page_query,
(
"Passwords do not match."
if passwords_mismatch
else (
"We couldn't create your account. "
"Check your details and try again."
)
),
),
cookies=cookies,
)
return
if path == "/ap/cvf/verify":
purpose_values = query.get("purpose", [])
if len(purpose_values) > 1 or (
purpose_values
and purpose_values[0] not in {"registration", "password-reset"}
):
self._send(
400,
b"Malformed verification purpose",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
purpose = purpose_values[0] if purpose_values else "registration"
purpose_query = {"purpose": [purpose]}
delivery_mode = (
"SMTP" if self.smtp_config is not None else "LOCAL_ONLY"
)
if purpose == "password-reset":
if fields == {"action": "retry-delivery"}:
pending_reset = self.store.pending_password_reset(
session_digest
)
queued = bool(
self.smtp_config is not None
and pending_reset is not None
and pending_reset.get("verified")
and self.store.retry_password_reset_mail(
session_digest
)
)
delivery = (
self.store.password_reset_delivery(session_digest)
if queued
else None
)
# Unknown, foreign, exhausted, and successfully queued
# flows share one response contract.
self._send(
303,
b"",
headers={
"Location": "/ap/cvf/verify?purpose=password-reset"
},
cookies=cookies,
)
self._dispatch_mail(delivery)
return
if fields == {"action": "resend"}:
queued = self.store.resend_password_reset_code(
session_digest, mail_mode=self._mail_mode()
)
delivery = (
self.store.password_reset_delivery(session_digest)
if queued
else None
)
# Missing, decoy, throttled, and queued flows use the
# same public response to avoid account enumeration.
self._send(
303,
b"",
headers={
"Location": "/ap/cvf/verify?purpose=password-reset"
},
cookies=cookies,
)
self._dispatch_mail(delivery)
return
code = (fields or {}).get("code", "").strip()
if set(fields or {}) != {"code"} or not re.fullmatch(
r"[0-9]{6}", code
):
reset_result = "invalid"
else:
reset_result = self.store.verify_password_reset_code(
session_digest, code
)
if reset_result == "verified":
self._send(
303,
b"",
headers={
"Location": "/ap/forgotpassword?stage=reset-password"
},
cookies=cookies,
)
return
reset_errors = {
"invalid": "The verification code you entered is not valid.",
"expired": "That verification code has expired. Request a new code.",
"locked": "Too many incorrect attempts. Request a new code.",
"missing": "Start password assistance again to request a new code.",
"used": "That verification code has already been used.",
}
self._send_html(
410 if reset_result == "expired" else 400,
auth_views.verification_page(
purpose_query,
error=reset_errors.get(
reset_result,
"We couldn't verify that code. Try again.",
),
mail_delivery_mode=delivery_mode,
mail_delivery=self._auth_mail_status(
session_digest, purpose
),
local_inbox_url=self.local_inbox_url,
),
cookies=cookies,
)
return
if fields == {"action": "retry-delivery"}:
queued = bool(
self.smtp_config is not None
and self.store.retry_registration_mail(session_digest)
)
if queued:
self._dispatch_mail(
self.store.registration_delivery(session_digest)
)
self._send(
303,
b"",
headers={"Location": "/ap/cvf/verify?purpose=registration"},
cookies=cookies,
)
return
if fields == {"action": "resend"}:
if self.store.resend_registration_code(
session_digest, mail_mode=self._mail_mode()
):
self._dispatch_mail(
self.store.registration_delivery(session_digest)
)
self._send(
303,
b"",
headers={"Location": "/ap/cvf/verify?purpose=registration"},
cookies=cookies,
)
return
self._send_html(
400,
auth_views.verification_page(
purpose_query,
error="Start account creation again to request a new code.",
mail_delivery_mode=delivery_mode,
mail_delivery=self._auth_mail_status(
session_digest, purpose
),
local_inbox_url=self.local_inbox_url,
),
cookies=cookies,
)
return
code = (fields or {}).get("code", "").strip()
if set(fields or {}) != {"code"} or not re.fullmatch(r"[0-9]{6}", code):
result, return_to = "invalid", None
else:
result, return_to = self.store.verify_registration_code(
session_digest, code
)
if result == "verified":
self._rotate_authenticated_session(session_digest, cookies)
self._send(
303,
b"",
headers={"Location": return_to or "/"},
cookies=cookies,
)
return
pending_registration = self.store.pending_registration(session_digest)
error_messages = {
"invalid": "The verification code you entered is not valid.",
"expired": "That verification code has expired. Request a new code.",
"locked": "Too many incorrect attempts. Request a new code.",
"missing": "Start account creation again to request a new code.",
"duplicate": "We couldn't create your account. Sign in or try again.",
}
status = 410 if result == "expired" else 400
self._send_html(
status,
auth_views.verification_page(
purpose_query,
masked_destination=(pending_registration or {}).get(
"masked_email"
),
error=error_messages.get(
result, "We couldn't verify that code. Try again."
),
mail_delivery_mode=delivery_mode,
mail_delivery=self._auth_mail_status(
session_digest, purpose
),
local_inbox_url=self.local_inbox_url,
),
cookies=cookies,
)
return
if path == "/ap/forgotpassword":
if fields is not None and "email" in fields and not {
"password",
"passwordCheck",
}.intersection(fields):
if set(fields) not in (
{"email"},
{"email", "openid.return_to"},
):
email = None
else:
email = valid_account_email(fields.get("email", ""))
if email is None:
self._send_html(
400,
auth_views.forgot_password_page(
{},
"We couldn't process that request. Check the email address and try again.",
),
cookies=cookies,
)
return
return_to = auth_views.safe_return_target(
{
"openid.return_to": [
fields.get("openid.return_to", "")
]
}
)
self.store.begin_password_reset(
session_digest,
email,
return_to,
mail_mode=self._mail_mode(),
)
delivery = self.store.password_reset_delivery(session_digest)
# This response is identical whether or not an account was
# found; only a database-backed account can receive mail.
self._send(
303,
b"",
headers={
"Location": "/ap/cvf/verify?purpose=password-reset"
},
cookies=cookies,
)
self._dispatch_mail(delivery)
return
if fields is not None and set(fields) == {
"password",
"passwordCheck",
}:
password = fields["password"]
password_check = fields["passwordCheck"]
if not (
6 <= len(password) <= 1024 and password == password_check
):
self._send_html(
400,
auth_views.forgot_password_page(
{"stage": ["reset-password"]},
"Passwords must match and contain at least 6 characters.",
),
cookies=cookies,
)
return
reset_result, return_to = self.store.complete_password_reset(
session_digest, password
)
if reset_result == "reset":
self._rotate_authenticated_session(session_digest, cookies)
self._send(
303,
b"",
headers={"Location": return_to or "/"},
cookies=cookies,
)
return
self._send_html(
410 if reset_result == "expired" else 400,
auth_views.forgot_password_page(
{"stage": ["reset-password"]},
"This password reset is no longer valid. Start again.",
),
cookies=cookies,
)
return
self._send_html(
400,
auth_views.forgot_password_page(
{}, "We couldn't process that password assistance request."
),
cookies=cookies,
)
return
self._send(
400,
b"Malformed authentication request",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
if path in WISHLIST_POST_PATHS:
if not self._auth_post_origin_is_safe():
self._send(
403,
b"Forbidden",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
if query:
self._send(
400,
b"Malformed Wishlist request",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
if self.store.account_for_session(session_digest) is None:
location = "/ap/signin?" + urlencode(
{"openid.return_to": wishlist_views.WISHLIST_INDEX_PATH}
)
self._send(
303, b"", headers={"Location": location}, cookies=cookies
)
return
fields = self._form_fields(raw_body)
valid_shape = False
selected_options: dict[str, str] = {}
if fields is not None:
expected_fields = {
wishlist_views.WISHLIST_CREATE_PATH: {"listName"},
wishlist_views.WISHLIST_RENAME_PATH: {
"listID",
"listName",
},
wishlist_views.WISHLIST_DELETE_PATH: {"listID"},
wishlist_views.WISHLIST_REMOVE_ITEM_PATH: {
"listID",
"itemID",
},
wishlist_views.WISHLIST_MOVE_TO_CART_PATH: {
"listID",
"itemID",
"quantity",
},
}
if path == wishlist_views.WISHLIST_ADD_ITEM_PATH:
base_fields = {"listID", "ASIN"}
option_fields = {
name
for name in fields
if name.startswith("option.")
and name.removeprefix("option.")
}
valid_shape = bool(
base_fields.issubset(fields)
and set(fields) == base_fields | option_fields
)
if valid_shape:
selected_options = {
name.removeprefix("option."): fields[name]
for name in option_fields
}
else:
valid_shape = set(fields) == expected_fields[path]
if (
path == wishlist_views.WISHLIST_MOVE_TO_CART_PATH
and fields.get("quantity") != "1"
):
valid_shape = False
if not valid_shape or fields is None:
self._send(
400,
b"Malformed Wishlist request",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
try:
if path == wishlist_views.WISHLIST_CREATE_PATH:
created_list = wishlist.create_list(
self.store, session_digest, fields["listName"]
)
location = wishlist_views.WISHLIST_INDEX_PATH + "?" + urlencode(
{
"listID": created_list["list_id"],
"status": "created",
}
)
elif path == wishlist_views.WISHLIST_RENAME_PATH:
renamed_list = wishlist.rename_list(
self.store,
session_digest,
fields["listID"],
fields["listName"],
)
location = wishlist_views.WISHLIST_INDEX_PATH + "?" + urlencode(
{
"listID": renamed_list["list_id"],
"status": "renamed",
}
)
elif path == wishlist_views.WISHLIST_DELETE_PATH:
wishlist.delete_list(
self.store, session_digest, fields["listID"]
)
location = wishlist_views.WISHLIST_INDEX_PATH + "?" + urlencode(
{"status": "deleted"}
)
elif path == wishlist_views.WISHLIST_ADD_ITEM_PATH:
result = wishlist.add_item(
self.store,
session_digest,
fields["listID"],
fields["ASIN"],
selected_options,
)
location = wishlist_views.WISHLIST_INDEX_PATH + "?" + urlencode(
{
"listID": fields["listID"],
"status": (
"added" if result["created"] else "already-added"
),
}
)
elif path == wishlist_views.WISHLIST_REMOVE_ITEM_PATH:
wishlist.remove_item(
self.store,
session_digest,
fields["listID"],
fields["itemID"],
)
location = wishlist_views.WISHLIST_INDEX_PATH + "?" + urlencode(
{"listID": fields["listID"], "status": "removed"}
)
else:
item = wishlist.item_for_move_to_cart(
self.store,
session_digest,
fields["listID"],
fields["itemID"],
)
self.store.add_cart_item(
session_digest,
item["asin"],
fields["quantity"],
item["selected_options"],
)
try:
wishlist.remove_item(
self.store,
session_digest,
item["list_id"],
item["item_id"],
)
except wishlist.WishlistNotFound:
# The cart mutation already succeeded. A concurrent
# removal must not turn that success into a retry that
# can double the quantity.
pass
location = "/gp/cart/view.html"
except wishlist.WishlistAuthenticationRequired:
location = "/ap/signin?" + urlencode(
{"openid.return_to": wishlist_views.WISHLIST_INDEX_PATH}
)
except wishlist.WishlistNotFound:
self._send_html(
404,
views.not_found_page(self.store.cart_count(session_digest)),
cookies=cookies,
)
return
except wishlist.WishlistValidationError as exc:
self._send_html(
400,
views.error_page(
str(exc), self.store.cart_count(session_digest), 400
),
cookies=cookies,
)
return
except (wishlist.WishlistConflict, ContractError) as exc:
self._send_html(
409,
views.error_page(
str(exc), self.store.cart_count(session_digest), 409
),
cookies=cookies,
)
return
self._send(
303, b"", headers={"Location": location}, cookies=cookies
)
return
if path in ADDRESS_BOOK_POST_PATHS:
if not self._auth_post_origin_is_safe():
self._send(
403,
b"Forbidden",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
account = self.store.account_for_session(session_digest)
if account is None:
location = "/ap/signin?" + urlencode(
{"openid.return_to": ADDRESS_BOOK_PATH}
)
self._send(303, b"", headers={"Location": location}, cookies=cookies)
return
fields = self._form_fields(raw_body)
make_default = False
address: dict[str, str] | None = None
if path == ADDRESS_CREATE_PATH:
allowed = ADDRESS_FORM_NAMES | {"makeDefault"}
valid_shape = bool(
fields is not None
and ADDRESS_FORM_NAMES.issubset(fields)
and set(fields).issubset(allowed)
)
elif path == ADDRESS_UPDATE_PATH:
allowed = ADDRESS_FORM_NAMES | {
"addressId",
"addressRevision",
"makeDefault",
}
valid_shape = bool(
fields is not None
and (ADDRESS_FORM_NAMES | {"addressId", "addressRevision"}).issubset(fields)
and set(fields).issubset(allowed)
)
else:
valid_shape = bool(
fields is not None
and set(fields) == {"addressId", "addressRevision"}
)
if not valid_shape or (
fields is not None
and "makeDefault" in fields
and fields["makeDefault"] != "1"
):
self._send(
400,
b"Malformed address request",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
assert fields is not None
if path in {ADDRESS_CREATE_PATH, ADDRESS_UPDATE_PATH}:
address = normalized_address_fields(fields)
if address is None:
self._send(
400,
b"Invalid address",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
make_default = fields.get("makeDefault") == "1"
try:
if path == ADDRESS_CREATE_PATH:
assert address is not None
self.store.create_address(
session_digest,
address,
make_default=make_default,
)
status_label = "added"
elif path == ADDRESS_UPDATE_PATH:
assert address is not None
self.store.update_address(
session_digest,
fields["addressId"],
fields["addressRevision"],
address,
make_default=make_default,
)
status_label = "updated"
elif path == ADDRESS_DEFAULT_PATH:
self.store.set_default_address(
session_digest,
fields["addressId"],
fields["addressRevision"],
)
status_label = "default"
else:
self.store.delete_address(
session_digest,
fields["addressId"],
fields["addressRevision"],
)
status_label = "deleted"
except AddressNotFound:
self._send(
404,
b"Not Found",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
except (AddressRevisionConflict, AddressInUse) as exc:
message = (
"This address is currently selected by an active checkout. Choose another checkout address before deleting it."
if isinstance(exc, AddressInUse)
else "This address changed in another request. Review the latest version and try again."
)
self._send_html(
409,
views.address_book_page(
self.store.addresses_for_session(session_digest),
self.store.cart_count(session_digest),
str(account["display_name"]),
error=message,
),
cookies=cookies,
)
return
except ContractError:
self._send(
400,
b"Invalid address request",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
self._send(
303,
b"",
headers={
"Location": ADDRESS_BOOK_PATH
+ "?"
+ urlencode({"status": status_label})
},
cookies=cookies,
)
return
if path in {ORDER_CANCEL_PATH, RETURN_CREATE_PATH}:
if not self._auth_post_origin_is_safe():
self._send(
403,
b"Forbidden",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
account = self.store.account_for_session(session_digest)
if account is None:
location = "/ap/signin?" + urlencode(
{"openid.return_to": "/gp/css/order-history"}
)
self._send(303, b"", headers={"Location": location}, cookies=cookies)
return
fields = self._form_fields(raw_body)
required = (
{"orderID", "idempotencyKey", "actionToken"}
if path == ORDER_CANCEL_PATH
else {
"orderID",
"reasonCode",
"customerNote",
"idempotencyKey",
"actionToken",
}
)
if (
fields is None
or set(fields) != required
or re.fullmatch(r"[1-9][0-9]{0,18}", fields.get("orderID", ""))
is None
or re.fullmatch(
r"[A-Za-z0-9_-]{20,128}", fields.get("idempotencyKey", "")
)
is None
or re.fullmatch(r"[0-9a-f]{64}", fields.get("actionToken", ""))
is None
):
self._send(
400,
b"Malformed order action",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
try:
if path == ORDER_CANCEL_PATH:
order = self.store.cancel_order(
session_digest,
fields["orderID"],
fields["idempotencyKey"],
fields["actionToken"],
)
location = ORDER_DETAIL_PATH + "?" + urlencode(
{"orderID": order["order_id"]}
)
else:
order = self.store.create_return_request(
session_digest,
fields["orderID"],
fields["reasonCode"],
fields["customerNote"],
fields["idempotencyKey"],
fields["actionToken"],
)
request_payload = order.get("return_request")
if not isinstance(request_payload, dict):
raise OrderStateConflict("return request was not created")
location = RETURN_DETAIL_PATH + "?" + urlencode(
{"returnID": request_payload["return_request_id"]}
)
except OrderActionTokenInvalid:
self._send(
403,
b"Forbidden",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
except OrderNotFound:
self._send(
404,
b"Not Found",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
except OrderStateConflict as exc:
self._send_html(
409,
views.error_page(str(exc), self.store.cart_count(session_digest), 409),
cookies=cookies,
)
return
except ContractError as exc:
self._send(
400,
str(exc).encode("utf-8"),
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
self._send(303, b"", headers={"Location": location}, cookies=cookies)
return
review_post_match = PRODUCT_REVIEWS_ROUTE.fullmatch(path)
helpful_post_match = PRODUCT_REVIEW_HELPFUL_ROUTE.fullmatch(path)
if review_post_match or helpful_post_match:
if not self._auth_post_origin_is_safe():
self._send(
403,
b"Forbidden",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
asin = (review_post_match or helpful_post_match).group(1)
product = product_for_pdp(self.store, asin)
source_scope = review_product_source_scope(self.store, asin)
if product is None or source_scope is None:
self._send(
404,
b"Not Found",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
self.store.register_review_product(asin, source_scope)
fields = self._form_fields(raw_body)
destination = f"/product-reviews/{asin}#customerReviews"
if review_post_match:
if self.store.account_for_session(session_digest) is None:
signin_location = "/ap/signin?" + urlencode(
{"openid.return_to": f"/product-reviews/{asin}#reviewComposer"}
)
self._send(
303,
b"",
headers={"Location": signin_location},
cookies=cookies,
)
return
if (
fields is None
or set(fields) != {"rating", "headline", "body"}
or re.fullmatch(r"[1-5]", fields.get("rating", "")) is None
):
self._send(
400,
b"Malformed review request",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
try:
self.store.upsert_review(
session_digest,
asin,
int(fields["rating"]),
fields["headline"],
fields["body"],
)
except ReviewAuthenticationRequired:
signin_location = "/ap/signin?" + urlencode(
{"openid.return_to": f"/product-reviews/{asin}#reviewComposer"}
)
self._send(
303,
b"",
headers={"Location": signin_location},
cookies=cookies,
)
return
except ReviewValidationError as exc:
self._send(
400,
str(exc).encode("utf-8"),
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
except ReviewPermissionDenied:
self._send(
403,
b"Forbidden",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
except ReviewNotFound:
self._send(
404,
b"Not Found",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
else:
if (
fields is None
or set(fields) != {"reviewId"}
or re.fullmatch(r"[1-9][0-9]*", fields.get("reviewId", "")) is None
):
self._send(
400,
b"Malformed helpful request",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
try:
self.store.toggle_review_helpful(
session_digest, asin, fields["reviewId"]
)
except ReviewValidationError as exc:
self._send(
400,
str(exc).encode("utf-8"),
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
except ReviewPermissionDenied:
self._send(
403,
b"You cannot mark your own review as helpful.",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
except ReviewNotFound:
self._send(
404,
b"Not Found",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
self._send(
303,
b"",
headers={"Location": destination},
cookies=cookies,
)
return
if path == ORDER_EMAIL_RETRY_PATH:
if not self._auth_post_origin_is_safe():
self._send(
403,
b"Forbidden",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
fields = self._form_fields(raw_body)
if (
query
or fields is None
or set(fields) != {"orderID"}
or re.fullmatch(r"[1-9][0-9]*", fields["orderID"]) is None
):
self._send(
400,
b"Malformed order email retry request",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
if self.store.account_for_session(session_digest) is None:
location = "/ap/signin?" + urlencode(
{"openid.return_to": ORDER_DETAIL_PATH}
)
self._send(
303, b"", headers={"Location": location}, cookies=cookies
)
return
order_id = fields["orderID"]
if self.store.order_for_session(session_digest, order_id) is None:
self._send(
404,
b"Not Found",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
if (
self.smtp_config is not None
and self.store.retry_order_mail(session_digest, order_id)
):
self._dispatch_mail(self.store.order_mail_delivery(order_id))
location = ORDER_DETAIL_PATH + "?" + urlencode({"orderID": order_id})
self._send(
303, b"", headers={"Location": location}, cookies=cookies
)
return
checkout_post_paths = {
CHECKOUT_START_PATH,
CHECKOUT_ADDRESS_PATH,
CHECKOUT_DELIVERY_PATH,
CHECKOUT_PAYMENT_PATH,
PLACE_ORDER_PATH,
STRIPE_CHECKOUT_PATH,
STRIPE_CANCEL_PATH,
}
if path in checkout_post_paths:
# Preserve the frozen benchmark's explicit nonterminal rejection.
if path == CHECKOUT_START_PATH and raw_body:
self.store.record_rejected_post(
session_digest,
path,
self.headers.get("Content-Type", "").split(";", 1)[0].strip().lower(),
raw_body,
)
self._send(404, b"Not Found", content_type="text/plain; charset=utf-8", cookies=cookies)
return
if not self._auth_post_origin_is_safe():
self._send(403, b"Forbidden", content_type="text/plain; charset=utf-8", cookies=cookies)
return
account = self.store.account_for_session(session_digest)
if account is None:
location = "/ap/signin?" + urlencode(
{"openid.return_to": CHECKOUT_ADDRESS_PATH}
)
self._send(303, b"", headers={"Location": location}, cookies=cookies)
return
fields = self._form_fields(raw_body)
if path == STRIPE_CHECKOUT_PATH:
if (
not self.payment_config.stripe_enabled
or self.stripe_gateway is None
):
self._send(
404,
b"Not Found",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
if (
fields is None
or set(fields) != {"idempotencyKey"}
or re.fullmatch(
r"[A-Za-z0-9_-]{20,160}",
fields.get("idempotencyKey", ""),
)
is None
):
self._send(
400,
b"Malformed Stripe checkout request",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
current = self.store.reconcile_checkout(session_digest)
if (
current is None
or str(current.get("idempotency_key") or "")
!= fields["idempotencyKey"]
):
self._send(
409,
b"Checkout state conflict",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
try:
preparation = self.store.prepare_stripe_checkout(
session_digest
)
success_url, cancel_url = self._stripe_return_urls()
provider_session = (
self.stripe_gateway.create_checkout_session(
preparation,
success_url=success_url,
cancel_url=cancel_url,
)
)
self.store.attach_stripe_checkout_session(
session_digest,
str(preparation["checkout_token"]),
provider_session,
)
location = str(provider_session.get("url") or "")
parsed_location = urlsplit(location)
if (
parsed_location.scheme != "https"
or parsed_location.hostname != "checkout.stripe.com"
or parsed_location.username
or parsed_location.password
or parsed_location.port is not None
or parsed_location.fragment
):
raise ContractError(
"Stripe returned an invalid checkout URL"
)
except StripeAPIError:
self._send_html(
503,
views.error_page(
"Stripe test Checkout is temporarily unavailable. "
"Your cart and frozen checkout were kept; return to "
"review and retry.",
self.store.cart_count(session_digest),
503,
),
cookies=cookies,
)
return
except ContractError as exc:
self._send_html(
409,
views.error_page(
str(exc),
self.store.cart_count(session_digest),
409,
),
cookies=cookies,
)
return
self._send(
303,
b"",
headers={"Location": location},
cookies=cookies,
)
return
if path == STRIPE_CANCEL_PATH:
if (
not self.payment_config.stripe_enabled
or self.stripe_gateway is None
or fields is None
or set(fields) != {"sessionID"}
):
self._send(
404,
b"Not Found",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
session_id = fields["sessionID"]
mapping = (
self.store.stripe_checkout_for_session(
session_digest, session_id
)
if STRIPE_PROVIDER_SESSION_PATTERN.fullmatch(session_id)
else None
)
if mapping is None:
self._send(
404,
b"Not Found",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
try:
provider_session = (
self.stripe_gateway.retrieve_checkout_session(
session_id
)
)
if (
str(
provider_session.get("payment_status") or ""
)
== "paid"
):
order = self.store.confirm_stripe_return(
session_digest,
session_id,
provider_session,
mail_mode=self._mail_mode(),
)
if order is None:
raise ContractError(
"paid Stripe Session was not fulfilled"
)
self._dispatch_mail(
self.store.order_mail_delivery(order["order_id"])
)
location = ORDER_DETAIL_PATH + "?" + urlencode(
{"orderID": order["order_id"]}
)
self._send(
303,
b"",
headers={"Location": location},
cookies=cookies,
)
return
if str(provider_session.get("status") or "") != "expired":
provider_session = (
self.stripe_gateway.expire_checkout_session(
session_id
)
)
self.store.cancel_stripe_checkout(
session_digest,
session_id,
provider_session,
)
except StripeAPIError:
self._send_html(
503,
views.stripe_payment_status_page(
mapping,
self.store.cart_count(session_digest),
str(account.get("display_name") or "Customer"),
session_id=session_id,
state="unavailable",
cancelled=True,
),
cookies=cookies,
)
return
except ContractError:
self._send(
409,
b"Stripe checkout state conflict",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
destination = CHECKOUT_PAYMENT_PATH + "?" + urlencode(
{"notice": "payment-cancelled"}
)
self._send(
303,
b"",
headers={"Location": destination},
cookies=cookies,
)
return
if path == CHECKOUT_START_PATH:
if fields != {}:
self._send(400, b"Malformed checkout request", content_type="text/plain; charset=utf-8", cookies=cookies)
return
try:
checkout = self.store.start_checkout(session_digest)
except ContractError:
self._send_html(
409,
views.error_page(
"Your cart is empty or checkout cannot be started.",
self.store.cart_count(session_digest),
409,
),
cookies=cookies,
)
return
destination = CHECKOUT_ADDRESS_PATH
if (
checkout.get("reconciliation_reason") == "cart-changed"
and checkout.get("status") == "DELIVERY_SELECTED"
):
destination = CHECKOUT_PAYMENT_PATH + "?" + urlencode(
{"notice": "cart-changed"}
)
self._send(
303,
b"",
headers={"Location": destination},
cookies=cookies,
)
return
if path == CHECKOUT_ADDRESS_PATH:
if fields is not None and set(fields) == {"addressSelection"}:
selection_match = re.fullmatch(
r"([1-9][0-9]*):([1-9][0-9]*)",
fields["addressSelection"],
)
if selection_match is None:
self._send(
400,
b"Malformed address selection",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
try:
self.store.select_checkout_address(
session_digest,
selection_match.group(1),
selection_match.group(2),
)
except ContractError:
self._send(
409,
b"Checkout address conflict",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
self._send(
303,
b"",
headers={"Location": CHECKOUT_DELIVERY_PATH},
cookies=cookies,
)
return
allowed = ADDRESS_FORM_NAMES | {"makeDefault"}
if (
fields is None
or not ADDRESS_FORM_NAMES.issubset(fields)
or not set(fields).issubset(allowed)
or (
"makeDefault" in fields
and fields["makeDefault"] != "1"
)
):
self._send(400, b"Malformed address", content_type="text/plain; charset=utf-8", cookies=cookies)
return
address = normalized_address_fields(fields)
if address is None:
self._send(400, b"Invalid address", content_type="text/plain; charset=utf-8", cookies=cookies)
return
try:
self.store.save_checkout_address(
session_digest,
address,
make_default=fields.get("makeDefault") == "1",
)
except ContractError:
self._send(409, b"Checkout state conflict", content_type="text/plain; charset=utf-8", cookies=cookies)
return
self._send(303, b"", headers={"Location": CHECKOUT_DELIVERY_PATH}, cookies=cookies)
return
if path == CHECKOUT_DELIVERY_PATH:
if fields is None or set(fields) != {"deliveryOption"}:
self._send(400, b"Malformed delivery option", content_type="text/plain; charset=utf-8", cookies=cookies)
return
try:
self.store.select_delivery(session_digest, fields["deliveryOption"])
except ContractError:
self._send(409, b"Checkout state conflict", content_type="text/plain; charset=utf-8", cookies=cookies)
return
self._send(303, b"", headers={"Location": CHECKOUT_PAYMENT_PATH}, cookies=cookies)
return
if path == CHECKOUT_PAYMENT_PATH:
if fields is None or set(fields) != {"paymentMethod"}:
self._send(400, b"Malformed payment method", content_type="text/plain; charset=utf-8", cookies=cookies)
return
try:
if self.payment_config.mode == PAYMENT_MODE_STRIPE_TEST:
if fields["paymentMethod"] != "stripe-test":
raise ContractError(
"Stripe test Checkout is required"
)
checkout = self.store.prepare_stripe_review(
session_digest
)
else:
checkout = self.store.select_test_payment(
session_digest, fields["paymentMethod"]
)
except ContractError:
self._send(409, b"Checkout state conflict", content_type="text/plain; charset=utf-8", cookies=cookies)
return
payment_attempt = checkout.get("payment_attempt")
destination = (
CHECKOUT_PAYMENT_PATH
+ "?"
+ urlencode({"notice": "payment-declined"})
if isinstance(payment_attempt, dict)
and payment_attempt.get("status") == "DECLINED"
else CHECKOUT_START_PATH
)
self._send(
303,
b"",
headers={"Location": destination},
cookies=cookies,
)
return
if (
self.payment_config.mode == PAYMENT_MODE_STRIPE_TEST
and path == PLACE_ORDER_PATH
):
self._send(
409,
b"Stripe test payment must be confirmed before ordering",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
if fields is None or set(fields) != {"idempotencyKey"} or not re.fullmatch(
r"[A-Za-z0-9_-]{20,160}", fields.get("idempotencyKey", "")
):
self._send(400, b"Malformed place-order request", content_type="text/plain; charset=utf-8", cookies=cookies)
return
try:
order = self.store.place_order(
session_digest,
fields["idempotencyKey"],
mail_mode=self._mail_mode(),
)
except CheckoutReconciliationRequired as exc:
destination = (
CHECKOUT_ADDRESS_PATH
if exc.reason == "unsupported-delivery-country"
else CHECKOUT_PAYMENT_PATH
) + "?" + urlencode({"notice": exc.reason})
self._send(
303,
b"",
headers={"Location": destination},
cookies=cookies,
)
return
except ContractError:
self._send(409, b"Checkout state conflict", content_type="text/plain; charset=utf-8", cookies=cookies)
return
self._dispatch_mail(
self.store.order_mail_delivery(order["order_id"])
)
location = ORDER_DETAIL_PATH + "?" + urlencode({"orderID": order["order_id"]})
self._send(303, b"", headers={"Location": location}, cookies=cookies)
return
if path in COMPARE_MUTATION_PATHS:
if not self._auth_post_origin_is_safe():
self._send(403, b"Forbidden", content_type="text/plain; charset=utf-8", cookies=cookies)
return
fields = self._form_fields(raw_body)
if path == "/gp/compare/clear":
if fields != {}:
self._send(400, b"Malformed compare request", content_type="text/plain; charset=utf-8", cookies=cookies)
return
self.store.clear_compare(session_digest)
self._send(303, b"", headers={"Location": COMPARE_PATH}, cookies=cookies)
return
if path == "/gp/compare/remove":
if fields is None or set(fields) != {"compareLineID"}:
self._send(400, b"Malformed compare request", content_type="text/plain; charset=utf-8", cookies=cookies)
return
compare_line_id = fields["compareLineID"]
if COMPARE_LINE_ID_PATTERN.fullmatch(compare_line_id) is None:
self._send(400, b"Malformed compare request", content_type="text/plain; charset=utf-8", cookies=cookies)
return
if not self.store.remove_compare(session_digest, compare_line_id):
self._send(409, b"Compare item not found", content_type="text/plain; charset=utf-8", cookies=cookies)
return
self._send(303, b"", headers={"Location": COMPARE_PATH}, cookies=cookies)
return
option_field_names = {
name for name in fields or {} if name.startswith("option.")
}
if (
fields is None
or "ASIN" not in fields
or set(fields) != {"ASIN"} | option_field_names
or any(not name.removeprefix("option.") for name in option_field_names)
):
self._send(400, b"Malformed compare request", content_type="text/plain; charset=utf-8", cookies=cookies)
return
asin = fields["ASIN"]
if ASIN_PATTERN.fullmatch(asin) is None:
self._send(400, b"Malformed compare request", content_type="text/plain; charset=utf-8", cookies=cookies)
return
if asin not in self.store.compare_eligible_asins():
self._send(404, b"Not Found", content_type="text/plain; charset=utf-8", cookies=cookies)
return
expected_option_names = {
f"option.{group['label']}"
for group in self.store.product_option_spec(asin)
}
if option_field_names and option_field_names != expected_option_names:
self._send(400, b"Malformed compare options", content_type="text/plain; charset=utf-8", cookies=cookies)
return
selected_options = (
{
name.removeprefix("option."): fields[name]
for name in option_field_names
}
if option_field_names
else None
)
try:
result = self.store.add_compare(
session_digest, asin, selected_options
)
except ContractError:
self._send(400, b"Invalid compare options", content_type="text/plain; charset=utf-8", cookies=cookies)
return
if result in {"full", "incompatible"}:
products = [
compare_product_for_view(self.store, item)
for item in self.store.compare_items(session_digest)
]
account = self.store.account_for_session(session_digest)
name = str(account["display_name"]) if account else None
message = (
"You can compare up to four products at a time."
if result == "full"
else "Choose products from the same product family."
)
self._send_html(
409,
views.compare_page(
products,
self.store.cart_count(session_digest),
name,
message,
),
cookies=cookies,
)
return
self._send(303, b"", headers={"Location": COMPARE_PATH}, cookies=cookies)
return
if path in CART_MUTATION_PATHS:
if not self._auth_post_origin_is_safe():
self._send(403, b"Forbidden", content_type="text/plain; charset=utf-8", cookies=cookies)
return
if (
path in AUTHENTICATED_CART_MUTATION_PATHS
and self.store.account_for_session(session_digest) is None
):
self._send(
303,
b"",
headers={"Location": self._signin_location_for_cart_mutation()},
cookies=cookies,
)
return
fields = self._form_fields(raw_body)
is_product_mutation = path in {BUY_NOW_PATH, "/gp/cart/add.html"}
needs_quantity = path in {
BUY_NOW_PATH,
"/gp/cart/add.html",
"/gp/cart/update.html",
}
if is_product_mutation:
base_names = {"ASIN", "quantity"}
elif needs_quantity:
base_names = {"lineID", "quantity"}
else:
base_names = {"lineID"}
option_field_names = (
{name for name in fields or {} if name.startswith("option.")}
if is_product_mutation
else set()
)
if fields is None or set(fields) != base_names | option_field_names:
self._send_html(
400,
views.error_page(
"The cart request was incomplete or malformed.",
self.store.cart_count(session_digest),
400,
),
cookies=cookies,
)
return
asin = ""
line_id = ""
selected_options: dict[str, str] | None = None
if is_product_mutation:
asin = fields["ASIN"]
if ASIN_PATTERN.fullmatch(asin) is None:
self._send_html(
400,
views.error_page(
"The selected item identifier is invalid.",
self.store.cart_count(session_digest),
400,
),
cookies=cookies,
)
return
if self.store.commerce_offer(asin) is None:
self._send_html(
404,
views.error_page(
"That item is not currently available in this marketplace.",
self.store.cart_count(session_digest),
404,
),
cookies=cookies,
)
return
option_spec = self.store.product_option_spec(asin)
expected_option_names = {
f"option.{group['label']}" for group in option_spec
}
if option_field_names and option_field_names != expected_option_names:
self._send_html(
400,
views.error_page(
"Choose one value for every available product option.",
self.store.cart_count(session_digest),
400,
),
cookies=cookies,
)
return
selected_options = (
{
name.removeprefix("option."): fields[name]
for name in option_field_names
}
if option_field_names
else None
)
else:
line_id = fields["lineID"]
if CART_LINE_ID_PATTERN.fullmatch(line_id) is None:
self._send_html(
400,
views.error_page(
"The cart line identity is invalid.",
self.store.cart_count(session_digest),
400,
),
cookies=cookies,
)
return
quantity = 1
if needs_quantity:
raw_quantity = fields["quantity"]
if not re.fullmatch(r"(?:[1-9]|[12][0-9]|30)", raw_quantity):
self._send_html(
400,
views.error_page(
"Choose a quantity from 1 through 30.",
self.store.cart_count(session_digest),
400,
),
cookies=cookies,
)
return
quantity = int(raw_quantity)
try:
buy_now_result: dict[str, Any] | None = None
added_line_id: str | None = None
if path == BUY_NOW_PATH:
buy_now_result = self.store.begin_buy_now(
session_digest,
asin,
quantity,
selected_options=selected_options,
)
changed = True
elif path == "/gp/cart/add.html":
changed = bool(
self.store.add_cart_item(
session_digest,
asin,
quantity,
selected_options=selected_options,
)
)
expected_selection = (
selected_options
if selected_options is not None
else self.store.default_product_options(asin)
)
added_line_id = next(
(
str(line["line_id"])
for line in self.store.cart(session_digest)
if line["asin"] == asin
and line.get("selected_options") == expected_selection
),
None,
)
elif path == "/gp/cart/update.html":
changed = self.store.set_cart_quantity(
session_digest, line_id, quantity
)
elif path == "/gp/cart/delete.html":
changed = self.store.delete_cart_item(session_digest, line_id)
elif path == "/gp/cart/save-for-later.html":
changed = self.store.save_for_later(session_digest, line_id)
else:
changed = self.store.move_to_cart(session_digest, line_id)
except ContractError as exc:
message = (
UNAVAILABLE_SELECTION_COPY
if str(exc) == UNAVAILABLE_SELECTION_COPY
else "That item cannot be added to this local marketplace cart."
)
self._send_html(
400,
views.error_page(
message,
self.store.cart_count(session_digest),
400,
),
cookies=cookies,
)
return
if not changed:
self._send_html(
409,
views.error_page(
"That cart item is no longer in the expected state.",
self.store.cart_count(session_digest),
409,
),
cookies=cookies,
)
return
if path == BUY_NOW_PATH:
if buy_now_result and buy_now_result.get(
"requires_authentication"
):
location = "/ap/signin?" + urlencode(
{"openid.return_to": BUY_NOW_CONTINUE_PATH}
)
else:
location = CHECKOUT_ADDRESS_PATH
self._send(
303,
b"",
headers={"Location": location},
cookies=cookies,
)
return
location = (
ADD_TO_CART_CONFIRMATION_PATH
+ "?"
+ urlencode({"lineID": str(added_line_id)})
if path == "/gp/cart/add.html" and added_line_id is not None
else "/gp/cart/view.html"
)
self._send(
303,
b"",
headers={"Location": location},
cookies=cookies,
)
return
if path == DELIVERY_PREFERENCE_PATH:
if not self._auth_post_origin_is_safe():
self._send(
403,
b"Forbidden",
content_type="text/plain; charset=utf-8",
cookies=cookies,
)
return
fields = self._form_fields(raw_body)
expected_fields = {
"dropdown-selection",
"glow-destination-type",
"glow-validation-token",
}
# A rejected choice answers with the same redirect shape as an
# accepted one, so a caller cannot use the status code to probe
# which part of the submission was wrong. Nothing is persisted
# unless every check passes, and re-submitting the same country is
# a no-op rather than a second write.
accepted = (
not query
and fields is not None
and set(fields) == expected_fields
and fields["glow-destination-type"] == "COUNTRY"
and hmac.compare_digest(
fields["glow-validation-token"],
delivery_location_token(session_digest),
)
and self.store.set_delivery_country(
session_digest, fields["dropdown-selection"]
)
)
self._send(
303,
b"",
headers={"Location": self._delivery_return_location(error=not accepted)},
cookies=cookies,
)
return
if path.startswith("/ap/"):
self._send(404, b"Not Found", content_type="text/plain; charset=utf-8", cookies=cookies)
return
if path.startswith("/__bench/") or path not in TERMINAL_PATHS:
self.store.record_rejected_post(
session_digest,
path,
self.headers.get("Content-Type", "").split(";", 1)[0].strip().lower(),
raw_body,
)
self._send(404, b"Not Found", content_type="text/plain; charset=utf-8", cookies=cookies)
return
media_type = self.headers.get("Content-Type", "").split(";", 1)[0].strip().lower()
try:
fields = parse_qsl(raw_body.decode("utf-8"), keep_blank_values=True, strict_parsing=True)
except (UnicodeDecodeError, ValueError):
fields = []
status, outcome = self.store.terminal_request(
session_digest,
path,
media_type,
raw_body,
fields,
self._flow_digest(),
self._terminal_source_is_canonical(),
)
if status == 303:
cookies.append(browser_cookie(FLOW_COOKIE, "", max_age=0))
target_lines = [
line
for line in self.store.cart(session_digest)
if str(line.get("asin") or "") == TARGET_ASIN
]
location = "/gp/cart/view.html"
if len(target_lines) == 1:
location = ADD_TO_CART_CONFIRMATION_PATH + "?" + urlencode(
{"lineID": str(target_lines[0]["line_id"])}
)
self._send(
303,
b"",
headers={"Location": location},
cookies=cookies,
)
return
message = {
"wrong-form-body": "Choose quantity 2 and submit the Amazon add-to-cart form once.",
"missing-navigation-sequence": "Open the External SSD Best Sellers list before this item.",
"wrong-navigation-stage": "Follow the Best Sellers → Samsung T7 journey in the same browser session.",
"invalid-flow-capability": "The product-page journey expired. Open the item from Best Sellers again.",
"invalid-terminal-source": "Submit the Add to cart form from the current Samsung T7 product page.",
"stale-navigation-sequence": "Return to the Samsung T7 product page before adding it to the cart.",
"capability-already-consumed": "This add-to-cart action was already completed.",
"target-line-already-exists": "The target item is already in this cart.",
}.get(outcome, f"The add-to-cart request did not match the local contract ({outcome}).")
self._send_html(
409,
views.error_page(message, self.store.cart_count(session_digest), 409),
cookies=cookies,
)
class AdminHandler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
store: Store
admin_token: str
smtp_summary: dict[str, object] = {"mode": "LOCAL_ONLY"}
server_version = "AmazonCloneAdmin/0.1"
def log_message(self, format_string: str, *args: Any) -> None:
sys.stdout.write(
json.dumps(
{
"stream": "admin",
"client": self.client_address[0],
"method": self.command,
"path": self.path,
"message": format_string % args,
},
ensure_ascii=False,
)
+ "\n"
)
sys.stdout.flush()
def _authorized(self) -> bool:
candidate = self.headers.get("X-Bench-Admin-Token", "")
return bool(candidate) and secrets.compare_digest(candidate, self.admin_token)
def _send_json(self, status: int, payload: Any) -> None:
body = json_bytes(payload)
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.send_header("X-Content-Type-Options", "nosniff")
self.end_headers()
if self.command != "HEAD":
self.wfile.write(body)
def _not_found(self) -> None:
self._send_json(404, {"error": "not-found"})
def _payload(self) -> dict[str, Any]:
content_length = int(self.headers.get("Content-Length", "0") or "0")
if content_length < 0 or content_length > MAX_ADMIN_BYTES:
raise ContractError("admin payload is too large")
if content_length == 0:
return {}
raw = self.rfile.read(content_length)
def unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
result: dict[str, Any] = {}
for key, value in pairs:
if key in result:
raise ContractError(f"duplicate admin field: {key}")
result[key] = value
return result
def reject_constant(value: str) -> None:
raise ContractError(f"invalid JSON constant: {value}")
payload = json.loads(
raw.decode("utf-8"),
object_pairs_hook=unique_object,
parse_constant=reject_constant,
)
if not isinstance(payload, dict):
raise ContractError("admin payload must be an object")
return payload
def do_HEAD(self) -> None:
self.do_GET()
def do_GET(self) -> None:
if not self._authorized():
self._not_found()
return
path = urlsplit(self.path).path
if path == "/__bench/health":
self._send_json(
200,
{
"ok": True,
"schema": "amazon-clone.admin.v1",
"snapshot_id": self.store.meta().get("snapshot_id"),
"mail_transport": self.smtp_summary,
"mail_delivery_status": self.store.mail_delivery_health(),
},
)
elif path == "/__bench/state":
self._send_json(200, self.store.normalized_state())
elif path == "/__bench/journal":
self._send_json(200, {"schema": "amazon-clone.journal.v1", "requests": self.store.journal()})
elif path == "/__bench/auth/registration-outbox":
self._send_json(
200,
{
"schema": "amazon-clone.registration-outbox.v1",
"delivery": self.smtp_summary["mode"],
"messages": self.store.registration_outbox(),
},
)
elif path == "/__bench/auth/password-reset-outbox":
self._send_json(
200,
{
"schema": "amazon-clone.password-reset-outbox.v1",
"delivery": self.smtp_summary["mode"],
"messages": self.store.password_reset_outbox(),
},
)
elif path == "/__bench/mail/outbox":
self._send_json(
200,
{
"schema": "amazon-clone.mail-outbox.v1",
"delivery": self.smtp_summary["mode"],
"messages": self.store.mail_delivery_outbox(),
},
)
else:
self._not_found()
def do_POST(self) -> None:
if not self._authorized():
self._not_found()
return
path = urlsplit(self.path).path
try:
payload = self._payload()
if path == "/__bench/reset":
unknown = set(payload) - {"fixture"}
if unknown:
raise ContractError(f"unsupported reset fields: {sorted(unknown)}")
state = self.store.reset(payload.get("fixture", "task-frozen-900136-v1.json"))
self._send_json(200, state)
elif path == "/__bench/clock/advance":
unknown = set(payload) - {"seconds"}
if unknown:
raise ContractError(f"unsupported clock fields: {sorted(unknown)}")
now = self.store.advance_clock(int(payload.get("seconds", 0)))
self._send_json(200, {"controlled_now": now})
elif path == "/__bench/orders/advance":
if set(payload) != {"orderID", "targetStatus"}:
raise ContractError(
"order advancement requires exactly orderID and targetStatus"
)
order_id = payload["orderID"]
if (
isinstance(order_id, bool)
or not isinstance(order_id, (int, str))
or re.fullmatch(r"[1-9][0-9]{0,18}", str(order_id)) is None
or not isinstance(payload["targetStatus"], str)
):
raise ContractError("invalid order advancement payload")
order = self.store.advance_order_shipment(
order_id, payload["targetStatus"]
)
self._send_json(
200,
{
"schema": "amazon-clone.order-lifecycle.v1",
"order": order,
},
)
elif path == "/__bench/returns/advance":
if set(payload) != {"returnID", "targetStatus"}:
raise ContractError(
"return advancement requires exactly returnID and targetStatus"
)
return_id = payload["returnID"]
if (
isinstance(return_id, bool)
or not isinstance(return_id, (int, str))
or re.fullmatch(r"[1-9][0-9]{0,18}", str(return_id)) is None
or not isinstance(payload["targetStatus"], str)
):
raise ContractError("invalid return advancement payload")
order = self.store.advance_return_request(
return_id, payload["targetStatus"]
)
self._send_json(
200,
{
"schema": "amazon-clone.return-lifecycle.v1",
"order": order,
},
)
else:
self._not_found()
except (OrderNotFound, ReturnNotFound):
self._not_found()
except OrderStateConflict as exc:
self._send_json(
409, {"error": "state-conflict", "detail": str(exc)}
)
except (ContractError, ValueError, json.JSONDecodeError) as exc:
self._send_json(400, {"error": "invalid-request", "detail": str(exc)})
def resolve_admin_token(admin_host: str, configured_token: str | None) -> str:
normalized_host = admin_host.strip().strip("[]")
try:
is_loopback = ipaddress.ip_address(normalized_host).is_loopback
except ValueError:
is_loopback = normalized_host.casefold() == "localhost"
token = (configured_token or "").strip()
if is_loopback:
return token or "local-amazon-bench"
if (
len(token) < 32
or token == "local-amazon-bench"
or any(ord(character) < 33 or ord(character) > 126 for character in token)
):
raise ValueError(
"a non-loopback admin host requires an explicit strong "
"AMAZON_ADMIN_TOKEN or --admin-token (at least 32 visible characters)"
)
return token
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Run the clean local Amazon benchmark clone")
parser.add_argument("--host", default=os.environ.get("AMAZON_HOST", "127.0.0.1"))
parser.add_argument("--port", type=int, default=int(os.environ.get("PORT", "8153")))
parser.add_argument("--admin-host", default=os.environ.get("AMAZON_ADMIN_HOST", "127.0.0.1"))
parser.add_argument("--admin-port", type=int, default=int(os.environ.get("AMAZON_ADMIN_PORT", "8154")))
parser.add_argument("--admin-token", default=os.environ.get("AMAZON_ADMIN_TOKEN"))
parser.add_argument(
"--db",
type=Path,
default=Path(os.environ.get("AMAZON_DB_PATH", str(DEFAULT_DB))),
)
parser.add_argument("--fixture", default="task-frozen-900136-v1.json")
parser.add_argument(
"--authorize-legacy-site-binding",
action="store_true",
help=(
"one-time explicit adoption of a recognizable unbound Amazon "
"database; never enabled by the deployment descriptor"
),
)
args = parser.parse_args()
try:
args.admin_token = resolve_admin_token(args.admin_host, args.admin_token)
except ValueError as exc:
parser.error(str(exc))
return args
def main() -> int:
args = parse_args()
try:
public_basic_auth_credentials()
except ValueError as exc:
print(json.dumps({"event": "amazon-clone-config-error", "error": str(exc)}))
return 2
try:
external_registration_verification = (
load_external_registration_verification()
)
except VerificationConfigurationError as exc:
print(
json.dumps(
{
"event": "amazon-clone-config-error",
"error": str(exc),
}
)
)
return 2
try:
payment_config = load_payment_config()
except StripeConfigurationError as exc:
print(
json.dumps(
{
"event": "amazon-clone-config-error",
"error": str(exc),
}
)
)
return 2
smtp_config = load_smtp_config()
local_inbox_url = load_local_inbox_url(smtp_config)
store = Store(
args.db.resolve(),
SCHEMA_PATH,
FIXTURE_ROOT,
authorize_legacy_site_binding=args.authorize_legacy_site_binding,
)
store.ensure_seeded(args.fixture)
wishlist.ensure_wishlist_schema(store)
PublicHandler.store = store
PublicHandler.smtp_config = smtp_config
PublicHandler.local_inbox_url = local_inbox_url
PublicHandler.external_registration_verification = (
external_registration_verification
)
PublicHandler.payment_config = payment_config
PublicHandler.stripe_gateway = (
StripeGateway(str(payment_config.api_base))
if payment_config.stripe_enabled
else None
)
AdminHandler.store = store
AdminHandler.admin_token = args.admin_token
AdminHandler.smtp_summary = smtp_public_summary(smtp_config)
released_mail_claims = 0
replayed_mail_jobs = 0
expired_mail_jobs = 0
exhausted_mail_jobs = 0
localized_mail_jobs = 0
if smtp_config is not None:
expired_mail_jobs = store.expire_stale_pending_auth_mail()
exhausted_mail_jobs = store.fail_exhausted_pending_mail()
released_mail_claims = store.recover_pending_mail_claims()
for delivery in store.pending_mail_deliveries():
if dispatch_mail_delivery(store, smtp_config, delivery):
replayed_mail_jobs += 1
else:
localized_mail_jobs = store.reconcile_mail_for_local_only()
public_server = ReusableThreadingHTTPServer((args.host, args.port), PublicHandler)
admin_server = ReusableThreadingHTTPServer((args.admin_host, args.admin_port), AdminHandler)
admin_thread = threading.Thread(target=admin_server.serve_forever, name="amazon-clone-admin", daemon=True)
admin_thread.start()
stopping = threading.Event()
def stop_servers(*_: Any) -> None:
if stopping.is_set():
return
stopping.set()
threading.Thread(target=public_server.shutdown, daemon=True).start()
threading.Thread(target=admin_server.shutdown, daemon=True).start()
if threading.current_thread() is threading.main_thread():
signal.signal(signal.SIGINT, stop_servers)
if hasattr(signal, "SIGTERM"):
signal.signal(signal.SIGTERM, stop_servers)
print(
json.dumps(
{
"event": "amazon-clone-started",
"public": f"http://{args.host}:{args.port}",
"admin": f"http://{args.admin_host}:{args.admin_port}",
"db": str(args.db.resolve()),
"snapshot": store.meta().get("snapshot_id"),
"mail_transport": smtp_public_summary(smtp_config),
"registration_verification": (
"redis-resend"
if external_registration_verification is not None
else "offline-local"
),
"payment_mode": payment_config.mode,
"mail_startup_replay": {
"expired_auth_jobs": expired_mail_jobs,
"exhausted_jobs": exhausted_mail_jobs,
"released_claims": released_mail_claims,
"dispatched": replayed_mail_jobs,
"localized_jobs": localized_mail_jobs,
},
},
ensure_ascii=False,
),
flush=True,
)
try:
public_server.serve_forever()
finally:
public_server.server_close()
admin_server.shutdown()
admin_server.server_close()
return 0
if __name__ == "__main__":
raise SystemExit(main())
|