-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathdata-package.ts
More file actions
591 lines (497 loc) · 20.1 KB
/
Copy pathdata-package.ts
File metadata and controls
591 lines (497 loc) · 20.1 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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
import { createHash } from 'node:crypto';
import { pipeline } from 'stream/promises';
import type { Static } from '@sinclair/typebox'
import { Type } from '@sinclair/typebox'
import Err from '@openaddresses/batch-error';
import { ZipArchive } from '@archiver/archiver';
import StreamZip from 'node-stream-zip'
import { Readable } from 'node:stream';
import CoT from './cot.js';
import { CoTParser } from './parser.js';
import xmljs from 'xml-js';
import os from 'node:os';
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import path from 'node:path';
import AJV from 'ajv';
export const Parameter = Type.Object({
_attributes: Type.Object({
name: Type.String(),
value: Type.String({ default: '' })
})
})
export const ManifestContent = Type.Object({
_attributes: Type.Object({
ignore: Type.Boolean(),
zipEntry: Type.String()
}),
Parameter: Type.Optional(Type.Union([Parameter, Type.Array(Parameter)]))
})
export const Group = Type.Object({
_attributes: Type.Object({
name: Type.String(),
}),
})
export const Permission = Type.Object({
_attributes: Type.Object({
name: Type.String(),
}),
})
const MissionPackageManifest = Type.Object({
_attributes: Type.Object({
version: Type.String()
}),
Configuration: Type.Object({
Parameter: Type.Array(Parameter)
}),
Contents: Type.Object({
Content: Type.Optional(Type.Union([ManifestContent, Type.Array(ManifestContent)]))
}),
// Used in MissionArchive Exports
Groups: Type.Optional(Type.Object({
group: Type.Optional(Type.Union([Group, Type.Array(Group)]))
})),
Role: Type.Optional(Type.Object({
_attributes: Type.Object({
name: Type.String()
}),
Permissions: Type.Optional(Type.Union([Permission, Type.Array(Permission)]))
}))
});
export const Manifest = Type.Object({ MissionPackageManifest });
const checkManifest = (new AJV({
strict: false,
useDefaults: true,
allErrors: true,
coerceTypes: true,
allowUnionTypes: true
}))
.compile(Manifest);
async function materializeDataPackageInput(
input: string | URL | Buffer | Readable,
name?: string,
): Promise<{
path: string;
parsedName: string;
}> {
if (typeof input === 'string' || input instanceof URL) {
const resolved = input instanceof URL ? path.normalize(decodeURIComponent(input.pathname)) : input;
return {
path: resolved,
parsedName: path.parse(name || resolved).name,
};
}
const ext = path.parse(name || 'package.zip').ext || '.zip';
const inputPath = path.resolve(os.tmpdir(), `${crypto.randomUUID()}${ext}`);
if (input instanceof Buffer) {
await fsp.writeFile(inputPath, input);
} else {
await pipeline(input, fs.createWriteStream(inputPath));
}
return {
path: inputPath,
parsedName: path.parse(name || inputPath).name,
};
}
/**
* Helper class for creating and parsing static Data Packages
* @class
*
* @prop path The local path to the Data Package working directory
* @prop destroyed Indcates that the DataPackage has been destroyed and all local files removed
* @prop version DataPackage schema version - 2 is most common
* @prop contents Array Manifest of DataPackage contents
* @prop settings Top level DataPackage settings
*/
export class DataPackage {
path: string;
destroyed: boolean;
version: string;
contents: Array<Static<typeof ManifestContent>>;
settings: {
uid: string;
name: string;
onReceiveImport?: boolean;
onReceiveDelete?: boolean;
[k: string]: boolean | string | undefined;
}
unknown: Record<string, unknown>;
/**
* @constructor
* @param uid Unique ID of the Data Package
* @param name Human Readable name of the DataPackage
* @param opts Optional Options
*/
constructor(
uid?: string,
name?: string,
opts: {
path?: string
} = {}
) {
if (opts && opts.path) {
this.path = opts.path;
} else {
this.path = os.tmpdir() + '/' + crypto.randomUUID();
}
this.destroyed = false;
fs.mkdirSync(this.path, {
recursive: true
});
this.version = '2';
this.unknown = {};
this.settings = {
uid: uid ?? crypto.randomUUID(),
name: name ?? 'New Data Package'
};
this.contents = [];
}
/**
* The Package should be imported and then removed
*/
setEphemeral() {
this.settings.onReceiveImport = true;
this.settings.onReceiveDelete = true;
}
/**
* The Package should be imported and the package retained
*/
setPermanent() {
this.settings.onReceiveImport = true;
this.settings.onReceiveDelete = false;
}
/**
* Return a string version of the Manifest document
*/
manifest(): string {
const manifest: Static<typeof Manifest> = {
MissionPackageManifest: {
_attributes: { version: this.version },
Configuration: {
Parameter: []
},
Contents: {
Content: this.contents
},
...this.unknown
}
};
for (const key in this.settings) {
if (!this.settings[key]) continue;
manifest.MissionPackageManifest.Configuration.Parameter.push({
_attributes: { name: key, value: String(this.settings[key]) }
})
}
const xml = `<?xml version="1.0" encoding="UTF-8"?>\n${xmljs.js2xml(manifest, { compact: true })}`;
return xml;
}
/**
* Mission Sync archived are returned in DataPackage format
* Return true if the DataPackage is a MissionSync Archive
*/
isMissionArchive(): boolean {
return !!(this.settings.mission_guid && this.settings.mission_name);
}
/**
* When DataPackages are uploaded to TAK Server they generally use an EUD
* calculated Hash
*/
static async hash(path: string): Promise<string> {
const input = fs.createReadStream(path);
const hash = createHash('sha256');
await pipeline(input, hash);
return hash.digest('hex');
}
/**
* When DataPackages are uploaded to TAK Server they generally use an EUD
* calculated Hash
*/
async hash(entry: string): Promise<string> {
return await DataPackage.hash(this.path + '/raw/' + entry);
}
/**
* Return a DataPackage version of a raw Data Package Zip
*
* @public
* @param input path, URL, Buffer, or ReadableStream containing a zipped DataPackage
* @param [opts] Parser Options
* @param [opts.strict] By default the DataPackage must contain a manifest file, turning strict mode off will generate a manifest based on the contents of the file
* @param [opts.cleanup] If the Zip is parsed as a DataSync successfully, remove the initial zip file or temporary upload materialization
* @param [opts.name] Optional input filename used for manifest-less archives when parsing from in-memory data
*/
static async parse(
input: string | URL | Buffer | Readable,
opts?: {
strict?: boolean
cleanup?: boolean
name?: string
}
): Promise<DataPackage> {
if (!opts) opts = {};
if (opts.strict === undefined) opts.strict = true;
if (opts.cleanup === undefined) opts.cleanup = true;
const source = await materializeDataPackageInput(input, opts.name);
const pkg = new DataPackage();
const zip = new StreamZip.async({
file: source.path,
skipEntryNameValidation: true
});
const preentries = await zip.entries();
if (opts.strict && !preentries['MANIFEST/manifest.xml']) {
throw new Err(400, null, 'No MANIFEST/manifest.xml found in Data Package');
}
await fsp.mkdir(pkg.path + '/raw', { recursive: true });
await zip.extract(null, pkg.path + '/raw/');
if (preentries['MANIFEST/manifest.xml']) {
const xml = xmljs.xml2js(String(await fsp.readFile(pkg.path + '/raw/MANIFEST/manifest.xml')), { compact: true })
checkManifest(xml);
if (checkManifest.errors) throw new Err(400, null, `${checkManifest.errors[0].message} (${checkManifest.errors[0].instancePath})`);
const manifest = xml as Static<typeof Manifest>;
pkg.version = manifest.MissionPackageManifest._attributes.version;
if (Array.isArray(manifest.MissionPackageManifest.Contents.Content)) {
pkg.contents = manifest.MissionPackageManifest.Contents.Content;
} else if (manifest.MissionPackageManifest.Contents.Content) {
pkg.contents = [ manifest.MissionPackageManifest.Contents.Content ];
}
for (const param of manifest.MissionPackageManifest.Configuration.Parameter) {
if (['onReceiveImport', 'onReceiveDelete'].includes(param._attributes.name) && typeof param._attributes.value === 'string') {
pkg.settings[param._attributes.name] = param._attributes.value === 'false' ? false : true;
} else {
pkg.settings[param._attributes.name] = param._attributes.value;
}
}
for (const [key, value] of Object.entries(manifest.MissionPackageManifest)) {
// Top level properties that are encoded in the class
if (['_attributes', 'Contents', 'Configuration'].includes(key)) continue;
pkg.unknown[key] = value;
}
} else {
pkg.settings.name = source.parsedName;
pkg.settings.uid = await this.hash(source.path);
pkg.setEphemeral();
for (const [key, value] of Object.entries(preentries)) {
if (value.isDirectory) continue;
pkg.#addContent(
key,
await pkg.hash(key)
);
}
}
await zip.close();
if (opts.cleanup) {
await fsp.unlink(source.path);
}
return pkg;
}
#addContent(zipEntry: string, uid: string, name?: string, ignore = false): void {
if (this.destroyed) throw new Err(400, null, 'Attempt to access Data Package after it has been destroyed');
// TODO: Seen in the wild but not currently implemented here:
// <Parameter name="contentType" value="KML"/>
// <Parameter name="visible" value="false"/>
this.contents.push({
_attributes: { ignore: ignore, zipEntry },
Parameter: [{
_attributes: { name: 'uid', value: uid },
},{
_attributes: { name: 'name', value: name ?? path.parse(zipEntry).base }
}]
});
}
/**
* Return CoT objects for all CoT type features in the Data Package
*
* CoTs have their `attachment_list` field populated if parseAttachments is set to true.
* While this field is populated automatically by some ATAK actions such as QuickPic
other attachment actions do not automatically populate this field other than the link
provided between a CoT and it's attachment in the MANIFEST file
*/
async cots(opts = {
respectIgnore: true,
parseAttachments: true
}): Promise<Array<CoT>> {
if (this.destroyed) throw new Err(400, null, 'Attempt to access Data Package after it has been destroyed');
const cotsMap: Map<string, CoT> = new Map();
const cots: CoT[] = [];
for (const content of this.contents) {
if (!content) continue;
if (path.parse(content._attributes.zipEntry).ext !== '.cot') continue;
if (opts.respectIgnore && content._attributes.ignore) continue;
const cot = CoTParser.from_xml(await fsp.readFile(this.path + '/raw/' + content._attributes.zipEntry));
cotsMap.set(cot.uid(), cot);
cots.push(cot);
}
if (opts.parseAttachments) {
const attachments = this.#attachments(cotsMap, {
respectIgnore: opts.respectIgnore
});
for (const cot of cots) {
if (!cot.raw.event.detail) {
cot.raw.event.detail = {};
}
const attaches = attachments.get(cot.uid());
if (!attaches) continue;
for (const attach of attaches) {
if (!cot.raw.event.detail.attachment_list) {
cot.raw.event.detail.attachment_list = {
_attributes: { hashes: '[]' }
};
}
const hashes: string[] = JSON.parse(cot.raw.event.detail.attachment_list._attributes.hashes)
// Until told otherwise the FileHash appears to always be the directory name
const hash = await this.hash(attach._attributes.zipEntry);
if (!hashes.includes(hash)) {
hashes.push(hash)
}
cot.raw.event.detail.attachment_list._attributes.hashes = JSON.stringify(hashes);
}
}
}
return cots;
}
#attachments(cots: Map<string, CoT>, opts = { respectIgnore: true }): Map<string, Array<Static<typeof ManifestContent>>> {
const attachments: Map<string, Array<Static<typeof ManifestContent>>> = new Map();
for (const content of this.contents) {
if (!content) continue;
if (path.parse(content._attributes.zipEntry).ext === '.cot') continue;
if (opts.respectIgnore && content._attributes.ignore) continue;
if (content.Parameter) {
const params = Array.isArray(content.Parameter) ? content.Parameter : [content.Parameter];
for (const param of params) {
if (param._attributes.name === 'uid' && cots.has(param._attributes.value)) {
const existing = attachments.get(param._attributes.value);
if (existing) {
existing.push(content);
} else {
attachments.set(param._attributes.value, [content]);
}
break;
}
}
}
}
return attachments;
}
/**
* Return a list of files that are NOT attachments or CoT markers
* The Set returned has a list of file paths that can be passed to getFile(path)
*/
async files(opts = { respectIgnore: true }): Promise<Set<string>> {
const attachments = await this.attachments(opts);
const files: Set<string> = new Set();
const attachment_entries = new Set<string>();
for (const entries of attachments.values()) {
for (const entry of entries) {
attachment_entries.add(entry._attributes.zipEntry)
}
}
for (const content of this.contents) {
if (!content) continue;
if (path.parse(content._attributes.zipEntry).ext === '.cot') continue;
if (opts.respectIgnore && content._attributes.ignore) continue;
if (attachment_entries.has(content._attributes.zipEntry)) {
continue;
}
files.add(content._attributes.zipEntry);
}
return files;
}
/**
* Return attachments that are associated in the Manifest with a given CoT
* Note: this does not return files that are NOT associated with a CoT
*/
async attachments(opts = { respectIgnore: true }): Promise<Map<string, Array<Static<typeof ManifestContent>>>> {
const cots: Map<string, CoT> = new Map();
for (const cot of await this.cots({
respectIgnore: opts.respectIgnore,
parseAttachments: false
})) {
cots.set(cot.uid(), cot);
}
return this.#attachments(cots, opts);
}
async getFileBuffer(path: string): Promise<Buffer> {
if (this.destroyed) throw new Err(400, null, 'Attempt to access Data Package after it has been destroyed');
try {
await fsp.access(`${this.path}/raw/${path}`)
} catch (err) {
throw new Err(400, err instanceof Error ? err : new Error(String(err)), 'Could not access file in Data Package');
}
return await fsp.readFile(`${this.path}/raw/${path}`);
}
/**
* Get any file from a Package
*/
async getFile(path: string): Promise<Readable> {
if (this.destroyed) throw new Err(400, null, 'Attempt to access Data Package after it has been destroyed');
try {
await fsp.access(`${this.path}/raw/${path}`)
} catch (err) {
throw new Err(400, err instanceof Error ? err : new Error(String(err)), 'Could not access file in Data Package');
}
return fs.createReadStream(`${this.path}/raw/${path}`)
}
/**
* Add any file to a Package
*
* @param file - Input ReadableStream of File at attach
* @param opts - Options
* @param opts.uid - Optional UID for the File, a UUID will be generated if not supplied
* @param opts.name - Filename for the file
* @param opts.ignore - Should the file be ignore, defaults to false
* @param opts.attachment - Should the file be associated as an attachment to a CoT. If so this should contain the UID of the CoT
*/
async addFile(file: Readable | Buffer | string, opts: {
uid?: string;
name: string;
ignore?: boolean;
attachment?: string;
}): Promise<void> {
if (this.destroyed) throw new Err(400, null, 'Attempt to access Data Package after it has been destroyed');
if (!opts.ignore) opts.ignore = false;
const uid = opts.uid ?? crypto.randomUUID();
this.#addContent(`${uid}/${opts.name}`, opts.attachment || uid, opts.name, opts.ignore);
await fsp.mkdir(`${this.path}/raw/${uid}/`, { recursive: true });
await fsp.writeFile(`${this.path}/raw/${uid}/${opts.name}`, file)
}
/**
* Add a CoT marker to the Package
*/
async addCoT(cot: CoT, opts: {
ignore: boolean
} = {
ignore: false
}): Promise<void> {
if (this.destroyed) throw new Err(400, null, 'Attempt to access Data Package after it has been destroyed');
const name = cot.callsign();
this.#addContent(`${cot.raw.event._attributes.uid}/${cot.raw.event._attributes.uid}.cot`, cot.raw.event._attributes.uid, name, opts.ignore);
await fsp.mkdir(`${this.path}/raw/${cot.raw.event._attributes.uid}/`, { recursive: true });
await fsp.writeFile(`${this.path}/raw/${cot.raw.event._attributes.uid}/${cot.raw.event._attributes.uid}.cot`, CoTParser.to_xml(cot))
}
/**
* Destory the underlying FS resources and prevent further mutation
*/
async destroy(): Promise<void> {
await fsp.rm(this.path, { recursive: true, force: true });
this.destroyed = true;
}
/**
* Compile the DataPackage into a TAK compatible ZIP File
* Note this function can be called multiple times and does not
* affect the ability of the class to continue building a Package
*/
async finalize(): Promise<string> {
if (this.destroyed) throw new Err(400, null, 'Attempt to access Data Package after it has been destroyed');
await fsp.mkdir(this.path + '/raw/MANIFEST', { recursive: true });
await fsp.writeFile(this.path + '/raw/MANIFEST/manifest.xml', this.manifest());
return new Promise((resolve) => {
const archive = new ZipArchive({ zlib: { level: 9 } });
const output = fs.createWriteStream(this.path + `/${this.settings.uid}.zip`)
archive.pipe(output);
output.on('close', () => {
return resolve(this.path + `/${this.settings.uid}.zip`);
});
archive.directory(this.path + '/raw/', '/');
archive.finalize()
});
}
}