forked from forcedotcom/salesforcedx-templates
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbaseGenerator.ts
More file actions
684 lines (610 loc) · 18.3 KB
/
Copy pathbaseGenerator.ts
File metadata and controls
684 lines (610 loc) · 18.3 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
/*
* Copyright (c) 2020, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import * as nodeFs from 'fs';
import * as path from 'path';
import { render } from 'ejs';
import { nls } from '../i18n';
import {
DEFAULT_API_VERSION,
dirnameTemplatesDefault,
} from '../utils/constants';
import {
CreateOutput,
GeneratorContext,
TemplateOptions,
} from '../utils/types';
type Changes = {
created: string[];
conflicted: string[];
identical: string[];
forced: string[];
};
interface FsError extends Error {
code: string;
}
export async function setCustomTemplatesRootPathOrGitRepo(
pathOrRepoUri?: string,
forceLoadingRemoteRepo = false,
fs: typeof nodeFs = nodeFs
): Promise<string | undefined> {
if (pathOrRepoUri === undefined) {
return;
}
try {
// if pathOrRepoUri is valid url, load the repo
const url = new URL(pathOrRepoUri);
if (process.env.ESBUILD_PLATFORM !== 'web' && url) {
const { loadCustomTemplatesGitRepo } = await import(
'../service/gitRepoUtils'
);
return await loadCustomTemplatesGitRepo(url, forceLoadingRemoteRepo, fs);
}
} catch (error) {
const err = error as FsError;
if (err.code !== 'ERR_INVALID_URL') {
throw error;
}
const localTemplatesPath = pathOrRepoUri;
if (fs.existsSync(localTemplatesPath)) {
return localTemplatesPath;
} else {
throw new Error(
nls.localize('localCustomTemplateDoNotExist', localTemplatesPath)
);
}
}
}
/**
* Look up package version of @salesforce/templates package to supply a default API version
*/
export function getDefaultApiVersion(): string {
return DEFAULT_API_VERSION;
}
abstract class NotYeoman {
public changes: Changes = {
created: [],
conflicted: [],
identical: [],
forced: [],
};
protected readonly _fs: typeof nodeFs;
protected readonly _cwd: string;
private _sourceRoot: string;
private _destinationRoot: string;
public constructor(context?: GeneratorContext, cwd?: string) {
this._fs = context?.fs ?? nodeFs;
this._cwd = cwd ?? process.cwd();
const defaultTemplatesRoot =
context?.templatesRootPath ?? dirnameTemplatesDefault;
this._sourceRoot = this.sourceRoot(defaultTemplatesRoot);
this._destinationRoot = this.destinationRoot(this._cwd);
}
public destinationPath(...dest: string[]): string {
let filepath = path.join(...dest);
if (!path.isAbsolute(filepath)) {
filepath = path.join(this.destinationRoot(), filepath);
}
return filepath;
}
public destinationRoot(rootPath?: string) {
if (typeof rootPath === 'string') {
this._destinationRoot = path.resolve(rootPath);
if (!this._fs.existsSync(this._destinationRoot)) {
this._fs.mkdirSync(this._destinationRoot, { recursive: true });
}
}
return this._destinationRoot || this._cwd;
}
public sourceRoot(rootPath?: string): string {
if (rootPath) {
this._sourceRoot = path.resolve(rootPath);
}
return this._sourceRoot;
}
public templatePath(...dest: string[]): string {
let filepath = path.join(...dest);
if (!path.isAbsolute(filepath)) {
filepath = path.join(this.sourceRoot(), filepath);
}
return filepath;
}
public async render(
source: string,
destination: string,
data?: Record<string, unknown>
): Promise<void> {
const template = await this._fs.promises.readFile(source, 'utf8');
const rendered = render(template, data ?? {});
if (rendered) {
const relativePath = path.relative(this._cwd, destination);
const existing = await this._fs.promises
.readFile(destination, 'utf8')
.catch(() => null);
if (existing) {
if (rendered.trim() === existing.trim()) {
this.register('identical', relativePath);
return;
} else {
this.register('conflicted', relativePath);
this.register('forced', relativePath);
}
} else {
this.register('created', relativePath);
}
const dir = path.dirname(destination);
await this._fs.promises.mkdir(dir, { recursive: true });
await this._fs.promises.writeFile(destination, rendered);
}
}
private register(verb: keyof Changes, file: string): void {
this.changes[verb].push(file);
}
}
// Allowlist-based validator for custom EJS templates.
// Instead of trying to block dangerous patterns (infinite bypass surface),
// we only permit the narrow subset of JS that templates legitimately need.
const ALLOWED_EXPRESSION_CALL_TARGETS = new Set([
'replace',
'uuid',
'join',
'toString',
'trim',
'toLowerCase',
'toUpperCase',
'slice',
'substring',
'indexOf',
'includes',
'split',
'concat',
'startsWith',
'endsWith',
'padStart',
'padEnd',
]);
const ALLOWED_SCRIPTLET_METHODS = new Set([
'forEach',
'map',
'filter',
'includes',
'indexOf',
'length',
'push',
'join',
'some',
'every',
'find',
'findIndex',
'slice',
'concat',
'keys',
'values',
'entries',
]);
function extractEjsTags(template: string): { type: string; code: string }[] {
const tags: { type: string; code: string }[] = [];
let i = 0;
while (i < template.length) {
const start = template.indexOf('<%', i);
if (start === -1) {
break;
}
const afterOpen = start + 2;
if (afterOpen >= template.length) {
break;
}
const firstChar = template[afterOpen];
if (firstChar === '#') {
const end = template.indexOf('%>', afterOpen);
i = end === -1 ? template.length : end + 2;
continue;
}
let type: string;
let codeStart: number;
if (firstChar === '=' || firstChar === '-') {
type = firstChar;
codeStart = afterOpen + 1;
} else {
type = '%';
codeStart = afterOpen;
}
let pos = codeStart;
let code = '';
let found = false;
while (pos < template.length) {
const ch = template[pos];
if (ch === "'" || ch === '"' || ch === '`') {
const quote = ch;
pos++;
while (pos < template.length && template[pos] !== quote) {
if (template[pos] === '\\') {
pos++;
}
pos++;
}
pos++;
} else if (template[pos] === '%' && template[pos + 1] === '>') {
code = template.slice(codeStart, pos);
found = true;
pos += 2;
break;
} else {
pos++;
}
}
if (!found) {
code = template.slice(codeStart);
pos = template.length;
}
tags.push({ type, code: code.trim() });
i = pos;
}
return tags;
}
function isSafeBracketContent(inner: string): boolean {
if (/^\d+$/.test(inner)) {
return true;
}
if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(inner)) {
return true;
}
const strLitMatch = inner.match(/^(['"])([a-zA-Z_$][\w.]*)\1$/);
if (strLitMatch) {
return true;
}
return false;
}
function containsDangerousBrackets(code: string): boolean {
const bracketContent = /\[([^\]]*)\]/g;
let m;
while ((m = bracketContent.exec(code)) !== null) {
if (!isSafeBracketContent(m[1].trim())) {
return true;
}
}
return false;
}
function isSimpleExpression(code: string): boolean {
const blocked =
/\b(function|class|new|delete|typeof|void|this|process|global|globalThis|require|import|module|eval|Function|constructor|__proto__|prototype|Reflect|Proxy|Object\s*\.\s*(?:create|assign|definePropert|getOwnPropertyNames|getPrototypeOf|setPrototypeOf)|Array\s*\.\s*from|String\s*\.\s*fromCharCode|Symbol|Buffer|setTimeout|setInterval|setImmediate|clearTimeout|clearInterval|queueMicrotask|Promise|async|await|yield|return|throw|try|catch|finally|while|for|do|switch|with)\b/;
if (blocked.test(code)) {
return false;
}
if (containsDangerousBrackets(code)) {
return false;
}
if (/`[^`]*\$\{/.test(code)) {
return false;
}
if (/(?<![=!<>])=(?!=)/.test(code)) {
return false;
}
const callPattern = /\.([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/g;
let m;
while ((m = callPattern.exec(code)) !== null) {
if (!ALLOWED_EXPRESSION_CALL_TARGETS.has(m[1])) {
return false;
}
}
const bareCalls = /(?<![.\w])([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/g;
while ((m = bareCalls.exec(code)) !== null) {
if (!ALLOWED_EXPRESSION_CALL_TARGETS.has(m[1])) {
return false;
}
}
return true;
}
function isAllowedScriptlet(code: string): boolean {
const statements = code.split(/[;\n]/).map((s) => s.trim()).filter(Boolean);
for (const stmt of statements) {
if (!isAllowedStatement(stmt)) {
return false;
}
}
return true;
}
function isAllowedStatement(stmt: string): boolean {
const hardBlocked =
/\b(process|global|globalThis|require|import|module|eval|Function|Reflect|Proxy|Buffer|setTimeout|setInterval|setImmediate|clearTimeout|clearInterval|queueMicrotask|__dirname|__filename|constructor|__proto__|prototype|with|yield|async|await)\b/;
if (hardBlocked.test(stmt)) {
return false;
}
if (/`[^`]*\$\{/.test(stmt)) {
return false;
}
if (containsDangerousBrackets(stmt)) {
return false;
}
if (/^\}?\s*\)?\s*;?\s*\}?\s*;?$/.test(stmt)) {
return true;
}
if (stmt === '{') {
return true;
}
if (/^(?:else\s+)?if\s*\(/.test(stmt)) {
return isSimpleCondition(stmt);
}
if (/^}\s*else\s*\{?$/.test(stmt) || stmt === 'else {' || stmt === 'else') {
return true;
}
if (/^for\s*\(/.test(stmt)) {
return isSimpleForLoop(stmt);
}
if (/^\w[\w.]*\s*\.\s*(forEach|map|filter|some|every|find|findIndex)\s*\(/.test(stmt)) {
return isSimpleIterator(stmt);
}
if (/^(?:const|let|var)\s+/.test(stmt)) {
return isSimpleDeclaration(stmt);
}
if (/^[a-zA-Z_$][\w.]*\s*\.\s*(push|pop|shift|unshift)\s*\(/.test(stmt)) {
return isSimpleMethodCall(stmt);
}
return false;
}
function isSimpleCondition(stmt: string): boolean {
const condMatch = stmt.match(/^(?:else\s+)?if\s*\(([\s\S]*)\)\s*\{?\s*$/);
if (!condMatch) {
return false;
}
const cond = condMatch[1];
const hardBlocked =
/\b(process|global|globalThis|require|import|module|eval|Function|Reflect|Proxy|constructor|__proto__)\b/;
if (hardBlocked.test(cond)) {
return false;
}
if (/`[^`]*\$\{/.test(cond)) {
return false;
}
const callPattern = /\.([a-zA-Z_$]\w*)\s*\(/g;
let m;
while ((m = callPattern.exec(cond)) !== null) {
if (!ALLOWED_SCRIPTLET_METHODS.has(m[1])) {
return false;
}
}
if (containsDangerousBrackets(cond)) {
return false;
}
return true;
}
function isSimpleForLoop(stmt: string): boolean {
if (/^for\s*\(\s*(?:const|let|var)\s+\[?\s*\w+(?:\s*,\s*\w+)*\s*\]?\s+(?:of|in)\s+/.test(stmt)) {
const hardBlocked = /\b(process|global|globalThis|require|import|module|eval|Function|Reflect|Proxy|constructor|__proto__)\b/;
return !hardBlocked.test(stmt);
}
return false;
}
function isSimpleIterator(stmt: string): boolean {
const hardBlocked =
/\b(process|global|globalThis|require|import|module|eval|Function|Reflect|Proxy|constructor|__proto__)\b/;
if (hardBlocked.test(stmt)) {
return false;
}
if (/`[^`]*\$\{/.test(stmt)) {
return false;
}
if (containsDangerousBrackets(stmt)) {
return false;
}
return true;
}
function isSimpleDeclaration(stmt: string): boolean {
const hardBlocked =
/\b(process|global|globalThis|require|import|module|eval|Function|Reflect|Proxy|constructor|__proto__|prototype)\b/;
if (hardBlocked.test(stmt)) {
return false;
}
if (/`[^`]*\$\{/.test(stmt)) {
return false;
}
if (/\bfunction\b/.test(stmt)) {
return false;
}
if (/=>\s*\{/.test(stmt)) {
return false;
}
if (containsDangerousBrackets(stmt)) {
return false;
}
return true;
}
function isSimpleMethodCall(stmt: string): boolean {
const hardBlocked =
/\b(process|global|globalThis|require|import|module|eval|Function|Reflect|Proxy|constructor|__proto__)\b/;
if (hardBlocked.test(stmt)) {
return false;
}
if (/`[^`]*\$\{/.test(stmt)) {
return false;
}
if (containsDangerousBrackets(stmt)) {
return false;
}
return true;
}
function normalizeCode(code: string): string {
let result = code;
// Strip JS comments that could hide content from analysis
result = result.replace(/\/\*[\s\S]*?\*\//g, ' ');
result = result.replace(/\/\/[^\n]*/g, ' ');
// Resolve string concatenations: 'a' + 'b' -> 'ab'
let prev = '';
while (result !== prev) {
prev = result;
result = result.replace(/'([^'\\]*)'\s*\+\s*'([^'\\]*)'/g, "'$1$2'");
result = result.replace(/"([^"\\]*)"\s*\+\s*"([^"\\]*)"/g, '"$1$2"');
result = result.replace(/'([^'\\]*)'\s*\+\s*"([^"\\]*)"/g, "'$1$2'");
result = result.replace(/"([^"\\]*)"\s*\+\s*'([^'\\]*)'/g, '"$1$2"');
}
// Normalize hex escapes in strings: '\x63' -> 'c'
result = result.replace(/\\x([0-9a-fA-F]{2})/g, (_, hex) =>
String.fromCharCode(parseInt(hex, 16))
);
// Normalize unicode escapes: '\u0063' -> 'c'
result = result.replace(/\\u([0-9a-fA-F]{4})/g, (_, hex) =>
String.fromCharCode(parseInt(hex, 16))
);
return result;
}
export function validateCustomTemplate(
templateContent: string,
templatePath: string
): void {
const tags = extractEjsTags(templateContent);
for (const tag of tags) {
const code = normalizeCode(tag.code);
if (tag.type === '=' || tag.type === '-') {
if (!isSimpleExpression(code)) {
throw new Error(
`Custom template "${templatePath}" contains disallowed code in expression tag: ${tag.code.slice(0, 80)}`
);
}
} else {
if (!isAllowedScriptlet(code)) {
throw new Error(
`Custom template "${templatePath}" contains disallowed code in scriptlet tag: ${tag.code.slice(0, 80)}`
);
}
}
}
}
export abstract class BaseGenerator<
TOptions extends TemplateOptions
> extends NotYeoman {
/**
* Set by sourceRootWithPartialPath called in generator
*/
public builtInTemplatesRootPath?: string;
protected outputdir: string;
protected apiversion: string;
private customTemplatesRootPath: string | undefined;
protected readonly templatesRootPath: string | undefined;
/**
* The constructor for the SfGenerator.
*
* @param options SfGenerator specific options.
* @param context optional generator context for fs and template path injection
*/
constructor(
public options: TOptions,
context?: GeneratorContext,
cwd?: string
) {
super(context, cwd);
this.templatesRootPath = context?.templatesRootPath;
this.apiversion = options.apiversion ?? getDefaultApiVersion();
this.outputdir = options.outputdir ?? this._cwd;
this.validateOptions();
}
/**
* Set source root to built-in templates or custom templates root if available.
* @param partialPath the relative path from the templates folder to templates root folder.
*/
public sourceRootWithPartialPath(partialPath: string): void {
this.builtInTemplatesRootPath = path.join(
this.templatesRootPath ?? dirnameTemplatesDefault ?? '',
partialPath
);
// set generator source directory to custom templates root if available
if (!this.customTemplatesRootPath) {
this.sourceRoot(path.join(this.builtInTemplatesRootPath));
} else {
if (
this._fs.existsSync(
path.join(this.customTemplatesRootPath, partialPath)
)
) {
this.sourceRoot(path.join(this.customTemplatesRootPath, partialPath));
}
}
}
public templatePath(...paths: string[]): string {
// The template paths are relative to the generator's source root
// If we have set a custom template root, the source root should have already been set.
// Otherwise we'll fallback to the built-in templates
const customPath = super.templatePath(...paths);
if (this._fs.existsSync(customPath)) {
return customPath;
} else {
// files that are builtin and not in the custom template folder
return super.templatePath(
path.join(this.builtInTemplatesRootPath!, ...paths)
);
}
}
public async render(
source: string,
destination: string,
data?: Record<string, unknown>
): Promise<void> {
const isBuiltIn = this.builtInTemplatesRootPath && source.startsWith(this.builtInTemplatesRootPath);
if (!isBuiltIn) {
const template = await this._fs.promises.readFile(source, 'utf8');
validateCustomTemplate(template, source);
const rendered = render(template, data ?? {});
if (rendered) {
const relativePath = path.relative(this._cwd, destination);
const existing = await this._fs.promises
.readFile(destination, 'utf8')
.catch(() => null);
if (existing) {
if (rendered.trim() === existing.trim()) {
this.changes.identical.push(relativePath);
return;
} else {
this.changes.conflicted.push(relativePath);
this.changes.forced.push(relativePath);
}
} else {
this.changes.created.push(relativePath);
}
const dir = path.dirname(destination);
await this._fs.promises.mkdir(dir, { recursive: true });
await this._fs.promises.writeFile(destination, rendered);
}
return;
}
return super.render(source, destination, data);
}
public async run(opts?: {
cwd?: string;
customTemplatesRootPathOrGitRepo?: string;
sourceRootPartial?: string;
}): Promise<CreateOutput> {
const cwd = opts?.cwd ?? this._cwd;
this.customTemplatesRootPath = await setCustomTemplatesRootPathOrGitRepo(
opts?.customTemplatesRootPathOrGitRepo,
false,
this._fs
);
await this.generate();
const created = [...this.changes.created, ...this.changes.forced];
const outputDir = path.resolve(cwd, this.outputdir);
const rawOutput = nls.localize('RawOutput', [
outputDir,
[
...(this.changes.created ?? []).map((file) => ` create ${file}`),
...(this.changes.identical ?? []).map((file) => ` identical ${file}`),
...(this.changes.conflicted ?? []).map((file) => ` conflict ${file}`),
...(this.changes.forced ?? []).map((file) => ` force ${file}`),
].join('\n') + '\n',
]);
return {
outputDir,
created,
rawOutput,
};
}
/**
* Validate provided options
*/
public abstract validateOptions(): void;
/**
* Generate the files
*/
public abstract generate(): Promise<void>;
}