auth-utils.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. "use strict";
  2. /**
  3. * Utilities for handling OAuth resource URIs.
  4. */
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.resourceUrlFromServerUrl = resourceUrlFromServerUrl;
  7. exports.checkResourceAllowed = checkResourceAllowed;
  8. /**
  9. * Converts a server URL to a resource URL by removing the fragment.
  10. * RFC 8707 section 2 states that resource URIs "MUST NOT include a fragment component".
  11. * Keeps everything else unchanged (scheme, domain, port, path, query).
  12. */
  13. function resourceUrlFromServerUrl(url) {
  14. const resourceURL = typeof url === 'string' ? new URL(url) : new URL(url.href);
  15. resourceURL.hash = ''; // Remove fragment
  16. return resourceURL;
  17. }
  18. /**
  19. * Checks if a requested resource URL matches a configured resource URL.
  20. * A requested resource matches if it has the same scheme, domain, port,
  21. * and its path starts with the configured resource's path.
  22. *
  23. * @param requestedResource The resource URL being requested
  24. * @param configuredResource The resource URL that has been configured
  25. * @returns true if the requested resource matches the configured resource, false otherwise
  26. */
  27. function checkResourceAllowed({ requestedResource, configuredResource }) {
  28. const requested = typeof requestedResource === 'string' ? new URL(requestedResource) : new URL(requestedResource.href);
  29. const configured = typeof configuredResource === 'string' ? new URL(configuredResource) : new URL(configuredResource.href);
  30. // Compare the origin (scheme, domain, and port)
  31. if (requested.origin !== configured.origin) {
  32. return false;
  33. }
  34. // Handle cases like requested=/foo and configured=/foo/
  35. if (requested.pathname.length < configured.pathname.length) {
  36. return false;
  37. }
  38. // Check if the requested path starts with the configured path
  39. // Ensure both paths end with / for proper comparison
  40. // This ensures that if we have paths like "/api" and "/api/users",
  41. // we properly detect that "/api/users" is a subpath of "/api"
  42. // By adding a trailing slash if missing, we avoid false positives
  43. // where paths like "/api123" would incorrectly match "/api"
  44. const requestedPath = requested.pathname.endsWith('/') ? requested.pathname : requested.pathname + '/';
  45. const configuredPath = configured.pathname.endsWith('/') ? configured.pathname : configured.pathname + '/';
  46. return requestedPath.startsWith(configuredPath);
  47. }
  48. //# sourceMappingURL=auth-utils.js.map