index.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. const REGEX_IS_INSTALLATION_LEGACY = /^v1\./;
  2. const REGEX_IS_INSTALLATION = /^ghs_/;
  3. const REGEX_IS_USER_TO_SERVER = /^ghu_/;
  4. async function auth(token) {
  5. const isApp = token.split(/\./).length === 3;
  6. const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) ||
  7. REGEX_IS_INSTALLATION.test(token);
  8. const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token);
  9. const tokenType = isApp
  10. ? "app"
  11. : isInstallation
  12. ? "installation"
  13. : isUserToServer
  14. ? "user-to-server"
  15. : "oauth";
  16. return {
  17. type: "token",
  18. token: token,
  19. tokenType,
  20. };
  21. }
  22. /**
  23. * Prefix token for usage in the Authorization header
  24. *
  25. * @param token OAuth token or JSON Web Token
  26. */
  27. function withAuthorizationPrefix(token) {
  28. if (token.split(/\./).length === 3) {
  29. return `bearer ${token}`;
  30. }
  31. return `token ${token}`;
  32. }
  33. async function hook(token, request, route, parameters) {
  34. const endpoint = request.endpoint.merge(route, parameters);
  35. endpoint.headers.authorization = withAuthorizationPrefix(token);
  36. return request(endpoint);
  37. }
  38. const createTokenAuth = function createTokenAuth(token) {
  39. if (!token) {
  40. throw new Error("[@octokit/auth-token] No token passed to createTokenAuth");
  41. }
  42. if (typeof token !== "string") {
  43. throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string");
  44. }
  45. token = token.replace(/^(token|bearer) +/i, "");
  46. return Object.assign(auth.bind(null, token), {
  47. hook: hook.bind(null, token),
  48. });
  49. };
  50. export { createTokenAuth };
  51. //# sourceMappingURL=index.js.map