Skip to content
This repository was archived by the owner on Sep 15, 2024. It is now read-only.

Commit

Permalink
[Cherry Pick] Head Repo (#306)
Browse files Browse the repository at this point in the history
* chore: specify yarn 1 in package.json

* fix: adjust upstash api

* fix: add webdav request filter

* fix: remove corsFetch

* fix: change matching pattern

* chore: update cors default path

* fix: fix upstash sync issue

* fix: fix webdav sync issue

* feat: bump version

* Fix Github Gist

- [+] refactor(gist.ts): replace corsFetch with native fetch function
- [+] refactor(gist.ts): rename error variable to e in catch block

* Fix Gosync

- [+] chore(gosync.ts): remove unused import 'corsFetch'
- [+] feat(gosync.ts): add explanatory note for createGoSyncClient function

---------

Co-authored-by: SukkaW <[email protected]>
Co-authored-by: fred-bf <[email protected]>
  • Loading branch information
3 people authored Mar 13, 2024
1 parent d46c41a commit 5e83b0c
Show file tree
Hide file tree
Showing 11 changed files with 243 additions and 178 deletions.
70 changes: 0 additions & 70 deletions app/api/cors/[...path]/route.ts

This file was deleted.

73 changes: 73 additions & 0 deletions app/api/upstash/[action]/[...key]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { NextRequest, NextResponse } from "next/server";

async function handle(
req: NextRequest,
{ params }: { params: { action: string; key: string[] } },
) {
const requestUrl = new URL(req.url);
const endpoint = requestUrl.searchParams.get("endpoint");

if (req.method === "OPTIONS") {
return NextResponse.json({ body: "OK" }, { status: 200 });
}
const [...key] = params.key;
// only allow to request to *.upstash.io
if (!endpoint || !new URL(endpoint).hostname.endsWith(".upstash.io")) {
return NextResponse.json(
{
error: true,
msg: "you are not allowed to request " + params.key.join("/"),
},
{
status: 403,
},
);
}

// only allow upstash get and set method
if (params.action !== "get" && params.action !== "set") {
console.log("[Upstash Route] forbidden action ", params.action);
return NextResponse.json(
{
error: true,
msg: "you are not allowed to request " + params.action,
},
{
status: 403,
},
);
}

const targetUrl = `${endpoint}/${params.action}/${params.key.join("/")}`;

const method = req.method;
const shouldNotHaveBody = ["get", "head"].includes(
method?.toLowerCase() ?? "",
);

const fetchOptions: RequestInit = {
headers: {
authorization: req.headers.get("authorization") ?? "",
},
body: shouldNotHaveBody ? null : req.body,
method,
// @ts-ignore
duplex: "half",
};

console.log("[Upstash Proxy]", targetUrl, fetchOptions);
const fetchResult = await fetch(targetUrl, fetchOptions);

console.log("[Any Proxy]", targetUrl, {
status: fetchResult.status,
statusText: fetchResult.statusText,
});

return fetchResult;
}

export const POST = handle;
export const GET = handle;
export const OPTIONS = handle;

export const runtime = "edge";
112 changes: 112 additions & 0 deletions app/api/webdav/[...path]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import { NextRequest, NextResponse } from "next/server";
import { STORAGE_KEY } from "../../../constant";
async function handle(
req: NextRequest,
{ params }: { params: { path: string[] } },
) {
if (req.method === "OPTIONS") {
return NextResponse.json({ body: "OK" }, { status: 200 });
}
const folder = STORAGE_KEY;
const fileName = `${folder}/backup.json`;

const requestUrl = new URL(req.url);
let endpoint = requestUrl.searchParams.get("endpoint");
if (!endpoint?.endsWith("/")) {
endpoint += "/";
}
const endpointPath = params.path.join("/");

// only allow MKCOL, GET, PUT
if (req.method !== "MKCOL" && req.method !== "GET" && req.method !== "PUT") {
return NextResponse.json(
{
error: true,
msg: "you are not allowed to request " + params.path.join("/"),
},
{
status: 403,
},
);
}

// for MKCOL request, only allow request ${folder}
if (
req.method == "MKCOL" &&
!new URL(endpointPath).pathname.endsWith(folder)
) {
return NextResponse.json(
{
error: true,
msg: "you are not allowed to request " + params.path.join("/"),
},
{
status: 403,
},
);
}

// for GET request, only allow request ending with fileName
if (
req.method == "GET" &&
!new URL(endpointPath).pathname.endsWith(fileName)
) {
return NextResponse.json(
{
error: true,
msg: "you are not allowed to request " + params.path.join("/"),
},
{
status: 403,
},
);
}

// for PUT request, only allow request ending with fileName
if (
req.method == "PUT" &&
!new URL(endpointPath).pathname.endsWith(fileName)
) {
return NextResponse.json(
{
error: true,
msg: "you are not allowed to request " + params.path.join("/"),
},
{
status: 403,
},
);
}

const targetUrl = `${endpoint + endpointPath}`;

const method = req.method;
const shouldNotHaveBody = ["get", "head"].includes(
method?.toLowerCase() ?? "",
);

const fetchOptions: RequestInit = {
headers: {
authorization: req.headers.get("authorization") ?? "",
},
body: shouldNotHaveBody ? null : req.body,
method,
// @ts-ignore
duplex: "half",
};

const fetchResult = await fetch(targetUrl, fetchOptions);

console.log("[Any Proxy]", targetUrl, {
status: fetchResult.status,
statusText: fetchResult.statusText,
});

return fetchResult;
}

export const POST = handle;
export const GET = handle;
export const OPTIONS = handle;

export const runtime = "edge";
2 changes: 1 addition & 1 deletion app/constant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export enum Path {
}

export enum ApiPath {
Cors = "/api/cors",
Cors = "",
OpenAI = "/api/openai",
}

Expand Down
13 changes: 6 additions & 7 deletions app/utils/cloud/gist.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { STORAGE_KEY, REPO_URL } from "@/app/constant";
import { chunks } from "../format";
import { SyncStore } from "@/app/store/sync";
import { corsFetch } from "../cors";

export type GistConfig = SyncStore["githubGist"] & { gistId: string };
export type GistClient = ReturnType<typeof createGistClient>;
Expand Down Expand Up @@ -37,7 +36,7 @@ export function createGistClient(store: SyncStore) {
};
}

return corsFetch("https://api.github.com/gists", {
return await fetch("https://api.github.com/gists", {
method: "POST",
headers: this.headers(),
body: JSON.stringify({
Expand Down Expand Up @@ -68,7 +67,7 @@ export function createGistClient(store: SyncStore) {
},

async check(): Promise<string> {
const res = await corsFetch(this.path(gistId), {
const res = await fetch(this.path(gistId), {
method: "GET",
headers: this.headers(),
});
Expand All @@ -85,7 +84,7 @@ export function createGistClient(store: SyncStore) {
},

async get() {
const res = await corsFetch(this.path(gistId), {
const res = await fetch(this.path(gistId), {
method: "GET",
headers: this.headers(),
});
Expand All @@ -110,7 +109,7 @@ export function createGistClient(store: SyncStore) {
const newContent = JSON.stringify(data, null, 2);
const description = `[Sync] [200 OK] [GithubGist] Last Sync: ${currentDate} Site: ${REPO_URL}`;

return corsFetch(this.path(gistId), {
return fetch(this.path(gistId), {
method: existingContent ? "PATCH" : "POST",
headers: this.headers(),
body: JSON.stringify({
Expand All @@ -131,11 +130,11 @@ export function createGistClient(store: SyncStore) {
);
return newContent;
})
.catch((error) => {
.catch((e) => {
console.error(
"[Gist] Set A Data oF File Name",
`${fileBackup}`,
error,
Error,
);
return "";
});
Expand Down
2 changes: 1 addition & 1 deletion app/utils/cloud/gosync.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { STORAGE_KEY } from "@/app/constant";
import { SyncStore } from "@/app/store/sync";
import { corsFetch } from "../cors";
import { chunks } from "../format";

export type GoSync = SyncStore["gosync"];
export type GoSyncClient = ReturnType<typeof createGoSyncClient>;

export function createGoSyncClient(store: SyncStore) {
/** TODO */
// Note: This my own sync writen in go, not yet ready
}
Loading

0 comments on commit 5e83b0c

Please sign in to comment.