route.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { NextRequest, NextResponse } from "next/server";
  2. import { getServerSideConfig } from "../../config/server";
  3. const serverConfig = getServerSideConfig();
  4. async function handle(
  5. req: NextRequest,
  6. { params }: { params: { path: string[] } },
  7. ) {
  8. const controller = new AbortController();
  9. const authValue = req.headers.get("Authorization") ?? "";
  10. const authHeaderName = serverConfig.isAzure ? "api-key" : "Authorization";
  11. const fetchUrl = serverConfig.OAUTH_USERINFO;
  12. console.log("[Proxy] ", fetchUrl);
  13. // this fix [Org ID] undefined in server side if not using custom point
  14. const timeoutId = setTimeout(
  15. () => {
  16. controller.abort();
  17. },
  18. 10 * 60 * 1000,
  19. );
  20. if (!fetchUrl) {
  21. const err = {
  22. code: 404,
  23. msg: "未配置",
  24. };
  25. return new Response(JSON.stringify(err), {
  26. status: 404,
  27. statusText: "not found",
  28. });
  29. }
  30. const fetchOptions: RequestInit = {
  31. headers: {
  32. "Content-Type": "application/json",
  33. "Cache-Control": "no-store",
  34. [authHeaderName]: authValue,
  35. },
  36. method: req.method,
  37. body: req.body,
  38. // to fix #2485: https://stackoverflow.com/questions/55920957/cloudflare-worker-typeerror-one-time-use-body
  39. redirect: "manual",
  40. // @ts-ignore
  41. duplex: "half",
  42. signal: controller.signal,
  43. };
  44. try {
  45. const res = await fetch(fetchUrl, fetchOptions);
  46. const newHeaders = new Headers(res.headers);
  47. newHeaders.delete("www-authenticate");
  48. newHeaders.set("X-Accel-Buffering", "no");
  49. return new Response(res.body, {
  50. status: res.status,
  51. statusText: res.statusText,
  52. headers: newHeaders,
  53. });
  54. } finally {
  55. clearTimeout(timeoutId);
  56. }
  57. }
  58. export const GET = handle;
  59. export const POST = handle;
  60. export const runtime = "edge";