Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -285,15 +285,26 @@ Obtains a license token for accessing a protected resource using the OAuth2 `cli
| `resourceUrl` | `string` | Yes | — | Full URL of the protected resource |
| `debug` | `bool` | No | `false` | Emit debug logs |
| `httpClient` | `?HttpClientInterface` | No | `null` | Inject a custom HTTP client |
| `baseUrl` | `?string` | No | `null` | Per-call Supertab API host override (defaults to `getBaseUrl()`) |

**Returns:** `string` (the access token). Throws `SupertabConnectException` on failure.

The SDK handles the full RSL flow automatically:
The SDK handles the full flow automatically:

1. Fetches `{origin}/license.xml` from the resource URL
2. Parses content blocks and finds the best matching URL pattern (exact > path pattern > wildcard by specificity)
3. POSTs to the token endpoint using OAuth2 `client_credentials`
4. Caches the token in memory (keyed by `clientId:resourceUrl`, reused until 30s before expiry)
2. Parses content blocks and picks where to mint, on one of two lanes:
- **RSL License lane** — a `<content>` block path-matches the resource
(exact > path pattern > wildcard by specificity; matches hosted on the
Supertab API host are preferred over other providers). The block's
`<license>` chunk is sent to that block's own `{server}/token`.
- **Agreement lane** — nothing matches, so the request goes license-less to
the generic `{baseUrl}/token`, where the backend resolves the merchant
system from the resource URL and the customer's single Active Agreement.
3. POSTs to the token endpoint using OAuth2 `client_credentials`, with
`resource` carrying the raw resource URL
4. Caches the token in memory (keyed by client ID, token server and scope —
the block's URL pattern on the matched lane, the resource origin on the
Agreement lane — reused until 30s before expiry)

### `SupertabConnect::setBaseUrl()` (static)

Expand Down
2 changes: 1 addition & 1 deletion src/Customer/ContentBlock.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ final class ContentBlock
{
public function __construct(
public readonly string $urlPattern,
public readonly string $server,
public readonly ?string $server,
public readonly string $licenseXml,
) {}
}
39 changes: 18 additions & 21 deletions src/Customer/ContentMatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ final class ContentMatcher
* Find the best matching content block for the given resource URL.
*
* Matching rules:
* 1. Host (including port) must match exactly
* 1. Canonical host (including non-default port) must match exactly;
* hosts are compared via UrlCanonicalizer (lowercased, punycoded,
* default ports stripped) and dot segments in paths are resolved,
* mirroring the WHATWG URL parsing the TypeScript SDK gets for free
* 2. Exact path match returns immediately (highest priority)
* 3. Robots.txt-style pattern matching via scorePathPattern():
* - `*` matches zero or more characters (including `/`)
Expand All @@ -32,8 +35,17 @@ public static function findBestMatch(array $contentBlocks, string $resourceUrl,
return null;
}

$host = self::extractHost($parsed);
$path = $parsed['path'] ?? '/';
// Canonicalize from the raw string: parse_url() corrupts some IDN hosts.
$host = UrlCanonicalizer::canonicalHost($resourceUrl);
if ($host === null) {
if ($debug) {
error_log("[SupertabConnect] Cannot canonicalize resource URL host: {$resourceUrl}");
}

return null;
}

$path = UrlCanonicalizer::resolveDotSegments($parsed['path'] ?? '/');

if ($debug) {
error_log("[SupertabConnect] Matching resource URL: {$resourceUrl} (host={$host}, path={$path})");
Expand All @@ -53,8 +65,8 @@ public static function findBestMatch(array $contentBlocks, string $resourceUrl,
}

if (isset($patternParsed['host'])) {
// Absolute URL pattern: host must match
$patternHost = self::extractHost($patternParsed);
// Absolute URL pattern: canonical host must match
$patternHost = UrlCanonicalizer::canonicalHost($block->urlPattern);

if ($patternHost !== $host) {
if ($debug) {
Expand All @@ -64,7 +76,7 @@ public static function findBestMatch(array $contentBlocks, string $resourceUrl,
continue;
}

$patternPath = $patternParsed['path'] ?? '/';
$patternPath = UrlCanonicalizer::resolveDotSegments($patternParsed['path'] ?? '/');
} else {
// Path-only pattern: must start with `/` and have no scheme.
// Rejects malformed absolute URLs like "https:/content/*".
Expand Down Expand Up @@ -153,19 +165,4 @@ public static function scorePathPattern(string $pattern, string $path): int

return -1;
}

/**
* Extract the host string including port.
*
* @param array<string, mixed> $parsed
*/
private static function extractHost(array $parsed): string
{
$host = (string) $parsed['host'];
if (isset($parsed['port'])) {
$host .= ':' . $parsed['port'];
}

return $host;
}
}
163 changes: 120 additions & 43 deletions src/Customer/LicenseTokenClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,33 @@

final class LicenseTokenClient
{
private const DEFAULT_SUPERTAB_BASE_URL = 'https://api-connect.supertab.co';

private readonly TokenCache $cache;

private readonly string $supertabBaseUrl;

public function __construct(
private readonly HttpClientInterface $httpClient,
private readonly bool $debug = false,
?TokenCache $cache = null,
string $supertabBaseUrl = self::DEFAULT_SUPERTAB_BASE_URL,
) {
$this->cache = $cache ?? new TokenCache;
$this->supertabBaseUrl = rtrim($supertabBaseUrl, '/');
}

/**
* Obtain a license token for accessing a protected resource.
*
* Uses the OAuth2 client_credentials flow via the resource's license.xml.
* Uses the OAuth2 client_credentials flow via the resource's license.xml,
* on one of two lanes:
* - RSL License lane: a <content> block path-matches the resource, so the
* <license> chunk goes to that block's own URN-scoped {server}/token.
* - Agreement lane: nothing matches, so the chunk is omitted and the
* request goes license-less to the generic {supertabBaseUrl}/token,
* where the backend resolves the merchant system from the resource URL
* and the customer's single Active Agreement.
*
* @throws SupertabConnectException on any failure
*/
Expand All @@ -31,21 +44,15 @@ public function obtainLicenseToken(
string $clientSecret,
string $resourceUrl,
): string {
// 1. Check cache
$cacheKey = "{$clientId}:{$resourceUrl}";
$cached = $this->cache->get($cacheKey, $this->debug);
if ($cached !== null) {
return $cached;
}

// 2. Fetch license.xml
$xml = $this->fetchLicenseXml($resourceUrl);
// 1. Fetch license.xml from the resource's origin
$origin = $this->buildOrigin($resourceUrl);
$xml = $this->fetchLicenseXml($origin);

if ($this->debug) {
error_log('[SupertabConnect] Fetched license.xml (' . strlen($xml) . ' chars)');
}

// 3. Parse and match
// 2. Parse and resolve the token endpoint
$contentBlocks = LicenseXmlParser::parseContentElements($xml, $this->debug);

if ($contentBlocks === []) {
Expand All @@ -58,26 +65,20 @@ public function obtainLicenseToken(
);
}

$matchedContent = ContentMatcher::findBestMatch($contentBlocks, $resourceUrl, $this->debug);
$endpoint = $this->selectTokenEndpoint($contentBlocks, $resourceUrl, $origin);

if ($matchedContent === null) {
if ($this->debug) {
$patterns = implode(', ', array_map(fn (ContentBlock $b) => $b->urlPattern, $contentBlocks));
error_log("[SupertabConnect] No <content> element matches resource URL: {$resourceUrl}. Available patterns: {$patterns}");
}

throw new SupertabConnectException(
"No <content> element in license.xml matches resource URL: {$resourceUrl}"
);
}

if ($this->debug) {
error_log("[SupertabConnect] Matched content block for resource URL: {$resourceUrl}");
error_log("[SupertabConnect] Using license XML: {$matchedContent->licenseXml}");
// 3. Check cache. Keyed by server + scope: on the matched lane scope is
// the block's urlPattern (token reuse across sibling paths); on the
// Agreement lane scope is the origin (one Agreement token per origin).
$cacheKey = "{$clientId}:{$endpoint->server}:{$endpoint->scope}";
$cached = $this->cache->get($cacheKey, $this->debug);
Comment thread
tomasstark marked this conversation as resolved.
Resolved
if ($cached !== null) {
return $cached;
}

// 4. Request token
$tokenEndpoint = rtrim($matchedContent->server, '/') . '/token';
// 4. Request token (both lanes construct TokenEndpoint with a
// normalized, trailing-slash-free server)
$tokenEndpoint = $endpoint->server . '/token';

if ($this->debug) {
error_log("[SupertabConnect] Requesting license token from {$tokenEndpoint}");
Expand All @@ -87,8 +88,8 @@ public function obtainLicenseToken(
$tokenEndpoint,
$clientId,
$clientSecret,
$matchedContent->licenseXml,
$matchedContent->urlPattern,
$endpoint->licenseXml,
$resourceUrl,
);

// 5. Cache token
Expand All @@ -98,22 +99,90 @@ public function obtainLicenseToken(
}

/**
* Fetch license.xml from the resource URL's origin.
* Resolve where to mint, decoupled from whether the live license.xml still
* grants the resource.
*
* @throws SupertabConnectException
* A path-matching server-bearing <content> block gives the RSL License
* lane: mint against that block's URN-scoped server with its <license>
* chunk. Matches hosted on the configured Supertab API host are preferred
* over matches from other providers, so a multi-provider license.xml never
* routes credentials to a third party when a Supertab block also matches.
* Anything else falls through to the Agreement lane, where the backend
* resolves the merchant system from the resource URL and the customer's
* single Active Agreement, so a diverged license.xml cannot veto the mint.
*
* @param list<ContentBlock> $contentBlocks
*/
private function fetchLicenseXml(string $resourceUrl): string
private function selectTokenEndpoint(array $contentBlocks, string $resourceUrl, string $origin): TokenEndpoint
{
$parsed = parse_url($resourceUrl);
if ($parsed === false || ! isset($parsed['scheme'], $parsed['host'])) {
throw new SupertabConnectException("Invalid resource URL: {$resourceUrl}");
$serverBlocks = array_values(array_filter($contentBlocks, fn (ContentBlock $b) => $b->server !== null));
$supertabBlocks = array_values(array_filter($serverBlocks, fn (ContentBlock $b) => $this->isSupertabServer($b->server)));

$matched = ContentMatcher::findBestMatch($supertabBlocks, $resourceUrl, $this->debug)
?? ContentMatcher::findBestMatch($serverBlocks, $resourceUrl, $this->debug);

if ($matched !== null && $matched->server !== null) {
if ($this->debug) {
error_log("[SupertabConnect] Matched content block for resource URL: {$resourceUrl}");
}

// Normalized once here so the cache key and the token URL agree
// even when license.xml writes the server with a trailing slash.
return new TokenEndpoint(
server: rtrim($matched->server, '/'),
scope: $matched->urlPattern,
matched: true,
licenseXml: $matched->licenseXml,
);
}

$origin = $parsed['scheme'] . '://' . $parsed['host'];
if (isset($parsed['port'])) {
$origin .= ':' . $parsed['port'];
if ($this->debug) {
$patterns = implode(', ', array_map(fn (ContentBlock $b) => $b->urlPattern, $serverBlocks));
error_log(
"[SupertabConnect] No <content> element matches resource URL: {$resourceUrl} (patterns: {$patterns}). "
. "Minting license-less against {$this->supertabBaseUrl}; the backend resolves the Agreement."
);
}

return new TokenEndpoint(server: $this->supertabBaseUrl, scope: $origin, matched: false);
}

/**
* True when the server's host matches the configured Supertab API base host.
*/
private function isSupertabServer(?string $server): bool
{
if ($server === null) {
return false;
}

$serverHost = UrlCanonicalizer::canonicalHost($server);

return $serverHost !== null && $serverHost === UrlCanonicalizer::canonicalHost($this->supertabBaseUrl);
}

/**
* Derive the canonical origin from the resource URL.
*
* @throws SupertabConnectException when the URL has no origin
*/
private function buildOrigin(string $resourceUrl): string
{
$origin = UrlCanonicalizer::canonicalOrigin($resourceUrl);
if ($origin === null) {
throw new SupertabConnectException("Invalid resource URL: {$resourceUrl}");
}

return $origin;
}

/**
* Fetch license.xml from the given origin.
*
* @throws SupertabConnectException
*/
private function fetchLicenseXml(string $origin): string
{
$licenseXmlUrl = $origin . '/license.xml';

try {
Expand Down Expand Up @@ -152,14 +221,22 @@ private function requestToken(
string $tokenEndpoint,
string $clientId,
string $clientSecret,
string $licenseXml,
?string $licenseXml,
string $resource,
): string {
$body = http_build_query([
$params = [
'grant_type' => 'client_credentials',
'license' => $licenseXml,
'resource' => $resource,
]);
];

// Only send the live <license> chunk when a public <content> block
// actually matched; on the Agreement lane the backend mints from the
// Agreement's pinned snapshot instead.
if ($licenseXml !== null) {
$params['license'] = $licenseXml;
}

$body = http_build_query($params);

$headers = [
'Content-Type' => 'application/x-www-form-urlencoded',
Expand Down
9 changes: 5 additions & 4 deletions src/Customer/LicenseXmlParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ final class LicenseXmlParser
*
* Each valid <content> element must have:
* - A `url` attribute (the URL pattern)
* - A `server` attribute (the token endpoint base)
* - A nested `<license>` element (preserved as raw XML)
*
* The `server` attribute (the token endpoint base) is optional; blocks
* without one are kept with a null server and never mint directly.
*
* @return list<ContentBlock>
*/
public static function parseContentElements(string $xml, bool $debug = false): array
Expand Down Expand Up @@ -70,16 +72,15 @@ public static function parseContentElements(string $xml, bool $debug = false): a
? $licenseNode->asXML()
: null;

if ($url !== null && $url !== '' && $server !== null && $server !== '' && $licenseXml !== null && $licenseXml !== false) {
if ($url !== null && $url !== '' && $licenseXml !== null && $licenseXml !== false) {
$contentBlocks[] = new ContentBlock(
urlPattern: $url,
server: $server,
server: ($server !== null && $server !== '') ? $server : null,
licenseXml: $licenseXml,
);
} elseif ($debug) {
$missing = array_filter([
($url === null || $url === '') ? 'url' : null,
($server === null || $server === '') ? 'server' : null,
($licenseXml === null || $licenseXml === false) ? '<license>' : null,
]);
error_log("[SupertabConnect] Skipping <content> element #{$elementCount}: missing " . implode(', ', $missing));
Expand Down
Loading
Loading