Skip to content

Commit

Permalink
chore: Update manifest version to 0.1.1 and add url storage permissio…
Browse files Browse the repository at this point in the history
…n and Handling back-end cors cross-domain issues
  • Loading branch information
LightL99 committed Sep 2, 2024
1 parent b9984d7 commit 1ae32e2
Show file tree
Hide file tree
Showing 5 changed files with 153 additions and 54 deletions.
8 changes: 0 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,6 @@ Cookie-share是一个 Chrome 扩展,允许用户在不同设备或浏览器之

6. 记下 Worker 的 URL,格式类似:`https://your-worker-name.your-subdomain.workers.dev` (被墙请自定义域名)

7. 修改`cookie-share.zip`中的`popup.js``host`变量为自己部署的后端域名。

## 环境变量定义

在 Cloudflare Worker 中使用的环境变量:

- `ADMIN_PASSWORD`: 字符串类型。用于验证管理员请求的密码。
- `COOKIE_STORE`: KV 命名空间。用于存储和检索 cookie 数据。

## 安全注意事项

Expand Down
123 changes: 97 additions & 26 deletions _worker.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,37 @@
addEventListener("fetch", (event) => {
event.respondWith(
handleRequest(event.request).catch(
(error) =>
new Response(JSON.stringify({ success: false, error: error.message }), {
handleRequest(event.request).catch((error) => {
const response = new Response(
JSON.stringify({ success: false, error: error.message }),
{
status: 500,
headers: { "Content-Type": "application/json" },
})
)
}
);
setCorsHeaders(response);
return response;
})
);
});

function setCorsHeaders(response) {
response.headers.set("Access-Control-Allow-Origin", "*");
response.headers.set(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS"
);
response.headers.set(
"Access-Control-Allow-Headers",
"Content-Type, X-Admin-Password"
);
}

function verifyAdminPassword(request) {
const adminPassword = request.headers.get("X-Admin-Password");
if (adminPassword !== ADMIN_PASSWORD) {
return new Response("Unauthorized", { status: 401 });
const response = new Response("Unauthorized", { status: 401 });
setCorsHeaders(response);
return response;
}
return null; // Continue if password is correct
}
Expand All @@ -26,6 +44,11 @@ async function handleRequest(request) {
const url = new URL(request.url);
const path = url.pathname;

// Handle CORS preflight requests
if (request.method === "OPTIONS") {
return handleCorsPreflightRequest();
}

// Admin password verification for new endpoints
if (path.startsWith("/admin/")) {
const authResponse = verifyAdminPassword(request);
Expand All @@ -51,15 +74,25 @@ async function handleRequest(request) {
} else if (request.method === "GET" && path === "/admin/list") {
return listAllData();
} else {
return new Response("Not Found", { status: 404 });
const response = new Response("Not Found", { status: 404 });
setCorsHeaders(response);
return response;
}
}

function handleCorsPreflightRequest() {
const response = new Response(null, {
status: 204,
});
setCorsHeaders(response);
return response;
}

async function handleSendCookies(request) {
const { id, url, cookies } = await request.json();

if (!isValidId(id)) {
return new Response(
const response = new Response(
JSON.stringify({
success: false,
message: "Invalid ID. Only letters and numbers are allowed.",
Expand All @@ -69,12 +102,14 @@ async function handleSendCookies(request) {
headers: { "Content-Type": "application/json" },
}
);
setCorsHeaders(response);
return response;
}

// Check if the ID already exists
const existing = await COOKIE_STORE.get(id);
if (existing !== null) {
return new Response(
const response = new Response(
JSON.stringify({
success: false,
message: "Cookie ID already exists. Please use a unique ID.",
Expand All @@ -84,12 +119,14 @@ async function handleSendCookies(request) {
headers: { "Content-Type": "application/json" },
}
);
setCorsHeaders(response);
return response;
}

// Store the new cookies
await COOKIE_STORE.put(id, JSON.stringify({ id, url, cookies }));

return new Response(
const response = new Response(
JSON.stringify({
success: true,
message: "Cookies received and stored successfully",
Expand All @@ -99,13 +136,15 @@ async function handleSendCookies(request) {
headers: { "Content-Type": "application/json" },
}
);
setCorsHeaders(response);
return response;
}

async function handleReceiveCookies(request, path) {
const id = path.split("/").pop();

if (!isValidId(id)) {
return new Response(
const response = new Response(
JSON.stringify({
success: false,
message: "Invalid ID. Only letters and numbers are allowed.",
Expand All @@ -115,11 +154,13 @@ async function handleReceiveCookies(request, path) {
headers: { "Content-Type": "application/json" },
}
);
setCorsHeaders(response);
return response;
}

const storedData = await COOKIE_STORE.get(id);
if (storedData === null) {
return new Response(
const response = new Response(
JSON.stringify({
success: false,
message: "No cookies found for the given ID: " + id,
Expand All @@ -129,11 +170,13 @@ async function handleReceiveCookies(request, path) {
headers: { "Content-Type": "application/json" },
}
);
setCorsHeaders(response);
return response;
}

const { cookies } = JSON.parse(storedData);

return new Response(
const response = new Response(
JSON.stringify({
success: true,
id,
Expand All @@ -144,6 +187,8 @@ async function handleReceiveCookies(request, path) {
headers: { "Content-Type": "application/json" },
}
);
setCorsHeaders(response);
return response;
}

async function handleListCookies() {
Expand All @@ -156,7 +201,7 @@ async function handleListCookies() {
cookies.push({ id, url });
}

return new Response(
const response = new Response(
JSON.stringify({
success: true,
cookies: cookies,
Expand All @@ -166,13 +211,15 @@ async function handleListCookies() {
headers: { "Content-Type": "application/json" },
}
);
setCorsHeaders(response);
return response;
}

async function createData(request) {
const { key, value } = await request.json();

if (!isValidId(key)) {
return new Response(
const response = new Response(
JSON.stringify({
success: false,
message: "Invalid key. Only letters and numbers are allowed.",
Expand All @@ -182,24 +229,28 @@ async function createData(request) {
headers: { "Content-Type": "application/json" },
}
);
setCorsHeaders(response);
return response;
}

await COOKIE_STORE.put(key, JSON.stringify(value));
return new Response(
const response = new Response(
JSON.stringify({ success: true, message: "Data created successfully" }),
{
status: 201,
headers: { "Content-Type": "application/json" },
}
);
setCorsHeaders(response);
return response;
}

async function readData(request) {
const url = new URL(request.url);
const key = url.searchParams.get("key");

if (!isValidId(key)) {
return new Response(
const response = new Response(
JSON.stringify({
success: false,
message: "Invalid key. Only letters and numbers are allowed.",
Expand All @@ -209,32 +260,38 @@ async function readData(request) {
headers: { "Content-Type": "application/json" },
}
);
setCorsHeaders(response);
return response;
}

const value = await COOKIE_STORE.get(key);
if (value === null) {
return new Response(
const response = new Response(
JSON.stringify({ success: false, message: "Data not found" }),
{
status: 404,
headers: { "Content-Type": "application/json" },
}
);
setCorsHeaders(response);
return response;
}
return new Response(
const response = new Response(
JSON.stringify({ success: true, data: JSON.parse(value) }),
{
status: 200,
headers: { "Content-Type": "application/json" },
}
);
setCorsHeaders(response);
return response;
}

async function updateData(request) {
const { key, value } = await request.json();

if (!isValidId(key)) {
return new Response(
const response = new Response(
JSON.stringify({
success: false,
message: "Invalid key. Only letters and numbers are allowed.",
Expand All @@ -244,34 +301,40 @@ async function updateData(request) {
headers: { "Content-Type": "application/json" },
}
);
setCorsHeaders(response);
return response;
}

const existingValue = await COOKIE_STORE.get(key);
if (existingValue === null) {
return new Response(
const response = new Response(
JSON.stringify({ success: false, message: "Data not found" }),
{
status: 404,
headers: { "Content-Type": "application/json" },
}
);
setCorsHeaders(response);
return response;
}
await COOKIE_STORE.put(key, JSON.stringify(value));
return new Response(
const response = new Response(
JSON.stringify({ success: true, message: "Data updated successfully" }),
{
status: 200,
headers: { "Content-Type": "application/json" },
}
);
setCorsHeaders(response);
return response;
}

async function deleteData(request) {
const url = new URL(request.url);
const key = url.searchParams.get("key");

if (!isValidId(key)) {
return new Response(
const response = new Response(
JSON.stringify({
success: false,
message: "Invalid key. Only letters and numbers are allowed.",
Expand All @@ -281,28 +344,34 @@ async function deleteData(request) {
headers: { "Content-Type": "application/json" },
}
);
setCorsHeaders(response);
return response;
}

await COOKIE_STORE.delete(key);
return new Response(
const response = new Response(
JSON.stringify({ success: true, message: "Data deleted successfully" }),
{
status: 200,
headers: { "Content-Type": "application/json" },
}
);
setCorsHeaders(response);
return response;
}

async function deleteAllData() {
const keys = await COOKIE_STORE.list();
await Promise.all(keys.keys.map((key) => COOKIE_STORE.delete(key.name)));
return new Response(
const response = new Response(
JSON.stringify({ success: true, message: "All data deleted successfully" }),
{
status: 200,
headers: { "Content-Type": "application/json" },
}
);
setCorsHeaders(response);
return response;
}

async function listAllData() {
Expand All @@ -314,7 +383,7 @@ async function listAllData() {
data.push({ key: key.name, value: JSON.parse(value) });
}

return new Response(
const response = new Response(
JSON.stringify({
success: true,
data: data,
Expand All @@ -324,4 +393,6 @@ async function listAllData() {
headers: { "Content-Type": "application/json" },
}
);
setCorsHeaders(response);
return response;
}
6 changes: 3 additions & 3 deletions manifest.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"manifest_version": 3,
"manifest_version": 2,
"name": "Cookie Share",
"version": "0.1",
"version": "0.1.1",
"description": "Sends and receives cookies with your friends",
"permissions": ["cookies", "activeTab", "tabs", "<all_urls>"],
"permissions": ["cookies", "activeTab", "tabs", "storage", "<all_urls>"],
"browser_action": {
"default_popup": "popup.html"
},
Expand Down
Loading

0 comments on commit 1ae32e2

Please sign in to comment.