Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[sitecore-jss] [mediaApi] updateImageUrl fix for invalid hash errors on Sitecore #681

Merged
merged 5 commits into from
Apr 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/data/routes/release-notes/en.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ There are [migration instructions](/upgrade-guides/18.0) from JSS 16-based appli
* [React-Native sample] Sitecore logo in header is touchable and will navigate to Home page when click on it.
* [React-Native sample] Removed usage of `dataConversation`.
* [PR #638](https://github.com/Sitecore/jss/pull/638) [samples/nextjs] The sitemap fetcher in `getStaticPaths` now uses pagination to fetch all pages, and the default `pageSize` value can be customized.
* [PR #645](https://github.com/Sitecore/jss/pull/645) Debug logging for SDKs (focused on Next.js) using the [debug](https://www.npmjs.com/package/debug) module.
* [PR #645](https://github.com/Sitecore/jss/pull/645) [Debug logging](/docs/fundamentals/troubleshooting/debug-logging) for SDKs (focused on Next.js) using the [debug](https://www.npmjs.com/package/debug) module.

### Bug Fixes

Expand All @@ -37,6 +37,7 @@ There are [migration instructions](/upgrade-guides/18.0) from JSS 16-based appli
* [React-Native sample] Fix connected tunnel mode for secure (https) Sitecore endpoints.
* [PR #638](https://github.com/Sitecore/jss/pull/638) [sitecore-jss-nextjs] [samples/nextjs] Fix issue with `getStaticPaths`only pre-rendering the first 10 pages.
* [PR #677](https://github.com/Sitecore/jss/pull/677) [sitecore-jss-forms] Fix issue where pre-filled (default) form data isn't removed for multi-valued fields when user de-selects values.
* [PR #681](https://github.com/Sitecore/jss/pull/681) [sitecore-jss] [mediaApi] `updateImageUrl` now *only* switches to JSS media handler prefix if `imageParams` are sent. Otherwise, the original media URL is returned. Fixes hash errors ("ERROR MediaRequestProtection: An invalid/missing hash value was encountered.") from appearing in Sitecore logs.

## Sitecore JSS 16.0 for Sitecore 10.1

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ exports[`<Image /> with network images with direct image object, no value/editab
resizeMode="cover"
source={
Object {
"uri": "https://jssapp/-/jssmedia/myfile.ashx&w=180&h=360",
"uri": "https://jssapp/-/media/myfile.ashx&w=180&h=360",
}
}
style={
Expand All @@ -24,7 +24,7 @@ exports[`<Image /> with network images with style prop with width or height spec
resizeMode="cover"
source={
Object {
"uri": "https://jssapp/-/jssmedia/myfile.ashx&w=180&h=360",
"uri": "https://jssapp/-/media/myfile.ashx&w=180&h=360",
}
}
style={
Expand All @@ -47,7 +47,7 @@ exports[`<Image /> with network images with value/editable image object should r
resizeMode="cover"
source={
Object {
"uri": "https://jssapp/-/jssmedia/myfile.ashx&w=180&h=360",
"uri": "https://jssapp/-/media/myfile.ashx&w=180&h=360",
}
}
style={
Expand Down
14 changes: 7 additions & 7 deletions packages/sitecore-jss-react/.vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,19 @@
"configurations": [
{
"name": "Run mocha",
"type": "node2",
"type": "node",
"request": "launch",
"program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
"stopOnEntry": false,
"args": [
"--compilers",
"js:babel-core/register",
"--require",
"./src/tests/jsdom-setup.js",
"./src/tests/enzyme-setup.js",
"./src/**/*.test.js",
"ts-node/register",
"./src/tests/jsdom-setup.ts",
"./src/tests/enzyme-setup.ts",
"--no-timeouts",
"./dist/test"
"--colors",
"./src/**/*.test.ts",
"./src/**/*.test.tsx"
],
"cwd": "${workspaceRoot}",
"runtimeExecutable": null
Expand Down
21 changes: 15 additions & 6 deletions packages/sitecore-jss-react/src/components/Image.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -181,18 +181,19 @@ describe('<Image />', () => {
id: 'some-id',
style: { width: '100%' },
className: 'the-dude-abides',
imageParams: { foo: 'bar' },
mediaUrlPrefix: /\/([-~]{1})assets\//i,
};
const rendered = mount(<Image {...props} />);

expect(rendered.find('img').prop('src')).to.equal('/~/jssmedia/img/test0.png');
expect(rendered.find('img').prop('src')).to.equal('/~/jssmedia/img/test0.png?foo=bar');

rendered.setProps({
...props,
media: { value: { src: '/-assets/img/test0.png', alt: 'my image' } },
});

expect(rendered.find('img').prop('src')).to.equal('/-/jssmedia/img/test0.png');
expect(rendered.find('img').prop('src')).to.equal('/-/jssmedia/img/test0.png?foo=bar');
});

it('should transform url with direct image object, no value/editable', () => {
Expand All @@ -207,11 +208,12 @@ describe('<Image />', () => {
width: '100%',
},
className: 'the-dude-abides',
imageParams: { foo: 'bar' },
mediaUrlPrefix: /\/([-~]{1})assets\//i,
};
const rendered = mount(<Image {...props} />);

expect(rendered.find('img').prop('src')).to.equal('/~/jssmedia/img/test0.png');
expect(rendered.find('img').prop('src')).to.equal('/~/jssmedia/img/test0.png?foo=bar');

rendered.setProps({
...props,
Expand All @@ -222,7 +224,7 @@ describe('<Image />', () => {
},
});

expect(rendered.find('img').prop('src')).to.equal('/-/jssmedia/img/test0.png');
expect(rendered.find('img').prop('src')).to.equal('/-/jssmedia/img/test0.png?foo=bar');
});

it('should transform url with responsive image object', () => {
Expand All @@ -239,7 +241,10 @@ describe('<Image />', () => {

const rendered = mount(<Image {...props} />);

expect(rendered.find('img').prop('src')).to.equal('/~/jssmedia/img/test0.png');
expect(rendered.find('img').prop('src')).to.equal('/~assets/img/test0.png');
expect(rendered.find('img').prop('srcSet')).to.equal(
'/~/jssmedia/img/test0.png?mw=100 100w, /~/jssmedia/img/test0.png?mw=300 300w'
);

rendered.setProps({
...props,
Expand All @@ -248,9 +253,13 @@ describe('<Image />', () => {
width: 8,
height: 10,
},
imageParams: { foo: 'bar' },
});

expect(rendered.find('img').prop('src')).to.equal('/-/jssmedia/img/test0.png');
expect(rendered.find('img').prop('src')).to.equal('/-/jssmedia/img/test0.png?foo=bar');
expect(rendered.find('img').prop('srcSet')).to.equal(
'/-/jssmedia/img/test0.png?foo=bar&mw=100 100w, /-/jssmedia/img/test0.png?foo=bar&mw=300 300w'
);
});
});

Expand Down
47 changes: 39 additions & 8 deletions packages/sitecore-jss/src/media-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,26 +64,57 @@ describe('getRequiredParams', () => {
});

describe('updateImageUrl', () => {
it('should return original if no params', () => {
const original =
'http://sitecore/-/media/lorem/ipsum.jpg?h=1&w=2&hash=CC5043DC03C6C27F40EDB08CF84AB8670C05D63D';
const updated = updateImageUrl(original);
expect(updated).to.equal(original);
});

it('should override parameters with those provided', () => {
const original = 'http://sitecore/-/media/lorem.png?mh=3&mw=4';
const updated = updateImageUrl(original, { mh: '5', mw: '6' });
const url = URL(updated, true);
expect(url.query.mh).to.equal('5');
expect(url.query.mw).to.equal('6');
});

it('should remove non-required query parameters not provided', () => {
const original =
'http://sitecore/-/media/lorem.png?h=1&w=2&mh=3&mw=4hash=CC5043DC03C6C27F40EDB08CF84AB8670C05D63D';
'http://sitecore/-/media/lorem.png?h=1&w=2&mh=3&mw=4&hash=CC5043DC03C6C27F40EDB08CF84AB8670C05D63D';
const updated = updateImageUrl(original, { mh: '5', mw: '6' });
const url = URL(updated, true);
expect(url.query.mh).to.equal('5');
expect(url.query.mw).to.equal('6');
expect(url.query.hash).to.be.undefined; // eslint-disable-line no-unused-expressions
expect(url.query.h).to.be.undefined;
expect(url.query.w).to.be.undefined;
expect(url.query.hash).to.be.undefined;
});

it('should preserve required query parameters', () => {
const original =
'http://sitecore/-/media/lorem.png?rev=100&db=master&la=en&vs=200&ts=foo&mh=3&mw=4';
const updated = updateImageUrl(original, { mh: '5', mw: '6' });
const url = URL(updated, true);
expect(url.query.mh).to.equal('5');
expect(url.query.mw).to.equal('6');
expect(url.query.rev).to.equal('100');
expect(url.query.db).to.equal('master');
expect(url.query.la).to.equal('en');
expect(url.query.vs).to.equal('200');
expect(url.query.ts).to.equal('foo');
});

it('should replace /-/media/ with /-/jssmedia/', () => {
const original = 'http://sitecore/-/media/lorem/ipsum.jpg';
const updated = updateImageUrl(original);
const updated = updateImageUrl(original, { foo: 'bar' });
const url = URL(updated);
expect(url.pathname).to.startsWith('/-/jssmedia/');
});

it('should replace /~/media/ with /~/jssmedia/', () => {
const original = 'http://sitecore/~/media/lorem/ipsum.jpg';
const updated = updateImageUrl(original);
const updated = updateImageUrl(original, { foo: 'bar' });
const url = URL(updated);
expect(url.pathname).to.startsWith('/~/jssmedia/');
});
Expand All @@ -92,31 +123,31 @@ describe('updateImageUrl', () => {
it('should replace /-assets/ with /-/jssmedia', () => {
const original = 'http://sitecore/-assets/lorem/ipsum.jpg';
const mediaUrlPrefix = /\/([-~]{1})assets\//i;
const updated = updateImageUrl(original, undefined, mediaUrlPrefix);
const updated = updateImageUrl(original, { foo: 'bar' }, mediaUrlPrefix);
const url = URL(updated);
expect(url.pathname).to.startsWith('/-/jssmedia/');
});

it('should replace /~assets/ with /~/jssmedia', () => {
const original = 'http://sitecore/~assets/lorem/ipsum.jpg';
const mediaUrlPrefix = /\/([-~]{1})assets\//i;
const updated = updateImageUrl(original, undefined, mediaUrlPrefix);
const updated = updateImageUrl(original, { foo: 'bar' }, mediaUrlPrefix);
const url = URL(updated);
expect(url.pathname).to.startsWith('/~/jssmedia/');
});

it('should replace /-/assets/ with /-/jssmedia/', () => {
const original = 'http://sitecore/-/assets/lorem/ipsum.jpg';
const mediaUrlPrefix = /\/([-~]{1})\/assets\//i;
const updated = updateImageUrl(original, undefined, mediaUrlPrefix);
const updated = updateImageUrl(original, { foo: 'bar' }, mediaUrlPrefix);
const url = URL(updated);
expect(url.pathname).to.startsWith('/-/jssmedia/');
});

it('should replace /~/assets/ with /~/jssmedia/', () => {
const original = 'http://sitecore/~/assets/lorem/ipsum.jpg';
const mediaUrlPrefix = /\/([-~]{1})\/assets\//i;
const updated = updateImageUrl(original, undefined, mediaUrlPrefix);
const updated = updateImageUrl(original, { foo: 'bar' }, mediaUrlPrefix);
const url = URL(updated);
expect(url.pathname).to.startsWith('/~/jssmedia/');
});
Expand Down
31 changes: 16 additions & 15 deletions packages/sitecore-jss/src/media-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,11 @@ export const getRequiredParams = (qs: { [key: string]: string | undefined }) =>
};

/**
* Receives a Sitecore media URL and replaces `/~/media` or `/-/media` with `/~/jssmedia` or `/-/jssmedia`, respectively.
* Can use `mediaUrlPrefix` in order to use custom checker.
* This replacement allows the JSS media handler to be used for JSS app assets.
* Also, any provided `params` are used as the querystring parameters for the media URL.
* Prepares a Sitecore media URL with `params` for use by the JSS media handler.
* This is done by replacing `/~/media` or `/-/media` with `/~/jssmedia` or `/-/jssmedia`, respectively.
* Provided `params` are used as the querystring parameters for the media URL.
* Can use `mediaUrlPrefix` in order to use a custom prefix.
* If no `params` are sent, the original media URL is returned.
* @param {string} url
* @param {Object} [params]
* @param {RegExp} [mediaUrlPrefix=mediaUrlPrefixRegex]
Expand All @@ -63,6 +64,10 @@ export const updateImageUrl = (
params?: { [key: string]: string | number | undefined } | null,
mediaUrlPrefix: RegExp = mediaUrlPrefixRegex
) => {
if (!params || Object.keys(params).length === 0) {
// if params aren't supplied, no need to run it through JSS media handler
return url;
}
// polyfill node `global` in browser to workaround https://github.com/unshiftio/url-parse/issues/150
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (typeof window !== 'undefined' && !(window as any).global) {
Expand All @@ -71,18 +76,14 @@ export const updateImageUrl = (
}
const parsed = URL(url, {}, true);

const query = { ...(params || parsed.query) };
ambrauer marked this conversation as resolved.
Show resolved Hide resolved

// In case if imageParams provided
if (params) {
const requiredParams = getRequiredParams(parsed.query);
const requiredParams = getRequiredParams(parsed.query);

Object.entries(requiredParams).forEach(([key, param]) => {
if (param) {
query[key] = param;
}
});
}
const query = { ...params };
Object.entries(requiredParams).forEach(([key, param]) => {
if (param) {
query[key] = param;
}
});

parsed.set('query', query);

Expand Down