-
Notifications
You must be signed in to change notification settings - Fork 1
/
common.ts
84 lines (78 loc) · 2.53 KB
/
common.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
import { ReactMutation } from 'convex/react';
import { api } from './convex/_generated/api';
var uuid = require('uuid');
var CryptoJS = require('crypto-js');
export type CreateResponse = {
name: string;
creatorKey: string;
password: string;
};
const encryptFile = async (blob: Blob, password: string): Promise<Blob> => {
// i don't know how to invert blob.text() when the file isn't ascii, so use blob.arrayBuffer().
const arrayBuffer = await blob.arrayBuffer();
const uint8Array = new Uint8Array(arrayBuffer);
const encodedString = Buffer.from(uint8Array).toString('base64');
const encrypted = CryptoJS.AES.encrypt(encodedString, password);
const encryptedEncoded = encrypted.toString(); // base64
return new Blob([encryptedEncoded]);
};
export async function createWhisper(
secret: string,
selectedFile: File | null,
expiration: string,
password: string,
createWhisperMutation: ReactMutation<typeof api.createWhisper.default>,
makeUploadURL: ReactMutation<typeof api.fileUploadURL.default>
): Promise<CreateResponse> {
const name = uuid.v4();
const creatorKey = uuid.v4();
if (password.length === 0) {
password = uuid.v4();
}
const storageIds = [];
if (selectedFile) {
const [uploadURL, encryptedFile] = await Promise.all([
makeUploadURL(),
encryptFile(selectedFile, password),
]);
const result = await fetch(uploadURL, {
method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' },
body: encryptedFile,
});
const resultJson = await result.json();
if (!result.ok) {
console.error(resultJson);
}
const storageId = resultJson['storageId'];
storageIds.push(storageId);
const name = Buffer.from(selectedFile.name, 'ascii').toString('hex');
secret += `\nAttachment: '${name}' ${storageId}`;
}
const encryptedSecret = CryptoJS.AES.encrypt(secret, password).toString();
const passwordHash = hashPassword(password);
await createWhisperMutation({
whisperName: name,
encryptedSecret,
storageIds,
passwordHash,
creatorKey,
expiration,
});
return {
password,
name,
creatorKey,
};
}
export function hashPassword(password: string): string {
return CryptoJS.SHA256(password).toString();
}
export function makeURL(name: string, password: string | null): string {
const currentURL = window.location;
const baseURL = currentURL.protocol + '//' + currentURL.host;
if (password === null) {
return `${baseURL}/access?name=${name}`;
}
return `${baseURL}/access?name=${name}&password=${password}`;
}