index.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. /**
  28. * @param {any} body
  29. * @param {number} status
  30. * @param {Object<string, string>} headers
  31. */
  32. function makeRes(body, status = 200, headers = {}) {
  33. headers['access-control-allow-origin'] = '*'
  34. return new Response(body, {status, headers})
  35. }
  36. /**
  37. * @param {string} urlStr
  38. */
  39. function newUrl(urlStr) {
  40. try {
  41. return new URL(urlStr)
  42. } catch (err) {
  43. return null
  44. }
  45. }
  46. addEventListener('fetch', e => {
  47. const ret = fetchHandler(e)
  48. .catch(err => makeRes('cfworker error:\n' + err.stack, 502))
  49. e.respondWith(ret)
  50. })
  51. function checkUrl(u) {
  52. for (let i of [exp1, exp2, exp3, exp4, exp5, ]) {
  53. if (u.search(i) === 0) {
  54. return true
  55. }
  56. }
  57. return false
  58. }
  59. /**
  60. * @param {FetchEvent} e
  61. */
  62. async function fetchHandler(e) {
  63. const req = e.request
  64. const urlStr = req.url
  65. const urlObj = new URL(urlStr)
  66. let path = urlObj.searchParams.get('q')
  67. if (path) {
  68. return Response.redirect('https://' + urlObj.host + PREFIX + path, 301)
  69. }
  70. // cfworker 会把路径中的 `//` 合并成 `/`
  71. path = urlObj.href.substr(urlObj.origin.length + PREFIX.length).replace(/^https?:\/+/, 'https://')
  72. if (path.search(exp1) === 0 || path.search(exp5) === 0 || !Config.cnpmjs && (path.search(exp3) === 0 || path.search(exp4) === 0)) {
  73. return httpHandler(req, path)
  74. } else if (path.search(exp2) === 0) {
  75. if (Config.jsdelivr) {
  76. const newUrl = path.replace('/blob/', '@').replace(/^(?:https?:\/\/)?github\.com/, 'https://cdn.jsdelivr.net/gh')
  77. return Response.redirect(newUrl, 302)
  78. } else {
  79. path = path.replace('/blob/', '/raw/')
  80. return httpHandler(req, path)
  81. }
  82. } else if (path.search(exp3) === 0) {
  83. const newUrl = path.replace(/^(?:https?:\/\/)?github\.com/, 'https://github.com.cnpmjs.org')
  84. return Response.redirect(newUrl, 302)
  85. } else if (path.search(exp4) === 0) {
  86. const newUrl = path.replace(/(?<=com\/.+?\/.+?)\/(.+?\/)/, '@$1').replace(/^(?:https?:\/\/)?raw\.(?:githubusercontent|github)\.com/, 'https://cdn.jsdelivr.net/gh')
  87. return Response.redirect(newUrl, 302)
  88. } else {
  89. return fetch(ASSET_URL + path)
  90. }
  91. }
  92. /**
  93. * @param {Request} req
  94. * @param {string} pathname
  95. */
  96. function httpHandler(req, pathname) {
  97. const reqHdrRaw = req.headers
  98. // preflight
  99. if (req.method === 'OPTIONS' &&
  100. reqHdrRaw.has('access-control-request-headers')
  101. ) {
  102. return new Response(null, PREFLIGHT_INIT)
  103. }
  104. const reqHdrNew = new Headers(reqHdrRaw)
  105. let urlStr = pathname
  106. if (urlStr.startsWith('github')) {
  107. urlStr = 'https://' + urlStr
  108. }
  109. const urlObj = newUrl(urlStr)
  110. /** @type {RequestInit} */
  111. const reqInit = {
  112. method: req.method,
  113. headers: reqHdrNew,
  114. redirect: 'manual',
  115. body: req.body
  116. }
  117. return proxy(urlObj, reqInit)
  118. }
  119. /**
  120. *
  121. * @param {URL} urlObj
  122. * @param {RequestInit} reqInit
  123. */
  124. async function proxy(urlObj, reqInit) {
  125. const res = await fetch(urlObj.href, reqInit)
  126. const resHdrOld = res.headers
  127. const resHdrNew = new Headers(resHdrOld)
  128. const status = res.status
  129. if (resHdrNew.has('location')) {
  130. let _location = resHdrNew.get('location')
  131. if (checkUrl(_location))
  132. resHdrNew.set('location', PREFIX + _location)
  133. else {
  134. reqInit.redirect = 'follow'
  135. return proxy(newUrl(_location), reqInit)
  136. }
  137. }
  138. resHdrNew.set('access-control-expose-headers', '*')
  139. resHdrNew.set('access-control-allow-origin', '*')
  140. resHdrNew.delete('content-security-policy')
  141. resHdrNew.delete('content-security-policy-report-only')
  142. resHdrNew.delete('clear-site-data')
  143. return new Response(res.body, {
  144. status,
  145. headers: resHdrNew,
  146. })
  147. }