feat: store logged account

This commit is contained in:
2025-05-24 12:05:57 +02:00
parent 06e0e90677
commit eb42b61b2c
8 changed files with 177 additions and 36 deletions

View File

@ -0,0 +1,64 @@
import { useDbContext } from "@/context/db/db";
import { deriveDeviceKey, getDeviceId } from "@/util/deviceId";
import { useCallback } from "react";
export interface LocalAccount {
accountId: string;
label: string;
email: string;
access: { data: number[]; iv: number[] };
refresh: { data: number[]; iv: number[] };
updatedAt: string;
}
export interface CreateAccountRequest {
accountId: string;
label: string;
email: string;
access: string;
refresh: string;
}
export const useAccountRepo = () => {
const { db } = useDbContext();
const encryptToken = useCallback(async (token: string) => {
const encoder = new TextEncoder();
const iv = crypto.getRandomValues(new Uint8Array(12));
const deviceId = await getDeviceId();
const deviceKey = await deriveDeviceKey(deviceId);
const cipherText = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv },
deviceKey,
encoder.encode(token)
);
return {
data: Array.from(new Uint8Array(cipherText)),
iv: Array.from(iv),
};
}, []);
const save = useCallback(
async (req: CreateAccountRequest) => {
console.log({ db });
const access = await encryptToken(req.access);
const refresh = await encryptToken(req.refresh);
await db?.put?.("accounts", {
accountId: req.accountId,
label: req.label,
email: req.email,
access,
refresh,
updatedAt: new Date().toISOString(),
});
},
[db, encryptToken]
);
return { save };
};