1
0

index.js 4.8 KB

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