Handling load error within subresource integrity check

时光毁灭记忆、已成空白 提交于 2019-12-12 13:08:55

问题


I'm implementing subresource integrity checks. I'd like to implement a fallback such that 1) the browsers loads from my CDN, performs the integrity check and carries on or 2) in the event of failing the integrity check, an embedded script launches and retrieves the needed script from my application server (resource under my control).

I have a simple javascript which catches window.onerror events, but the script is actually detecting an uncaught ReferenceError (my page references a script within the external resource), and not the browser error "Failed to find a valid digest...".

Has anyone found a way to detect the integrity check has failed, and then use javascript to pull the third-party hosted resource from a more trusted location?


回答1:


Take a look at this implementation of SRI-fallback:

https://github.com/cyph/sri-fallback




回答2:


You can check if the loaded resource is present and load a fallback local copy:

<script src="https://code.jquery.com/jquery-1.12.0.min.js" integrity="sha256-Xxq2X+KtazgaGuA2cWR1v3jJsuMJUozyIXDB3e793L8=" crossorigin="anonymous"></script>
<script>
if (!window.jQuery) {
                var script = document.createElement('script');
                script.src = '/local-resources/js/jquery-1.12.0.min.js';
                script.async = false;
                document.head.appendChild(script);
            }
</script>



回答3:


you have to catch the error and do whatever is necessary.

  • Create and attach a MutationObserver
  • add a callback
  • catch the error and act accordingly

Look in both examples below. Borrow whatever is useful. Send a big thank you to the authors ;-)

Here you could find an example https://github.com/cyph/sri-fallback/blob/master/sri-fallback.js

Another very good reading is available here https://aldaris.github.io/dev/security/2018/03/05/subresource-integrity.html

PS: window.onerror is not probably the best approach for you might end up with more errors than expected and to tungle up into many conditions...



来源:https://stackoverflow.com/questions/40408636/handling-load-error-within-subresource-integrity-check

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!