-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatic-secret.js
More file actions
313 lines (264 loc) · 8.26 KB
/
static-secret.js
File metadata and controls
313 lines (264 loc) · 8.26 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
/*
MIT License
Copyright (c) 2024 Ilia Pozdnyakov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
if (import.meta.url) {
const importUrl = new URL(import.meta.url);
const importHashQuery = new URLSearchParams(importUrl.hash.slice(1));
if (importHashQuery.has("decrypt")) {
const hashQuery = new URLSearchParams(window.location.hash.slice(1));
const passwordParameter = importHashQuery.get("pwin") ?? "p";
const password = hashQuery.get(passwordParameter);
hashQuery.delete(passwordParameter);
const clearedUrl = new URL(window.location);
clearedUrl.hash = hashQuery.toString();
history.replaceState(null, "", clearedUrl);
window.addEventListener("load", () => {
decryptElements({ root: document, password });
});
}
}
/**
* @param {string} opts.password
* @param {HTMLElement} [opts.root]
* @returns {Promise<void>}
*/
export function decryptElements({ password, root = document }) {
return new Promise((resolve) => {
const elements = root.querySelectorAll("[data-static-secret]");
let elementsProcessed = 0;
const onElementProcessed = () => {
elementsProcessed += 1;
if (elementsProcessed === elements.length) {
root.dispatchEvent(new Event("decrypted"));
resolve();
}
};
for (const element of elements) {
if (
element instanceof HTMLImageElement ||
element instanceof HTMLMediaElement ||
element instanceof HTMLIFrameElement ||
(element instanceof HTMLScriptElement && element.src)
) {
fetch(element.src)
.then((response) => decrypt(response, password, element.dataset.staticSecret))
.then((data) => {
element.src = URL.createObjectURL(new Blob([data]));
element.dataset.staticSecretDecrypted = "";
})
.catch((error) => console.error(error))
.finally(onElementProcessed);
continue;
}
if (element instanceof HTMLAnchorElement && element.download !== undefined) {
fetch(element.href)
.then((response) => decrypt(response, password, element.dataset.staticSecret))
.then((data) => {
element.href = URL.createObjectURL(new Blob([data]));
element.dataset.staticSecretDecrypted = "";
})
.catch((error) => console.error(error))
.finally(onElementProcessed);
continue;
}
if (element.innerHTML) {
decrypt(fromBase64(element.innerHTML.trim()), password, element.dataset.staticSecret)
.then((data) => {
element.innerHTML = new TextDecoder().decode(data);
element.dataset.staticSecretDecrypted = "";
elements.push(...element.querySelectorAll("[data-static-secret]"));
})
.catch((error) => console.error(error))
.finally(onElementProcessed);
continue;
}
}
});
}
/**
* @typedef {object} EncryptionParams
* @property {number} iterations
* @property {Uint8Array} salt
* @property {Uint8Array} iv
*/
/**
* @typedef {object} EncryptedData
* @property {Uint8Array} bytes
* @property {string} params
*/
/**
* @param {Uint8Array | Blob | Response} bytes
* @param {string} password
* @param {EncryptionParams | string} params
* @returns {Promise<Uint8Array>}
*/
export async function decrypt(bytes, password, params) {
if (typeof params === "string") params = decodeParams(params);
let { salt, iv, iterations } = params;
if (bytes instanceof Response || bytes instanceof Blob) {
bytes = new Uint8Array(await bytes.arrayBuffer());
}
const key = await deriveKey(password, { salt, iterations });
/** @type {ArrayBuffer} */ let result;
try {
result = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, bytes);
} catch (error) {
throw new DecryptionError(error);
}
return new Uint8Array(result);
}
/**
* @param {Uint8Array | Blob} data
* @param {string} password
* @param {number | undefined} [opts.iterations]
* @returns {EncryptedData}
*/
export async function encrypt(data, password, { iterations = 100000 }) {
if (data instanceof Blob) {
data = new Uint8Array(await data.arrayBuffer());
}
const salt = crypto.getRandomValues(new Uint8Array(16));
const iv = crypto.getRandomValues(new Uint8Array(12));
const key = await deriveKey(password, { salt, iterations });
/** @type {ArrayBuffer} */ let result;
try {
result = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, data);
} catch (error) {
throw new EncryptionError(error);
}
return {
bytes: new Uint8Array(result),
params: encodeParams({ iterations, salt, iv }),
};
}
/**
*
* @param {string} password
* @param {Uint8Array} salt
* @param {number} iterations
* @returns {Promise<CryptoKey>}
*/
async function deriveKey(password, { salt, iterations }) {
try {
const keyMaterial = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(password),
"PBKDF2",
false,
["deriveKey"]
);
return await crypto.subtle.deriveKey(
// derivation algorithm
{
name: "PBKDF2",
salt,
hash: "SHA-256",
iterations,
},
// derivation material
keyMaterial,
// encryption algoritm
{
name: "AES-GCM",
length: 256,
},
// exportable
false,
// usages
["encrypt", "decrypt"]
);
} catch (error) {
throw new KeyGenerationError(error);
}
}
/**
* @param {EncryptionParams} params
* @returns {string}
*/
function encodeParams(params) {
const data = new Uint8Array(8 + params.salt.length + params.iv.length);
const view = new DataView(data.buffer);
let offset = 0;
view.setUint32(offset, params.iterations, true);
offset += 4;
view.setUint16(offset, params.salt.length, true);
offset += 2;
data.set(params.salt, offset);
offset += params.salt.length;
view.setUint16(offset, params.iv.length, true);
offset += 2;
data.set(params.iv, offset);
offset += params.iv.length;
return toBase64(data);
}
/**
* @param {string} str
* @returns {EncryptionParams}
*/
function decodeParams(data) {
data = fromBase64(data);
const view = new DataView(data.buffer);
let offset = 0;
const iterations = view.getUint32(offset, true);
offset += 4;
const saltLength = view.getUint16(offset, true);
offset += 2;
const salt = data.slice(offset, offset + saltLength);
offset += saltLength;
const ivLength = view.getUint16(offset);
offset += 2;
const iv = data.slice(offset, offset + ivLength);
offset += ivLength;
return { iterations, salt, iv };
}
export class KeyGenerationError extends Error {
name = KeyGenerationError.name;
/** @param {Error} cause */
constructor(cause) {
super(cause.message);
}
}
export class EncryptionError extends Error {
name = EncryptionError.name;
/** @param {Error} cause */
constructor(cause) {
super(cause.message);
}
}
export class DecryptionError extends Error {
name = DecryptionError.name;
/** @param {Error} cause */
constructor(cause) {
super(cause.message);
}
}
/**
* @param {Uint8Array} bytes
* @returns {string}
*/
function toBase64(bytes) {
return btoa(String.fromCharCode(...bytes));
}
/**
* @param {string} str
* @returns {Uint8Array}
*/
function fromBase64(str) {
return Uint8Array.from(atob(str), (c) => c.charCodeAt(0));
}