index.js 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. 'use strict'
  2. /**
  3. * static files (404.html, sw.js, conf.js)
  4. */
  5. const ASSET_URL = 'https://hunshcn.github.io/gh-proxy/'
  6. // 前缀,如果自定义路由为example.com/gh/*,将PREFIX改为 '/gh/',注意,少一个杠都会错!
  7. const PREFIX = '/'
  8. // git使用cnpmjs镜像、分支文件使用jsDelivr镜像的开关,0为关闭,默认开启
  9. const Config = {
  10. jsdelivr: 1,
  11. cnpmjs: 1
  12. }
  13. /** @type {RequestInit} */
  14. const PREFLIGHT_INIT = {
  15. status: 204,
  16. headers: new Headers({
  17. 'access-control-allow-origin': '*',
  18. 'access-control-allow-methods': 'GET,POST,PUT,PATCH,TRACE,DELETE,HEAD,OPTIONS',
  19. 'access-control-max-age': '1728000',
  20. }),
  21. }
  22. const exp1 = /^(?:https?:\/\/)?github\.com\/.+?\/.+?\/(?:releases|archive)\/.*$/i
  23. const exp2 = /^(?:https?:\/\/)?github\.com\/.+?\/.+?\/(?:blob|raw)\/.*$/i
  24. const exp3 = /^(?:https?:\/\/)?github\.com\/.+?\/.+?\/(?:info|git-).*$/i
  25. const exp4 = /^(?:https?:\/\/)?raw\.(?:githubusercontent|github)\.com\/.+?\/.+?\/.+?\/.+$/i
  26. const exp5 = /^(?:https?:\/\/)?gist\.(?:githubusercontent|github)\.com\/.+?\/.+?\/.+$/i
  27. const exp6 = /^(?:https?:\/\/)?github\.com\/.+?\/.+?\/tags.*$/i
  28. /**
  29. * @param {any} body
  30. * @param {number} status
  31. * @param {Object<string, string>} headers
  32. */
  33. function makeRes(body, status = 200, headers = {}) {
  34. headers['access-control-allow-origin'] = '*'
  35. return new Response(body, {status, headers})
  36. }
  37. /**
  38. * @param {string} urlStr
  39. */
  40. function newUrl(urlStr) {
  41. try {
  42. return new URL(urlStr)
  43. } catch (err) {
  44. return null
  45. }
  46. }
  47. addEventListener('fetch', e => {
  48. const ret = fetchHandler(e)
  49. .catch(err => makeRes('cfworker error:\n' + err.stack, 502))
  50. e.respondWith(ret)
  51. })
  52. function checkUrl(u) {
  53. for (let i of [exp1, exp2, exp3, exp4, exp5, exp6 ]) {
  54. if (u.search(i) === 0) {
  55. return true
  56. }
  57. }
  58. return false
  59. }
  60. /**
  61. * @param {FetchEvent} e
  62. */
  63. async function fetchHandler(e) {
  64. const req = e.request
  65. const urlStr = req.url
  66. const urlObj = new URL(urlStr)
  67. let path = urlObj.searchParams.get('q')
  68. if (path) {
  69. return Response.redirect('https://' + urlObj.host + PREFIX + path, 301)
  70. }
  71. // cfworker 会把路径中的 `//` 合并成 `/`
  72. path = urlObj.href.substr(urlObj.origin.length + PREFIX.length).replace(/^https?:\/+/, 'https://')
  73. if (path.search(exp1) === 0 || path.search(exp5) === 0 || path.search(exp6) === 0 || !Config.cnpmjs && (path.search(exp3) === 0 || path.search(exp4) === 0)) {
  74. return httpHandler(req, path)
  75. } else if (path.search(exp2) === 0) {
  76. if (Config.jsdelivr) {
  77. const newUrl = path.replace('/blob/', '@').replace(/^(?:https?:\/\/)?github\.com/, 'https://cdn.jsdelivr.net/gh')
  78. return Response.redirect(newUrl, 302)
  79. } else {
  80. path = path.replace('/blob/', '/raw/')
  81. return httpHandler(req, path)
  82. }
  83. } else if (path.search(exp3) === 0) {
  84. const newUrl = path.replace(/^(?:https?:\/\/)?github\.com/, 'https://github.com.cnpmjs.org')
  85. return Response.redirect(newUrl, 302)
  86. } else if (path.search(exp4) === 0) {
  87. const newUrl = path.replace(/(?<=com\/.+?\/.+?)\/(.+?\/)/, '@$1').replace(/^(?:https?:\/\/)?raw\.(?:githubusercontent|github)\.com/, 'https://cdn.jsdelivr.net/gh')
  88. return Response.redirect(newUrl, 302)
  89. } else {
  90. return fetch(ASSET_URL + path)
  91. }
  92. }
  93. /**
  94. * @param {Request} req
  95. * @param {string} pathname
  96. */
  97. function httpHandler(req, pathname) {
  98. const reqHdrRaw = req.headers
  99. // preflight
  100. if (req.method === 'OPTIONS' &&
  101. reqHdrRaw.has('access-control-request-headers')
  102. ) {
  103. return new Response(null, PREFLIGHT_INIT)
  104. }
  105. const reqHdrNew = new Headers(reqHdrRaw)
  106. let urlStr = pathname
  107. if (urlStr.startsWith('github')) {
  108. urlStr = 'https://' + urlStr
  109. }
  110. const urlObj = newUrl(urlStr)
  111. /** @type {RequestInit} */
  112. const reqInit = {
  113. method: req.method,
  114. headers: reqHdrNew,
  115. redirect: 'manual',
  116. body: req.body
  117. }
  118. return proxy(urlObj, reqInit)
  119. }
  120. /**
  121. *
  122. * @param {URL} urlObj
  123. * @param {RequestInit} reqInit
  124. */
  125. async function proxy(urlObj, reqInit) {
  126. const res = await fetch(urlObj.href, reqInit)
  127. const resHdrOld = res.headers
  128. const resHdrNew = new Headers(resHdrOld)
  129. const status = res.status
  130. if (resHdrNew.has('location')) {
  131. let _location = resHdrNew.get('location')
  132. if (checkUrl(_location))
  133. resHdrNew.set('location', PREFIX + _location)
  134. else {
  135. reqInit.redirect = 'follow'
  136. return proxy(newUrl(_location), reqInit)
  137. }
  138. }
  139. resHdrNew.set('access-control-expose-headers', '*')
  140. resHdrNew.set('access-control-allow-origin', '*')
  141. resHdrNew.delete('content-security-policy')
  142. resHdrNew.delete('content-security-policy-report-only')
  143. resHdrNew.delete('clear-site-data')
  144. return new Response(res.body, {
  145. status,
  146. headers: resHdrNew,
  147. })
  148. }