Repository navigation
Expand file tree
/
Copy pathpolicy.js
More file actions
1158 lines (1079 loc) · 43.4 KB
/
Copy pathpolicy.js
File metadata and controls
1158 lines (1079 loc) · 43.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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'fs';
import { dirname, isAbsolute, join, relative, resolve, sep } from 'path';
import { createRequire } from 'module';
import { fileURLToPath, pathToFileURL } from 'url';
import yaml from 'js-yaml';
import { checkPattern, compilePattern, explainPatternFailure } from './regex-engine.js';
import { containsSecret } from './secrets.js';
/**
* @typedef {'info' | 'warn' | 'error'} PolicySeverity
* @typedef {{
* id: string,
* severity: PolicySeverity,
* path: string,
* message: string,
* pack?: string
* }} PolicyFinding
*
* @typedef {{
* id: string,
* severity: PolicySeverity,
* when?: Array<'added' | 'removed' | 'changed'>,
* match?: { path?: string, pathFlags?: string, pathEquals?: string, pathPrefix?: string },
* beforeEquals?: unknown,
* afterEquals?: unknown,
* beforeIn?: unknown[],
* afterIn?: unknown[],
* beforeTruthy?: true,
* afterTruthy?: true,
* beforeLooksSecret?: true,
* afterLooksSecret?: true,
* afterMatches?: string,
* afterAnyMatches?: string,
* numericJump?: { minMultiple: number },
* numericDelta?: { min: number },
* allOf?: PolicyMatchClause[],
* anyOf?: PolicyMatchClause[],
* message?: string,
* messageTemplate?: string
* }} PolicyRule
*
* @typedef {{
* match?: { path?: string, pathFlags?: string, pathEquals?: string, pathPrefix?: string },
* beforeEquals?: unknown,
* afterEquals?: unknown,
* beforeIn?: unknown[],
* afterIn?: unknown[],
* beforeTruthy?: true,
* afterTruthy?: true,
* beforeLooksSecret?: true,
* afterLooksSecret?: true,
* afterMatches?: string,
* afterAnyMatches?: string,
* numericJump?: { minMultiple: number },
* numericDelta?: { min: number }
* }} PolicyMatchClause
*
* @typedef {{ id: string, expandSubtrees?: boolean, rules: PolicyRule[] }} PolicyPack
*
* @typedef {{
* id: string,
* packageName: string,
* packageVersion: string | null,
* packFile: string,
* targetPath: string,
* ruleCount: number,
* overwritten: boolean,
* overridesBuiltin: boolean,
* shadowed: string[],
* shipsCode: boolean
* }} AddedPolicyPack
*
* @typedef {{
* cwd?: string,
* file?: string,
* profile?: string | null,
* source?: 'watch' | 'ci' | 'diff',
* policies?: string[],
* plugins?: string[],
* packRoots?: string[],
* severityRemap?: Record<string, PolicySeverity | 'off'>
* }} PolicyEvalOptions
*/
const SEVERITY_RANK = { info: 1, warn: 2, error: 3 };
const PACKS_DIR = join(dirname(fileURLToPath(import.meta.url)), 'packs');
/**
* Is this pack one Flecto ships, rather than one the repository supplies?
*
* The distinction decides which regex engine its patterns compile on, so it is
* drawn on the resolved path rather than the pack id: a local
* `policies/default.json` overrides the built-in `default` and is still a file
* a pull request can write.
* @param {string} path
* @returns {boolean}
*/
function isBuiltinPackPath(path) {
return resolve(path).startsWith(PACKS_DIR + sep);
}
const CHANGE_TYPES = new Set(['added', 'removed', 'changed']);
const RULE_FIELDS = new Set([
'id', 'severity', 'when', 'match', 'beforeEquals', 'afterEquals',
'beforeIn', 'afterIn', 'beforeTruthy', 'afterTruthy', 'numericJump',
'beforeLooksSecret', 'afterLooksSecret',
'afterMatches', 'afterAnyMatches', 'numericDelta', 'allOf', 'anyOf', 'message', 'messageTemplate',
]);
const CLAUSE_FIELDS = new Set([
'match', 'beforeEquals', 'afterEquals', 'beforeIn', 'afterIn',
'beforeTruthy', 'afterTruthy', 'beforeLooksSecret', 'afterLooksSecret',
'afterMatches', 'afterAnyMatches', 'numericJump', 'numericDelta',
]);
const MATCH_FIELDS = new Set(['path', 'pathFlags', 'pathEquals', 'pathPrefix']);
// Community distribution convention: an npm package named flecto-pack-<id>
// carrying a declarative pack file. Nothing in such a package is ever imported.
const PACK_PACKAGE_PREFIX = 'flecto-pack-';
const PACK_FILE_CANDIDATES = ['flecto-pack.json', 'flecto-pack.yaml', 'flecto-pack.yml'];
const PACK_EXTENSIONS = ['.json', '.yaml', '.yml'];
const PACK_MANIFEST_FILE = '.flecto-packs.json';
const PACK_ID_PATTERN = /^[a-z0-9][a-z0-9._-]*$/i;
/**
* @param {string} path
* @param {string} message
* @returns {never}
*/
function invalidPack(path, message) {
throw new Error(`Invalid policy pack at ${path}: ${message}`);
}
/**
* @param {unknown} value
* @returns {value is Record<string, unknown>}
*/
function isObject(value) {
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
}
/**
* @param {unknown} value
* @returns {boolean}
*/
function isTruthyToggle(value) {
if (value === true) return true;
if (typeof value !== 'string') return false;
return ['true', '1', 'yes'].includes(value.trim().toLowerCase());
}
/**
* Validate a parsed policy pack and reject typos before evaluation.
* @param {unknown} pack
* @param {string} path
* @param {boolean} [trusted] true only for packs Flecto ships in src/packs/
* @returns {asserts pack is PolicyPack}
*/
function validatePack(pack, path, trusted = false) {
if (!isObject(pack)) invalidPack(path, 'pack must be an object');
const packFields = new Set(['id', 'expandSubtrees', 'rules']);
for (const field of Object.keys(pack)) {
if (!packFields.has(field)) invalidPack(path, `pack.${field} is not allowed`);
}
if (Object.hasOwn(pack, 'id') && (typeof pack.id !== 'string' || !pack.id.trim())) {
invalidPack(path, 'pack.id must be a non-empty string');
}
if (Object.hasOwn(pack, 'expandSubtrees') && typeof pack.expandSubtrees !== 'boolean') {
invalidPack(path, 'pack.expandSubtrees must be a boolean');
}
if (!Array.isArray(pack.rules)) invalidPack(path, 'pack.rules must be an array');
for (const [index, rule] of pack.rules.entries()) {
try {
validateRule(rule, `rules[${index}]`, false, trusted);
} catch (error) {
const label = isObject(rule) && typeof rule.id === 'string' && rule.id
? `rule "${rule.id}"`
: `rules[${index}]`;
const message = error.message.replace(/^Invalid policy rule at [^:]+: /, '')
.replace(/^unknown field "([^"]+)"$/, '$1 is not allowed (unknown field "$1")')
.replace(/^unknown match field "([^"]+)"$/, 'match.$1 is not allowed (unknown match field "$1")')
// The trailing parenthetical carries the engine's reason, so this is
// no longer anchored at the end.
.replace(/^match\.path is not a valid regular expression/, 'match.path must be a valid regular expression');
invalidPack(path, `${label}.${message}`);
}
}
}
/**
* Every directory whose `policies/` is searched for a local pack, in order.
* The first entry is the primary cwd; later entries are fallbacks (the policy
* fixture harness runs from the fixture directory but packs are installed into
* the invoking project — see #114).
* @param {string | string[]} cwd
* @returns {string[]}
*/
function packRoots(cwd) {
const roots = (Array.isArray(cwd) ? cwd : [cwd])
.filter((root) => typeof root === 'string' && root)
.map((root) => resolve(root));
// Distinct roots only: a fixture run from the project root would otherwise
// search the same policies/ directory twice and report it twice on failure.
return [...new Set(roots)];
}
/**
* @param {string | string[]} cwd
* @param {string} packId
* @returns {string | null}
*/
function resolvePackPath(cwd, packId) {
for (const root of packRoots(cwd)) {
for (const ext of ['.json', '.yaml', '.yml']) {
const localPath = resolve(root, 'policies', `${packId}${ext}`);
if (existsSync(localPath)) return localPath;
}
}
const builtinJson = join(PACKS_DIR, `${packId}.json`);
if (existsSync(builtinJson)) return builtinJson;
return null;
}
/**
* @param {string} path
* @param {string} fallbackId
* @returns {PolicyPack}
*/
function readPackFile(path, fallbackId) {
const raw = readFileSync(path, 'utf8');
let parsed;
try {
parsed = path.endsWith('.json') ? JSON.parse(raw) : yaml.load(raw);
} catch (error) {
invalidPack(path, `could not parse file (${error.message})`);
}
validatePack(parsed, path, isBuiltinPackPath(path));
return { ...parsed, id: parsed.id ?? fallbackId };
}
/**
* Validate a rule or composition clause so pack typos fail closed at load time.
* @param {unknown} candidate
* @param {string} location
* @param {boolean} [isClause]
*/
function validateRule(candidate, location, isClause = false, trusted = false) {
if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) {
throw new Error(`Invalid policy rule at ${location}: expected an object`);
}
const allowedFields = isClause ? CLAUSE_FIELDS : RULE_FIELDS;
for (const key of Object.keys(candidate)) {
if (!allowedFields.has(key)) {
throw new Error(`Invalid policy rule at ${location}: unknown field "${key}"`);
}
}
const rule = /** @type {Record<string, unknown>} */ (candidate);
if (!isClause && (typeof rule.id !== 'string' || !rule.id)) {
throw new Error(`Invalid policy rule at ${location}: id is required`);
}
if (!isClause && (!Object.hasOwn(rule, 'severity') || !Object.hasOwn(SEVERITY_RANK, rule.severity))) {
throw new Error(`Invalid policy rule at ${location}: severity must be one of: info, warn, error`);
}
if (rule.when !== undefined
&& (!Array.isArray(rule.when) || rule.when.length === 0 || rule.when.some((type) => !CHANGE_TYPES.has(type)))) {
const invalidIndex = Array.isArray(rule.when)
? rule.when.findIndex((type) => !CHANGE_TYPES.has(type))
: -1;
throw new Error(`Invalid policy rule at ${location}: when${invalidIndex >= 0 ? `[${invalidIndex}]` : ''} must be one of: added, removed, changed`);
}
validateMatch(rule.match, location, trusted);
validateArrayPredicate(rule.beforeIn, 'beforeIn', location);
validateArrayPredicate(rule.afterIn, 'afterIn', location);
validateTruthyPredicate(rule.beforeTruthy, 'beforeTruthy', location);
validateTruthyPredicate(rule.afterTruthy, 'afterTruthy', location);
validateTruthyPredicate(rule.beforeLooksSecret, 'beforeLooksSecret', location);
validateTruthyPredicate(rule.afterLooksSecret, 'afterLooksSecret', location);
validateRegexPredicate(rule.afterMatches, 'afterMatches', location, trusted);
validateRegexPredicate(rule.afterAnyMatches, 'afterAnyMatches', location, trusted);
validateNumericPredicate(rule.numericJump, 'numericJump', 'minMultiple', location, true);
validateNumericPredicate(rule.numericDelta, 'numericDelta', 'min', location, false);
for (const name of ['message', 'messageTemplate']) {
if (rule[name] !== undefined && typeof rule[name] !== 'string') {
throw new Error(`Invalid policy rule at ${location}: ${name} must be a string`);
}
}
if (!isClause) {
validateComposition(rule.allOf, 'allOf', location, trusted);
validateComposition(rule.anyOf, 'anyOf', location, trusted);
}
}
/** @param {unknown} match @param {string} location */
function validateMatch(match, location, trusted = false) {
if (match === undefined) return;
if (!match || typeof match !== 'object' || Array.isArray(match)) {
throw new Error(`Invalid policy rule at ${location}: match must be an object`);
}
for (const key of Object.keys(match)) {
if (!MATCH_FIELDS.has(key)) {
throw new Error(`Invalid policy rule at ${location}: unknown match field "${key}"`);
}
}
const typedMatch = /** @type {Record<string, unknown>} */ (match);
for (const key of MATCH_FIELDS) {
if (typedMatch[key] !== undefined && typeof typedMatch[key] !== 'string') {
throw new Error(`Invalid policy rule at ${location}: match.${key} must be a string`);
}
}
if (typedMatch.path !== undefined) {
const compiled = checkPattern(typedMatch.path, typedMatch.pathFlags ?? '', { trusted });
if (!compiled.ok) {
if (typedMatch.pathFlags !== undefined && !checkPattern('(?:)', typedMatch.pathFlags, { trusted }).ok) {
throw new Error(`Invalid policy rule at ${location}: match.pathFlags must be valid regular expression flags`);
}
throw new Error(
`Invalid policy rule at ${location}: match.path is not a valid regular expression`
+ ` (${explainPatternFailure(compiled.reason)})`,
);
}
}
}
/** @param {unknown} value @param {string} name @param {string} location */
function validateArrayPredicate(value, name, location) {
if (value !== undefined && !Array.isArray(value)) {
throw new Error(`Invalid policy rule at ${location}: ${name} must be an array`);
}
}
/** @param {unknown} value @param {string} name @param {string} location */
function validateTruthyPredicate(value, name, location) {
if (value !== undefined && value !== true) {
throw new Error(`Invalid policy rule at ${location}: ${name} must be true`);
}
}
/** @param {unknown} value @param {string} name @param {string} location @param {boolean} [trusted] */
function validateRegexPredicate(value, name, location, trusted = false) {
if (value === undefined) return;
if (typeof value !== 'string') {
throw new Error(`Invalid policy rule at ${location}: ${name} must be a string`);
}
const compiled = checkPattern(value, '', { trusted });
if (!compiled.ok) {
throw new Error(
`Invalid policy rule at ${location}: ${name} is not a valid regular expression`
+ ` (${explainPatternFailure(compiled.reason)})`,
);
}
}
/** @param {unknown} value @param {string} name @param {string} property @param {string} location @param {boolean} positive */
function validateNumericPredicate(value, name, property, location, positive) {
if (value === undefined) return;
if (!value || typeof value !== 'object' || Array.isArray(value)
|| typeof value[property] !== 'number' || !Number.isFinite(value[property])
|| (positive ? value[property] <= 0 : value[property] < 0)) {
throw new Error(`Invalid policy rule at ${location}: ${name}.${property} must be a ${positive ? 'positive' : 'non-negative'} finite number`);
}
}
/** @param {unknown} clauses @param {string} name @param {string} location @param {boolean} [trusted] */
function validateComposition(clauses, name, location, trusted = false) {
if (clauses === undefined) return;
if (!Array.isArray(clauses) || clauses.length === 0) {
throw new Error(`Invalid policy rule at ${location}: ${name} must be a non-empty array of match clauses`);
}
clauses.forEach((clause, index) => validateRule(clause, `${location}.${name}[${index}]`, true, trusted));
}
/**
* Loaded, validated, and regex-compiled packs, keyed by cwd + resolved file
* path + that file's mtime. `evaluatePolicies()` calls loadPack() once per
* file in `ci` and once per change event in `watch`; this cache turns every
* repeat call for an unchanged pack file into a Map lookup instead of a
* `readFileSync` + `JSON.parse` + full schema walk.
*
* The key deliberately does *not* memoize on packId alone:
* - Including the resolved path means a local `policies/<id>.json` that
* starts shadowing a built-in (or stops shadowing it) after this process
* started is picked up on the very next call, because resolvePackPath()
* runs fresh every time and produces a different path.
* - Including cwd keeps two different working directories (e.g. two
* in-process callers, or tests) from ever sharing a cache slot merely
* because they happened to load the same-named local pack.
* - Including mtimeMs means editing policies/<id>.json mid-`watch` changes
* the key, so the very next change event re-reads and re-validates the
* file rather than serving the stale in-memory pack. A pack that fails to
* parse or validate throws exactly as before — nothing here catches or
* downgrades that error into "serve the last cached pack", which would
* quietly defeat watch mode's fail-closed behavior on a bad edit.
* @type {Map<string, PolicyPack>}
*/
const packCache = new Map();
/**
* @param {string[]} roots already-resolved search roots, in order
* @param {string} path
* @param {number} mtimeMs
* @returns {string}
*/
function packCacheKey(roots, path, mtimeMs) {
// Roots are NUL-joined for the same reason the other fields are
// NUL-separated: two different root lists must never concatenate into the
// same key.
return `${roots.join('\u0000')}\u0000${path}\u0000${mtimeMs}`;
}
/**
* Load a pack by id from policies/ then built-ins.
*
* severityRemap is intentionally not part of this function or its cache: it
* is applied per profile, downstream, in evaluatePack(). Caching happens at
* this layer — below any remapping — so the object returned here is the same
* regardless of which profile asked for it, and one profile's remap can
* never leak into another's findings.
* @param {string} packId
* @param {string} [cwd]
* @returns {PolicyPack}
*/
export function loadPack(packId, cwd = process.cwd()) {
const id = String(packId ?? '').trim();
if (!id) throw new Error('Policy pack id is required');
const path = resolvePackPath(cwd, id);
if (!path) {
// Name the directories actually searched. The old message always said
// "Add policies/<id>.json", which was actively misleading when the pack
// existed but in a directory this lookup never consulted (#114).
const searched = packRoots(cwd)
.map((root) => join(root, 'policies'))
.concat(PACKS_DIR)
.join(', ');
throw new Error(
`Unknown policy pack "${id}". Searched: ${searched}.`
+ ` Add policies/${id}.json in one of these, or use a built-in pack.`,
);
}
const mtimeMs = statSync(path).mtimeMs;
const cacheKey = packCacheKey(packRoots(cwd), path, mtimeMs);
const cached = packCache.get(cacheKey);
if (cached) return cached;
const pack = readPackFile(path, id);
compilePackRegexes(pack, isBuiltinPackPath(path));
packCache.set(cacheKey, pack);
return pack;
}
/**
* List built-in pack ids.
* @returns {string[]}
*/
export function listBuiltinPackIds() {
if (!existsSync(PACKS_DIR)) return [];
return readdirSync(PACKS_DIR)
.filter((f) => f.endsWith('.json'))
.map((f) => f.replace(/\.json$/, ''));
}
/**
* Read the sidecar record of packs installed by `flecto policies add`. The
* record is provenance only: pack resolution never consults it.
* @param {string} cwd
* @returns {Record<string, { package: string, version: string | null, addedAt: string }>}
*/
function readPackManifest(cwd) {
const manifestPath = resolve(cwd, 'policies', PACK_MANIFEST_FILE);
if (!existsSync(manifestPath)) return {};
try {
const parsed = JSON.parse(readFileSync(manifestPath, 'utf8'));
return isObject(parsed?.packs) ? parsed.packs : {};
} catch {
// Provenance is a nicety; a corrupt sidecar must never break listing.
return {};
}
}
/**
* List every policy pack resolvable from a working directory. Local packs take
* precedence over built-ins using the same order as loadPack().
* @param {string} [cwd]
* @returns {Array<{
* id: string,
* sourcePath: string,
* source: 'builtin' | 'local',
* ruleCount: number,
* overridesBuiltin: boolean,
* package?: string
* }>}
*/
export function listPolicyPacks(cwd = process.cwd()) {
const localDir = resolve(cwd, 'policies');
const localIds = existsSync(localDir)
? readdirSync(localDir)
// Hidden files are never pack ids — this is where the sidecar lives.
.filter((file) => !file.startsWith('.') && /\.(json|yaml|yml)$/.test(file))
.map((file) => file.replace(/\.(json|yaml|yml)$/, ''))
: [];
const manifest = readPackManifest(cwd);
const builtinIds = listBuiltinPackIds();
const builtinIdSet = new Set(builtinIds);
return [...new Set([...builtinIds, ...localIds])]
.sort()
.map((id) => {
const sourcePath = resolvePackPath(cwd, id);
if (!sourcePath) {
throw new Error(`Unable to resolve policy pack "${id}"`);
}
const pack = readPackFile(sourcePath, id);
const isLocal = localIds.includes(id);
const packageName = isLocal && typeof manifest[id]?.package === 'string'
? manifest[id].package
: null;
return {
id,
sourcePath,
source: isLocal ? 'local' : 'builtin',
ruleCount: pack.rules.length,
overridesBuiltin: isLocal && builtinIdSet.has(id),
// Present only for packs installed from npm, so hand-written local
// packs keep the exact shape they have always had.
...(packageName ? { package: packageName } : {}),
};
});
}
/**
* Map either form of a pack name onto the other: the short pack id
* (`deployment-safety`) and the npm package name
* (`flecto-pack-deployment-safety`, optionally scoped).
* @param {string} name
* @returns {{ id: string, packageName: string }}
*/
export function normalizePackPackageName(name) {
const raw = String(name ?? '').trim();
if (!raw) throw new Error('Policy pack name is required');
const scopeMatch = /^(@[^/]+\/)(.+)$/.exec(raw);
const scope = scopeMatch ? scopeMatch[1] : '';
const rest = scopeMatch ? scopeMatch[2] : raw;
const id = rest.startsWith(PACK_PACKAGE_PREFIX) ? rest.slice(PACK_PACKAGE_PREFIX.length) : rest;
// The id becomes a filename under policies/, so it must be a plain segment.
if (!PACK_ID_PATTERN.test(id)) {
throw new Error(
`Invalid policy pack name "${raw}". Use a pack id such as "deployment-safety" or a package name such as "flecto-pack-deployment-safety".`,
);
}
return { id, packageName: `${scope}${PACK_PACKAGE_PREFIX}${id}` };
}
/**
* Locate an installed pack package without loading any of its code.
* @param {string} packageName
* @param {string} cwd
* @returns {string | null} Absolute package directory, or null when not installed.
*/
function resolvePackPackageDir(packageName, cwd) {
// resolve() only computes a path; it never evaluates the target.
const require = createRequire(join(resolve(cwd), 'package.json'));
try {
return dirname(require.resolve(`${packageName}/package.json`));
} catch {
// A package with an "exports" map that omits ./package.json still has one
// on disk, so fall back to the plain node_modules lookup.
}
let dir = resolve(cwd);
for (;;) {
const candidate = join(dir, 'node_modules', ...packageName.split('/'), 'package.json');
if (existsSync(candidate)) return dirname(candidate);
const parent = dirname(dir);
if (parent === dir) return null;
dir = parent;
}
}
/**
* @param {string} packageDir
* @param {string} packageName
* @returns {Record<string, unknown>}
*/
function readPackagePackageJson(packageDir, packageName) {
try {
const parsed = JSON.parse(readFileSync(join(packageDir, 'package.json'), 'utf8'));
return isObject(parsed) ? parsed : {};
} catch (error) {
throw new Error(`Could not read package.json for "${packageName}": ${error.message}`);
}
}
/**
* Find the declarative pack file inside a pack package: a `flecto-pack.*` file
* at the package root, or the path named by its package.json "flecto" field.
* @param {string} packageDir
* @param {Record<string, unknown>} packageJson
* @param {string} packageName
* @returns {string}
*/
function resolvePackFileInPackage(packageDir, packageJson, packageName) {
const declared = packageJson.flecto;
/** @type {string | null} */
let relPath = null;
if (typeof declared === 'string') {
relPath = declared;
} else if (isObject(declared)) {
if (typeof declared.pack !== 'string' || !declared.pack.trim()) {
throw new Error(
`Invalid "flecto" field in ${packageName}: expected { "pack": "<path to pack file>" }.`,
);
}
relPath = declared.pack;
} else if (declared !== undefined) {
throw new Error(
`Invalid "flecto" field in ${packageName}: expected a pack file path or { "pack": "<path>" }.`,
);
}
if (relPath) {
const abs = resolve(packageDir, relPath);
const inside = relative(packageDir, abs);
if (isAbsolute(relPath) || inside.startsWith('..') || isAbsolute(inside)) {
throw new Error(`Invalid "flecto" field in ${packageName}: "${relPath}" escapes the package directory.`);
}
if (!PACK_EXTENSIONS.some((ext) => abs.toLowerCase().endsWith(ext))) {
throw new Error(
`Invalid "flecto" field in ${packageName}: "${relPath}" must be a .json, .yaml, or .yml pack file. Flecto never loads JavaScript from a pack package.`,
);
}
if (!existsSync(abs)) {
throw new Error(`Pack file missing in ${packageName}: "${relPath}" does not exist.`);
}
return abs;
}
for (const candidate of PACK_FILE_CANDIDATES) {
const abs = join(packageDir, candidate);
if (existsSync(abs)) return abs;
}
throw new Error(
`"${packageName}" is not a Flecto policy pack: expected ${PACK_FILE_CANDIDATES.join(', ')} at the package root, or a "flecto" field in its package.json.`,
);
}
/**
* @param {string} packageDir
* @param {Record<string, unknown>} packageJson
* @returns {boolean}
*/
function packageShipsCode(packageDir, packageJson) {
if (packageJson.main || packageJson.exports || packageJson.bin) return true;
try {
return readdirSync(packageDir).some((file) => /\.(c|m)?js$/.test(file));
} catch {
return false;
}
}
/**
* @param {string} cwd
* @param {string} id
* @returns {string[]} Existing local pack files for this id, in resolution order.
*/
function localPackFilesForId(cwd, id) {
return PACK_EXTENSIONS
.map((ext) => resolve(cwd, 'policies', `${id}${ext}`))
.filter((path) => existsSync(path));
}
/**
* @param {string} cwd
* @param {string} id
* @param {{ package: string, version: string | null }} entry
*/
function writePackManifestEntry(cwd, id, entry) {
const manifestPath = resolve(cwd, 'policies', PACK_MANIFEST_FILE);
const packs = readPackManifest(cwd);
packs[id] = { ...entry, addedAt: new Date().toISOString() };
writeFileSync(manifestPath, `${JSON.stringify({ packs }, null, 2)}\n`, 'utf8');
}
/**
* Install a policy pack from an already-installed `flecto-pack-*` npm package
* into `policies/<id>.json`, so the normal resolution order picks it up.
*
* Only declarative JSON/YAML is read — no package code is imported or run.
* @param {string} name Pack id or npm package name.
* @param {{ cwd?: string, force?: boolean }} [options]
* @returns {AddedPolicyPack}
*/
export function addPolicyPackFromPackage(name, options = {}) {
const cwd = options.cwd ?? process.cwd();
const force = Boolean(options.force);
const { id, packageName } = normalizePackPackageName(name);
const packageDir = resolvePackPackageDir(packageName, cwd);
if (!packageDir) {
throw new Error(
`Policy pack package "${packageName}" is not installed. Install it first:\n\n npm install --save-dev ${packageName}\n`,
);
}
const packageJson = readPackagePackageJson(packageDir, packageName);
const packFile = resolvePackFileInPackage(packageDir, packageJson, packageName);
// Full pack validation happens here, before anything is written: a malformed
// third-party pack fails at add time rather than during evaluation.
const pack = readPackFile(packFile, id);
if (pack.id !== id) {
throw new Error(
`Policy pack id mismatch: ${packageName} declares id "${pack.id}", but the package name implies "${id}". Rename the pack id or publish under "${PACK_PACKAGE_PREFIX}${pack.id}".`,
);
}
const existingLocal = localPackFilesForId(cwd, id);
if (existingLocal.length > 0 && !force) {
throw new Error(
`A local policy pack "${id}" already exists: ${existingLocal.join(', ')}. Re-run with --force to overwrite it.`,
);
}
const targetPath = resolve(cwd, 'policies', `${id}.json`);
mkdirSync(dirname(targetPath), { recursive: true });
// Only written when the source pack opts in, so packs that never set it keep
// byte-identical output.
const payload = pack.expandSubtrees
? { id, expandSubtrees: true, rules: pack.rules }
: { id, rules: pack.rules };
writeFileSync(targetPath, `${JSON.stringify(payload, null, 2)}\n`, 'utf8');
writePackManifestEntry(cwd, id, {
package: packageName,
version: typeof packageJson.version === 'string' ? packageJson.version : null,
});
return {
id,
packageName,
packageVersion: typeof packageJson.version === 'string' ? packageJson.version : null,
packFile,
targetPath,
ruleCount: pack.rules.length,
overwritten: existingLocal.includes(targetPath),
overridesBuiltin: existsSync(join(PACKS_DIR, `${id}.json`)),
shadowed: existingLocal.filter((path) => path !== targetPath),
shipsCode: packageShipsCode(packageDir, packageJson),
};
}
/**
* Compile each rule's `match.path`, `afterMatches`, and `afterAnyMatches`
* regular expressions once, at pack-load time, storing them as non-enumerable
* properties on the loaded rule/clause objects. matchClause() runs per change
* event — for a rule with a path match, once per event per rule — so compiling
* here instead of inside that loop turns a `new RegExp(...)` call into a
* property read.
*
* validatePack() has already proven, by this point, that every `match.path`,
* `afterMatches`, and `afterAnyMatches` string constructs a valid RegExp, so
* construction here cannot throw a new error the caller hasn't already seen.
* @param {PolicyPack} pack
*/
function compilePackRegexes(pack, trusted = false) {
for (const rule of pack.rules ?? []) {
compileClauseRegexes(rule, trusted);
for (const clause of rule.allOf ?? []) compileClauseRegexes(clause, trusted);
for (const clause of rule.anyOf ?? []) compileClauseRegexes(clause, trusted);
}
}
/**
* @param {PolicyRule | PolicyMatchClause} clause
* @param {boolean} [trusted]
*/
function compileClauseRegexes(clause, trusted = false) {
if (clause.match?.path !== undefined) {
Object.defineProperty(clause.match, '_pathRegex', {
value: compilePattern(clause.match.path, clause.match.pathFlags ?? '', { trusted }),
enumerable: false,
});
}
if (clause.afterMatches !== undefined) {
Object.defineProperty(clause, '_afterMatchesRegex', {
value: compilePattern(clause.afterMatches, '', { trusted }),
enumerable: false,
});
}
if (clause.afterAnyMatches !== undefined) {
Object.defineProperty(clause, '_afterAnyMatchesRegex', {
value: compilePattern(clause.afterAnyMatches, '', { trusted }),
enumerable: false,
});
}
}
/**
* @param {{ path?: string, pathFlags?: string, _pathRegex?: RegExp }} match
* @returns {RegExp}
*/
function pathRegexFor(match) {
// Packs loaded via loadPack() always carry a pre-compiled regex here. The
// fallback covers a pack built some other way (bypassing loadPack), whose
// provenance is therefore unknown -- so it compiles as UNTRUSTED, which is
// the fail-safe direction but not what it did before RE2. Such a pack using
// lookahead now throws during evaluation rather than at load, and each call
// recompiles. Both are acceptable for a path no shipped caller takes.
return match._pathRegex ?? compilePattern(match.path, match.pathFlags ?? '');
}
/**
* @param {{ afterMatches?: string, _afterMatchesRegex?: RegExp }} clause
* @returns {RegExp}
*/
function afterMatchesRegexFor(clause) {
return clause._afterMatchesRegex ?? compilePattern(clause.afterMatches);
}
/**
* @param {{ afterAnyMatches?: string, _afterAnyMatchesRegex?: RegExp }} clause
* @returns {RegExp}
*/
function afterAnyMatchesRegexFor(clause) {
return clause._afterAnyMatchesRegex ?? compilePattern(clause.afterAnyMatches);
}
/**
* True when `value` is an array carrying at least one string element that
* matches. Deliberately a flat scan: it does not descend into nested arrays or
* objects, because a rule's text should say what it matches without the reader
* having to reason about how deep the walk goes. Non-array values never match,
* which is what keeps `afterMatches` and this predicate from overlapping.
* @param {unknown} value
* @param {RegExp} regex
* @returns {boolean}
*/
function anyElementMatches(value, regex) {
return Array.isArray(value)
&& value.some((element) => typeof element === 'string' && regex.test(element));
}
/**
* @param {PolicyRule} rule
* @param {import('./differ.js').ChangeEvent} change
* @returns {boolean}
*/
function ruleMatches(rule, change) {
const when = rule.when ?? ['added', 'removed', 'changed'];
if (!when.includes(change.type)) return false;
if (!matchClause(rule, change)) return false;
if (rule.allOf?.some((clause) => !matchClause(clause, change))) return false;
if (rule.anyOf && !rule.anyOf.some((clause) => matchClause(clause, change))) return false;
return true;
}
/**
* @param {PolicyMatchClause} clause
* @param {import('./differ.js').ChangeEvent} change
* @returns {boolean}
*/
function matchClause(clause, change) {
const path = change.path ?? '';
const match = clause.match;
if (match?.path && !pathRegexFor(match).test(path)) return false;
if (match?.pathEquals !== undefined && path !== match.pathEquals) return false;
if (match?.pathPrefix !== undefined && !path.startsWith(match.pathPrefix)) return false;
if (Object.prototype.hasOwnProperty.call(clause, 'beforeEquals') && change.before !== clause.beforeEquals) return false;
if (Object.prototype.hasOwnProperty.call(clause, 'afterEquals') && change.after !== clause.afterEquals) return false;
if (clause.beforeIn && !clause.beforeIn.includes(change.before)) return false;
if (clause.afterIn && !clause.afterIn.includes(change.after)) return false;
if (clause.beforeTruthy && !isTruthyToggle(change.before)) return false;
if (clause.afterTruthy && !isTruthyToggle(change.after)) return false;
// Value-shaped secret detection, shared with the masking path so a rule and
// the redaction it triggers never disagree.
if (clause.beforeLooksSecret && !containsSecret(change.before)) return false;
if (clause.afterLooksSecret && !containsSecret(change.after)) return false;
if (clause.afterMatches && (typeof change.after !== 'string' || !afterMatchesRegexFor(clause).test(change.after))) return false;
// The list counterpart, for the change that turns a scalar into a list in
// one edit -- reported as a single `changed` event whose `after` is an array,
// which no scalar predicate can see into.
if (clause.afterAnyMatches && !anyElementMatches(change.after, afterAnyMatchesRegexFor(clause))) return false;
if (clause.numericJump) {
const before = change.before;
const after = change.after;
if (typeof before !== 'number' || typeof after !== 'number') return false;
if (!(before > 0 && after >= before * clause.numericJump.minMultiple)) return false;
}
if (clause.numericDelta) {
const before = change.before;
const after = change.after;
if (typeof before !== 'number' || typeof after !== 'number') return false;
if (Math.abs(after - before) < clause.numericDelta.min) return false;
}
return true;
}
/**
* @param {PolicyRule} rule
* @param {import('./differ.js').ChangeEvent} change
* @returns {string}
*/
function formatMessage(rule, change) {
if (rule.messageTemplate) {
return rule.messageTemplate
.replaceAll('{before}', String(change.before))
.replaceAll('{after}', String(change.after))
.replaceAll('{path}', String(change.path ?? ''));
}
return rule.message ?? `Policy ${rule.id} matched`;
}
/**
* Bracket segment for one array element, mirroring the differ so a synthesized
* path is spelled the same way the differ would have spelled it: a quoted
* identity key when every element carries a unique `id` (then `name`), an index
* otherwise.
* @param {unknown[]} items
* @returns {string[]}
*/
function subtreeArraySegments(items) {
for (const idKey of ['id', 'name']) {
/** @type {string[]} */
const keys = [];
let usable = items.length > 0;
for (const item of items) {
if (!isObject(item) || !Object.hasOwn(item, idKey)) { usable = false; break; }
const value = item[idKey];
if (value == null || typeof value === 'object') { usable = false; break; }
keys.push(JSON.stringify(String(value)));
}
if (usable && new Set(keys).size === keys.length) return keys;
}
return items.map((_, index) => String(index));
}
/**
* Walk a value, collecting every scalar leaf with its full path.
*
* `ancestors` holds the containers on the path currently being walked. A
* recursive YAML anchor (`a: &x\n b: *x`) parses to a genuinely cyclic object,
* and the differ never recurses into an added or removed subtree, so this walk
* is the first thing to enter one. Revisiting an ancestor stops the descent;
* a value merely referenced twice on separate branches is still walked twice.
* @param {unknown} value
* @param {string} basePath
* @param {Array<{ path: string, value: unknown }>} out
* @param {Set<object>} ancestors
*/
function collectLeaves(value, basePath, out, ancestors) {
const isContainer = Array.isArray(value) || isObject(value);
if (isContainer) {
if (ancestors.has(/** @type {object} */ (value))) return;
ancestors.add(/** @type {object} */ (value));
}
if (Array.isArray(value)) {
const segments = subtreeArraySegments(value);
value.forEach((item, index) => collectLeaves(item, `${basePath}[${segments[index]}]`, out, ancestors));
} else if (isObject(value)) {
for (const key of Object.keys(value)) {
collectLeaves(value[key], basePath ? `${basePath}.${key}` : key, out, ancestors);
}
} else {
out.push({ path: basePath, value });
}
if (isContainer) ancestors.delete(/** @type {object} */ (value));
}
/**
* Expand whole-subtree additions and removals into the leaf-level changes they
* imply, keeping the original event alongside them.
*
* The differ reports an added or removed key once, carrying the entire subtree
* as the value — adding a Kubernetes `Service` document, or a container's whole
* `securityContext` block, is a single change at the parent path. Path-anchored
* rules cannot see inside such a value, so a pack that must reason about leaves
* (`…securityContext.privileged`) would silently miss the exact case that
* matters most. Expanding restores one uniform shape: a rule anchored at the
* leaf fires whether the leaf changed in place or arrived with its parent.
*
* Subtrees never overlap, so the total work is linear in the size of the input.
* @param {import('./differ.js').ChangeEvent[]} changes
* @returns {import('./differ.js').ChangeEvent[]}
*/
export function expandChangeSubtrees(changes) {
/** @type {import('./differ.js').ChangeEvent[]} */
const expanded = [];
for (const change of changes) {
expanded.push(change);
if (change.type !== 'added' && change.type !== 'removed') continue;
const side = change.type === 'added' ? 'after' : 'before';
const value = change[side];