index.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. // 分支文件使用jsDelivr镜像的开关,0为关闭,默认关闭
  9. const Config = {
  10. jsdelivr: 0
  11. }
  12. const whiteList = [] // 白名单,路径里面有包含字符的才会通过,e.g. ['/username/']
  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 || 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(exp4) === 0) {
  84. const newUrl = path.replace(/(?<=com\/.+?\/.+?)\/(.+?\/)/, '@$1').replace(/^(?:https?:\/\/)?raw\.(?:githubusercontent|github)\.com/, 'https://cdn.jsdelivr.net/gh')
  85. return Response.redirect(newUrl, 302)
  86. } else {
  87. return fetch(ASSET_URL + path)
  88. }
  89. }
  90. /**
  91. * @param {Request} req
  92. * @param {string} pathname
  93. */
  94. function httpHandler(req, pathname) {
  95. const reqHdrRaw = req.headers
  96. // preflight
  97. if (req.method === 'OPTIONS' &&
  98. reqHdrRaw.has('access-control-request-headers')
  99. ) {
  100. return new Response(null, PREFLIGHT_INIT)
  101. }
  102. const reqHdrNew = new Headers(reqHdrRaw)
  103. let urlStr = pathname
  104. let flag = !Boolean(whiteList.length)
  105. for (let i of whiteList) {
  106. if (urlStr.includes(i)) {
  107. flag = true
  108. break
  109. }
  110. }
  111. if (!flag) {
  112. return new Response("blocked", {status: 403})
  113. }
  114. if (urlStr.startsWith('github')) {
  115. urlStr = 'https://' + urlStr
  116. }
  117. const urlObj = newUrl(urlStr)
  118. /** @type {RequestInit} */
  119. const reqInit = {
  120. method: req.method,
  121. headers: reqHdrNew,
  122. redirect: 'manual',
  123. body: req.body
  124. }
  125. return proxy(urlObj, reqInit)
  126. }
  127. /**
  128. *
  129. * @param {URL} urlObj
  130. * @param {RequestInit} reqInit
  131. */
  132. async function proxy(urlObj, reqInit) {
  133. const res = await fetch(urlObj.href, reqInit)
  134. const resHdrOld = res.headers
  135. const resHdrNew = new Headers(resHdrOld)
  136. const status = res.status
  137. if (resHdrNew.has('location')) {
  138. let _location = resHdrNew.get('location')
  139. if (checkUrl(_location))
  140. resHdrNew.set('location', PREFIX + _location)
  141. else {
  142. reqInit.redirect = 'follow'
  143. return proxy(newUrl(_location), reqInit)
  144. }
  145. }
  146. resHdrNew.set('access-control-expose-headers', '*')
  147. resHdrNew.set('access-control-allow-origin', '*')
  148. resHdrNew.delete('content-security-policy')
  149. resHdrNew.delete('content-security-policy-report-only')
  150. resHdrNew.delete('clear-site-data')
  151. return new Response(res.body, {
  152. status,
  153. headers: resHdrNew,
  154. })
  155. }