spd-lib 1.2.2 → 1.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ai.py +66 -0
- package/dist/index.js +1 -415
- package/fatman.spd +0 -0
- package/high-zip/index.js +28 -0
- package/high-zip/node_modules/.package-lock.json +7 -0
- package/high-zip/package-lock.json +13 -0
- package/high-zip/package.json +13 -0
- package/high-zip/tool.js +78 -0
- package/img.py +44 -0
- package/obfuscate.js +131 -0
- package/package/dist/index.js +1 -0
- package/package/package-lock.json +1332 -0
- package/package/package.json +34 -0
- package/package.json +5 -2
- package/readme.md +137 -0
- package/readme.md.gz +0 -0
- package/readme.md.gz.lo +137 -0
- package/src/index.js +972 -0
- package/t.py +47 -0
- package/test.js +10 -0
package/ai.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
from panda3d.core import Point3
|
|
2
|
+
from panda3d.gui import OnscreenText
|
|
3
|
+
from panda3d import core, render
|
|
4
|
+
from panda3d.core import CollisionNode, CollisionSphere, CollisionHandlerQueue, CollisionRay, CollisionTraverser
|
|
5
|
+
from panda3d.core import NodePath
|
|
6
|
+
import random
|
|
7
|
+
|
|
8
|
+
from panda3d import ShowBase
|
|
9
|
+
|
|
10
|
+
class MazeGame(ShowBase):
|
|
11
|
+
def __init__(self):
|
|
12
|
+
super().__init__()
|
|
13
|
+
|
|
14
|
+
self.maze_size = 10
|
|
15
|
+
self.create_maze()
|
|
16
|
+
|
|
17
|
+
# Set up the agent (player)
|
|
18
|
+
self.agent = self.loader.loadModel("models/box")
|
|
19
|
+
self.agent.setScale(0.5, 0.5, 0.5)
|
|
20
|
+
self.agent.setPos(1, 1, 0.25)
|
|
21
|
+
self.agent.reparentTo(self.render)
|
|
22
|
+
|
|
23
|
+
# Set up goal
|
|
24
|
+
self.goal = self.loader.loadModel("models/box")
|
|
25
|
+
self.goal.setScale(0.5, 0.5, 0.5)
|
|
26
|
+
self.goal.setPos(8, 8, 0.25)
|
|
27
|
+
self.goal.reparentTo(self.render)
|
|
28
|
+
|
|
29
|
+
# Camera settings
|
|
30
|
+
self.camera.setPos(5, -15, 10)
|
|
31
|
+
self.camera.lookAt(self.agent)
|
|
32
|
+
|
|
33
|
+
# Collision setup
|
|
34
|
+
self.collision_traverser = CollisionTraverser()
|
|
35
|
+
self.collision_handler = CollisionHandlerQueue()
|
|
36
|
+
|
|
37
|
+
# Set up agent's collision detection
|
|
38
|
+
self.collision_ray = CollisionRay()
|
|
39
|
+
self.collision_ray.setOrigin(0, 0, 1)
|
|
40
|
+
self.collision_ray.setDirection(0, 1, 0)
|
|
41
|
+
self.agent_collider = CollisionNode("agent_ray")
|
|
42
|
+
self.agent_collider.addSolid(self.collision_ray)
|
|
43
|
+
self.agent_collider.setFromCollideMask(core.CollisionNode.getDefaultCollideMask())
|
|
44
|
+
self.agent_collider.setIntoCollideMask(core.CollisionNode.getDefaultCollideMask())
|
|
45
|
+
self.agent_collider_path = self.agent.attachNewNode(self.agent_collider)
|
|
46
|
+
|
|
47
|
+
# Add collision traverser
|
|
48
|
+
self.collision_traverser.addCollider(self.agent_collider_path, self.collision_handler)
|
|
49
|
+
|
|
50
|
+
def create_maze(self):
|
|
51
|
+
"""Creates a simple maze of walls."""
|
|
52
|
+
for i in range(self.maze_size):
|
|
53
|
+
for j in range(self.maze_size):
|
|
54
|
+
if random.random() < 0.2:
|
|
55
|
+
wall = self.loader.loadModel("models/box")
|
|
56
|
+
wall.setScale(1, 1, 2)
|
|
57
|
+
wall.setPos(i, j, 1)
|
|
58
|
+
wall.reparentTo(self.render)
|
|
59
|
+
|
|
60
|
+
def check_collisions(self):
|
|
61
|
+
"""Checks for collisions between the agent and walls."""
|
|
62
|
+
self.collision_traverser.traverse(self.render)
|
|
63
|
+
return len(self.collision_handler.getEntries()) > 0
|
|
64
|
+
|
|
65
|
+
app = MazeGame()
|
|
66
|
+
app.run()
|
package/dist/index.js
CHANGED
|
@@ -1,415 +1 @@
|
|
|
1
|
-
const fs = require('fs')
|
|
2
|
-
const zlib = require('zlib');
|
|
3
|
-
const sodium = require('libsodium-wrappers');
|
|
4
|
-
const crypto = require('crypto');
|
|
5
|
-
const argon2 = require('argon2');
|
|
6
|
-
|
|
7
|
-
class SPD {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
constructor() {
|
|
11
|
-
this.data = [];
|
|
12
|
-
this.keyPair; // Generate a key pair for encryption/decryption
|
|
13
|
-
this.userKey;
|
|
14
|
-
this.salt;
|
|
15
|
-
this.init();
|
|
16
|
-
}
|
|
17
|
-
async init() {
|
|
18
|
-
await sodium.ready;
|
|
19
|
-
this.keyPair = sodium.crypto_kx_keypair()
|
|
20
|
-
}
|
|
21
|
-
async setPassKey(passcode){
|
|
22
|
-
await sodium.ready;
|
|
23
|
-
this.init()
|
|
24
|
-
const { pqcKey, salt } = await new SPD().convertPasscodeToPQCKey(passcode);
|
|
25
|
-
const userKey = pqcKey.publicKey;
|
|
26
|
-
this.userKey = userKey;
|
|
27
|
-
this.salt = salt;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
async migrateFromFile(spdPath,passcode)
|
|
31
|
-
{
|
|
32
|
-
|
|
33
|
-
const spd = await SPD.loadFromFile(spdPath,passcode)
|
|
34
|
-
const extractData_OLD = async ()=>{
|
|
35
|
-
return new Promise(async(res,rej)=>{
|
|
36
|
-
try{
|
|
37
|
-
await sodium.ready;
|
|
38
|
-
let extractedFiles = {};
|
|
39
|
-
this.data.forEach(async dat => {
|
|
40
|
-
try{
|
|
41
|
-
const decryptedData = sodium.crypto_secretbox_open_easy(dat.data, dat.nonce, this.userKey);
|
|
42
|
-
const decompressedData = zlib.inflateSync(decryptedData,{level:9});
|
|
43
|
-
const dt = decompressedData.toString('utf8');
|
|
44
|
-
extractedFiles[dat.dataName] = await this.CSTI(dt, dat.dataType);
|
|
45
|
-
}catch{
|
|
46
|
-
rej()
|
|
47
|
-
}
|
|
48
|
-
});
|
|
49
|
-
res(extractedFiles);
|
|
50
|
-
}catch{
|
|
51
|
-
rej()
|
|
52
|
-
}
|
|
53
|
-
})
|
|
54
|
-
}
|
|
55
|
-
spd.extractData_OLD = extractData_OLD
|
|
56
|
-
const _data = await spd.extractData_OLD()
|
|
57
|
-
const n_spd = new SPD()
|
|
58
|
-
await n_spd.setPassKey(passcode)
|
|
59
|
-
for(let key in _data)
|
|
60
|
-
{
|
|
61
|
-
await n_spd.addData(key,_data[key])
|
|
62
|
-
}
|
|
63
|
-
n_spd.saveToFile(spdPath)
|
|
64
|
-
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
async migrateFromString(spdData,passcode)
|
|
68
|
-
{
|
|
69
|
-
const spd = await SPD.loadFromString(spdData,passcode)
|
|
70
|
-
const extractData_OLD = async ()=>{
|
|
71
|
-
return new Promise(async(res,rej)=>{
|
|
72
|
-
try{
|
|
73
|
-
await sodium.ready;
|
|
74
|
-
let extractedFiles = {};
|
|
75
|
-
this.data.forEach(async dat => {
|
|
76
|
-
try{
|
|
77
|
-
const decryptedData = sodium.crypto_secretbox_open_easy(dat.data, dat.nonce, this.userKey);
|
|
78
|
-
const decompressedData = zlib.inflateSync(decryptedData,{level:9});
|
|
79
|
-
const dt = decompressedData.toString('utf8');
|
|
80
|
-
extractedFiles[dat.dataName] = await this.CSTI(dt, dat.dataType);
|
|
81
|
-
}catch{
|
|
82
|
-
rej()
|
|
83
|
-
}
|
|
84
|
-
});
|
|
85
|
-
res(extractedFiles);
|
|
86
|
-
}catch{
|
|
87
|
-
rej()
|
|
88
|
-
}
|
|
89
|
-
})
|
|
90
|
-
}
|
|
91
|
-
spd.extractData_OLD = extractData_OLD
|
|
92
|
-
const _data = await spd.extractData_OLD()
|
|
93
|
-
const n_spd = new SPD()
|
|
94
|
-
await n_spd.setPassKey(passcode)
|
|
95
|
-
for(let key in _data)
|
|
96
|
-
{
|
|
97
|
-
await n_spd.addData(key,_data[key])
|
|
98
|
-
}
|
|
99
|
-
return n_spd.saveData()
|
|
100
|
-
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
async addData(name, data) {
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
const dmap = await this.CITS(data)
|
|
107
|
-
await sodium.ready;
|
|
108
|
-
const dat = Buffer.from(dmap[0]);
|
|
109
|
-
const compressedData = zlib.deflateSync(dat,{
|
|
110
|
-
level:9
|
|
111
|
-
});
|
|
112
|
-
const nonce = sodium.randombytes_buf(sodium.crypto_box_NONCEBYTES);
|
|
113
|
-
const encryptedData = sodium.crypto_aead_xchacha20poly1305_ietf_encrypt(
|
|
114
|
-
compressedData,
|
|
115
|
-
null,
|
|
116
|
-
null,
|
|
117
|
-
nonce,
|
|
118
|
-
this.userKey
|
|
119
|
-
)
|
|
120
|
-
//sodium.crypto_secretbox_easy(compressedData, nonce, this.userKey);
|
|
121
|
-
const hash = crypto.createHash('sha3-512').update(encryptedData).digest('hex');
|
|
122
|
-
|
|
123
|
-
this.data.push({ dataName: name, nonce: Array.from(nonce), data: Array.from(encryptedData), hash, dataType: dmap[1] });
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
saveToFile(outputPath) {
|
|
127
|
-
if (!outputPath || typeof outputPath !== 'string' || !outputPath.trim() || !this.salt || !(this.salt instanceof Uint8Array) || this.salt.length !== 16) {
|
|
128
|
-
throw new Error('Invalid output path or salt.');
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
const spdData = JSON.stringify({ data: this.data, salt: Array.from(this.salt) });
|
|
132
|
-
const compressedSpdData = zlib.deflateSync(spdData,{
|
|
133
|
-
level:9
|
|
134
|
-
});
|
|
135
|
-
fs.writeFileSync(outputPath, compressedSpdData, { mode: 0o600 });
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
static async loadFromFile(spdPath, passcode) {
|
|
140
|
-
return new Promise(async (res,rej)=>{
|
|
141
|
-
try{
|
|
142
|
-
if (!spdPath || typeof spdPath !== 'string' || !spdPath.trim() || !passcode || typeof passcode !== 'string' || !passcode.trim()) {
|
|
143
|
-
rej(new Error('Invalid SPD path or passcode.'));
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
await sodium.ready;
|
|
147
|
-
|
|
148
|
-
const compressedSpdData = fs.readFileSync(spdPath);
|
|
149
|
-
const spdData = zlib.inflateSync(compressedSpdData,{level:9}).toString('utf8');
|
|
150
|
-
|
|
151
|
-
const { data, salt } = JSON.parse(spdData);
|
|
152
|
-
|
|
153
|
-
const { pqcKey } = await new SPD().convertPasscodeToPQCKeySalted(passcode, new Uint8Array(salt));
|
|
154
|
-
const pbk = pqcKey.publicKey;
|
|
155
|
-
const spd = new SPD();
|
|
156
|
-
spd.userKey = pbk;
|
|
157
|
-
spd.keyPair = {
|
|
158
|
-
publicKey: pbk.publicKey
|
|
159
|
-
};
|
|
160
|
-
spd.data = data.map(dat => ({
|
|
161
|
-
dataName: dat.dataName,
|
|
162
|
-
nonce: Buffer.from(dat.nonce),
|
|
163
|
-
data: Buffer.from(dat.data),
|
|
164
|
-
hash: dat.hash,
|
|
165
|
-
dataType: dat.dataType
|
|
166
|
-
}));
|
|
167
|
-
spd.data.forEach(dat => {
|
|
168
|
-
//const calculatedHash = crypto.createHash('sha256').update(Buffer.from(dat.data)).digest('hex');
|
|
169
|
-
const calculatedHash = crypto.createHash('sha3-512').update(Buffer.from(dat.data)).digest('hex');
|
|
170
|
-
|
|
171
|
-
if (calculatedHash !== dat.hash) {
|
|
172
|
-
rej(new Error(`Data integrity check failed for ${dat.dataName}`));
|
|
173
|
-
}
|
|
174
|
-
});
|
|
175
|
-
res(spd);
|
|
176
|
-
}catch{
|
|
177
|
-
rej()
|
|
178
|
-
}
|
|
179
|
-
})
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
async extractData() {
|
|
183
|
-
return new Promise(async(res,rej)=>{
|
|
184
|
-
try{
|
|
185
|
-
await sodium.ready;
|
|
186
|
-
let extractedFiles = {};
|
|
187
|
-
this.data.forEach(async dat => {
|
|
188
|
-
try{
|
|
189
|
-
const decryptedData = sodium.crypto_aead_xchacha20poly1305_ietf_decrypt(null,dat.data,null, dat.nonce, this.userKey);
|
|
190
|
-
const decompressedData = zlib.inflateSync(decryptedData,{level:9});
|
|
191
|
-
|
|
192
|
-
const dt = decompressedData.toString('utf8');
|
|
193
|
-
extractedFiles[dat.dataName] = await this.CSTI(dt, dat.dataType);
|
|
194
|
-
}catch{
|
|
195
|
-
rej()
|
|
196
|
-
}
|
|
197
|
-
});
|
|
198
|
-
res(extractedFiles);
|
|
199
|
-
}catch{
|
|
200
|
-
rej()
|
|
201
|
-
}
|
|
202
|
-
})
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
static async derivePBK(passcode, salt) {
|
|
208
|
-
if (!passcode || typeof passcode !== 'string' || !passcode.trim() || !salt || !(salt instanceof Uint8Array) || salt.length !== 16) {
|
|
209
|
-
throw new Error('Invalid passcode or salt.');
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
return new Promise(async(resolve, reject) => {
|
|
213
|
-
argon2.hash(passcode, { salt:Buffer.from(salt), type: argon2.argon2id }).then((data)=>{
|
|
214
|
-
|
|
215
|
-
resolve({ pbk: data, salt: salt });
|
|
216
|
-
}).catch((err)=>{
|
|
217
|
-
console.log(err)
|
|
218
|
-
reject(err);
|
|
219
|
-
})
|
|
220
|
-
|
|
221
|
-
});
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
saveData() {
|
|
225
|
-
const spdData = JSON.stringify({ data: this.data, salt: Array.from(this.salt) });
|
|
226
|
-
const compressedSpdData = zlib.deflateSync(spdData,{level:9});
|
|
227
|
-
return compressedSpdData;
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
static async loadFromString(spdData, passcode) {
|
|
231
|
-
return new Promise(async (res,rej)=>{
|
|
232
|
-
try{
|
|
233
|
-
if (!spdData || typeof spdData !== 'string' || !spdData.trim() || !passcode || typeof passcode !== 'string' || !passcode.trim()) {
|
|
234
|
-
rej(new Error('Invalid SPD path or passcode.'));
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
await sodium.ready;
|
|
238
|
-
const spdDataBuffer = Buffer.from(spdData, 'base64');
|
|
239
|
-
const spdData2 = zlib.inflateSync(spdDataBuffer,{level:9}).toString('utf8');
|
|
240
|
-
const { data, salt } = JSON.parse(spdData2);
|
|
241
|
-
const { pqcKey } = await new SPD().convertPasscodeToPQCKeySalted(passcode, new Uint8Array(salt));
|
|
242
|
-
const pbk = pqcKey.publicKey;
|
|
243
|
-
const spd = new SPD();
|
|
244
|
-
spd.userKey = pbk;
|
|
245
|
-
spd.keyPair = {
|
|
246
|
-
publicKey: pbk.publicKey
|
|
247
|
-
};
|
|
248
|
-
spd.data = data.map(dat => ({
|
|
249
|
-
dataName: dat.dataName,
|
|
250
|
-
nonce: Buffer.from(dat.nonce),
|
|
251
|
-
data: Buffer.from(dat.data),
|
|
252
|
-
hash: dat.hash,
|
|
253
|
-
dataType: dat.dataType
|
|
254
|
-
}));
|
|
255
|
-
spd.data.forEach(dat => {
|
|
256
|
-
const calculatedHash = crypto.createHash('sha3-512').update(Buffer.from(dat.data)).digest('hex');
|
|
257
|
-
if (calculatedHash !== dat.hash) {
|
|
258
|
-
rej(new Error(`Data integrity check failed for ${dat.dataName}`));
|
|
259
|
-
}
|
|
260
|
-
});
|
|
261
|
-
res(spd);
|
|
262
|
-
}catch{
|
|
263
|
-
rej()
|
|
264
|
-
}
|
|
265
|
-
})
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
async convertPasscodeToPQCKeySalted(passcode, salt) {
|
|
269
|
-
if (!passcode || typeof passcode !== 'string' || !passcode.trim() || passcode.length < 8 || !salt || !(salt instanceof Uint8Array) || salt.length !== 16) {
|
|
270
|
-
throw new Error('Invalid passcode or salt.');
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
const { pbk } = await SPD.derivePBK(passcode, salt);
|
|
274
|
-
|
|
275
|
-
await sodium.ready;
|
|
276
|
-
|
|
277
|
-
const keyPair = sodium.crypto_kx_seed_keypair(pbk.slice(0, sodium.crypto_kx_SEEDBYTES));
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
return { pqcKey: { publicKey: keyPair.publicKey }, salt };
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
async convertPasscodeToPQCKey(passcode) {
|
|
284
|
-
if (!passcode || typeof passcode !== 'string' || !passcode.trim() || passcode.length < 8) {
|
|
285
|
-
throw new Error('Invalid passcode.');
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
const { pbk, salt } = await SPD.derivePBK(passcode, crypto.getRandomValues(new Uint8Array(16)));
|
|
289
|
-
|
|
290
|
-
await sodium.ready;
|
|
291
|
-
const keyPair = sodium.crypto_kx_seed_keypair(pbk.slice(0, sodium.crypto_kx_SEEDBYTES));
|
|
292
|
-
|
|
293
|
-
return { pqcKey: { publicKey: keyPair.publicKey }, salt };
|
|
294
|
-
}
|
|
295
|
-
async TDT(data) {
|
|
296
|
-
const classTypeMap = {
|
|
297
|
-
'[object Array]': 'Array',
|
|
298
|
-
'[object Uint8Array]': 'Uint8Array',
|
|
299
|
-
'[object Uint16Array]': 'Uint16Array',
|
|
300
|
-
'[object Uint32Array]': 'Uint32Array',
|
|
301
|
-
'[object BigInt64Array]': 'BigInt64Array',
|
|
302
|
-
'[object BigUint64Array]': 'BigUint64Array',
|
|
303
|
-
'[object Float32Array]': 'Float32Array',
|
|
304
|
-
'[object Float64Array]': 'Float64Array',
|
|
305
|
-
'[object Map]': 'Map',
|
|
306
|
-
'[object Set]': 'Set',
|
|
307
|
-
'[object Date]': 'Date',
|
|
308
|
-
'[object RegExp]': 'RegExp',
|
|
309
|
-
'[object Error]': 'Error'
|
|
310
|
-
};
|
|
311
|
-
|
|
312
|
-
const objectType = Object.prototype.toString.call(data);
|
|
313
|
-
const mappedType = classTypeMap[objectType];
|
|
314
|
-
return mappedType;
|
|
315
|
-
}
|
|
316
|
-
async isNumArr(dataType) {
|
|
317
|
-
if(dataType === 'Uint8Array' || dataType === 'Uint16Array' || dataType === 'Uint32Array' || dataType === 'BigInt64Array' || dataType === 'BigUint64Array' || dataType === 'Float32Array' || dataType === 'Float64Array'){
|
|
318
|
-
return true;
|
|
319
|
-
}
|
|
320
|
-
}
|
|
321
|
-
async isSWM(dataType) {
|
|
322
|
-
if(dataType === 'Map' || dataType === 'Set' || dataType === 'WeakMap' || dataType === 'WeakSet'){
|
|
323
|
-
return true;
|
|
324
|
-
}
|
|
325
|
-
}
|
|
326
|
-
async isDRE(dataType) {
|
|
327
|
-
if(dataType === 'Date' || dataType === 'RegExp' || dataType === 'Error'){
|
|
328
|
-
return true;
|
|
329
|
-
}
|
|
330
|
-
}
|
|
331
|
-
async CITS(data) {
|
|
332
|
-
const dataType = typeof data;
|
|
333
|
-
if (dataType === 'string' || dataType === 'number' || dataType === 'boolean') {
|
|
334
|
-
return [data.toString(), dataType];
|
|
335
|
-
}
|
|
336
|
-
if(typeof data === 'object'){
|
|
337
|
-
const type = await this.TDT(data)
|
|
338
|
-
if(type === 'Array'){
|
|
339
|
-
return [JSON.stringify(data),'Array'];
|
|
340
|
-
}
|
|
341
|
-
if(await this.isNumArr(type)){
|
|
342
|
-
return [JSON.stringify(Array.from(data)),type];
|
|
343
|
-
}
|
|
344
|
-
if(await this.isSWM(type)){
|
|
345
|
-
|
|
346
|
-
return [JSON.stringify([...data]),type];
|
|
347
|
-
}
|
|
348
|
-
if(await this.isDRE(type)){
|
|
349
|
-
return [data.toString(),type];
|
|
350
|
-
}
|
|
351
|
-
return [JSON.stringify(data), typeof data];
|
|
352
|
-
}
|
|
353
|
-
}
|
|
354
|
-
async CSTI(data,type) {
|
|
355
|
-
if(type === 'string') {
|
|
356
|
-
return data
|
|
357
|
-
}
|
|
358
|
-
if(type === 'number'){
|
|
359
|
-
return parseFloat(data);
|
|
360
|
-
}
|
|
361
|
-
if(type === 'boolean'){
|
|
362
|
-
return (data === 'true')&&(data !== 'false');
|
|
363
|
-
}
|
|
364
|
-
if(type === 'object' || type === 'Array'){
|
|
365
|
-
return JSON.parse(data);
|
|
366
|
-
}
|
|
367
|
-
if(type === 'Uint8Array'){
|
|
368
|
-
return new Uint8Array(JSON.parse(data));
|
|
369
|
-
}
|
|
370
|
-
if(type === 'Uint16Array'){
|
|
371
|
-
return new Uint16Array(JSON.parse(data));
|
|
372
|
-
}
|
|
373
|
-
if(type === 'Uint32Array'){
|
|
374
|
-
|
|
375
|
-
return new Uint32Array(JSON.parse(data));
|
|
376
|
-
}
|
|
377
|
-
if(type === 'BigInt64Array'){
|
|
378
|
-
return new BigInt64Array(JSON.parse(data));
|
|
379
|
-
}
|
|
380
|
-
if(type === 'BigUint64Array'){
|
|
381
|
-
return new BigUint64Array(JSON.parse(data));
|
|
382
|
-
}
|
|
383
|
-
if(type === 'Float32Array'){
|
|
384
|
-
return new Float32Array(JSON.parse(data));
|
|
385
|
-
}
|
|
386
|
-
if(type === 'Float64Array'){
|
|
387
|
-
return new Float64Array(JSON.parse(data));
|
|
388
|
-
}
|
|
389
|
-
if(type === 'Map'){
|
|
390
|
-
return new Map(JSON.parse(data));
|
|
391
|
-
}
|
|
392
|
-
if(type === 'Set'){
|
|
393
|
-
return new Set(JSON.parse(data));
|
|
394
|
-
}
|
|
395
|
-
if(type === 'WeakMap'){
|
|
396
|
-
return new WeakMap(JSON.parse(data));
|
|
397
|
-
}
|
|
398
|
-
if(type === 'WeakSet'){
|
|
399
|
-
return new WeakSet(JSON.parse(data));
|
|
400
|
-
}
|
|
401
|
-
if(type === 'Date'){
|
|
402
|
-
return new Date(data);
|
|
403
|
-
}
|
|
404
|
-
if(type === 'RegExp'){
|
|
405
|
-
return new RegExp(data);
|
|
406
|
-
}
|
|
407
|
-
if(type === 'Error'){
|
|
408
|
-
return new Error(data);
|
|
409
|
-
}
|
|
410
|
-
}
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
module.exports = {
|
|
414
|
-
SPD,
|
|
415
|
-
};
|
|
1
|
+
const fs=require("fs"),zlib=require("zlib"),sodium=require("libsodium-wrappers"),crypto=require("crypto"),argon2=require("argon2");class SPD{constructor(){this.data=[],this.keyPair,this.userKey,this.salt,this.hash="sha3-512",this.compression_level=9}async init(){await sodium.ready}async changePasscode(a,t){if(!a||!t)throw new Error("Old and new passcodes must be provided.");await sodium.ready;const{pqcKey:r,salt:e}=await this.convertPasscodeToPQCKeySalted(a,this.salt),i=r.privateKey,s={data:this.data,salt:Array.from(this.salt)},o=Buffer.from(JSON.stringify(s),"utf8"),n=crypto.createHmac("sha512",i).update(o).digest(),c=this.generateMAC(o,this.userKey);if(!crypto.timingSafeEqual(n,c))throw new Error("Old passcode is incorrect or data integrity check failed.");const y=await Promise.all(this.data.map((async a=>{const t=sodium.crypto_aead_xchacha20poly1305_ietf_decrypt(Buffer.from(a.data),Buffer.from(a.nonce),i),r=zlib.inflateSync(t).toString("utf8");return{name:a.dataName,parsed:await this.CSTI(r,a.dataType),type:a.dataType}}))),{pqcKey:d,salt:l}=await this.convertPasscodeToPQCKey(t),p=d.privateKey;this.salt=l,this.userKey=p,this.data=[];for(const a of y)await this.addData(a.name,a.parsed)}generateMAC(a,t,r={}){const e=Buffer.concat([a,Buffer.from(r.dataName||"","utf8"),Buffer.from(r.dataType||"","utf8")]);return crypto.createHmac("sha512",t).update(e).digest()}checkPasscodeStrength(a){if("string"!=typeof a||a.length<12)throw new Error("Passcode must be at least 12 characters long.");if([/[a-z]/,/[A-Z]/,/[0-9]/,/[^A-Za-z0-9]/].filter((t=>!t.test(a))).length>1)throw new Error("Passcode must contain at least three of the following: lowercase letters, uppercase letters, digits, special characters.");return 1}#a;async setPassKey(a){this.checkPasscodeStrength(a),await sodium.ready,await this.init();const{pqcKey:t,salt:r}=await this.convertPasscodeToPQCKey(a),e=t.privateKey;this.userKey=e,this.salt=r}setHash(a="sha3-512"){this.hash=a}setCompressionLevel(a=9){this.compression_level=a}getSodium(){return sodium}sanitizeName(a){if("string"!=typeof a)throw new Error("dataName must be a string");return a.normalize("NFKC").trim().toLowerCase().replace(/[^a-z0-9_\-]/g,"_")}async addData(a,t){const r=await this.CITS(t);await sodium.ready;const e=Buffer.from(r[0]),i=zlib.deflateSync(e,{level:this.compression_level}),s=(this.sanitizeName(a),sodium.randombytes_buf(sodium.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES)),o=sodium.crypto_aead_xchacha20poly1305_ietf_encrypt(i,null,null,s,this.userKey),n=crypto.createHash(this.hash).update(o).digest("hex");this.data.push({dataName:a,nonce:Buffer.from(s),data:Buffer.from(o),hash:n,dataType:r[1]})}async addMany(a){await sodium.ready;const t=a.map((async({name:a,data:t})=>{const r=await this.CITS(t),e=Buffer.from(r[0]),i=zlib.deflateSync(e,{level:this.compression_level}),s=sodium.randombytes_buf(sodium.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES),o=sodium.crypto_aead_xchacha20poly1305_ietf_encrypt(i,null,null,s,this.userKey),n=crypto.createHash(this.hash).update(o).digest("hex");return{dataName:a,nonce:Array.from(s),data:Array.from(o),hash:n,dataType:r[1]}})),r=await Promise.all(t);this.data.push(...r)}clearCache(){this.data=[],this.salt=null,this.userKey=null}async saveToFile(a,t){if("string"!=typeof a||!a.trim())throw new Error("Invalid output path.");const{encryptedSalt:r,saltNonce:e,wrapSalt:i}=await SPD.encryptSalt(this.salt,t),s={data:this.data,encryptedSalt:r,saltNonce:e,wrapSalt:i,version:24},o=JSON.stringify(s),n=Buffer.from(o,"utf8"),c=this.generateMAC(n,this.userKey,{dataName:"",dataType:"application/json"}),y={payload:Buffer.from(n),mac:Buffer.from(c)},d=zlib.deflateSync(Buffer.from(JSON.stringify(y)),{level:this.compression_level});fs.writeFileSync(a,d,{mode:384})}static async loadFromFile(a,t,r="sha3-512",e=9){try{if(!(a&&"string"==typeof a&&a.trim()&&t&&"string"==typeof t&&t.trim()))throw new Error("Invalid SPD path or passcode.");await sodium.ready;const i=fs.readFileSync(a),s=zlib.inflateSync(i,{level:e}).toString("utf8"),{payload:o,mac:n}=JSON.parse(s),c=Buffer.from(o),y=new SPD,{data:d,encryptedSalt:l,saltNonce:p,wrapSalt:f,version:u}=JSON.parse(Buffer.from(o).toString("utf-8"));if("number"!=typeof u||24!==u)throw new Error(`Unsupported SPD version: ${u}`);const h=await SPD.decryptSalt(l,p,f,t),{pqcKey:m}=await y.convertPasscodeToPQCKey(t,new Uint8Array(h)),w=m.privateKey,S=crypto.createHmac("sha512",w).update(Buffer.concat([c,Buffer.from("","utf8"),Buffer.from("application/json","utf8")])).digest();if(!crypto.timingSafeEqual(Buffer.from(n),S))throw new Error("MAC verification failed — data may be tampered with.");const g=new SPD;return g.setHash(r),g.setCompressionLevel(e),g.userKey=w,g.keyPair={publicKey:w.publicKey},g.data=d.map((a=>({dataName:a.dataName,nonce:Buffer.from(a.nonce),data:Buffer.from(a.data),hash:a.hash,dataType:a.dataType}))),await Promise.all(g.data.map((a=>{if(crypto.createHash(r).update(Buffer.from(a.data)).digest("hex")!==a.hash)throw new Error(`Data integrity check failed for ${a.dataName}`)}))),g}catch(a){throw new Error(a)}}async extractData(){await sodium.ready;const a=this.data.map((async a=>{try{const t=sodium.crypto_aead_xchacha20poly1305_ietf_decrypt(null,a.data,null,a.nonce,this.userKey),r=zlib.inflateSync(t,{level:this.compression_level}).toString("utf8"),e=await this.CSTI(r,a.dataType);return[a.dataName,e]}catch(t){throw new Error(`Failed to process ${a.dataName}: ${t.message}`)}})),t=await Promise.all(a);return Object.fromEntries(t)}static async derivePBK(a,t){if(!(t&&t instanceof Uint8Array&&16===t.length))throw new Error("Invalid salt.");if(!(a&&"string"==typeof a&&t&&t instanceof Uint8Array&&16===t.length))throw new Error("Invalid passcode or salt.");return{pbk:(await argon2.hash(a,{salt:Buffer.from(t),type:argon2.argon2id,raw:1,memoryCost:65536,timeCost:5,parallelism:1,hashLength:sodium.crypto_kx_SEEDBYTES})).slice(0,sodium.crypto_kx_SEEDBYTES),salt:t}}async saveData(a=""){const{encryptedSalt:t,saltNonce:r,wrapSalt:e}=await SPD.encryptSalt(this.salt,a),i={data:this.data,encryptedSalt:t,saltNonce:r,wrapSalt:e,version:24},s=JSON.stringify(i),o=Buffer.from(s,"utf8"),n=this.generateMAC(o,this.userKey,{dataName:"",dataType:"application/json"}),c={payload:Buffer.from(o),mac:Buffer.from(n)};return zlib.deflateSync(Buffer.from(JSON.stringify(c)),{level:this.compression_level}).toString("base64")}static async decryptSalt(a,t,r,e){const{pbk:i}=await SPD.derivePBK(e,new Uint8Array(r));await sodium.ready;const s=sodium.crypto_aead_xchacha20poly1305_ietf_decrypt(null,new Uint8Array(a),null,new Uint8Array(t),new Uint8Array(i));if(!s)throw new Error("Failed to decrypt salt.");return s}static async encryptSalt(a,t){const r=crypto.getRandomValues(new Uint8Array(16)),{pbk:e}=await SPD.derivePBK(t,r);await sodium.ready;const i=sodium.randombytes_buf(sodium.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES),s=sodium.crypto_aead_xchacha20poly1305_ietf_encrypt(a,null,null,i,new Uint8Array(e));return{encryptedSalt:Array.from(s),saltNonce:Array.from(i),wrapSalt:Array.from(r)}}static async loadFromString(a,t,r="sha3-512",e=9){try{if(!(a&&"string"==typeof a&&a.trim()&&t&&"string"==typeof t&&t.trim()))throw new Error("Invalid SPD path or passcode.");await sodium.ready;const i=Buffer.from(a,"base64"),s=zlib.inflateSync(i,{level:e}).toString("utf8"),{payload:o,mac:n}=JSON.parse(s),{data:c,encryptedSalt:y,saltNonce:d,wrapSalt:l,version:p}=JSON.parse(Buffer.from(o).toString("utf-8")),f=await SPD.decryptSalt(y,d,l,t);if("number"!=typeof p||24!==p)throw new Error(`Unsupported SPD version: ${p}`);const u=Buffer.from(o),h=new SPD,{pqcKey:m}=await h.convertPasscodeToPQCKey(t,new Uint8Array(f)),w=m.privateKey,S=crypto.createHmac("sha512",w).update(Buffer.concat([u,Buffer.from("","utf8"),Buffer.from("application/json","utf8")])).digest();if(!crypto.timingSafeEqual(Buffer.from(n),S))throw new Error("MAC verification failed — data may be tampered with.");const g=new SPD;return g.setHash(r),g.setCompressionLevel(e),g.userKey=w,g.keyPair={publicKey:w.publicKey},g.data=c.map((a=>({dataName:a.dataName,nonce:Buffer.from(a.nonce),data:Buffer.from(a.data),hash:a.hash,dataType:a.dataType}))),await Promise.all(g.data.map((a=>{if(crypto.createHash(r).update(Buffer.from(a.data)).digest("hex")!==a.hash)throw new Error(`Data integrity check failed for ${a.dataName}`)}))),g}catch(a){throw new Error(a)}}static toBase64(a){return Buffer.from(a).toString("base64")}static fromBase64(a){return new Uint8Array(Buffer.from(a,"base64"))}async convertPasscodeToPQCKey(a,t=crypto.getRandomValues(new Uint8Array(16))){if("string"!=typeof a||a.length<8)throw new Error("Invalid passcode.");const{pbk:r}=await SPD.derivePBK(a,t);await this.init();const e=sodium.crypto_kx_seed_keypair(r);return sodium.memzero(r),{pqcKey:{privateKey:e.privateKey},salt:t}}async TDT(a){return{"[object Array]":"Array","[object Uint8Array]":"Uint8Array","[object Uint16Array]":"Uint16Array","[object Uint32Array]":"Uint32Array","[object BigInt64Array]":"BigInt64Array","[object BigUint64Array]":"BigUint64Array","[object Float32Array]":"Float32Array","[object Float64Array]":"Float64Array","[object Map]":"Map","[object Set]":"Set","[object Date]":"Date","[object RegExp]":"RegExp","[object Error]":"Error"}[Object.prototype.toString.call(a)]}async isNumArr(a){if("Uint8Array"===a||"Uint16Array"===a||"Uint32Array"===a||"BigInt64Array"===a||"BigUint64Array"===a||"Float32Array"===a||"Float64Array"===a)return 1}async isSWM(a){if("Map"===a||"Set"===a||"WeakMap"===a||"WeakSet"===a)return 1}async isDRE(a){if("Date"===a||"RegExp"===a||"Error"===a)return 1}async CITS(a){const t=typeof a;if("string"===t||"number"===t||"boolean"===t)return[a.toString(),t];if("object"==typeof a){const t=await this.TDT(a);return"Array"===t?[JSON.stringify(a),"Array"]:await this.isNumArr(t)?[JSON.stringify(Array.from(a)),t]:await this.isSWM(t)?[JSON.stringify([...a]),t]:await this.isDRE(t)?[a.toString(),t]:[JSON.stringify(a),typeof a]}}async CSTI(a,t){try{switch(t){case"string":if("string"!=typeof a)throw new Error("Expected string");return a;case"number":const r=parseFloat(a);if(isNaN(r))throw new Error("Invalid number");return r;case"boolean":if("true"!==a&&"false"!==a)throw new Error("Invalid boolean");return"true"===a;case"Array":case"object":const e=JSON.parse(a);if("object"!=typeof e||null===e)throw new Error("Invalid object");return e;case"Uint8Array":return new Uint8Array(JSON.parse(a));case"Uint16Array":return new Uint16Array(JSON.parse(a));case"Uint32Array":return new Uint32Array(JSON.parse(a));case"BigInt64Array":return new BigInt64Array(JSON.parse(a));case"BigUint64Array":return new BigUint64Array(JSON.parse(a));case"Float32Array":return new Float32Array(JSON.parse(a));case"Float64Array":return new Float64Array(JSON.parse(a));case"Map":return new Map(JSON.parse(a));case"Set":return new Set(JSON.parse(a));case"Date":const i=new Date(a);if(isNaN(i.getTime()))throw new Error("Invalid Date");return i;case"RegExp":return new RegExp(a);case"Error":return new Error(a);default:throw new Error(`Unknown or unsupported type: ${t}`)}}catch(a){throw new Error(`Failed to restore data of type "${t}": ${a.message}`)}}}class SPD_Legacy{constructor(){this.data=[],this.keyPair,this.userKey,this.salt,this.init()}async init(){await sodium.ready,this.keyPair=sodium.crypto_box_keypair()}async setPassKey(a){await sodium.ready,this.init();const{pqcKey:t,salt:r}=await(new SPD_Legacy).convertPasscodeToPQCKey(a),e=t.publicKey;this.userKey=e,this.salt=r}async addData(a,t){const r=await this.CITS(t);await sodium.ready;const e=Buffer.from(r[0]),i=zlib.deflateSync(e,{level:9}),s=sodium.randombytes_buf(sodium.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES),o=sodium.crypto_secretbox_easy(i,s,this.userKey),n=crypto.createHash("sha256").update(o).digest("hex");this.data.push({dataName:a,nonce:Array.from(s),data:Array.from(o),hash:n,dataType:r[1]})}saveToFile(a){if(!(a&&"string"==typeof a&&a.trim()&&this.salt&&this.salt instanceof Uint8Array&&16===this.salt.length))throw new Error("Invalid output path or salt.");const t=JSON.stringify({data:this.data,salt:Array.from(this.salt)}),r=zlib.deflateSync(t,{level:9});fs.writeFileSync(a,r,{mode:384})}static async loadFromFile(a,t){if(!(a&&"string"==typeof a&&a.trim()&&t&&"string"==typeof t&&t.trim()))throw new Error("Invalid SPD path or passcode.");await sodium.ready;try{const r=fs.readFileSync(a),e=zlib.inflateSync(r,{level:9}).toString("utf8"),{data:i,salt:s}=JSON.parse(e),o=new SPD_Legacy,{pqcKey:n}=await o.convertPasscodeToPQCKeySalted(t,new Uint8Array(s)),c=n.publicKey,y=new SPD_Legacy;y.userKey=c,y.keyPair={publicKey:c.publicKey},y.data=i.map((a=>({dataName:a.dataName,nonce:Buffer.from(a.nonce),data:Buffer.from(a.data),hash:a.hash,dataType:a.dataType})));const d=y.data.map((a=>new Promise(((t,r)=>{crypto.createHash("sha256").update(a.data).digest("hex")!==a.hash?r(new Error(`Data integrity check failed for ${a.dataName}`)):t()}))));return await Promise.all(d),y}catch(a){throw new Error(`Failed to load SPD file: ${a.message}`)}}async extractData(){await sodium.ready;try{const a=this.data.map((async a=>{try{const t=sodium.crypto_secretbox_open_easy(a.data,a.nonce,this.userKey),r=zlib.inflateSync(t,{level:9}).toString("utf8"),e=await this.CSTI(r,a.dataType);return[a.dataName,e]}catch(t){throw new Error(`Failed to process ${a.dataName}: ${t.message}`)}})),t=await Promise.all(a);return Object.fromEntries(t)}catch(a){throw new Error(`Data extraction failed: ${a.message}`)}}static async derivePBK(a,t){if(!(a&&"string"==typeof a&&a.trim()&&t&&t instanceof Uint8Array&&16===t.length))throw new Error("Invalid passcode or salt.");return new Promise(((r,e)=>{crypto.pbkdf2(a,t,1e5,32,"sha256",((a,i)=>{a?e(a):r({pbk:i,salt:t})}))}))}saveData(){const a=JSON.stringify({data:this.data,salt:Array.from(this.salt)});return zlib.deflateSync(a,{level:9})}static async loadFromString(a,t){if(!(a&&"string"==typeof a&&a.trim()&&t&&"string"==typeof t&&t.trim()))throw new Error("Invalid SPD data or passcode.");await sodium.ready;try{const r=Buffer.from(a,"base64"),e=zlib.inflateSync(r,{level:9}).toString("utf8"),{data:i,salt:s}=JSON.parse(e),o=new SPD_Legacy,{pqcKey:n}=await o.convertPasscodeToPQCKeySalted(t,new Uint8Array(s)),c=n.publicKey,y=new SPD_Legacy;y.userKey=c,y.keyPair={publicKey:c.publicKey},y.data=i.map((a=>({dataName:a.dataName,nonce:Buffer.from(a.nonce),data:Buffer.from(a.data),hash:a.hash,dataType:a.dataType})));const d=y.data.map((a=>new Promise(((t,r)=>{crypto.createHash("sha256").update(a.data).digest("hex")!==a.hash?r(new Error(`Data integrity check failed for ${a.dataName}`)):t()}))));return await Promise.all(d),y}catch(a){throw new Error(`Failed to load SPD data: ${a.message}`)}}async convertPasscodeToPQCKeySalted(a,t){if(!a||"string"!=typeof a||!a.trim()||a.length<8||!t||!(t instanceof Uint8Array)||16!==t.length)throw new Error("Invalid passcode or salt.");const{pbk:r}=await SPD.derivePBK(a,t);await sodium.ready;return{pqcKey:{publicKey:sodium.crypto_kx_seed_keypair(r).publicKey},salt:t}}async convertPasscodeToPQCKey(a){if(!a||"string"!=typeof a||!a.trim()||a.length<8)throw new Error("Invalid passcode.");const{pbk:t,salt:r}=await SPD.derivePBK(a,crypto.getRandomValues(new Uint8Array(16)));await sodium.ready;return{pqcKey:{publicKey:sodium.crypto_kx_seed_keypair(t.slice(0,sodium.crypto_kx_SEEDBYTES)).publicKey},salt:r}}async TDT(a){return{"[object Array]":"Array","[object Uint8Array]":"Uint8Array","[object Uint16Array]":"Uint16Array","[object Uint32Array]":"Uint32Array","[object BigInt64Array]":"BigInt64Array","[object BigUint64Array]":"BigUint64Array","[object Float32Array]":"Float32Array","[object Float64Array]":"Float64Array","[object Map]":"Map","[object Set]":"Set","[object Date]":"Date","[object RegExp]":"RegExp","[object Error]":"Error"}[Object.prototype.toString.call(a)]}async isNumArr(a){if("Uint8Array"===a||"Uint16Array"===a||"Uint32Array"===a||"BigInt64Array"===a||"BigUint64Array"===a||"Float32Array"===a||"Float64Array"===a)return 1}async isSWM(a){if("Map"===a||"Set"===a||"WeakMap"===a||"WeakSet"===a)return 1}async isDRE(a){if("Date"===a||"RegExp"===a||"Error"===a)return 1}async CITS(a){const t=typeof a;if("string"===t||"number"===t||"boolean"===t)return[a.toString(),t];if("object"==typeof a){const t=await this.TDT(a);return"Array"===t?[JSON.stringify(a),"Array"]:await this.isNumArr(t)?[JSON.stringify(Array.from(a)),t]:await this.isSWM(t)?[JSON.stringify([...a]),t]:await this.isDRE(t)?[a.toString(),t]:[JSON.stringify(a),typeof a]}}async CSTI(a,t){return"string"===t?a:"number"===t?parseFloat(a):"boolean"===t?"true"===a&&"false"!==a:"object"===t||"Array"===t?JSON.parse(a):"Uint8Array"===t?new Uint8Array(JSON.parse(a)):"Uint16Array"===t?new Uint16Array(JSON.parse(a)):"Uint32Array"===t?new Uint32Array(JSON.parse(a)):"BigInt64Array"===t?new BigInt64Array(JSON.parse(a)):"BigUint64Array"===t?new BigUint64Array(JSON.parse(a)):"Float32Array"===t?new Float32Array(JSON.parse(a)):"Float64Array"===t?new Float64Array(JSON.parse(a)):"Map"===t?new Map(JSON.parse(a)):"Set"===t?new Set(JSON.parse(a)):"WeakMap"===t?new WeakMap(JSON.parse(a)):"WeakSet"===t?new WeakSet(JSON.parse(a)):"Date"===t?new Date(a):"RegExp"===t?new RegExp(a):"Error"===t?new Error(a):void 0}}module.exports={SPD,SPD_LEG:SPD_Legacy};
|
package/fatman.spd
ADDED
|
Binary file
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
const tools = require("./tool")
|
|
2
|
+
const fs = require("fs")
|
|
3
|
+
async function compressFile(file_path="",dist_path="")
|
|
4
|
+
{
|
|
5
|
+
const read = fs.createReadStream(file_path)
|
|
6
|
+
const write = fs.createWriteStream(dist_path)
|
|
7
|
+
await tools.compress(read,write)
|
|
8
|
+
}
|
|
9
|
+
async function decompressFile(file_path="",dist_path="")
|
|
10
|
+
{
|
|
11
|
+
const read = fs.createReadStream(file_path)
|
|
12
|
+
const write = fs.createWriteStream(dist_path)
|
|
13
|
+
await tools.decompress(read,write)
|
|
14
|
+
}
|
|
15
|
+
async function compressBuffer(buf=new Buffer())
|
|
16
|
+
{
|
|
17
|
+
return await tools.compressBuffer(buf)
|
|
18
|
+
}
|
|
19
|
+
async function decompressBuffer(buf=new Buffer())
|
|
20
|
+
{
|
|
21
|
+
return await tools.decompressBuffer(buf)
|
|
22
|
+
}
|
|
23
|
+
module.exports = {
|
|
24
|
+
compressFile,
|
|
25
|
+
decompressFile,
|
|
26
|
+
compressBuffer,
|
|
27
|
+
decompressBuffer
|
|
28
|
+
}
|
package/high-zip/tool.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const zlib = require('zlib');
|
|
3
|
+
const { pipeline } = require('stream');
|
|
4
|
+
const { promisify } = require('util');
|
|
5
|
+
|
|
6
|
+
const streamPipeline = promisify(pipeline);
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Compress using Brotli at level 11 (generic mode).
|
|
10
|
+
* Supports file streams.
|
|
11
|
+
* @param {ReadableStream} inputStream
|
|
12
|
+
* @param {WritableStream} outputStream
|
|
13
|
+
* @returns {Promise<void>}
|
|
14
|
+
*/
|
|
15
|
+
async function compress(inputStream, outputStream) {
|
|
16
|
+
const brotli = zlib.createBrotliCompress({
|
|
17
|
+
params: {
|
|
18
|
+
[zlib.constants.BROTLI_PARAM_QUALITY]: 11,
|
|
19
|
+
[zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_GENERIC
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
await streamPipeline(inputStream, brotli, outputStream);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Decompress Brotli stream.
|
|
27
|
+
* @param {ReadableStream} inputStream
|
|
28
|
+
* @param {WritableStream} outputStream
|
|
29
|
+
* @returns {Promise<void>}
|
|
30
|
+
*/
|
|
31
|
+
async function decompress(inputStream, outputStream) {
|
|
32
|
+
const brotli = zlib.createBrotliDecompress();
|
|
33
|
+
await streamPipeline(inputStream, brotli, outputStream);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Compress a Buffer using Brotli level 11.
|
|
38
|
+
* @param {Buffer} buffer
|
|
39
|
+
* @returns {Promise<Buffer>}
|
|
40
|
+
*/
|
|
41
|
+
function compressBuffer(buffer) {
|
|
42
|
+
return new Promise((resolve, reject) => {
|
|
43
|
+
zlib.brotliCompress(
|
|
44
|
+
buffer,
|
|
45
|
+
{
|
|
46
|
+
params: {
|
|
47
|
+
[zlib.constants.BROTLI_PARAM_QUALITY]: 11,
|
|
48
|
+
[zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_GENERIC
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
(err, result) => {
|
|
52
|
+
if (err) return reject(err);
|
|
53
|
+
resolve(result);
|
|
54
|
+
}
|
|
55
|
+
);
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Decompress a Brotli-compressed Buffer.
|
|
61
|
+
* @param {Buffer} buffer
|
|
62
|
+
* @returns {Promise<Buffer>}
|
|
63
|
+
*/
|
|
64
|
+
function decompressBuffer(buffer) {
|
|
65
|
+
return new Promise((resolve, reject) => {
|
|
66
|
+
zlib.brotliDecompress(buffer, (err, result) => {
|
|
67
|
+
if (err) return reject(err);
|
|
68
|
+
resolve(result);
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
module.exports = {
|
|
74
|
+
compress,
|
|
75
|
+
decompress,
|
|
76
|
+
compressBuffer,
|
|
77
|
+
decompressBuffer
|
|
78
|
+
};
|