Skip to content

Commit

Permalink
Sanitize uploaded file path (#325)
Browse files Browse the repository at this point in the history
Co-authored-by: Ryan Clayton <[email protected]>
Co-authored-by: Chris Millar <[email protected]>
  • Loading branch information
3 people authored Jan 18, 2025
1 parent ae4eb18 commit 77a78fc
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
11 changes: 9 additions & 2 deletions blocks/browse/da-list/helpers/drag-n-drop.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,18 +81,25 @@ export async function getFullEntryList(entries) {
return files.filter((file) => file);
}

export function sanitizePath(path) {
const pathArray = path.split('/');
const sanitizedArray = pathArray.map((element) => element.replaceAll(/[^a-zA-Z0-9.]/g, '-').toLowerCase());
return [...sanitizedArray].join('/');
}

export async function handleUpload(list, fullpath, file) {
const { data, path } = file;
const formData = new FormData();
formData.append('data', data);
const opts = { method: 'POST', body: formData };
const postpath = `${fullpath}${path}`;
const sanitizedPath = sanitizePath(path);
const postpath = `${fullpath}${sanitizedPath}`;

try {
await daFetch(`${DA_ORIGIN}/source${postpath}`, opts);
file.imported = true;

const [displayName] = path.split('/').slice(1);
const [displayName] = sanitizedPath.split('/').slice(1);
const [filename, ...rest] = displayName.split('.');
const ext = rest.pop();
const rejoined = [filename, ...rest].join('.');
Expand Down
9 changes: 8 additions & 1 deletion test/unit/blocks/browse/helpers/helpers.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { expect } from '@esm-bundle/chai';
import { stub } from 'sinon';
import { getFullEntryList, handleUpload } from '../../../../../blocks/browse/da-list/helpers/drag-n-drop.js';
import { getFullEntryList, handleUpload, sanitizePath } from '../../../../../blocks/browse/da-list/helpers/drag-n-drop.js';

const goodEntry = {
isDirectory: false,
Expand Down Expand Up @@ -81,4 +81,11 @@ describe('Upload and format', () => {
const item = await handleUpload(list, fullpath, packagedFile);
expect(item).to.exist;
});

it('Returns sanitize file path', async () => {
const path = '/new folder/geo_metrixx.jpg';
const item = sanitizePath(path);
console.log('item', item);
expect(item).to.equal('/new-folder/geo-metrixx.jpg');
});
});

0 comments on commit 77a78fc

Please sign in to comment.