-
Notifications
You must be signed in to change notification settings - Fork 0
/
integrity-and-fetch.html
190 lines (185 loc) · 6.83 KB
/
integrity-and-fetch.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>Demo Page for Subresource Integrity and Fetch</title>
<meta name=description content="demo page for Subresource Integrity (SRI) and fetching resource such as image">
<meta http-equiv=X-UA-Compatible content="IE=Edge">
<meta name=viewport content="width=device-width,initial-scale=1.0">
<meta name=robots content=index,follow>
<link rel=canonical href=https://laysent.github.io/subresource-integrity-demo/integrity-and-fetch.html />
<link
href=./main.css
rel=stylesheet
integrity="sha512-mbzzgGIjfEC93ZP2SML7m8+qpNxg4KQH5s28RcwDGfgB8mpa9MbIlSg1GDd6IMeHowT1owpRqNnSJK7Feob12g=="
crossorigin=anonymous
/>
<link
href=https://cdnjs.cloudflare.com/ajax/libs/prism/1.15.0/themes/prism.css
rel=stylesheet
integrity="sha256-/Kfdz9pXGPe+bFF+TtxHqbg6F9c3Rb0jN48uy+2b/do="
crossorigin=anonymous
/>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-31656866-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-31656866-1');
</script>
</head>
<body>
<main>
<h1>Subresource Integrity and Fetch</h1>
<section>
<h2>explaination</h2>
<p>
By default, browser only support <em>integrity</em> for script and stylesheet. However,
<em>fetch</em> can provides option <em>integrity</em> as well, which makes it possible to
use this feature for other resources, such as image in this demo page.
</p>
<p>
In this demo, it uses <em>fetch</em> to download an image resource with <em>integrity</em>
option provided. The browser will validate after resource is being downloaded. When succeed,
image will be shown, otherwise an error will be catched and app can do further steps (for
example, load a backup resource from own server).
</p>
<ul>
<li>
<em>correct-integrity=true</em> to set correct hash in <em>integrity</em>.
</li>
<li>
<em>correct-integrity=false</em> to set incorrect hash in <em>integrity</em>.
</li>
</ul>
</section>
<section>
<h2>code example</h2>
<p>
Following is an example written using React. Image will be loaded with <em>integrity</em>
validation. Loading component is used when still fetching the resource.
</p>
<pre><code class="language-jsx">import React from 'react';
function getFetch(src, integrity) {
return fetch(src, { integrity, mode: 'cors' })
.then(response => response.blob())
.then(blob => URL.createObjectURL(blob));
};
const ImageComponent =
/**
* React.memo is used to ensure that
* request will be fetched once only.
*/
React.memo(({ src, integrity, alt, ...rest }) => {
/**
* Use React.lazy with React.Suspense
* to display loading effect when still
* fetching the resource.
*/
const Component = React.lazy(
() => getFetch(src, integrity)
.then(
url => ({
default: (props) => (
React.useEffect(() => () => {
URL.revokeObjectURL(url);
}, []);
<img src={url} alt={props.alt} {...props} />
),
}),
error => ({
default: () => (
<div>Error: {error.toString()}</div>
);
}),
),
);
return <Component alt={alt} {...rest} />;
});
const Image = ({ src, integrity, alt, ...rest }) => {
return (
<React.Suspense fallback={<div>loading...</div>}>
<ImageComponent
src={src}
integrity={integrity}
alt={alt}
{...rest}
/>
</React.Suspense>
);
};
export default Image;
</code></pre>
</section>
<section>
<h2>drawback</h2>
<p>
<em>fetch</em> does not have the same request priority as image or other resources.
Meanwhile, browser will not share cache when resource is being used again from a native
approach, such as an <img> tag.
</p>
</section>
<section>
<h2>Status of resources loading</h2>
<img id=img alt=pikachu style="width:120px;height:120px;color:#ddd" />
</section>
<section>
<a href=./index.html>Back</a>
</section>
<footer>
© 2018 LaySent.
</footer>
</main>
<script>
const querystring = location.search.substr(1).split('&').reduce((acc, pair) => {
var parts = pair.split('=');
acc[parts[0]] = parts[1];
return acc;
}, { });
const correctIntegrity = 'sha256-zr0qbVJgRXq631jLJkxyQ1EPdv7hBYBd4JuGg7SUZks=';
const incorrectIntegrity = 'sha256-wrong';
const useIncorrectIntegrity = querystring['correct-integrity'] && querystring['correct-integrity'] === 'false';
const integrity = useIncorrectIntegrity ? incorrectIntegrity : correctIntegrity;
const img = document.getElementById('img');
/**
* `cors` mode is required, to ensure response can be tranformed to blob using JavaScript
* and later used in <img> tag as `src`. CDN server should support it to make it work.
*/
fetch('./pikachu.png', { integrity, mode: 'cors' })
.then(
/**
* Convert response to URL, so that it can be used directly in `src` attribute.
* Re-assigning same image URL to image `src` won't work, as browser will not re-use
* downloaded resource as cache, because the request type are different, one is `fetch`
* and one is `png`.
* Check network tab in Chrome DevTool for details.
*/
(resp) => resp.blob().then(blob => img.src = URL.createObjectURL(blob)),
/**
* Further actions can be made when error occurs, including
* + inform server for possible issue
* + use backup resource instead
*/
(e) => {
console.error(e);
/* inform server for possible issue */
// navigator.sendBeacon(/* blablabla */);
img.src = ''; // should be a backup resource here
}
);
</script>
<script
type=text/javascript
src=https://cdnjs.cloudflare.com/ajax/libs/prism/1.15.0/prism.min.js
integrity="sha256-jc6y1s/Y+F+78EgCT/lI2lyU7ys+PFYrRSJ6q8/R8+o="
crossorigin=anonymous
></script>
<script
type=text/javascript
src=https://cdnjs.cloudflare.com/ajax/libs/prism/1.15.0/components/prism-jsx.min.js
integrity="sha256-8Kkghwrxh0GwDxr3zJ3EhJMVF2w7+tw5mZZmLN+bg4c="
crossorigin=anonymous
></script>
</body>
</html>