forked from GladysAssistant/Gladys
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexternalIntegration.validateManifest.js
More file actions
952 lines (935 loc) · 39.4 KB
/
Copy pathexternalIntegration.validateManifest.js
File metadata and controls
952 lines (935 loc) · 39.4 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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
const semver = require('semver');
const { Error422 } = require('../../utils/httpErrors');
const {
SUPPORTED_MANIFEST_VERSION,
MAX_SUB_CONTAINERS,
MAX_SUB_CONTAINER_VOLUMES,
MAX_SUB_CONTAINER_PORTS,
SUB_CONTAINER_NAME_REGEX,
SUB_CONTAINER_PORT_NAME_REGEX,
SUB_CONTAINER_MEMORY_MIN_MB,
SUB_CONTAINER_MEMORY_MAX_MB,
SUB_CONTAINER_CPU_MIN,
SUB_CONTAINER_CPU_MAX,
SUB_CONTAINER_SHM_MIN_MB,
SUB_CONTAINER_SHM_MAX_MB,
SUB_CONTAINER_START_MODES,
HARDWARE_CLASSES,
NETWORK_DISCOVERY_TYPES,
MAX_NETWORK_DISCOVERY_ENTRIES,
MAX_UDP_BROADCAST_PORTS,
MAX_ACTIONS,
ACTION_MIN_TIMEOUT_SECONDS,
ACTION_MAX_TIMEOUT_SECONDS,
MANIFEST_TRANSPORTS,
MAX_WEBHOOKS,
WEBHOOK_MODES,
} = require('./constants');
// These rules are the exact mirror of the canonical manifest schema owned by
// GladysAssistant/integration-store (vendored copy in manifest.schema.json):
// a manifest accepted by the indexer must always install here, and vice versa.
const MANIFEST_TYPES = ['device', 'communication', 'weather'];
const MANIFEST_FIELDS = [
'manifest_version',
'type',
'name',
'description',
'version',
'docker_image',
'gladys_version',
'cover_image',
'config_schema',
'containers',
'location',
'network_wake',
'network_discovery',
'actions',
'transports',
'webhooks',
'messaging',
'contact_schema',
];
// communication type only: chat channels (receive true, the default —
// inbound + outbound, code-based link) vs notification channels (receive
// false — send only, per-user identity through contact_schema)
const MESSAGING_FIELDS = ['receive'];
const SUB_CONTAINER_FIELDS = [
'name',
'docker_image',
'start',
'env',
'volumes',
'ports',
'devices',
'read_only',
'memory_mb',
'cpu',
'shm_mb',
'command',
];
const PORT_FIELDS = ['container_port', 'protocol', 'label', 'name', 'browsable'];
const PORT_PROTOCOLS = ['tcp', 'udp'];
// {{port:<name>}} placeholder of the section texts, resolved by the
// frontend with the host port assigned to the named declared port (C.1).
// Strict syntax, no spaces inside the braces.
const PORT_PLACEHOLDER_REGEX = /\{\{port:([a-z0-9_]+)\}\}/g;
const ACTION_FIELDS = ['key', 'label', 'description', 'timeout_seconds', 'fields'];
// inbound webhooks via Gladys Plus (B.17): shown on the install screen
// ("will be able to receive events from the Internet via Gladys Plus")
const WEBHOOK_FIELDS = ['key', 'label', 'mode'];
// per capture type: the required specific field + its rules. The entries
// are an authorization contract (same philosophy as hardware requests):
// shown on the install screen, no arbitrary capture ever.
const NETWORK_DISCOVERY_FIELDS = {
'udp-broadcast': ['type', 'ports'],
'udp-active-broadcast': ['type', 'ports'],
mdns: ['type', 'service'],
ssdp: ['type', 'st'],
};
// standard DNS-SD service type, e.g. _hue._tcp
const MDNS_SERVICE_REGEX = /^_[a-z0-9-]+\._(tcp|udp)$/;
const SSDP_ST_MAX_LENGTH = 200;
const CONFIG_FIELD_TYPES = ['string', 'number', 'boolean', 'select', 'multi_select', 'secret', 'oauth2', 'section'];
const OPTION_FIELD_TYPES = ['select', 'multi_select'];
// `section` intro blocks: purely presentational chapters splitting the
// generated form (title + plain text + typed https links) — the
// declarative answer to onboarding guidance, zero rich content rendered
const SECTION_DESCRIPTION_MAX_LENGTH = 1000;
const MAX_SECTION_LINKS = 5;
const SECTION_LINK_FIELDS = ['url', 'label'];
const SELECT_DISPLAYS = ['dropdown', 'radio'];
// Dynamic options of a select/multi_select: a reserved enum defined by the
// core — never a URL nor an expression, nothing arbitrary enters the
// rendering. "devices": the UI populates the options with the
// already-created devices of the integration (value = external_id).
const SELECT_SOURCES = ['devices'];
const CONFIG_FIELD_FIELDS = [
'key',
'type',
'label',
'description',
'placeholder',
'required',
'default',
'min',
'max',
'options',
'source',
'display',
'links',
];
// boolean has no input to hint, select shows its options
const PLACEHOLDER_FIELD_TYPES = ['string', 'number', 'secret'];
const OPTION_FIELDS = ['value', 'label'];
const LANGUAGE_KEY_REGEX = /^[a-z]{2}(-[A-Z]{2})?$/;
const CONFIG_KEY_REGEX = /^[a-z0-9_]+$/;
// Grammar from the OCI distribution reference specification, restricted to a
// well-formed name with an EXPLICIT tag or digest (same as the indexer — an
// implicit `latest` would make update detection meaningless).
const DOMAIN_COMPONENT = '(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])';
const DOMAIN = `${DOMAIN_COMPONENT}(?:\\.${DOMAIN_COMPONENT})*(?::[0-9]+)?`;
const PATH_COMPONENT = '[a-z0-9]+(?:(?:\\.|_|__|-+)[a-z0-9]+)*';
const NAME = `(?:${DOMAIN}/)?${PATH_COMPONENT}(?:/${PATH_COMPONENT})*`;
const TAG = '[\\w][\\w.-]{0,127}';
const DIGEST = '[a-z0-9]+(?:[.+_-][a-z0-9]+)*:[a-fA-F0-9]{32,}';
const DOCKER_IMAGE_REGEX = new RegExp(`^(${NAME})(?::(${TAG}))?(?:@(${DIGEST}))?$`);
const DOCKER_IMAGE_NAME_MAX_LENGTH = 255;
/**
* @description Check a Docker image reference: well-formed OCI reference with
* an explicit tag or digest.
* @param {string} reference - The image reference.
* @returns {boolean} True when the reference is acceptable.
* @example
* isValidDockerImageReference('ghcr.io/john/demo:1.2.0');
*/
function isValidDockerImageReference(reference) {
if (typeof reference !== 'string') {
return false;
}
const match = DOCKER_IMAGE_REGEX.exec(reference);
if (!match) {
return false;
}
const [, name, tag, digest] = match;
if (name.length > DOCKER_IMAGE_NAME_MAX_LENGTH) {
return false;
}
return tag !== undefined || digest !== undefined;
}
/**
* @description Validate a multi-language text object ({ en: '...', fr: '...' }).
* @param {object} value - The value to validate.
* @param {string} path - The path of the field, for error messages.
* @param {Array} errors - The array of errors to push to.
* @param {number} [minLength] - Minimum length of each translation.
* @param {number} [maxLength] - Maximum length of each translation.
* @example
* validateMultiLanguageText({ en: 'My integration' }, 'description', errors);
*/
function validateMultiLanguageText(value, path, errors, minLength = 1, maxLength = Infinity) {
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
errors.push(`${path}: must be an object mapping language codes to strings`);
return;
}
if (typeof value.en !== 'string') {
errors.push(`${path}.en: english translation is required`);
}
Object.keys(value).forEach((language) => {
if (!LANGUAGE_KEY_REGEX.test(language)) {
errors.push(`${path}.${language}: invalid language code`);
return;
}
const text = value[language];
if (typeof text !== 'string' || text.length < minLength || text.length > maxLength) {
errors.push(`${path}.${language}: must be a string of ${minLength}-${maxLength} characters`);
}
});
}
/**
* @description Validate the `default` value of a config field against its type.
* A secret has no meaningful default: it would end up published in the store.
* @param {object} field - The config field.
* @param {string} path - The path of the field, for error messages.
* @param {Array} errors - The array of errors to push to.
* @example
* validateConfigFieldDefault({ key: 'latitude', type: 'number', default: 48.85 }, 'config_schema[0]', errors);
*/
function validateConfigFieldDefault(field, path, errors) {
if (field.default === undefined) {
return;
}
if (field.source !== undefined && OPTION_FIELD_TYPES.includes(field.type)) {
// the dynamic values are unknown at validation time
errors.push(`${path}.default: not allowed with a dynamic source`);
return;
}
switch (field.type) {
case 'string':
if (typeof field.default !== 'string') {
errors.push(`${path}.default: must be a string`);
}
break;
case 'number':
if (typeof field.default !== 'number') {
errors.push(`${path}.default: must be a number`);
}
break;
case 'boolean':
if (typeof field.default !== 'boolean') {
errors.push(`${path}.default: must be a boolean`);
}
break;
case 'select':
if (!Array.isArray(field.options) || !field.options.some((option) => option.value === field.default)) {
errors.push(`${path}.default: must be one of the select options`);
}
break;
case 'multi_select': {
const validValues = (Array.isArray(field.options) ? field.options : []).map((option) => option.value);
if (!Array.isArray(field.default) || !field.default.every((value) => validValues.includes(value))) {
errors.push(`${path}.default: must be an array of the multi_select option values`);
}
break;
}
default:
// secret: it would end up published in the store ;
// oauth2: the value is the Connect flow, tokens live off-schema ;
// section: purely presentational, no value at all
errors.push(`${path}.default: not allowed for ${field.type} fields`);
}
}
/**
* @description Run a callback on every {{port:<name>}} placeholder found in a
* multi-language text, with the referenced name and the language it sits in.
* @param {object} value - The multi-language text to scan.
* @param {Function} callback - Called with (name, language) per placeholder.
* @example
* forEachPortPlaceholder({ en: 'ws://host:{{port:ocpp}}' }, (name) => names.push(name));
*/
function forEachPortPlaceholder(value, callback) {
if (value === null || typeof value !== 'object') {
return;
}
Object.keys(value).forEach((language) => {
const text = value[language];
if (typeof text !== 'string') {
return;
}
[...text.matchAll(PORT_PLACEHOLDER_REGEX)].forEach((match) => callback(match[1], language));
});
}
/**
* @description Check the {{port:<name>}} placeholders of a section text:
* every referenced name must be the `name` of a port declared in the
* manifest — an unknown reference would sit unresolved on screen forever.
* @param {object} value - The multi-language text to scan.
* @param {string} path - The path of the field, for error messages.
* @param {Set} declaredPortNames - Port names declared in the manifest.
* @param {Array} errors - The array of errors to push to.
* @example
* validateSectionPortPlaceholders({ en: '{{port:ocpp}}' }, 'config_schema[0].description', declaredPortNames, errors);
*/
function validateSectionPortPlaceholders(value, path, declaredPortNames, errors) {
forEachPortPlaceholder(value, (name, language) => {
if (!declaredPortNames.has(name)) {
errors.push(`${path}.${language}: {{port:${name}}} does not reference any declared port name`);
}
});
}
/**
* @description Reject the {{port:<name>}} placeholders of a per-user contact
* schema section. The block is rendered from the reduced view a non-admin
* gets, which deliberately carries no container state (C.5): the token would
* resolve for an admin and stay raw for everyone else. `{{gladys_host}}`
* stays allowed — the browser resolves it whatever the role.
* @param {object} value - The multi-language text to scan.
* @param {string} path - The path of the field, for error messages.
* @param {Array} errors - The array of errors to push to.
* @example
* rejectContactSchemaPortPlaceholders({ en: '{{port:ocpp}}' }, 'contact_schema[0].label', errors);
*/
function rejectContactSchemaPortPlaceholders(value, path, errors) {
forEachPortPlaceholder(value, (name, language) => {
errors.push(`${path}.${language}: {{port:${name}}} is not available in the per-user contact schema`);
});
}
/**
* @description Validate one entry of the config_schema flat list.
* @param {object} field - The field to validate.
* @param {number} index - Index of the field in the list.
* @param {Set} seenKeys - Keys already seen, to detect duplicates.
* @param {Array} errors - The array of errors to push to.
* @param {string} basePath - Path prefix for error messages (the action
* mini forms and the contact schema reuse the same format under another path).
* @param {Set} declaredPortNames - Port names declared in the manifest,
* for the {{port:<name>}} placeholder references of section texts.
* @example
* validateConfigField(field, 0, seenKeys, errors, 'config_schema', declaredPortNames);
*/
function validateConfigField(field, index, seenKeys, errors, basePath, declaredPortNames) {
const path = `${basePath}[${index}]`;
if (field === null || typeof field !== 'object' || Array.isArray(field)) {
errors.push(`${path}: must be an object`);
return;
}
Object.keys(field).forEach((key) => {
if (!CONFIG_FIELD_FIELDS.includes(key)) {
errors.push(`${path}.${key}: unknown field`);
}
});
if (typeof field.key !== 'string' || !CONFIG_KEY_REGEX.test(field.key)) {
errors.push(`${path}.key: must be a non-empty string matching [a-z0-9_]`);
} else if (seenKeys.has(field.key)) {
errors.push(`${path}.key: duplicate key "${field.key}"`);
} else {
seenKeys.add(field.key);
}
if (!CONFIG_FIELD_TYPES.includes(field.type)) {
errors.push(`${path}.type: must be one of ${CONFIG_FIELD_TYPES.join(', ')}`);
}
validateMultiLanguageText(field.label, `${path}.label`, errors);
if (field.description !== undefined) {
if (field.type === 'section') {
// plain text only, bounded: the long walkthrough belongs to the
// mandatory repo documentation
validateMultiLanguageText(field.description, `${path}.description`, errors, 1, SECTION_DESCRIPTION_MAX_LENGTH);
} else {
validateMultiLanguageText(field.description, `${path}.description`, errors);
}
}
if (field.type === 'section') {
// {{port:<name>}} placeholders only live in section texts: an unknown
// reference would never resolve on screen
validateSectionPortPlaceholders(field.label, `${path}.label`, declaredPortNames, errors);
validateSectionPortPlaceholders(field.description, `${path}.description`, declaredPortNames, errors);
}
if (field.placeholder !== undefined) {
if (!PLACEHOLDER_FIELD_TYPES.includes(field.type)) {
errors.push(`${path}.placeholder: only allowed on ${PLACEHOLDER_FIELD_TYPES.join(', ')} fields`);
} else {
validateMultiLanguageText(field.placeholder, `${path}.placeholder`, errors);
}
}
if (field.required !== undefined) {
if (field.type === 'section') {
// purely presentational: a section holds no value to require
errors.push(`${path}.required: not allowed on section fields`);
} else if (typeof field.required !== 'boolean') {
errors.push(`${path}.required: must be a boolean`);
}
}
validateConfigFieldDefault(field, path, errors);
if (field.links !== undefined) {
if (field.type !== 'section') {
errors.push(`${path}.links: only allowed on section fields`);
} else if (!Array.isArray(field.links) || field.links.length === 0 || field.links.length > MAX_SECTION_LINKS) {
errors.push(`${path}.links: must be a list of 1-${MAX_SECTION_LINKS} links`);
} else {
field.links.forEach((link, linkIndex) => {
const linkPath = `${path}.links[${linkIndex}]`;
if (link === null || typeof link !== 'object' || Array.isArray(link)) {
errors.push(`${linkPath}: must be an object`);
return;
}
Object.keys(link).forEach((key) => {
if (!SECTION_LINK_FIELDS.includes(key)) {
errors.push(`${linkPath}.${key}: unknown field`);
}
});
// third-party non-moderated content: https only, and the front
// displays the target domain next to the label
if (typeof link.url !== 'string' || !link.url.startsWith('https://')) {
errors.push(`${linkPath}.url: must be an https URL`);
}
validateMultiLanguageText(link.label, `${linkPath}.label`, errors);
});
}
}
if (field.type === 'number') {
if (field.min !== undefined && typeof field.min !== 'number') {
errors.push(`${path}.min: must be a number`);
}
if (field.max !== undefined && typeof field.max !== 'number') {
errors.push(`${path}.max: must be a number`);
}
if (typeof field.min === 'number' && typeof field.max === 'number' && field.min > field.max) {
errors.push(`${path}.min: must be lower than or equal to max`);
}
} else if (field.min !== undefined || field.max !== undefined) {
errors.push(`${path}.min: only allowed on number fields`);
}
if (field.display !== undefined) {
if (field.type !== 'select') {
errors.push(`${path}.display: only allowed on select fields`);
} else if (!SELECT_DISPLAYS.includes(field.display)) {
errors.push(`${path}.display: must be one of ${SELECT_DISPLAYS.join(', ')}`);
}
}
if (field.source !== undefined) {
if (!OPTION_FIELD_TYPES.includes(field.type)) {
errors.push(`${path}.source: only allowed on select and multi_select fields`);
} else if (!SELECT_SOURCES.includes(field.source)) {
errors.push(`${path}.source: must be one of ${SELECT_SOURCES.join(', ')}`);
}
if (field.options !== undefined) {
errors.push(`${path}.options: mutually exclusive with source`);
}
} else if (OPTION_FIELD_TYPES.includes(field.type)) {
if (!Array.isArray(field.options) || field.options.length === 0) {
errors.push(`${path}.options: ${field.type} fields must have a non-empty options list`);
} else {
field.options.forEach((option, optionIndex) => {
if (option === null || typeof option !== 'object' || Array.isArray(option)) {
errors.push(`${path}.options[${optionIndex}]: must be an object`);
return;
}
Object.keys(option).forEach((key) => {
if (!OPTION_FIELDS.includes(key)) {
errors.push(`${path}.options[${optionIndex}].${key}: unknown field`);
}
});
if (typeof option.value !== 'string' || option.value.length === 0) {
errors.push(`${path}.options[${optionIndex}].value: must be a non-empty string`);
}
validateMultiLanguageText(option.label, `${path}.options[${optionIndex}].label`, errors);
});
}
} else if (field.options !== undefined) {
errors.push(`${path}.options: only allowed on select and multi_select fields`);
}
}
/**
* @description Validate one entry of the manifest actions list: an
* on-demand operation rendered as a button in the Configuration screen,
* with an optional flat form reusing the config_schema field format and a
* per-action ack timeout (these operations can be long).
* @param {object} action - The action to validate.
* @param {number} index - Index of the action in the list.
* @param {Set} seenKeys - Action keys already seen, to detect duplicates.
* @param {Array} errors - The array of errors to push to.
* @param {Set} declaredPortNames - Port names declared in the manifest,
* for the {{port:<name>}} placeholder references of section texts.
* @example
* validateAction({ key: 'detect_protocol', label: { en: 'Detect' } }, 0, seenKeys, errors, declaredPortNames);
*/
function validateAction(action, index, seenKeys, errors, declaredPortNames) {
const path = `actions[${index}]`;
if (action === null || typeof action !== 'object' || Array.isArray(action)) {
errors.push(`${path}: must be an object`);
return;
}
Object.keys(action).forEach((key) => {
if (!ACTION_FIELDS.includes(key)) {
errors.push(`${path}.${key}: unknown field`);
}
});
if (typeof action.key !== 'string' || !CONFIG_KEY_REGEX.test(action.key)) {
errors.push(`${path}.key: must be a non-empty string matching [a-z0-9_]`);
} else if (seenKeys.has(action.key)) {
errors.push(`${path}.key: duplicate key "${action.key}"`);
} else {
seenKeys.add(action.key);
}
validateMultiLanguageText(action.label, `${path}.label`, errors);
if (action.description !== undefined) {
validateMultiLanguageText(action.description, `${path}.description`, errors);
}
if (action.timeout_seconds !== undefined) {
if (
!Number.isInteger(action.timeout_seconds) ||
action.timeout_seconds < ACTION_MIN_TIMEOUT_SECONDS ||
action.timeout_seconds > ACTION_MAX_TIMEOUT_SECONDS
) {
errors.push(
`${path}.timeout_seconds: must be an integer between ${ACTION_MIN_TIMEOUT_SECONDS} and ${ACTION_MAX_TIMEOUT_SECONDS}`,
);
}
}
if (action.fields !== undefined) {
if (!Array.isArray(action.fields)) {
errors.push(`${path}.fields: must be an array`);
} else {
// same format and rules as the config_schema (the mini form is
// rendered by the same engine); keys unique within the action
const seenFieldKeys = new Set();
action.fields.forEach((field, fieldIndex) => {
validateConfigField(field, fieldIndex, seenFieldKeys, errors, `${path}.fields`, declaredPortNames);
});
}
}
}
/**
* @description Validate one entry of the manifest webhooks list: an inbound
* webhook relayed by Gladys Plus. `fire_and_forget` (default) answers the
* third party immediately and relays asynchronously; `sync` relays the
* integration's own response to the caller (challenge/response providers).
* @param {object} webhook - The webhook to validate.
* @param {number} index - Index of the webhook in the list.
* @param {Set} seenKeys - Webhook keys already seen, to detect duplicates.
* @param {Array} errors - The array of errors to push to.
* @example
* validateWebhook({ key: 'events', label: { en: 'Netatmo events' } }, 0, seenKeys, errors);
*/
function validateWebhook(webhook, index, seenKeys, errors) {
const path = `webhooks[${index}]`;
if (webhook === null || typeof webhook !== 'object' || Array.isArray(webhook)) {
errors.push(`${path}: must be an object`);
return;
}
Object.keys(webhook).forEach((key) => {
if (!WEBHOOK_FIELDS.includes(key)) {
errors.push(`${path}.${key}: unknown field`);
}
});
if (typeof webhook.key !== 'string' || !CONFIG_KEY_REGEX.test(webhook.key)) {
errors.push(`${path}.key: must be a non-empty string matching [a-z0-9_]`);
} else if (seenKeys.has(webhook.key)) {
errors.push(`${path}.key: duplicate key "${webhook.key}"`);
} else {
seenKeys.add(webhook.key);
}
validateMultiLanguageText(webhook.label, `${path}.label`, errors);
if (webhook.mode !== undefined && !WEBHOOK_MODES.includes(webhook.mode)) {
errors.push(`${path}.mode: must be one of ${WEBHOOK_MODES.join(', ')}`);
}
}
/**
* @description Validate one entry of the network_discovery capture list.
* @param {object} entry - The capture request to validate.
* @param {number} index - Index of the entry in the list.
* @param {Array} errors - The array of errors to push to.
* @example
* validateNetworkDiscoveryEntry({ type: 'udp-broadcast', ports: [6666] }, 0, errors);
*/
function validateNetworkDiscoveryEntry(entry, index, errors) {
const path = `network_discovery[${index}]`;
if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {
errors.push(`${path}: must be an object`);
return;
}
if (!NETWORK_DISCOVERY_TYPES.includes(entry.type)) {
errors.push(`${path}.type: must be one of ${NETWORK_DISCOVERY_TYPES.join(', ')}`);
return;
}
const allowedFields = NETWORK_DISCOVERY_FIELDS[entry.type];
Object.keys(entry).forEach((key) => {
if (!allowedFields.includes(key)) {
errors.push(`${path}.${key}: unknown field for type ${entry.type}`);
}
});
if (entry.type === 'udp-broadcast' || entry.type === 'udp-active-broadcast') {
if (!Array.isArray(entry.ports) || entry.ports.length === 0 || entry.ports.length > MAX_UDP_BROADCAST_PORTS) {
errors.push(`${path}.ports: must be a list of 1-${MAX_UDP_BROADCAST_PORTS} ports`);
} else {
const seenPorts = new Set();
entry.ports.forEach((port, portIndex) => {
if (!Number.isInteger(port) || port < 1 || port > 65535) {
errors.push(`${path}.ports[${portIndex}]: must be an integer between 1 and 65535`);
} else if (seenPorts.has(port)) {
errors.push(`${path}.ports[${portIndex}]: duplicate port ${port}`);
} else {
seenPorts.add(port);
}
});
}
} else if (entry.type === 'mdns') {
if (typeof entry.service !== 'string' || !MDNS_SERVICE_REGEX.test(entry.service)) {
errors.push(`${path}.service: must be a DNS-SD service type (e.g. _hue._tcp)`);
}
} else if (typeof entry.st !== 'string' || entry.st.length === 0 || entry.st.length > SSDP_ST_MAX_LENGTH) {
errors.push(`${path}.st: must be a string of 1-${SSDP_ST_MAX_LENGTH} characters`);
}
}
/**
* @description Validate one `ports` entry of a sub-container declaration.
* The host port is never declared: it is chosen by Gladys (free, persisted).
* @param {object} port - The port entry.
* @param {string} path - The path of the entry, for error messages.
* @param {Array} errors - The array of errors to push to.
* @param {Set} seenPortNames - Port names already seen, manifest-wide: the
* {{port:<name>}} placeholder references a name with no container prefix,
* so a name must be unique across every container of the manifest.
* @example
* validateSubContainerPort({ container_port: 5000, label: { en: 'UI' } }, 'containers[0].ports[0]', errors, names);
*/
function validateSubContainerPort(port, path, errors, seenPortNames) {
if (port === null || typeof port !== 'object' || Array.isArray(port)) {
errors.push(`${path}: must be an object`);
return;
}
Object.keys(port).forEach((key) => {
if (!PORT_FIELDS.includes(key)) {
errors.push(`${path}.${key}: unknown field`);
}
});
if (!Number.isInteger(port.container_port) || port.container_port < 1 || port.container_port > 65535) {
errors.push(`${path}.container_port: must be an integer between 1 and 65535`);
}
if (port.protocol !== undefined && !PORT_PROTOCOLS.includes(port.protocol)) {
errors.push(`${path}.protocol: must be one of ${PORT_PROTOCOLS.join(', ')}`);
}
if (port.name !== undefined) {
if (typeof port.name !== 'string' || !SUB_CONTAINER_PORT_NAME_REGEX.test(port.name)) {
errors.push(`${path}.name: must be a string matching [a-z0-9_]{2,20}`);
} else if (seenPortNames.has(port.name)) {
errors.push(`${path}.name: duplicate port name "${port.name}"`);
} else {
seenPortNames.add(port.name);
}
}
if (port.browsable !== undefined && typeof port.browsable !== 'boolean') {
errors.push(`${path}.browsable: must be a boolean`);
}
validateMultiLanguageText(port.label, `${path}.label`, errors);
}
/**
* @description Validate one entry of the `containers` list: the
* authorization contract of the sub-containers (everything shown on the
* install screen; the /container API can only drive what is declared here).
* @param {object} entry - The sub-container declaration.
* @param {number} index - Index of the entry in the list.
* @param {Set} seenNames - Names already seen, to detect duplicates.
* @param {Array} errors - The array of errors to push to.
* @param {Set} seenPortNames - Port names already seen, manifest-wide.
* @example
* validateSubContainer({ name: 'mqtt', docker_image: 'eclipse-mosquitto:2.0.18' }, 0, seenNames, errors, names);
*/
function validateSubContainer(entry, index, seenNames, errors, seenPortNames) {
const path = `containers[${index}]`;
if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {
errors.push(`${path}: must be an object`);
return;
}
Object.keys(entry).forEach((key) => {
if (!SUB_CONTAINER_FIELDS.includes(key)) {
errors.push(`${path}.${key}: unknown field`);
}
});
if (typeof entry.name !== 'string' || !SUB_CONTAINER_NAME_REGEX.test(entry.name)) {
errors.push(`${path}.name: must be a string matching [a-z0-9-]{2,20}`);
} else if (seenNames.has(entry.name)) {
errors.push(`${path}.name: duplicate name "${entry.name}"`);
} else {
seenNames.add(entry.name);
}
if (!isValidDockerImageReference(entry.docker_image)) {
errors.push(`${path}.docker_image: must be a valid image reference with an explicit tag or digest`);
}
if (entry.start !== undefined && !SUB_CONTAINER_START_MODES.includes(entry.start)) {
errors.push(`${path}.start: must be one of ${SUB_CONTAINER_START_MODES.join(', ')}`);
}
if (entry.env !== undefined) {
if (entry.env === null || typeof entry.env !== 'object' || Array.isArray(entry.env)) {
errors.push(`${path}.env: must be an object mapping keys to strings`);
} else {
Object.keys(entry.env).forEach((key) => {
// the manifest is public: GLADYS_* is reserved (no token, no identity)
if (key.toUpperCase().startsWith('GLADYS_')) {
errors.push(`${path}.env.${key}: GLADYS_* keys are reserved`);
}
if (typeof entry.env[key] !== 'string') {
errors.push(`${path}.env.${key}: must be a string`);
}
});
}
}
if (entry.volumes !== undefined) {
if (!Array.isArray(entry.volumes) || entry.volumes.length > MAX_SUB_CONTAINER_VOLUMES) {
errors.push(`${path}.volumes: must be an array of at most ${MAX_SUB_CONTAINER_VOLUMES} container paths`);
} else {
entry.volumes.forEach((volume, volumeIndex) => {
// the host path is derived from the volume path by the supervisor:
// absolute, and no `..` segment that could escape the integration folder
const hasTraversal = typeof volume === 'string' && volume.split('/').includes('..');
if (typeof volume !== 'string' || !volume.startsWith('/') || hasTraversal) {
errors.push(`${path}.volumes[${volumeIndex}]: must be an absolute container path without ..`);
}
});
}
}
if (entry.ports !== undefined) {
if (!Array.isArray(entry.ports) || entry.ports.length > MAX_SUB_CONTAINER_PORTS) {
errors.push(`${path}.ports: must be an array of at most ${MAX_SUB_CONTAINER_PORTS} entries`);
} else {
entry.ports.forEach((port, portIndex) =>
validateSubContainerPort(port, `${path}.ports[${portIndex}]`, errors, seenPortNames),
);
}
}
if (entry.devices !== undefined) {
if (!Array.isArray(entry.devices)) {
errors.push(`${path}.devices: must be an array of hardware classes`);
} else {
const seenClasses = new Set();
entry.devices.forEach((hardwareClass, classIndex) => {
if (!Object.keys(HARDWARE_CLASSES).includes(hardwareClass)) {
errors.push(`${path}.devices[${classIndex}]: must be one of ${Object.keys(HARDWARE_CLASSES).join(', ')}`);
} else if (seenClasses.has(hardwareClass)) {
errors.push(`${path}.devices[${classIndex}]: duplicate class "${hardwareClass}"`);
} else {
seenClasses.add(hardwareClass);
}
});
}
}
if (entry.read_only !== undefined && typeof entry.read_only !== 'boolean') {
errors.push(`${path}.read_only: must be a boolean`);
}
if (
entry.memory_mb !== undefined &&
(!Number.isInteger(entry.memory_mb) ||
entry.memory_mb < SUB_CONTAINER_MEMORY_MIN_MB ||
entry.memory_mb > SUB_CONTAINER_MEMORY_MAX_MB)
) {
errors.push(
`${path}.memory_mb: must be an integer between ${SUB_CONTAINER_MEMORY_MIN_MB} and ${SUB_CONTAINER_MEMORY_MAX_MB}`,
);
}
if (
entry.cpu !== undefined &&
(typeof entry.cpu !== 'number' || entry.cpu < SUB_CONTAINER_CPU_MIN || entry.cpu > SUB_CONTAINER_CPU_MAX)
) {
errors.push(`${path}.cpu: must be a number between ${SUB_CONTAINER_CPU_MIN} and ${SUB_CONTAINER_CPU_MAX}`);
}
if (
entry.shm_mb !== undefined &&
(!Number.isInteger(entry.shm_mb) ||
entry.shm_mb < SUB_CONTAINER_SHM_MIN_MB ||
entry.shm_mb > SUB_CONTAINER_SHM_MAX_MB)
) {
errors.push(
`${path}.shm_mb: must be an integer between ${SUB_CONTAINER_SHM_MIN_MB} and ${SUB_CONTAINER_SHM_MAX_MB}`,
);
}
if (entry.command !== undefined) {
if (!Array.isArray(entry.command) || entry.command.some((part) => typeof part !== 'string')) {
errors.push(`${path}.command: must be an array of strings`);
}
}
}
/**
* @description Validate an external integration manifest against the vendored
* manifest schema rules (exact same rules as the store indexer, see
* manifest.schema.json). Throws an Error422 listing every problem if the
* manifest is invalid.
* @param {object} manifest - The manifest to validate.
* @returns {object} The validated manifest.
* @example
* gladys.externalIntegration.validateManifest(manifest);
*/
function validateManifest(manifest) {
const errors = [];
if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest)) {
throw new Error422('manifest: must be an object');
}
if (!Number.isInteger(manifest.manifest_version)) {
errors.push('manifest_version: must be an integer');
} else if (manifest.manifest_version > SUPPORTED_MANIFEST_VERSION) {
errors.push(
`manifest_version: version ${manifest.manifest_version} is not supported by this Gladys (max: ${SUPPORTED_MANIFEST_VERSION})`,
);
} else if (manifest.manifest_version < 1) {
errors.push('manifest_version: must be >= 1');
}
Object.keys(manifest).forEach((key) => {
if (!MANIFEST_FIELDS.includes(key)) {
errors.push(`${key}: unknown field`);
}
});
if (!MANIFEST_TYPES.includes(manifest.type)) {
errors.push(`type: must be one of ${MANIFEST_TYPES.join(', ')}`);
}
if (typeof manifest.name !== 'string' || manifest.name.length < 3 || manifest.name.length > 30) {
errors.push('name: must be a string of 3-30 characters');
}
validateMultiLanguageText(manifest.description, 'description', errors, 10, 100);
if (typeof manifest.version !== 'string' || semver.valid(manifest.version) !== manifest.version) {
errors.push('version: must be valid semver');
}
if (!isValidDockerImageReference(manifest.docker_image)) {
errors.push('docker_image: must be a valid image reference with an explicit tag or digest');
}
if (typeof manifest.gladys_version !== 'string' || semver.validRange(manifest.gladys_version) === null) {
errors.push('gladys_version: must be a valid semver range');
}
if (manifest.cover_image !== undefined) {
if (typeof manifest.cover_image !== 'string' || !manifest.cover_image.startsWith('https://')) {
errors.push('cover_image: must be an https URL');
}
}
// gathered before the schemas are validated: the section texts of the
// config_schema, action fields and contact_schema may reference these
// names through the {{port:<name>}} placeholder (C.1)
const declaredPortNames = new Set();
if (Array.isArray(manifest.containers)) {
manifest.containers.forEach((entry) => {
const ports = entry && Array.isArray(entry.ports) ? entry.ports : [];
ports.forEach((port) => {
if (port && typeof port.name === 'string') {
declaredPortNames.add(port.name);
}
});
});
}
if (manifest.config_schema !== undefined) {
if (!Array.isArray(manifest.config_schema)) {
errors.push('config_schema: must be an array');
} else {
const seenKeys = new Set();
manifest.config_schema.forEach((field, index) =>
validateConfigField(field, index, seenKeys, errors, 'config_schema', declaredPortNames),
);
}
}
if (manifest.containers !== undefined) {
if (!Array.isArray(manifest.containers) || manifest.containers.length > MAX_SUB_CONTAINERS) {
errors.push(`containers: must be an array of at most ${MAX_SUB_CONTAINERS} entries`);
} else {
const seenNames = new Set();
const seenPortNames = new Set();
manifest.containers.forEach((entry, index) =>
validateSubContainer(entry, index, seenNames, errors, seenPortNames),
);
}
}
if (manifest.location !== undefined && typeof manifest.location !== 'boolean') {
errors.push('location: must be a boolean');
}
if (manifest.network_wake !== undefined && typeof manifest.network_wake !== 'boolean') {
errors.push('network_wake: must be a boolean');
}
if (manifest.network_discovery !== undefined) {
if (
!Array.isArray(manifest.network_discovery) ||
manifest.network_discovery.length === 0 ||
manifest.network_discovery.length > MAX_NETWORK_DISCOVERY_ENTRIES
) {
errors.push(`network_discovery: must be a list of 1-${MAX_NETWORK_DISCOVERY_ENTRIES} capture requests`);
} else {
manifest.network_discovery.forEach((entry, index) => validateNetworkDiscoveryEntry(entry, index, errors));
}
}
if (manifest.actions !== undefined) {
if (!Array.isArray(manifest.actions) || manifest.actions.length === 0 || manifest.actions.length > MAX_ACTIONS) {
errors.push(`actions: must be a list of 1-${MAX_ACTIONS} actions`);
} else {
const seenActionKeys = new Set();
manifest.actions.forEach((action, index) =>
validateAction(action, index, seenActionKeys, errors, declaredPortNames),
);
}
}
if (manifest.messaging !== undefined) {
if (manifest.type !== 'communication') {
errors.push('messaging: only allowed on communication integrations');
} else if (
manifest.messaging === null ||
typeof manifest.messaging !== 'object' ||
Array.isArray(manifest.messaging)
) {
errors.push('messaging: must be an object');
} else {
Object.keys(manifest.messaging).forEach((key) => {
if (!MESSAGING_FIELDS.includes(key)) {
errors.push(`messaging.${key}: unknown field`);
}
});
if (typeof manifest.messaging.receive !== 'boolean') {
errors.push('messaging.receive: must be a boolean');
}
}
}
if (manifest.contact_schema !== undefined) {
// the per-user identity form only makes sense on a send-only channel:
// a chat channel identity comes from the code-based link instead
const sendOnlyChannel =
manifest.type === 'communication' && manifest.messaging && manifest.messaging.receive === false;
if (!sendOnlyChannel) {
errors.push('contact_schema: only allowed on send-only communication integrations (messaging.receive false)');
} else if (!Array.isArray(manifest.contact_schema)) {
errors.push('contact_schema: must be an array');
} else {
const seenContactKeys = new Set();
manifest.contact_schema.forEach((field, index) => {
validateConfigField(field, index, seenContactKeys, errors, 'contact_schema', declaredPortNames);
if (field && field.type === 'oauth2') {
// the OAuth relay is integration-scoped, never per user
errors.push(`contact_schema[${index}].type: oauth2 is not allowed in the per-user contact schema`);
}
if (field && field.type === 'section') {
// the per-user block is the one screen a non-admin reaches, and
// their reduced view carries no container state
rejectContactSchemaPortPlaceholders(field.label, `contact_schema[${index}].label`, errors);
rejectContactSchemaPortPlaceholders(field.description, `contact_schema[${index}].description`, errors);
}
});
}
}
if (manifest.webhooks !== undefined) {
const invalidWebhooksList =
!Array.isArray(manifest.webhooks) || manifest.webhooks.length === 0 || manifest.webhooks.length > MAX_WEBHOOKS;
if (invalidWebhooksList) {
errors.push(`webhooks: must be a list of 1-${MAX_WEBHOOKS} webhooks`);
} else {
const seenWebhookKeys = new Set();
manifest.webhooks.forEach((webhook, index) => validateWebhook(webhook, index, seenWebhookKeys, errors));
}
}
if (manifest.transports !== undefined) {
if (
!Array.isArray(manifest.transports) ||
manifest.transports.length === 0 ||
!manifest.transports.every((transport) => MANIFEST_TRANSPORTS.includes(transport)) ||
new Set(manifest.transports).size !== manifest.transports.length
) {
errors.push(`transports: must be a non-empty subset of ${MANIFEST_TRANSPORTS.join(', ')}`);
}
}
if (errors.length > 0) {
throw new Error422(errors.join(' ; '));
}
return manifest;
}
module.exports = {
validateManifest,
};