initial commit with imported utils from old github project
This commit is contained in:
commit
66bb463e23
39 files changed
+1944
No files matched your search
@@ -0,0 +1,5 @@
|
||||
const changeBasePath = (asset: string) => {
|
||||
return process.env.BASE_PATH + asset;
|
||||
};
|
||||
|
||||
export default changeBasePath;
|
||||
@@ -0,0 +1,6 @@
|
||||
import { clsx, type ClassValue } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
|
||||
export async function signup(email: string, password: string) {
|
||||
const supabase = await createClient();
|
||||
|
||||
// type-casting here for convenience
|
||||
// in practice, you should validate your inputs
|
||||
const login_data = {
|
||||
email: email,
|
||||
password: password,
|
||||
};
|
||||
const { data, error } = await supabase.auth.signUp(login_data);
|
||||
|
||||
if (error) {
|
||||
return { data, error };
|
||||
} else {
|
||||
if (
|
||||
data.user?.identities?.length == undefined ||
|
||||
data.user.identities.length < 1
|
||||
) {
|
||||
const error = { message: "Email already in use" };
|
||||
return { data, error };
|
||||
} else {
|
||||
//TODO add username field and insert it
|
||||
const name = "anon";
|
||||
//TODO add avatar url field and insert it
|
||||
const { error } = await supabase
|
||||
.from("users")
|
||||
.insert({ id: data.user.id, name: name, email: data.user.email });
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
revalidatePath("/", "layout");
|
||||
redirect("/");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
import { validateIdentity } from "@/utils/security/validate_identity";
|
||||
import { storeAccessKey_Cookie } from "@/utils/security/access_storage";
|
||||
import { deriveKey } from "@/utils/security/encryption";
|
||||
|
||||
export async function login(email: string, password: string) {
|
||||
const supabase = await createClient();
|
||||
|
||||
const login_data = {
|
||||
email: email,
|
||||
password: password,
|
||||
};
|
||||
const { data, error } = await supabase.auth.signInWithPassword(login_data);
|
||||
|
||||
if (error) {
|
||||
return { data, error };
|
||||
} else {
|
||||
await validateIdentity(password);
|
||||
const { data, error } = await supabase
|
||||
.from("users")
|
||||
.select("salt")
|
||||
.eq("id", (await supabase.auth.getUser()).data.user?.id)
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
const salt = Uint8Array.from(atob(data.salt), (c) => c.charCodeAt(0));
|
||||
const key = await deriveKey(password, salt);
|
||||
storeAccessKey_Cookie(key);
|
||||
revalidatePath("/profile", "layout");
|
||||
redirect("/profile");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
"use server";
|
||||
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
|
||||
export interface Friend {
|
||||
friend_id: string;
|
||||
friend_alias: string;
|
||||
}
|
||||
|
||||
export async function acceptFriend(sender_id: string) {
|
||||
const supabase = createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await (await supabase).auth.getUser();
|
||||
if (!user) return;
|
||||
const receiver_id = user.id;
|
||||
|
||||
const add_user = async (sender_id: string, receiver_id: string) => {
|
||||
const { data: friend } = await (await supabase)
|
||||
.from("users")
|
||||
.select("name, public_key_dec")
|
||||
.eq("id", receiver_id)
|
||||
.single();
|
||||
if (!friend) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const { error } = await (await supabase).from("friends").insert({
|
||||
user_id: sender_id,
|
||||
friend_id: receiver_id,
|
||||
friend_alias: friend.name,
|
||||
friend_public_key: friend.public_key_dec,
|
||||
});
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const remove_request = async (sender_id: string, receiver_id: string) => {
|
||||
const { data, error } = await (await supabase)
|
||||
.from("friend_requests")
|
||||
.delete()
|
||||
.eq("sender_id", sender_id)
|
||||
.eq("receiver_id", receiver_id);
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
if (data) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
add_user(sender_id, receiver_id);
|
||||
add_user(receiver_id, sender_id);
|
||||
remove_request(sender_id, receiver_id);
|
||||
}
|
||||
|
||||
export async function listRequests() {
|
||||
const supabase = createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await (await supabase).auth.getUser();
|
||||
if (!user) return;
|
||||
|
||||
const { data, error } = await (await supabase)
|
||||
.from("friend_requests")
|
||||
.select("id, sender_id")
|
||||
.eq("receiver_id", user.id);
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
if (data) {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
export async function sendFriendRequest(receiver_id: string) {
|
||||
const supabase = createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await (await supabase).auth.getUser();
|
||||
if (!user) return;
|
||||
const isReverse = await reverseRequest(receiver_id);
|
||||
|
||||
if (isReverse) {
|
||||
acceptFriend(receiver_id);
|
||||
return true;
|
||||
}
|
||||
|
||||
const { error } = await (await supabase)
|
||||
.from("friend_requests")
|
||||
.insert([{ sender_id: user.id, receiver_id: receiver_id }]);
|
||||
if (error) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function listFriends() {
|
||||
const supabase = createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await (await supabase).auth.getUser();
|
||||
if (!user) return;
|
||||
const { data, error } = await (await supabase)
|
||||
.from("friends")
|
||||
.select("friend_id, friend_alias")
|
||||
.eq("user_id", user.id);
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
if (data) {
|
||||
return data;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function reverseRequest(friend_id: string) {
|
||||
const supabase = createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await (await supabase).auth.getUser();
|
||||
if (!user) return;
|
||||
const { data, error } = await (await supabase)
|
||||
.from("friend_requests")
|
||||
.select("sender_id, receiver_id")
|
||||
.eq("sender_id", friend_id)
|
||||
.eq("receiver_id", user.id);
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
if (data) {
|
||||
if (data.length == 1) {
|
||||
return true;
|
||||
}
|
||||
if (data.length < 1) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
"use server";
|
||||
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
import { redirect } from "next/navigation";
|
||||
import { removeAccessKey_Cookie } from "@/utils/security/access_storage";
|
||||
|
||||
export async function signOut() {
|
||||
const supabase = createClient();
|
||||
removeAccessKey_Cookie();
|
||||
(await supabase).auth.signOut();
|
||||
redirect("/login");
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
"use server";
|
||||
import { privateEncrypt } from "crypto";
|
||||
import { decryptPrivateKey } from "@/utils/security/decrypt_private_key";
|
||||
export async function encryptMessage(message: string) {
|
||||
const privateKey = await decryptPrivateKey();
|
||||
if (privateKey == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const message_buffer = Buffer.from(message, "utf-8");
|
||||
const message_encrypted = privateEncrypt(privateKey, message_buffer);
|
||||
|
||||
return message_encrypted;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
"use server";
|
||||
import { privateEncrypt } from "crypto";
|
||||
import { decryptPrivateKey } from "@/utils/security/decrypt_private_key";
|
||||
export async function encryptMessage(message: string) {
|
||||
const privateKey = await decryptPrivateKey();
|
||||
if (privateKey == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const message_buffer = Buffer.from(message, "utf-8");
|
||||
const message_encrypted = privateEncrypt(privateKey, message_buffer);
|
||||
|
||||
return message_encrypted;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
"use server";
|
||||
import { error } from "console";
|
||||
import { subtle } from "crypto";
|
||||
import { cookies } from "next/headers";
|
||||
|
||||
export async function storeAccessKey_Cookie(key: CryptoKey) {
|
||||
if (key.extractable) {
|
||||
try {
|
||||
const exported = await subtle.exportKey("raw", key);
|
||||
const exportedKeyBuffer = new Uint8Array(exported);
|
||||
const key_base64 = Buffer.from(exportedKeyBuffer).toString("base64");
|
||||
(await cookies()).set("user_identity", key_base64);
|
||||
} catch (err) {
|
||||
throw error.apply(err);
|
||||
}
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
export async function removeAccessKey_Cookie() {
|
||||
(await cookies()).set("user_identity", "");
|
||||
}
|
||||
|
||||
export async function retreiveAccessKey_Cookie() {
|
||||
const cookieStore = await cookies();
|
||||
try {
|
||||
const key_base64 = cookieStore.get("user_identity");
|
||||
if (key_base64 == null || key_base64.value.length < 1) {
|
||||
return null;
|
||||
}
|
||||
const key_raw = Uint8Array.from(atob(key_base64.value), (c) =>
|
||||
c.charCodeAt(0),
|
||||
);
|
||||
const key = subtle.importKey("raw", key_raw, "AES-GCM", true, [
|
||||
"encrypt",
|
||||
"decrypt",
|
||||
]);
|
||||
return key;
|
||||
} catch (err) {
|
||||
return error.apply(err);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
"use server";
|
||||
import { subtle } from "crypto";
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
import { deriveKey } from "./encryption";
|
||||
import { retreiveAccessKey_Cookie } from "./access_storage";
|
||||
|
||||
export async function setAccessKey(plain_pw: string) {
|
||||
const supabase = await createClient();
|
||||
const { data: key_data, error } = await supabase
|
||||
.from("users")
|
||||
.select("private_key_enc, salt, iv, auth_tag")
|
||||
.eq("id", (await supabase.auth.getUser()).data.user?.id)
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
return null;
|
||||
}
|
||||
const salt_Base64 = key_data?.salt || "";
|
||||
const encryptedPrivateKey_Base64 = key_data?.private_key_enc || "";
|
||||
const authTag_base64 = key_data?.auth_tag || "";
|
||||
|
||||
const encodedPrivateKey = Uint8Array.from(
|
||||
atob(encryptedPrivateKey_Base64),
|
||||
(c) => c.charCodeAt(0),
|
||||
);
|
||||
const authTag = Uint8Array.from(atob(authTag_base64), (c) => c.charCodeAt(0));
|
||||
const salt = Uint8Array.from(atob(salt_Base64), (c) => c.charCodeAt(0));
|
||||
|
||||
const dataWithAuthTag = new Uint8Array(
|
||||
encodedPrivateKey.length + authTag.length,
|
||||
);
|
||||
dataWithAuthTag.set(encodedPrivateKey, 0);
|
||||
dataWithAuthTag.set(authTag, encodedPrivateKey.length);
|
||||
|
||||
const key = await deriveKey(plain_pw, salt);
|
||||
|
||||
if (key == null) {
|
||||
return null;
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
export async function decryptPrivateKey() {
|
||||
const supabase = await createClient();
|
||||
const { data: key_data, error } = await supabase
|
||||
.from("users")
|
||||
.select("private_key_enc, salt, iv, auth_tag")
|
||||
.eq("id", (await supabase.auth.getUser()).data.user?.id)
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
return null;
|
||||
}
|
||||
const iv_Base64 = key_data?.iv || "";
|
||||
const encryptedPrivateKey_Base64 = key_data?.private_key_enc || "";
|
||||
const authTag_base64 = key_data?.auth_tag || "";
|
||||
|
||||
const encodedPrivateKey = Uint8Array.from(
|
||||
atob(encryptedPrivateKey_Base64),
|
||||
(c) => c.charCodeAt(0),
|
||||
);
|
||||
const authTag = Uint8Array.from(atob(authTag_base64), (c) => c.charCodeAt(0));
|
||||
const iv = Uint8Array.from(atob(iv_Base64), (c) => c.charCodeAt(0));
|
||||
|
||||
const dataWithAuthTag = new Uint8Array(
|
||||
encodedPrivateKey.length + authTag.length,
|
||||
);
|
||||
dataWithAuthTag.set(encodedPrivateKey, 0);
|
||||
dataWithAuthTag.set(authTag, encodedPrivateKey.length);
|
||||
|
||||
const key = await retreiveAccessKey_Cookie();
|
||||
if (key == null) {
|
||||
return null;
|
||||
}
|
||||
const decryptedContent = await subtle.decrypt(
|
||||
{ name: "AES-GCM", iv, tagLength: 128 },
|
||||
key,
|
||||
dataWithAuthTag,
|
||||
);
|
||||
const decodedPrivateKey = new TextDecoder().decode(decryptedContent);
|
||||
return decodedPrivateKey;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
"use server";
|
||||
import { generateKeyPairSync, getRandomValues, subtle } from "crypto";
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
import { deriveKey } from "./encryption";
|
||||
|
||||
export async function generateKeyPair(plain_pw: string, user_id: string) {
|
||||
const supabase = await createClient();
|
||||
const { publicKey, privateKey } = generateKeyPairSync("rsa", {
|
||||
modulusLength: 4096,
|
||||
publicKeyEncoding: {
|
||||
type: "spki",
|
||||
format: "pem",
|
||||
},
|
||||
privateKeyEncoding: {
|
||||
type: "pkcs8",
|
||||
format: "pem",
|
||||
cipher: "aes-256-cbc",
|
||||
passphrase: "",
|
||||
},
|
||||
});
|
||||
|
||||
const salt = getRandomValues(new Uint8Array(16));
|
||||
const iv = getRandomValues(new Uint8Array(32));
|
||||
const key = await deriveKey(plain_pw, salt);
|
||||
const encodedPrivateKey = new TextEncoder().encode(privateKey);
|
||||
const encryptedContent = await subtle.encrypt(
|
||||
{
|
||||
name: "AES-GCM",
|
||||
iv,
|
||||
tagLength: 128, // 128-bit tag length
|
||||
},
|
||||
key,
|
||||
encodedPrivateKey,
|
||||
);
|
||||
|
||||
const encryptedPrivateKey = encryptedContent.slice(
|
||||
0,
|
||||
encryptedContent.byteLength - 16,
|
||||
);
|
||||
const encryptedPrivateKey_Base64 =
|
||||
Buffer.from(encryptedPrivateKey).toString("base64");
|
||||
|
||||
const authTag = encryptedContent.slice(encryptedContent.byteLength - 16);
|
||||
const authTag_Base64 = Buffer.from(authTag).toString("base64");
|
||||
const salt_Base64 = Buffer.from(salt).toString("base64");
|
||||
const iv_Base64 = Buffer.from(iv).toString("base64");
|
||||
|
||||
const { error } = await supabase
|
||||
.from("users")
|
||||
.update({
|
||||
private_key_enc: encryptedPrivateKey_Base64,
|
||||
public_key_dec: publicKey,
|
||||
salt: salt_Base64,
|
||||
iv: iv_Base64,
|
||||
auth_tag: authTag_Base64,
|
||||
})
|
||||
.eq("id", user_id);
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
return key;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
"use server";
|
||||
import { subtle } from "crypto";
|
||||
|
||||
export async function deriveKey(passphrase: string, salt: Uint8Array) {
|
||||
const encodedPassword = new TextEncoder().encode(passphrase);
|
||||
const baseKey = await subtle.importKey(
|
||||
"raw",
|
||||
encodedPassword,
|
||||
{ name: "PBKDF2" },
|
||||
false,
|
||||
["deriveKey"],
|
||||
);
|
||||
|
||||
const derivedKey = await subtle.deriveKey(
|
||||
{
|
||||
name: "PBKDF2",
|
||||
salt,
|
||||
iterations: 600000,
|
||||
hash: "SHA-256",
|
||||
},
|
||||
baseKey,
|
||||
{ name: "AES-GCM", length: 256 },
|
||||
true,
|
||||
["encrypt", "decrypt"],
|
||||
);
|
||||
|
||||
return derivedKey;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
"use server";
|
||||
|
||||
import { generateKeyPair } from "@/utils/security/encrypt_private_key";
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
|
||||
export async function validateIdentity(plain_pw: string) {
|
||||
const supabase = createClient();
|
||||
const user_id = (await (await supabase).auth.getUser()).data.user?.id;
|
||||
if (user_id == null) {
|
||||
return null;
|
||||
}
|
||||
const { data, error } = await (await supabase)
|
||||
.from("users")
|
||||
.select("has_identity")
|
||||
.eq("id", user_id)
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!data.has_identity) {
|
||||
generateKeyPair(plain_pw, user_id);
|
||||
const { error } = await (await supabase)
|
||||
.from("users")
|
||||
.update({ has_identity: true })
|
||||
.eq("id", user_id)
|
||||
.single();
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { createBrowserClient } from "@supabase/ssr";
|
||||
|
||||
export function createClient() {
|
||||
return createBrowserClient(
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { createServerClient } from "@supabase/ssr";
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
|
||||
export async function updateSession(request: NextRequest) {
|
||||
let supabaseResponse = NextResponse.next({
|
||||
request,
|
||||
});
|
||||
|
||||
const supabase = createServerClient(
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
|
||||
{
|
||||
cookies: {
|
||||
getAll() {
|
||||
return request.cookies.getAll();
|
||||
},
|
||||
setAll(cookiesToSet) {
|
||||
cookiesToSet.forEach(({ name, value }) =>
|
||||
request.cookies.set(name, value),
|
||||
);
|
||||
supabaseResponse = NextResponse.next({
|
||||
request,
|
||||
});
|
||||
cookiesToSet.forEach(({ name, value, options }) =>
|
||||
supabaseResponse.cookies.set(name, value, options),
|
||||
);
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
// IMPORTANT: Avoid writing any logic between createServerClient and
|
||||
// supabase.auth.getUser(). A simple mistake could make it very hard to debug
|
||||
// issues with users being randomly logged out.
|
||||
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
|
||||
if (
|
||||
!user &&
|
||||
!request.nextUrl.pathname.startsWith("/login") &&
|
||||
!request.nextUrl.pathname.startsWith("/register") &&
|
||||
!request.nextUrl.pathname.startsWith("/auth")
|
||||
) {
|
||||
// no user, potentially respond by redirecting the user to the login page
|
||||
const url = request.nextUrl.clone();
|
||||
url.pathname = "/login";
|
||||
return NextResponse.redirect(url);
|
||||
}
|
||||
|
||||
// IMPORTANT: You *must* return the supabaseResponse object as it is. If you're
|
||||
// creating a new response object with NextResponse.next() make sure to:
|
||||
// 1. Pass the request in it, like so:
|
||||
// const myNewResponse = NextResponse.next({ request })
|
||||
// 2. Copy over the cookies, like so:
|
||||
// myNewResponse.cookies.setAll(supabaseResponse.cookies.getAll())
|
||||
// 3. Change the myNewResponse object to fit your needs, but avoid changing
|
||||
// the cookies!
|
||||
// 4. Finally:
|
||||
// return myNewResponse
|
||||
// If this is not done, you may be causing the browser and server to go out
|
||||
// of sync and terminate the user's session prematurely!
|
||||
|
||||
return supabaseResponse;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
"use server";
|
||||
|
||||
import { createClient } from "./server";
|
||||
|
||||
export async function realtimeToken() {
|
||||
const supabase = createClient();
|
||||
|
||||
const token = (await (await supabase).auth.getSession()).data.session
|
||||
?.access_token;
|
||||
if (!token) return null;
|
||||
return token;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { createServerClient } from "@supabase/ssr";
|
||||
import { cookies } from "next/headers";
|
||||
|
||||
export async function createClient() {
|
||||
const cookieStore = await cookies();
|
||||
|
||||
return createServerClient(
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
|
||||
{
|
||||
cookies: {
|
||||
getAll() {
|
||||
return cookieStore.getAll();
|
||||
},
|
||||
setAll(cookiesToSet) {
|
||||
try {
|
||||
cookiesToSet.forEach(({ name, value, options }) =>
|
||||
cookieStore.set(name, value, options),
|
||||
);
|
||||
} catch {
|
||||
// The `setAll` method was called from a Server Component.
|
||||
// This can be ignored if you have middleware refreshing
|
||||
// user sessions.
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user