-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmain.ts
More file actions
362 lines (316 loc) · 11.8 KB
/
main.ts
File metadata and controls
362 lines (316 loc) · 11.8 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
import "./style.css";
import { createActor } from "../../src/declarations/basic_ibe";
import { Principal } from "@dfinity/principal";
import {
TransportSecretKey,
DerivedPublicKey,
EncryptedVetKey,
VetKey,
IbeCiphertext,
IbeIdentity,
IbeSeed,
} from "@dfinity/vetkeys";
import {
Inbox,
_SERVICE,
} from "../../src/declarations/basic_ibe/basic_ibe.did";
import { AuthClient } from "@dfinity/auth-client";
import type { ActorSubclass } from "@dfinity/agent";
let ibePrivateKey: VetKey | undefined = undefined;
let ibePublicKey: DerivedPublicKey | undefined = undefined;
let myPrincipal: Principal | undefined = undefined;
let authClient: AuthClient | undefined;
let basicIbeCanister: ActorSubclass<_SERVICE> | undefined;
function getBasicIbeCanister(): ActorSubclass<_SERVICE> {
if (basicIbeCanister) return basicIbeCanister;
if (!process.env.CANISTER_ID_BASIC_IBE) {
throw Error("CANISTER_ID_BASIC_IBE is not set");
}
if (!authClient) {
throw Error("Auth client is not initialized");
}
const host =
process.env.DFX_NETWORK === "ic"
? `https://${process.env.CANISTER_ID_BASIC_IBE}.ic0.app`
: "http://localhost:8000";
basicIbeCanister = createActor(process.env.CANISTER_ID_BASIC_IBE, {
agentOptions: {
identity: authClient.getIdentity(),
host,
},
});
return basicIbeCanister;
}
async function getIbePublicKey(): Promise<DerivedPublicKey> {
if (ibePublicKey) return ibePublicKey;
ibePublicKey = DerivedPublicKey.deserialize(
new Uint8Array(await getBasicIbeCanister().get_ibe_public_key()),
);
return ibePublicKey;
}
async function encrypt(
cleartext: Uint8Array,
receiver: Principal,
): Promise<Uint8Array> {
const publicKey = await getIbePublicKey();
const ciphertext = IbeCiphertext.encrypt(
publicKey,
IbeIdentity.fromPrincipal(receiver),
cleartext,
IbeSeed.random(),
);
return ciphertext.serialize();
}
async function getMyIbePrivateKey(): Promise<VetKey> {
if (ibePrivateKey) return ibePrivateKey;
if (!myPrincipal) {
throw Error("My principal is not set");
} else {
const transportSecretKey = TransportSecretKey.random();
const encryptedKey = Uint8Array.from(
await getBasicIbeCanister().get_my_encrypted_ibe_key(
transportSecretKey.publicKeyBytes(),
),
);
ibePrivateKey = EncryptedVetKey.deserialize(
encryptedKey,
).decryptAndVerify(
transportSecretKey,
await getIbePublicKey(),
new Uint8Array(myPrincipal.toUint8Array()),
);
return ibePrivateKey;
}
}
async function decryptMessage(encryptedMessage: Uint8Array): Promise<string> {
const ibeKey = await getMyIbePrivateKey();
const ciphertext = IbeCiphertext.deserialize(encryptedMessage);
const plaintext = ciphertext.decrypt(ibeKey);
return new TextDecoder().decode(plaintext);
}
async function sendMessage() {
const message = prompt("Enter your message:");
if (!message) throw Error("Message is required");
const receiver = prompt("Enter receiver principal:");
if (!receiver) throw Error("Receiver is required");
const receiverPrincipal = Principal.fromText(receiver);
try {
const encryptedMessage = await encrypt(
new TextEncoder().encode(message),
receiverPrincipal,
);
const result = await getBasicIbeCanister().send_message({
encrypted_message: encryptedMessage,
receiver: receiverPrincipal,
});
if ("Err" in result) {
alert("Error sending message: " + result.Err);
} else {
alert("Message sent successfully!");
}
} catch (error) {
alert("Error sending message: " + (error as Error).message);
}
}
async function showMessages() {
const inbox = await getBasicIbeCanister().get_my_messages();
await displayMessages(inbox);
}
function createMessageElement(
sender: Principal,
timestamp: bigint,
plaintextString: string,
index: number,
): HTMLDivElement {
const messageElement = document.createElement("div");
messageElement.className = "message";
const messageContent = document.createElement("div");
messageContent.className = "message-content";
const messageText = document.createElement("div");
messageText.className = "message-text";
messageText.textContent = plaintextString;
const messageInfo = document.createElement("div");
messageInfo.className = "message-info";
const senderInfo = document.createElement("div");
senderInfo.className = "sender";
senderInfo.textContent = `From: ${sender.toString()}`;
const timestampInfo = document.createElement("div");
timestampInfo.className = "timestamp";
const date = new Date(Number(timestamp) / 1_000_000);
timestampInfo.textContent = `Sent: ${date.toLocaleString()}`;
const messageActions = document.createElement("div");
messageActions.className = "message-actions";
const deleteButton = document.createElement("button");
deleteButton.className = "delete-button";
deleteButton.textContent = "Delete";
deleteButton.dataset.index = index.toString();
messageActions.appendChild(deleteButton);
messageInfo.appendChild(senderInfo);
messageInfo.appendChild(timestampInfo);
messageContent.appendChild(messageText);
messageContent.appendChild(messageInfo);
messageContent.appendChild(messageActions);
messageElement.appendChild(messageContent);
return messageElement;
}
async function displayMessages(inbox: Inbox) {
const messagesDiv = document.getElementById("messages")!;
messagesDiv.innerHTML = "";
if (inbox.messages.length === 0) {
const noMessagesDiv = document.createElement("div");
noMessagesDiv.className = "no-messages";
noMessagesDiv.textContent = "No messages in the inbox.";
messagesDiv.appendChild(noMessagesDiv);
return;
}
// Iterate through messages in reverse order
for (let i = inbox.messages.length - 1; i >= 0; i--) {
const message = inbox.messages[i];
const plaintextString = await decryptMessage(
new Uint8Array(message.encrypted_message),
);
const messageElement = createMessageElement(
message.sender,
message.timestamp,
plaintextString,
i,
);
messagesDiv.appendChild(messageElement);
}
// Add event listeners to delete buttons
const deleteButtons = document.querySelectorAll(".delete-button");
deleteButtons.forEach((button) => {
button.addEventListener("click", (e) => {
const target = e.target as HTMLButtonElement;
const index = parseInt(target.dataset.index!);
// Disable all delete buttons
deleteButtons.forEach(
(btn) => ((btn as HTMLButtonElement).disabled = true),
);
void (async () => {
try {
const result =
await getBasicIbeCanister().remove_my_message_by_index(
BigInt(index),
);
if ("Err" in result) {
alert("Error deleting message: " + result.Err);
} else {
// Remove the message element from the DOM
const messageElement = target.closest(".message");
if (messageElement) {
messageElement.remove();
// If this was the last message, show the "no messages" message
const messagesDiv =
document.getElementById("messages")!;
if (messagesDiv.children.length === 0) {
const noMessagesDiv =
document.createElement("div");
noMessagesDiv.className = "no-messages";
noMessagesDiv.textContent =
"No messages in the inbox.";
messagesDiv.appendChild(noMessagesDiv);
}
}
}
} catch (error) {
alert(
"Error deleting message: " + (error as Error).message,
);
} finally {
// Re-enable all delete buttons
deleteButtons.forEach(
(btn) => ((btn as HTMLButtonElement).disabled = false),
);
}
})();
});
});
}
export function login(client: AuthClient) {
void client.login({
maxTimeToLive: BigInt(1800) * BigInt(1_000_000_000),
identityProvider:
process.env.DFX_NETWORK === "ic"
? "https://identity.ic0.app/#authorize"
: `http://rdmx6-jaaaa-aaaaa-aaadq-cai.localhost:8000/#authorize`,
onSuccess: () => {
myPrincipal = client.getIdentity().getPrincipal();
updateUI(true);
},
onError: (error) => {
alert("Authentication failed: " + error);
},
});
}
export function logout() {
void authClient?.logout();
const messagesDiv = document.getElementById("messages")!;
messagesDiv.innerHTML = "";
ibePrivateKey = undefined;
myPrincipal = undefined;
basicIbeCanister = undefined;
updateUI(false);
}
async function initAuth() {
authClient = await AuthClient.create();
const isAuthenticated = await authClient.isAuthenticated();
if (isAuthenticated) {
myPrincipal = authClient.getIdentity().getPrincipal();
updateUI(true);
} else {
updateUI(false);
}
}
function updateUI(isAuthenticated: boolean) {
const loginButton = document.getElementById("loginButton")!;
const messageButtons = document.getElementById("messageButtons")!;
const principalDisplay = document.getElementById("principalDisplay")!;
const logoutButton = document.getElementById("logoutButton")!;
loginButton.style.display = isAuthenticated ? "none" : "block";
messageButtons.style.display = isAuthenticated ? "flex" : "none";
principalDisplay.style.display = isAuthenticated ? "block" : "none";
logoutButton.style.display = isAuthenticated ? "block" : "none";
if (isAuthenticated && myPrincipal) {
principalDisplay.textContent = `Principal: ${myPrincipal.toString()}`;
}
}
function handleLogin() {
if (!authClient) {
alert("Auth client not initialized");
return;
}
login(authClient);
}
document.querySelector<HTMLDivElement>("#app")!.innerHTML = `
<div>
<h1>Basic IBE Message System with VetKeys</h1>
<div class="principal-container">
<div id="principalDisplay" class="principal-display"></div>
<button id="logoutButton" style="display: none;">Logout</button>
</div>
<div class="login-container">
<button id="loginButton">Login</button>
</div>
<div id="messageButtons" class="buttons" style="display: none;">
<button id="sendMessage">Send Message</button>
<button id="showMessages">Show My Messages</button>
</div>
<div id="messages"></div>
</div>
`;
// Add event listeners
document.getElementById("loginButton")!.addEventListener("click", handleLogin);
document.getElementById("logoutButton")!.addEventListener("click", logout);
document.getElementById("sendMessage")!.addEventListener("click", () => {
void (async () => {
await sendMessage();
})();
});
document.getElementById("showMessages")!.addEventListener("click", () => {
void (async () => {
await showMessages();
})();
});
// Initialize auth
void initAuth();