83 lines
2.5 KiB
TypeScript
83 lines
2.5 KiB
TypeScript
"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;
|
|
}
|