commit 8de72714c116c0100614662ff76b0afcc791a502 Author: Codex Date: Thu Dec 3 11:06:28 2026 +0000 Add YOURLS Amazon KDP Marketplace Redirect plugin diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6f194e0 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +/.gitattributes export-ignore +/tests export-ignore diff --git a/README.md b/README.md new file mode 100644 index 0000000..c8d0edf --- /dev/null +++ b/README.md @@ -0,0 +1,57 @@ +# Amazon KDP Marketplace Redirect for YOURLS + +## Installation + +1. Place the `sebstr_amazon_kdp` directory in `user/plugins` on the development YOURLS installation. +2. Activate **Amazon KDP Marketplace Redirect** in **Manage Plugins**. +3. Open **Amazon KDP** in the administration menu. Enter an ASIN and an optional title, then select **Save ASIN**. Saving the same ASIN updates its title. Use **Remove** to unregister an edition. +4. Shorten a standard Amazon product URL as usual. Register each edition's ASIN separately, including left-handed editions. Registration applies to existing and future short links across all source marketplaces in the table. + +The registry uses the YOURLS option `sebstr_amazon_kdp_asins`. Short-link destination records retain the original URLs. The plugin targets YOURLS 1.10.6 and PHP 8.4 or newer. + +## Redirect behaviour + +The plugin recognises ten-character ASINs in Amazon `/dp/`, `/gp/product/`, and `/gp/aw/d/` product URLs. It matches only the marketplace hosts below, including their `www.` and `m.` variants. Explicit seller and offer URLs take precedence, including URLs with a merchant or seller parameter such as `smid` and URLs containing the legacy seller plugin's `cx_skuctr_share` marker. + +For a registered edition, the same-marketplace and unavailable-country cases use the stored URL verbatim. Cross-marketplace redirects use a standard HTTPS product URL with the same ASIN and original fragment. Query parameters retain their original encoding and order, and the first occurrence of a repeated name is used for the rewritten URL. Amazon controls whether a parameter such as an affiliate tag has meaning on the destination marketplace. + +Only eligible registered links bypass the legacy Amazon seller callback. YOURLS runs its usual click counter and detailed logging once per origin request, subject to its statistics settings, and then sends the 302. The plugin works with the seller plugin enabled or disabled. + +## Cloudflare + +Enable **IP Geolocation** for the dev zone. The origin's PHP `REMOTE_ADDR` must identify the Cloudflare peer for geolocation to work. If a reverse proxy or real-IP module replaces it with the visitor address, the plugin uses the original URL. Forwarded IP headers are ignored for this trust decision. The bundled IPv4 and IPv6 ranges come from Cloudflare's published lists and should be updated when those lists change. [IP Geolocation](https://developers.cloudflare.com/network/ip-geolocation/) · [Cloudflare IP ranges](https://www.cloudflare.com/ips/) + +Eligible redirects send `Cache-Control: private, no-store, max-age=0` and `Cloudflare-CDN-Cache-Control: no-store`, including fallback redirects. If a zone rule overrides origin cache headers, set a Cache Rule to bypass caching for YOURLS short-link requests. Purge any previously cached redirects for those paths. A browser may retain a permanent redirect issued before activation until its local cache is cleared or expires. [Cloudflare default cache behaviour](https://developers.cloudflare.com/cache/concepts/default-cache-behavior/) · [Cloudflare CDN cache-control headers](https://developers.cloudflare.com/cache/concepts/cdn-cache-control/) + +## Marketplace mapping + +| Country | Marketplace | Country | Marketplace | +| --- | --- | --- | --- | +| AU | amazon.com.au | BE | amazon.com.be | +| BR | amazon.com.br | CA | amazon.ca | +| DE | amazon.de | ES | amazon.es | +| FR | amazon.fr | GB | amazon.co.uk | +| IE | amazon.ie | IN | amazon.in | +| IT | amazon.it | JP | amazon.co.jp | +| MX | amazon.com.mx | NL | amazon.nl | +| PL | amazon.pl | SE | amazon.se | +| US | amazon.com | | | + +The mapping includes marketplaces listed across Amazon's KDP print and Kindle documentation. Availability varies by edition, format, and distribution rights. For example, Brazil and Mexico support KDP eBooks, and Amazon has announced that Kindle eBook purchases on Amazon.in end on 26 February 2027. Review the India mapping before that transition. The plugin does no Amazon availability lookup, so a mapped marketplace may show an unavailable product if the edition is unavailable there. [KDP print distribution](https://kdp.amazon.com/en_US/help/topic/G201834280) · [KDP eBook distribution](https://kdp.amazon.com/en_US/help/topic/G200652410) · [India Kindle changes](https://kdp.amazon.com/en_US/help/topic/GK7ZLSRK7P8B9TV7) + +## Automated tests + +In a YOURLS installation with the existing seller plugin at `user/plugins/sebstr_amazon`, run `php user/plugins/sebstr_amazon_kdp/tests/run.php` from the YOURLS root. The suite uses PHP CLI and `php-cgi`. It loads the real YOURLS redirect and hook functions with isolated registry and statistics fixtures. It makes no database or network calls. + +## Release package + +Build the installable ZIP from the tagged commit: + +```sh +git archive --format=zip --prefix=sebstr_amazon_kdp/ \ + -o sebstr_amazon_kdp-1.0.0.zip v1.0.0 +``` + +Extract the ZIP under the target installation's `user/plugins` directory. +The package contains the plugin PHP files and this README. Register the +edition ASINs in YOURLS admin on the target installation. diff --git a/plugin.php b/plugin.php new file mode 100644 index 0000000..9fec6a3 --- /dev/null +++ b/plugin.php @@ -0,0 +1,135 @@ + +

Amazon KDP ASINs

+

Register each edition once. Registration applies to all short links for that ASIN.

+ +

+ +
+ + + + +
+ + + + + $title): ?> + + + + + + + +
ASINTitleAction
+
+ + + +
+
+ 'amazon.com.au', 'BE' => 'amazon.com.be', 'BR' => 'amazon.com.br', + 'CA' => 'amazon.ca', 'DE' => 'amazon.de', 'ES' => 'amazon.es', + 'FR' => 'amazon.fr', 'GB' => 'amazon.co.uk', 'IE' => 'amazon.ie', + 'IN' => 'amazon.in', 'IT' => 'amazon.it', 'JP' => 'amazon.co.jp', + 'MX' => 'amazon.com.mx', 'NL' => 'amazon.nl', 'PL' => 'amazon.pl', + 'SE' => 'amazon.se', 'US' => 'amazon.com', +]; + +const CLOUDFLARE_NETWORKS = [ + '173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', + '141.101.64.0/18', '108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20', + '197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15', '104.16.0.0/13', + '104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22', + '2400:cb00::/32', '2606:4700::/32', '2803:f800::/32', '2405:b500::/32', + '2405:8100::/32', '2a06:98c0::/29', '2c0f:f248::/32', +]; + +function normalize_asin(string $asin): ?string +{ + return preg_match('/\A[A-Z0-9]{10}\z/i', $asin) === 1 ? strtoupper($asin) : null; +} + +/** Return the components of an eligible product URL. */ +function product_url(string $url): ?array +{ + if (preg_match('/[\x00-\x20\x7f]/', $url) || str_contains($url, '\\')) { + return null; + } + + $parts = parse_url($url); + if ($parts === false || !in_array(strtolower($parts['scheme'] ?? ''), ['http', 'https'], true) + || isset($parts['user']) || isset($parts['pass']) || isset($parts['port'])) { + return null; + } + + $host = preg_replace('/^(?:www|m)\./', '', strtolower($parts['host'] ?? '')); + $path = $parts['path'] ?? ''; + if (!in_array($host, MARKETPLACES, true) + || !preg_match('~\A/(?:[^/]+/)?dp/([a-z0-9]{10})(?:/|\z)|\A/gp/(?:product|aw/d)/([a-z0-9]{10})(?:/|\z)~i', $path, $matches) + || preg_match('~(?:^|/)(?:offer-listing(?:/|$)|ref=[^/]*cx_skuctr_share|[^/]*[?&](?:smid|seller|merchant|m|me)=)~i', rawurldecode($path))) { + return null; + } + + $parameters = []; + foreach (explode('&', $parts['query'] ?? '') as $parameter) { + if ($parameter === '') { + continue; + } + $fields = explode('=', $parameter, 2); + $name = urldecode($fields[0]); + if (preg_match('/\A(?:smid|seller|sellerid|merchant|merchantid|m|me|offerlistingid)(?:\[|\z)/i', $name) + || (strcasecmp($name, 'ref') === 0 && str_starts_with(strtolower(urldecode($fields[1] ?? '')), 'cx_skuctr_share'))) { + return null; + } + $parameters[$name] ??= $parameter; + } + + return [ + 'host' => $host, + 'asin' => strtoupper(($matches[1] ?? '') ?: $matches[2]), + 'query' => implode('&', $parameters), + 'fragment' => $parts['fragment'] ?? null, + ]; +} + +function marketplace_url(string $original, array $product, ?string $country): string +{ + $marketplace = MARKETPLACES[$country] ?? null; + if ($marketplace === null || $marketplace === $product['host']) { + return $original; + } + + $url = 'https://www.' . $marketplace . '/dp/' . $product['asin']; + if ($product['query'] !== '') { + $url .= '?' . $product['query']; + } + if ($product['fragment'] !== null) { + $url .= '#' . $product['fragment']; + } + return $url; +} + +function visitor_country(string $peer, string $country): ?string +{ + $country = strtoupper($country); + if (!isset(MARKETPLACES[$country]) || !filter_var($peer, FILTER_VALIDATE_IP)) { + return null; + } + + $address = inet_pton($peer); + if (str_starts_with($address, str_repeat("\0", 10) . "\xff\xff")) { + $address = substr($address, 12); + } + + foreach (CLOUDFLARE_NETWORKS as $cidr) { + [$network, $prefix] = explode('/', $cidr); + $network = inet_pton($network); + if (strlen($address) !== strlen($network)) { + continue; + } + + $bytes = intdiv((int) $prefix, 8); + $remaining = (int) $prefix % 8; + if (substr($address, 0, $bytes) === substr($network, 0, $bytes) + && ($remaining === 0 || ((ord($address[$bytes]) ^ ord($network[$bytes])) >> (8 - $remaining)) === 0)) { + return $country; + } + } + + return null; +} diff --git a/tests/request.php b/tests/request.php new file mode 100644 index 0000000..a9c96c3 --- /dev/null +++ b/tests/request.php @@ -0,0 +1,43 @@ + 'Standard', '1234567890' => 'Left-handed'] : $default; +} + +$clicks = $logs = 0; +yourls_add_filter('shunt_update_clicks', static function () use (&$clicks) { + ++$clicks; + return true; +}); +yourls_add_filter('shunt_log_redirect', static function () use (&$logs) { + ++$logs; + return true; +}); +yourls_add_filter('shunt_robots_tag_header', static fn () => true); +register_shutdown_function(static function () use (&$clicks, &$logs) { + echo "clicks=$clicks logs=$logs"; +}); + +if (getenv('SEBSTR_KDP_TEST_KDP') === '1') { + require dirname(__DIR__) . '/plugin.php'; +} +if (getenv('SEBSTR_KDP_TEST_SELLER') === '1') { + require dirname(__DIR__, 2) . '/sebstr_amazon/plugin.php'; +} + +$_SERVER['REMOTE_ADDR'] = getenv('SEBSTR_KDP_TEST_PEER'); +$country = getenv('SEBSTR_KDP_TEST_COUNTRY'); +if ($country !== '') { + $_SERVER['HTTP_CF_IPCOUNTRY'] = $country; +} +yourls_redirect_shorturl(getenv('SEBSTR_KDP_TEST_URL'), 'existing-keyword'); diff --git a/tests/run.php b/tests/run.php new file mode 100644 index 0000000..70b121e --- /dev/null +++ b/tests/run.php @@ -0,0 +1,168 @@ + '200', + 'GATEWAY_INTERFACE' => 'CGI/1.1', + 'REQUEST_METHOD' => 'GET', + 'SERVER_PROTOCOL' => 'HTTP/1.1', + 'SCRIPT_FILENAME' => __DIR__ . '/request.php', + 'SEBSTR_KDP_TEST_URL' => $url, + 'SEBSTR_KDP_TEST_COUNTRY' => $country, + 'SEBSTR_KDP_TEST_PEER' => $case[7] ?? '104.16.0.1', + 'SEBSTR_KDP_TEST_KDP' => ($case[5] ?? true) ? '1' : '0', + 'SEBSTR_KDP_TEST_SELLER' => ($case[6] ?? true) ? '1' : '0', + ]; + $process = proc_open(['php-cgi', '-d', 'display_errors=stderr', '-d', 'log_errors=0'], [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, null, $environment); + check(is_resource($process), 'Start php-cgi'); + $output = stream_get_contents($pipes[1]); + $errors = stream_get_contents($pipes[2]); + fclose($pipes[1]); + fclose($pipes[2]); + check(proc_close($process) === 0, "$label CGI error $errors $output"); + $locationPattern = str_replace(preg_quote('{seller-id}', '~'), '[A-Z0-9]+', preg_quote($expected, '~')); + check(str_contains($output, "Status: $status ") && preg_match("~^Location: $locationPattern\\r?$~m", $output) === 1, + "$label unexpected response $output $errors"); + check(str_contains($output, 'clicks=1 logs=1'), "$label tracking mismatch"); + check(str_contains($output, 'Cache-Control: private, no-store, max-age=0') === ($status === 302), "$label browser cache header mismatch"); + check(str_contains($output, 'Cloudflare-CDN-Cache-Control: no-store') === ($status === 302), "$label Cloudflare cache header mismatch"); +} + +echo count($cases) . " CGI redirect cases and five IP checks passed.\n"; + +define('YOURLS_ABSPATH', dirname(__DIR__, 4) . '/'); +define('YOURLS_ADMIN', true); +require YOURLS_ABSPATH . 'includes/functions-plugins.php'; + +function yourls_get_option($name, $default = false) +{ + return $GLOBALS['test_options'][$name] ?? $default; +} + +function yourls_update_option($name, $value) +{ + $GLOBALS['test_options'][$name] = $value; + return true; +} + +function yourls_get_db($context) +{ + return new class { + public function add_plugin_page($slug, $title, $callback): void + { + $GLOBALS['test_pages'][$slug] = $callback; + } + }; +} + +function yourls_create_nonce($action) +{ + return 'test-' . $action; +} + +function yourls_verify_nonce($action, $nonce) +{ + if ($nonce !== yourls_create_nonce($action)) { + throw new InvalidArgumentException('Invalid nonce'); + } +} + +require dirname(__DIR__) . '/plugin.php'; +yourls_do_action('plugins_loaded'); +$page = $GLOBALS['test_pages']['sebstr_amazon_kdp'] ?? null; +check(is_callable($page), 'YOURLS admin page registration'); + +$_SERVER['REQUEST_METHOD'] = 'POST'; +$key = Sebstr\AmazonKdp\SETTINGS; +$_POST = ['operation' => 'save', 'asin' => 'testbook01', 'title' => '', 'nonce' => 'invalid']; +ob_start(); +try { + $page(); + check(false, 'Invalid nonce accepted'); +} catch (InvalidArgumentException $exception) { + check(yourls_get_option($key, []) === [], 'Invalid nonce changed registry'); +} finally { + ob_end_clean(); +} +$_POST['nonce'] = yourls_create_nonce($key); +ob_start(); +$page(); +$html = ob_get_clean(); +check(str_contains($html, '<Standard>'), 'Title is escaped'); +check(yourls_get_option($key) === ['TESTBOOK01' => ''], 'ASIN and title saved'); + +$_POST = ['operation' => 'remove', 'asin' => 'TESTBOOK01', 'nonce' => yourls_create_nonce($key)]; +ob_start(); +$page(); +ob_end_clean(); +check(yourls_get_option($key) === [], 'ASIN removed'); + +echo "Admin registration, nonce rejection, title escaping, addition and removal passed.\n";