Skip to content

Commit

Permalink
fix: more secure path extension replacement
Browse files Browse the repository at this point in the history
  • Loading branch information
tada5hi committed Feb 16, 2023
1 parent 7063185 commit 51f2056
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
29 changes: 26 additions & 3 deletions src/data-source/options/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,33 @@ export function changeTSToJSPath(

const tsExtensions = ['ts', 'cts', 'mts'];
for (let i = 0; i < tsExtensions.length; i++) {
const baseExtensionIndex = base.indexOf(tsExtensions[i]);
if (baseExtensionIndex !== -1) {
base = base.replace(tsExtensions[i], jsExtensions[i]);
const regex = new RegExp(`(\\.${tsExtensions[i]}|${tsExtensions[i]})`, 'g');
let matchesSum : number | undefined;
const matches = base.match(regex);
if (Array.isArray(matches)) {
matchesSum = matches.length;
}

let matchesCounter = 0;

const bracketIndex = base.lastIndexOf('{');
base = base.replace(
regex,
(...args) => {
matchesCounter++;

// if the file extension name comes after the last bracket index,
// we can be pretty sure that the extension name is not part of a filename
if (
(args[2] >= bracketIndex && bracketIndex !== -1) ||
(bracketIndex === -1 && matchesCounter === matchesSum)
) {
return args[0].startsWith('.') ? `.${jsExtensions[i]}` : jsExtensions[i];
}

return args[0];
},
);
}

if (baseIndex !== -1) {
Expand Down
12 changes: 12 additions & 0 deletions test/unit/connection/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,18 @@ describe('src/connection/utils.ts', () => {
srcPath = '/src/entities.ts';
expect(changeTSToJSPath(srcPath)).toEqual('/dist/entities.js');

srcPath = 'src/ts.{ts}';
expect(changeTSToJSPath(srcPath)).toEqual('dist/ts.{js}');

srcPath = 'src/ts.ts.{ts,cts}';
expect(changeTSToJSPath(srcPath)).toEqual('dist/ts.ts.{js,cjs}');

srcPath = 'src/*.{ts,cts}';
expect(changeTSToJSPath(srcPath)).toEqual('dist/*.{js,cjs}');

srcPath = 'src/ts.ts';
expect(changeTSToJSPath(srcPath)).toEqual('dist/ts.js');

const srcPaths = ['src/entities.ts', './src/entities.ts'];
for(let i=0; i<srcPaths.length; i++) {
srcPath = srcPaths[i];
Expand Down

0 comments on commit 51f2056

Please sign in to comment.