-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelpers.ts
More file actions
196 lines (179 loc) · 5.53 KB
/
helpers.ts
File metadata and controls
196 lines (179 loc) · 5.53 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
import { Bytes, DocumentSnapshot } from 'firebase/firestore';
import { useToastStore } from './stores/toastStore';
import { encryptedFieldTypeGuard, firebaseErrorTypeGuard } from './typeguards';
import { EncryptedField, List } from './types';
import { defaultListName } from './constants';
import JSZip from 'jszip';
type DecryptFunc<T> = (val: EncryptedField, key: CryptoKey) => Promise<T>;
const decryptEncryptedField = (
{ iv, data }: EncryptedField,
key: CryptoKey,
) => {
return crypto.subtle.decrypt(
{ name: 'AES-GCM', iv: iv.toUint8Array() },
key,
data.toUint8Array(),
);
};
export const cleanSearch = (text: string) => {
// The purpose of this function is to "forgive" the user for any punctuation while searching
// Removes: hyphen, period, single quote, double quote, space, and curly apostrophe
const forgivingRegex = /[-.'" \u2019]/g;
return text.replace(forgivingRegex, '').toLowerCase();
};
export const censorEmail = (email: string) => {
const [user, domain] = email.split('@');
const first = user.slice(0, 2);
const stars = '*'.repeat(user.length - 3);
const last = user[user.length - 1];
return `${first}${stars}${last}@${domain}`;
};
export async function decryptParams<T extends Record<string, unknown>>(
key: CryptoKey,
decryptFunc: DecryptFunc<unknown>,
obj: Record<string, unknown>,
...params: Extract<keyof T, string>[]
) {
const newObj = { ...obj };
for (const param of params) {
const val = obj[param];
if (encryptedFieldTypeGuard(val))
newObj[param] = await decryptFunc(val, key);
}
return newObj;
}
export const addId = (d: DocumentSnapshot): Record<string, unknown> => ({
...d.data(),
id: d.id,
});
export const findDefaultListId = (lists: List[]) => {
return lists.find((list) => list.name === defaultListName)?.id;
};
export const fullTrim = (s: string) => {
return s
.trim()
.split('\n')
.map((p) => p.trimEnd())
.join('\n');
};
export function generateUserKey() {
return crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, [
'encrypt',
'decrypt',
]);
}
export async function derivePasswordKey(
password: string,
salt: Uint8Array,
): Promise<CryptoKey> {
const encoder = new TextEncoder();
const baseKey = await crypto.subtle.importKey(
'raw',
encoder.encode(password),
'PBKDF2',
false,
['deriveKey'],
);
return crypto.subtle.deriveKey(
{ name: 'PBKDF2', salt, iterations: 100000, hash: 'SHA-256' },
baseKey,
{ name: 'AES-GCM', length: 256 },
true,
['encrypt', 'decrypt'],
);
}
export async function encryptWithKey(
plainTextOrCryptoKey: string | CryptoKey,
key: CryptoKey,
): Promise<EncryptedField> {
const iv = crypto.getRandomValues(new Uint8Array(12));
let toEncrypt: Uint8Array;
if (typeof plainTextOrCryptoKey === 'string') {
const encoder = new TextEncoder();
toEncrypt = encoder.encode(plainTextOrCryptoKey);
} else {
const raw = await crypto.subtle.exportKey('raw', plainTextOrCryptoKey);
toEncrypt = new Uint8Array(raw);
}
const encrypted = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
key,
toEncrypt,
);
const encryptedData = new Uint8Array(encrypted);
return {
iv: Bytes.fromUint8Array(iv),
data: Bytes.fromUint8Array(encryptedData),
};
}
export const decryptString: DecryptFunc<string> = async (
encryptedText,
key,
) => {
const decrypted = await decryptEncryptedField(encryptedText, key);
return new TextDecoder().decode(decrypted);
};
export const decryptCryptoKey: DecryptFunc<CryptoKey> = async (
encryptedKey,
key,
) => {
const decrypted = await decryptEncryptedField(encryptedKey, key);
return crypto.subtle.importKey('raw', decrypted, { name: 'AES-GCM' }, true, [
'encrypt',
'decrypt',
]);
};
export function generateSalt() {
return crypto.getRandomValues(new Uint8Array(16));
}
export const getError = (err: unknown) => {
console.error(err);
if (firebaseErrorTypeGuard(err)) {
const { code, message } = err;
const errorCodeMap: Record<string, string> = {
'auth/invalid-credential': 'Invalid credentials',
'auth/invalid-email': 'Invalid email address',
'auth/user-not-found': 'User not found',
'auth/wrong-password': 'Wrong password',
'permission-denied': 'Permission denied',
};
return errorCodeMap[code] ?? message;
}
return null;
};
export const handleError = (err: unknown) => {
if (firebaseErrorTypeGuard(err)) {
const { code, message } = err;
console.warn(`Firebase error\nCode: ${code}\nMessage: ${message}`);
const errorCodeMap: Record<string, string> = {
'auth/invalid-credential': 'Invalid credentials',
'auth/invalid-email': 'Invalid email address',
'auth/user-not-found': 'User not found',
'auth/wrong-password': 'Wrong password',
'permission-denied': 'Permission denied',
};
useToastStore
.getState()
.add('error', 'Error', errorCodeMap[code] ?? message);
} else console.error(err);
};
export async function zipAndDownloadJSON(
files: { filename: string; data: unknown[] }[],
zipFilename: string,
) {
// Must be used in a client component
const zip = new JSZip();
files.forEach(({ filename, data }) => {
const json = JSON.stringify(data, null, 2);
zip.file(filename, json);
});
const content = await zip.generateAsync({ type: 'blob' });
const url = URL.createObjectURL(content);
const a = document.createElement('a');
a.href = url;
a.download = zipFilename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}