feat: encode access-code in header for better safety

This commit is contained in:
Yuwen Sun 2023-04-08 11:52:56 -04:00
parent 40b8b225f9
commit 71d666fe84
2 changed files with 4 additions and 6 deletions

View File

@ -1,6 +1,7 @@
import type { ChatRequest, ChatReponse } from "./api/openai/typing";
import { Message, ModelConfig, useAccessStore, useChatStore } from "./store";
import { showToast } from "./components/ui-lib";
import md5 from "spark-md5";
const TIME_OUT_MS = 30000;
@ -37,8 +38,8 @@ function getHeaders() {
const accessStore = useAccessStore.getState();
let headers: Record<string, string> = {};
if (accessStore.enabledAccessControl()) {
headers["access-code"] = accessStore.accessCode;
if (accessStore.enabledAccessControl() && accessStore.accessCode.length) {
headers["access-code"] = md5.hash(accessStore.accessCode);
}
if (accessStore.token && accessStore.token.length > 0) {

View File

@ -1,6 +1,5 @@
import { NextRequest, NextResponse } from "next/server";
import { ACCESS_CODES } from "./app/api/access";
import md5 from "spark-md5";
export const config = {
matcher: ["/api/openai", "/api/chat-stream"],
@ -9,13 +8,11 @@ export const config = {
export function middleware(req: NextRequest) {
const accessCode = req.headers.get("access-code");
const token = req.headers.get("token");
const hashedCode = md5.hash(accessCode ?? "").trim();
console.log("[Auth] allowed hashed codes: ", [...ACCESS_CODES]);
console.log("[Auth] got access code:", accessCode);
console.log("[Auth] hashed access code:", hashedCode);
if (ACCESS_CODES.size > 0 && !ACCESS_CODES.has(hashedCode) && !token) {
if (ACCESS_CODES.size > 0 && (!accessCode || !ACCESS_CODES.has(accessCode)) && !token) {
return NextResponse.json(
{
error: true,