-
Notifications
You must be signed in to change notification settings - Fork 0
/
import-chat-by-keys.ts
102 lines (92 loc) · 2.71 KB
/
import-chat-by-keys.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { EncryptionTools } from "../utils";
import { NostrQueries, useNostrPublishMutation } from "../nostr";
import { useContext } from "react";
import { Kind } from "nostr-tools";
import { UploadKeys } from "../types";
import { ChatContext } from "../chat-context-provider";
import { useSaveKeys } from "../api";
interface Payload {
ecencyChatKey: string;
pin: string;
}
export function useImportChatByKeys(
onSuccess?: () => void,
meta?: Record<string, unknown>,
) {
const queryClient = useQueryClient();
const { activeUsername, storage } = useContext(ChatContext);
const { mutateAsync: uploadChatKeys } = useSaveKeys();
const { mutateAsync: uploadKeys } = useMutation({
mutationKey: ["chats/upload-public-key"],
mutationFn: async (keys: Parameters<UploadKeys>[1]) =>
uploadChatKeys({
pubkey: keys.pub,
iv: keys.iv.toString("base64"),
key: keys.priv,
meta: meta ?? {},
}),
});
const { mutateAsync: updateProfile } = useNostrPublishMutation(
["chats/update-nostr-profile"],
Kind.Metadata,
() => {},
);
return useMutation({
mutationKey: ["chats/import-chat-by-key"],
mutationFn: async ({ ecencyChatKey, pin }: Payload) => {
if (!activeUsername) {
return;
}
let publicKey;
let privateKey;
let iv;
try {
const parsedObject = JSON.parse(
Buffer.from(ecencyChatKey, "base64").toString(),
);
publicKey = parsedObject.pub;
privateKey = parsedObject.priv;
iv = parsedObject.iv;
} catch (e) {
throw new Error(
"[Chat][Nostr] – no private, public keys or initial vector value in importing",
);
}
if (!privateKey || !publicKey || !iv) {
throw new Error(
"[Chat][Nostr] – no private, public keys or initial vector value in importing",
);
}
const initialVector = Buffer.from(iv, "base64");
const encryptedKey = EncryptionTools.encrypt(
privateKey,
pin,
initialVector,
);
await uploadKeys({
pub: publicKey,
priv: encryptedKey,
iv: initialVector,
});
storage?.setItem("ecency_nostr_pr_" + activeUsername, pin);
queryClient.setQueryData(
[NostrQueries.PUBLIC_KEY, activeUsername],
publicKey,
);
queryClient.setQueryData(
[NostrQueries.PRIVATE_KEY, activeUsername],
privateKey,
);
await updateProfile({
tags: [["p", publicKey]],
eventMetadata: {
name: activeUsername!,
about: "",
picture: "",
},
});
},
onSuccess,
});
}