url-sanitizer 2.0.12 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +118 -175
- package/dist/url-sanitizer-wo-dompurify.min.js +1 -1
- package/dist/url-sanitizer-wo-dompurify.min.js.map +3 -3
- package/dist/url-sanitizer.min.js +4 -3
- package/dist/url-sanitizer.min.js.map +3 -3
- package/package.json +5 -4
- package/src/lib/iana/uri-schemes.json +1 -1
- package/src/mjs/file-reader.js +4 -8
- package/src/mjs/sanitizer.js +3 -3
- package/types/mjs/file-reader.d.ts +2 -2
- package/types/mjs/sanitizer.d.ts +16 -16
package/README.md
CHANGED
|
@@ -5,77 +5,111 @@
|
|
|
5
5
|
[](https://www.npmjs.com/package/url-sanitizer)
|
|
6
6
|
[](https://github.com/asamuzaK/urlSanitizer/releases)
|
|
7
7
|
|
|
8
|
-
URL sanitizer for Node.js, browsers and
|
|
9
|
-
|
|
10
|
-
It also
|
|
11
|
-
|
|
8
|
+
A robust URL sanitizer for Node.js, browsers, and websites.
|
|
9
|
+
It sanitizes not only regular URLs but also deeply inspects `data` URLs and `blob` URLs.
|
|
10
|
+
It also provides built-in utilities to parse URLs and verify URI schemes.
|
|
11
|
+
|
|
12
|
+
## Features
|
|
13
|
+
|
|
14
|
+
* **Secure by Default**: Automatically denies `javascript:` and `vbscript:` schemes.
|
|
15
|
+
* **Deep Data URL Inspection**: Parses, decodes (including base64), and sanitizes nested data URLs.
|
|
16
|
+
* **Blob URL Support**: Converts and sanitizes blob URLs into safe data URLs (async).
|
|
17
|
+
* **DOMPurify Integration**: Safely purifies HTML/SVG content embedded within data URLs.
|
|
18
|
+
* **Pure ESM with TypeScript Support**: Works seamlessly across modern environments like Node.js, Deno, websites, and browsers (including WebExtensions).
|
|
19
|
+
|
|
20
|
+
## Table of Contents
|
|
21
|
+
* [Install](#install)
|
|
22
|
+
* [Usage](#usage)
|
|
23
|
+
* [API Reference](#api-reference)
|
|
24
|
+
* [sanitizeURL(url, opt)](#sanitizeurlurl-opt)
|
|
25
|
+
* [sanitizeURLSync(url, opt)](#sanitizeurlsyncurl-opt)
|
|
26
|
+
* [parseURL(url)](#parseurlurl)
|
|
27
|
+
* [parseURLSync(url)](#parseurlsyncurl)
|
|
28
|
+
* [isURI(uri)](#isuriuri)
|
|
29
|
+
* [isURISync(uri)](#isurisyncuri)
|
|
30
|
+
* [urlSanitizer Instance](#urlsanitizer)
|
|
31
|
+
* [Acknowledgments](#acknowledgments)
|
|
12
32
|
|
|
13
33
|
## Install
|
|
14
34
|
|
|
15
|
-
|
|
35
|
+
### Node.js
|
|
36
|
+
|
|
37
|
+
``` shell
|
|
16
38
|
npm i url-sanitizer
|
|
17
39
|
```
|
|
18
40
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
41
|
+
### Deno
|
|
42
|
+
|
|
43
|
+
You can import directly in your code without installing:
|
|
44
|
+
``` javascript
|
|
45
|
+
import urlSanitizer from "npm:url-sanitizer";
|
|
46
|
+
```
|
|
22
47
|
|
|
23
|
-
|
|
48
|
+
### Browsers and Websites
|
|
24
49
|
|
|
25
|
-
|
|
26
|
-
If you use it, make sure DOMPurify is exposed globally, e.g. `window.DOMPurify`.
|
|
50
|
+
Standalone ESM builds are available in the `dist/` directory:
|
|
27
51
|
|
|
52
|
+
* node_modules/url-sanitizer/dist/url-sanitizer.min.js
|
|
53
|
+
* node_modules/url-sanitizer/dist/url-sanitizer-wo-dompurify.min.js
|
|
54
|
+
|
|
55
|
+
Alternatively, download them from [Releases](https://github.com/asamuzaK/urlSanitizer/releases).
|
|
56
|
+
**NOTE:** url-sanitizer-wo-dompurify.min.js is a lightweight build without [DOMPurify](https://www.npmjs.com/package/dompurify) bundled.
|
|
57
|
+
If you use this build, ensure DOMPurify is exposed globally (e.g., `window.DOMPurify`), otherwise the sanitizer will throw an error at runtime.
|
|
28
58
|
|
|
29
59
|
## Usage
|
|
30
60
|
|
|
31
|
-
```javascript
|
|
61
|
+
``` javascript
|
|
32
62
|
import urlSanitizer, {
|
|
33
63
|
isURI, isURISync, parseURL, parseURLSync, sanitizeURL, sanitizeURLSync
|
|
34
64
|
} from 'url-sanitizer';
|
|
35
65
|
```
|
|
36
66
|
|
|
67
|
+
## API Reference
|
|
37
68
|
|
|
38
|
-
|
|
69
|
+
### sanitizeURL(url, opt)
|
|
39
70
|
|
|
40
|
-
|
|
41
|
-
* `blob`, `data` and `file` schemes must be explicitly allowed.
|
|
42
|
-
* Given a `blob` URL, returns a sanitized `data` URL.
|
|
71
|
+
Sanitizes the given URL asynchronously.
|
|
43
72
|
|
|
44
|
-
|
|
73
|
+
* `blob`, `data`, and `file` schemes must be explicitly allowed.
|
|
74
|
+
* Given a blob URL, it returns a sanitized **data** URL.
|
|
45
75
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
*
|
|
76
|
+
#### Parameters
|
|
77
|
+
|
|
78
|
+
* url **string** URL input.
|
|
79
|
+
* opt **object?** Options.
|
|
80
|
+
* opt.allow **Array<string>?** Array of allowed schemes, e.g., ['data'].
|
|
81
|
+
* opt.deny **Array<string>?** Array of denied schemes, e.g., ['web+foo'].
|
|
82
|
+
* opt.only **Array<string>?** Array of specific schemes to allow, e.g., ['git', 'https'].
|
|
51
83
|
`only` takes precedence over `allow` and `deny`.
|
|
52
84
|
|
|
53
|
-
Returns **
|
|
85
|
+
**Returns** **Promise<string?>** Sanitized URL, nullable.
|
|
86
|
+
|
|
87
|
+
#### Samples
|
|
54
88
|
|
|
55
|
-
|
|
56
|
-
|
|
89
|
+
Sanitize tags and quotes:
|
|
90
|
+
``` javascript
|
|
57
91
|
const res1 = await sanitizeURL('https://example.com/?<script>alert(1)</script>');
|
|
58
92
|
// => 'https://example.com/'
|
|
59
93
|
|
|
60
94
|
const res1_2 = await sanitizeURL('https://example.com/" onclick="alert(1)"');
|
|
61
95
|
// => 'https://example.com/'
|
|
96
|
+
```
|
|
62
97
|
|
|
63
|
-
|
|
64
|
-
|
|
98
|
+
Parse and sanitize data URLs:
|
|
99
|
+
``` javascript
|
|
65
100
|
const res2 = await sanitizeURL('data:text/html,<div><script>alert(1);</script></div><p onclick="alert(2)"></p>', {
|
|
66
101
|
allow: ['data']
|
|
67
|
-
})
|
|
102
|
+
});
|
|
68
103
|
// => 'data:text/html,%3Cdiv%3E%3C/div%3E%3Cp%3E%3C/p%3E'
|
|
69
104
|
|
|
70
105
|
console.log(decodeURIComponent(res2));
|
|
71
106
|
// => 'data:text/html,<div></div><p></p>'
|
|
72
107
|
|
|
73
|
-
|
|
74
|
-
// Also can parse and sanitize base64 encoded data
|
|
108
|
+
// Also can parse and sanitize base64 encoded data:
|
|
75
109
|
const base64data3 = btoa('<div><script>alert(1);</script></div>');
|
|
76
110
|
const res3 = await sanitizeURL(`data:text/html;base64,${base64data3}`, {
|
|
77
111
|
allow: ['data']
|
|
78
|
-
})
|
|
112
|
+
});
|
|
79
113
|
// => 'data:text/html,%3Cdiv%3E%3C/div%3E'
|
|
80
114
|
|
|
81
115
|
console.log(decodeURIComponent(res3));
|
|
@@ -87,9 +121,10 @@ const res3_2 = await sanitizeURL(`data:text/html;base64,${base64data3_2}`);
|
|
|
87
121
|
|
|
88
122
|
console.log(decodeURIComponent(res3_2));
|
|
89
123
|
// => 'data:text/html,<div><img></div>'
|
|
124
|
+
```
|
|
90
125
|
|
|
91
|
-
|
|
92
|
-
|
|
126
|
+
Parse and sanitize blob URLs:
|
|
127
|
+
``` javascript
|
|
93
128
|
const blob4 = new Blob(['<svg><g onload="alert(1)"/></svg>'], {
|
|
94
129
|
type: 'image/svg+xml'
|
|
95
130
|
});
|
|
@@ -101,16 +136,18 @@ const res4 = await sanitizeURL(url4, {
|
|
|
101
136
|
|
|
102
137
|
console.log(decodeURIComponent(res4));
|
|
103
138
|
// => 'data:image/svg+xml,<svg><g></g></svg>'
|
|
139
|
+
```
|
|
104
140
|
|
|
105
|
-
|
|
106
|
-
|
|
141
|
+
Denies if the scheme matches the `deny` list:
|
|
142
|
+
``` javascript
|
|
107
143
|
const res5 = await sanitizeURL('web+foo://example.com', {
|
|
108
144
|
deny: ['web+foo']
|
|
109
145
|
});
|
|
110
146
|
// => null
|
|
147
|
+
```
|
|
111
148
|
|
|
112
|
-
|
|
113
|
-
|
|
149
|
+
Allows only if the scheme matches the `only` list:
|
|
150
|
+
``` javascript
|
|
114
151
|
const res6 = await sanitizeURL('http://example.com', {
|
|
115
152
|
only: ['data', 'git', 'https']
|
|
116
153
|
});
|
|
@@ -121,7 +158,6 @@ const res6_2 = await sanitizeURL('https://example.com/"onmouseover="alert(1)"',
|
|
|
121
158
|
});
|
|
122
159
|
// => 'https://example.com/'
|
|
123
160
|
|
|
124
|
-
|
|
125
161
|
// `only` also allows combination of the schemes in the list
|
|
126
162
|
const res7 = await sanitizeURL('git+https://example.com/foo.git?<script>alert(1)</script>', {
|
|
127
163
|
only: ['data', 'git', 'https']
|
|
@@ -129,53 +165,38 @@ const res7 = await sanitizeURL('git+https://example.com/foo.git?<script>alert(1)
|
|
|
129
165
|
// => 'git+https://example.com/foo.git'
|
|
130
166
|
```
|
|
131
167
|
|
|
168
|
+
### sanitizeURLSync(url, opt)
|
|
132
169
|
|
|
133
|
-
|
|
170
|
+
Synchronous version of `sanitizeURL()`.
|
|
134
171
|
|
|
135
|
-
Synchronous version of the [sanitizeURL()](#sanitizeurlurl-opt).
|
|
136
172
|
* `data` and `file` schemes must be explicitly allowed.
|
|
137
|
-
* `blob` scheme is not supported
|
|
138
|
-
Use async [sanitizeURL()](#sanitizeurlurl-opt) for `blob`.
|
|
173
|
+
* `blob` scheme is not supported and will return `null`. Use the async version for `blob`.
|
|
139
174
|
|
|
175
|
+
### parseURL(url)
|
|
140
176
|
|
|
141
|
-
|
|
177
|
+
Parses the given URL asynchronously.
|
|
142
178
|
|
|
143
|
-
|
|
144
|
-
* Blob URLs are simply parsed and not yet sanitized.
|
|
179
|
+
* Blob URLs are simply parsed and not yet sanitized at this stage.
|
|
145
180
|
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
* `url` **[string][1]** URL input.
|
|
149
|
-
|
|
150
|
-
Returns **[Promise][5]<[ParsedURL](#parsedurl)>** Result.
|
|
181
|
+
#### Parameters
|
|
151
182
|
|
|
152
|
-
|
|
183
|
+
* url **string** URL input.
|
|
153
184
|
|
|
154
|
-
|
|
185
|
+
**Returns** **Promise<ParsedURL>** Result.
|
|
155
186
|
|
|
156
|
-
|
|
187
|
+
#### ParsedURL
|
|
157
188
|
|
|
158
|
-
|
|
189
|
+
An object with additional properties based on the standard [URL](https://developer.mozilla.org/ja/docs/Web/API/URL) API.
|
|
159
190
|
|
|
160
|
-
* `input` **
|
|
161
|
-
* `valid` **
|
|
162
|
-
* `data` **
|
|
163
|
-
* `data.mime` **
|
|
164
|
-
* `data.base64` **
|
|
165
|
-
* `data.data` **
|
|
166
|
-
* `href` **
|
|
167
|
-
* `origin` **[string][1]?** Scheme, domain and port of the sanitized URL.
|
|
168
|
-
* `protocol` **[string][1]?** Protocol scheme of the sanitized URL.
|
|
169
|
-
* `username` **[string][1]?** Username specified before the domain name.
|
|
170
|
-
* `password` **[string][1]?** Password specified before the domain name.
|
|
171
|
-
* `host` **[string][1]?** Domain and port of the sanitized URL.
|
|
172
|
-
* `hostname` **[string][1]?** Domain of the sanitized URL.
|
|
173
|
-
* `port` **[string][1]?** Port number of the sanitized URL.
|
|
174
|
-
* `pathname` **[string][1]?** Path of the sanitized URL.
|
|
175
|
-
* `search` **[string][1]?** Query string of the sanitized URL.
|
|
176
|
-
* `hash` **[string][1]?** Fragment identifier of the sanitized URL.
|
|
191
|
+
* `input` **string** URL input.
|
|
192
|
+
* `valid` **boolean** Is valid URI.
|
|
193
|
+
* `data` **object?** Parsed result of data URL, nullable.
|
|
194
|
+
* `data.mime` **string?** MIME type.
|
|
195
|
+
* `data.base64` **boolean?** Is base64 encoded.
|
|
196
|
+
* `data.data` **string?** Data part of the data URL.
|
|
197
|
+
* `href`, `origin`, `protocol`, `username`, `password`, `host`, `hostname`, `port`, `pathname`, `search`, `hash` — **string?** Properties same as the standard URL API.
|
|
177
198
|
|
|
178
|
-
```javascript
|
|
199
|
+
``` javascript
|
|
179
200
|
const res1 = await parseURL('javascript:alert(1)');
|
|
180
201
|
/* => {
|
|
181
202
|
input: 'javascript:alert(1)',
|
|
@@ -249,25 +270,24 @@ const res5 = await parseURL(url5);
|
|
|
249
270
|
} */
|
|
250
271
|
```
|
|
251
272
|
|
|
273
|
+
### parseURLSync(url)
|
|
252
274
|
|
|
253
|
-
|
|
275
|
+
Synchronous version of `parseURL()`.
|
|
254
276
|
|
|
255
|
-
|
|
277
|
+
### isURI(uri)
|
|
256
278
|
|
|
279
|
+
Verifies if the given URI is valid and registered.
|
|
257
280
|
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
Verify if the given URI is valid and registered.
|
|
281
|
+
#### Parameters
|
|
261
282
|
|
|
262
|
-
|
|
283
|
+
* uri **string** URI input.
|
|
263
284
|
|
|
264
|
-
|
|
285
|
+
**Returns** **Promise<boolean>** Result.
|
|
265
286
|
|
|
266
|
-
|
|
267
|
-
* Always `true` for `web+*` and `ext+*` schemes, except `web+javascript`, `web+vbscript`, `ext+javascript`, `ext+vbscript`.
|
|
287
|
+
* Always `true` for `web+*` and `ext+*` schemes (except `web+javascript`, `web+vbscript`, `ext+javascript`, and `ext+vbscript`).
|
|
268
288
|
* `false` for `javascript` and `vbscript` schemes.
|
|
269
289
|
|
|
270
|
-
```javascript
|
|
290
|
+
``` javascript
|
|
271
291
|
const res1 = await isURI('https://example.com/foo');
|
|
272
292
|
// => true
|
|
273
293
|
|
|
@@ -287,122 +307,45 @@ const res6 = await isURI('web+javascript:alert(1)');
|
|
|
287
307
|
// => false
|
|
288
308
|
```
|
|
289
309
|
|
|
310
|
+
### isURISync(uri)
|
|
290
311
|
|
|
291
|
-
|
|
312
|
+
Synchronous version of `isURI()`.
|
|
292
313
|
|
|
293
|
-
|
|
314
|
+
### urlSanitizer
|
|
294
315
|
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
## urlSanitizer
|
|
298
|
-
|
|
299
|
-
Instance of the sanitizer.
|
|
316
|
+
The instance of the sanitizer.
|
|
300
317
|
|
|
301
|
-
|
|
318
|
+
#### urlSanitizer.get()
|
|
302
319
|
|
|
303
|
-
Get a list of registered URI schemes.
|
|
320
|
+
Get a list of registered URI schemes (includes [IANA registered schemes](https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml) by default).
|
|
304
321
|
|
|
305
|
-
|
|
306
|
-
*
|
|
307
|
-
* Historical schemes omitted.
|
|
308
|
-
* `moz-extension` scheme added.
|
|
309
|
-
* Also includes custom schemes added via [urlSanitizer.add()](#urlsanitizeraddscheme).
|
|
310
|
-
|
|
311
|
-
```javascript
|
|
312
|
-
const schemes = urlSanitizer.get();
|
|
313
|
-
// => ['aaa', 'aaas', 'about', 'acap', 'acct', ...]
|
|
314
|
-
```
|
|
322
|
+
* Historical schemes are omitted.
|
|
323
|
+
* `moz-extension` scheme is added.
|
|
315
324
|
|
|
316
|
-
|
|
325
|
+
#### urlSanitizer.has(scheme)
|
|
317
326
|
|
|
318
327
|
Check if the given scheme is registered.
|
|
319
328
|
|
|
320
|
-
####
|
|
321
|
-
|
|
322
|
-
* `scheme` **[string][1]** Scheme.
|
|
329
|
+
#### urlSanitizer.add(scheme)
|
|
323
330
|
|
|
324
|
-
|
|
331
|
+
Add a scheme to the list of registered URI schemes (throws if `javascript` or `vbscript`).
|
|
325
332
|
|
|
326
|
-
|
|
327
|
-
const res1 = urlSanitizer.has('https');
|
|
328
|
-
// => true
|
|
329
|
-
|
|
330
|
-
const res2 = urlSanitizer.has('foo');
|
|
331
|
-
// => false
|
|
332
|
-
```
|
|
333
|
-
|
|
334
|
-
### urlSanitizer.add(scheme)
|
|
335
|
-
|
|
336
|
-
Add a scheme to the list of registered URI schemes.
|
|
337
|
-
* `javascript` and `vbscript` schemes can not be registered. It throws.
|
|
338
|
-
|
|
339
|
-
#### Parameters
|
|
340
|
-
|
|
341
|
-
* `scheme` **[string][1]** Scheme.
|
|
342
|
-
|
|
343
|
-
Returns **[Array][4]<[string][1]>** Array of registered URI schemes.
|
|
344
|
-
|
|
345
|
-
```javascript
|
|
346
|
-
console.log(urlSanitizer.has('foo'));
|
|
347
|
-
// => false
|
|
348
|
-
|
|
349
|
-
const res = urlSanitizer.add('foo');
|
|
350
|
-
// => ['aaa', 'aaas', 'about', 'acap', ... 'foo', ...]
|
|
351
|
-
|
|
352
|
-
console.log(urlSanitizer.has('foo'));
|
|
353
|
-
// => true
|
|
354
|
-
```
|
|
355
|
-
|
|
356
|
-
### urlSanitizer.remove(scheme)
|
|
333
|
+
#### urlSanitizer.remove(scheme)
|
|
357
334
|
|
|
358
335
|
Remove a scheme from the list of registered URI schemes.
|
|
359
336
|
|
|
360
|
-
####
|
|
361
|
-
|
|
362
|
-
* `scheme` **[string][1]** Scheme.
|
|
337
|
+
#### urlSanitizer.reset()
|
|
363
338
|
|
|
364
|
-
|
|
365
|
-
* `true` if the scheme is successfully removed, `false` otherwise.
|
|
366
|
-
|
|
367
|
-
```javascript
|
|
368
|
-
console.log(urlSanitizer.has('aaa'));
|
|
369
|
-
// => true
|
|
370
|
-
|
|
371
|
-
const res1 = urlSanitizer.remove('aaa');
|
|
372
|
-
// => true
|
|
373
|
-
|
|
374
|
-
console.log(urlSanitizer.has('aaa'));
|
|
375
|
-
// => false
|
|
376
|
-
|
|
377
|
-
const res2 = urlSanitizer.remove('foo');
|
|
378
|
-
// => false
|
|
379
|
-
```
|
|
380
|
-
|
|
381
|
-
### urlSanitizer.reset()
|
|
382
|
-
|
|
383
|
-
Reset sanitizer.
|
|
384
|
-
|
|
385
|
-
Returns **void**
|
|
386
|
-
|
|
387
|
-
---
|
|
339
|
+
Reset registered schemes to the default list and clear internal cache.
|
|
388
340
|
|
|
389
341
|
## Acknowledgments
|
|
390
342
|
|
|
391
|
-
The following resources have been of great help in the development of the URL Sanitizer
|
|
343
|
+
The following resources have been of great help in the development of the URL Sanitizer:
|
|
392
344
|
|
|
393
345
|
* [DOMPurify](https://www.npmjs.com/package/dompurify)
|
|
394
346
|
* [Uniform Resource Identifier (URI) Schemes - IANA](https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml)
|
|
395
347
|
* [Encoding -- determine the character encoding of a text file. - file/file](https://github.com/file/file/blob/master/src/encoding.c)
|
|
396
348
|
|
|
397
349
|
---
|
|
398
|
-
Copyright (c) 2023 [asamuzaK (Kazz)](https://github.com/asamuzaK/)
|
|
399
|
-
|
|
400
|
-
[1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
|
|
401
350
|
|
|
402
|
-
[
|
|
403
|
-
|
|
404
|
-
[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
|
|
405
|
-
|
|
406
|
-
[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array
|
|
407
|
-
|
|
408
|
-
[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise
|
|
351
|
+
Copyright (c) 2023 [asamuzaK (Kazz)](https://github.com/asamuzaK/)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var{DOMPurify:N}=globalThis;var H=/^[\w+/=-]+$/;var S=/data:[\w#&+./;=-]*,/,D=/data:[\w#&+./;=^]*base64,[\w+/=-]+/i,q=/data:[\w#&+./;=-]*,[^\x22]+/g,X=/&#(x(?:00)?[\dA-F]{2}|0?\d{1,3});?/gi,Y=/^(?:application\/(?:[\w#&.;-]+\+)?x|image\/svg\+x|text\/(?:ht|x))ml;?/;var Q=/^[a-z][\da-z+.-]*$/,J=/^(?:ext|web)\+[a-z]+$/,j=/(?:java|vb)script/,A=/(?:java|vb)script|blob/,M=/%(?:22|27|3C|3E)|[\x22\x27<>]/,K=/^%[\dA-F]{2}$/i;var g=t=>Object.prototype.toString.call(t).slice(8,-1),d=t=>typeof t=="string"||t instanceof String;var{FileReader:V}=globalThis;var L=[7,8,9,10,11,12,13,27,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,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,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255];var C=["aaa","aaas","about","acap","acct","acd","acr","adiumxtra","adt","afp","afs","agtp","aim","amss","android","appdata","apt","ar","ari","ark","at","attachment","aw","barion","beshare","bitcoin","bitcoincash","bl","blob","bluetooth","bolo","brid","browserext","cabal","caip","calculator","callto","cap","cast","casts","chrome","chrome-extension","cid","coap","coaps","com-eventbrite-attendee","content","content-type","crid","cstr","cvs","dab","dat","data","dav","dhttp","diaspora","dict","did","dilithium3","dis","dlna-playcontainer","dlna-playsingle","dnp","dns","dntp","doi","donau","dpp","drm","dtmi","dtn","dvb","dvx","dweb","ed2k","eid","elsi","embedded","ens","esim","ethereum","example","facetime","feed","feedready","fido","file","finger","first-run-pen-experience","fish","fm","ftp","fuchsia-pkg","geo","gg","git","gitoid","gizmoproject","go","gopher","graph","gtalk","h323","ham","hcap","hcp","hs20","http","https","hxxp","hxxps","hydrazone","hyper","i0","iax","ibi","ibi-","icap","icon","ilstring","im","imap","info","iotdisco","ipfs","ipn","ipns","ipp","ipps","irc","irc6","ircs","iris","iris.beep","iris.lwz","iris.xpc","iris.xpcs","isostore","itms","jabber","jar","jms","keyparc","lastfm","lbry","ldap","ldaps","leaptofrogans","lid","linkid","lorawan","lpa","lvlt","machineProvisioningProgressReporter","magnet","mailto","maps","market","matrix","message","microsoft.windows.camera","microsoft.windows.camera.multipicker","microsoft.windows.camera.picker","mid","mms","mongodb","moz","moz-extension","mqtt","mqtts","ms-access","ms-appinstaller","ms-browser-extension","ms-calculator","ms-drive-to","ms-enrollment","ms-excel","ms-eyecontrolspeech","ms-gamebarservices","ms-gamingoverlay","ms-getoffice","ms-help","ms-infopath","ms-inputapp","ms-launchremotedesktop","ms-lockscreencomponent-config","ms-media-stream-id","ms-meetnow","ms-mixedrealitycapture","ms-mobileplans","ms-newsandinterests","ms-officeapp","ms-people","ms-personacard","ms-powerpoint","ms-project","ms-publisher","ms-recall","ms-remotedesktop","ms-remotedesktop-launch","ms-restoretabcompanion","ms-screenclip","ms-screensketch","ms-search","ms-search-repair","ms-secondary-screen-controller","ms-secondary-screen-setup","ms-settings","ms-settings-airplanemode","ms-settings-bluetooth","ms-settings-camera","ms-settings-cellular","ms-settings-cloudstorage","ms-settings-connectabledevices","ms-settings-displays-topology","ms-settings-emailandaccounts","ms-settings-language","ms-settings-location","ms-settings-lock","ms-settings-nfctransactions","ms-settings-notifications","ms-settings-power","ms-settings-privacy","ms-settings-proximity","ms-settings-screenrotation","ms-settings-wifi","ms-settings-workplace","ms-spd","ms-stickers","ms-sttoverlay","ms-transit-to","ms-useractivityset","ms-uup","ms-virtualtouchpad","ms-visio","ms-walk-to","ms-whiteboard","ms-whiteboard-cmd","ms-widgetboard","ms-widgets","ms-word","msnim","msrp","msrps","mss","mt","mtqp","mtrust","mumble","mupdate","mvn","mvrp","mvrps","news","nfs","ni","nih","nntp","notes","num","ocf","oid","onenote","onenote-cmd","opaquelocktoken","openid","openpgp4fpr","otpauth","palm","paparazzi","payto","pkcs11","platform","pop","pres","proxy","psyc","pttp","pwid","qb","query","quic-transport","redis","rediss","reload","res","resource","rmi","rsync","rtmfp","rtmp","rtsp","rtsps","rtspu","sarif","secondlife","secret-token","service","session","sftp","sgn","shc","shelter","sieve","simpleledger","simplex","sip","sips","skype","smb","smp","sms","smtp","snmp","soap.beep","soap.beeps","soldat","spacify","spiffe","spotify","ssb","ssh","starknet","steam","stun","stuns","submit","svn","swh","swid","swidpath","tag","taler","teamspeak","teapot","teapots","tel","teliaeid","telnet","tftp","things","thismessage","tip","tn3270","tool","turn","turns","tv","udp","unreal","upn","urn","ut2004","uuid-in-package","v-event","vemmi","ventrilo","ves","view-source","vnc","vscode","vscode-insiders","vsls","w3","wasm","wasm-js","wcr","web3","webcal","wifi","ws","wss","wtai","wyciwyg","xcompute","xcon","xcon-userid","xfire","xftp","xmlrpc.beep","xmlrpc.beeps","xmpp","xrcp","xri","ymsgr","z39.50r","z39.50s"];var W=t=>{if(!d(t))throw new TypeError(`Expected String but got ${g(t)}.`);let e=[];for(let s of t)e.push(`%${s.charCodeAt(0).toString(16).toUpperCase()}`);return e.join("")},Z=t=>{d(t)&&K.test(t)&&(t=t.toUpperCase());let[e,s,r,i,o,a]=["&","#","<",">",'"',"'"].map(W),c;return t===e?c=`${e}amp;`:t===r?c=`${e}lt;`:t===i?c=`${e}gt;`:t===o?c=`${e}quot;`:t===a?c=`${e}${s}39;`:c=t,c},ee=t=>{if(d(t)){if(!H.test(t))throw new Error(`Invalid base64 data: ${t}`)}else throw new TypeError(`Expected String but got ${g(t)}.`);let e=atob(t),s=Uint8Array.from([...e].map(o=>o.charCodeAt(0))),r=new Set(L),i;return s.every(o=>r.has(o))?i=e.replace(/\s/g,W):i=t,i},P=(t,e=0)=>{if(!d(t))throw new TypeError(`Expected String but got ${g(t)}.`);if(Number.isInteger(e)){if(e>16)throw new Error("Character references nested too deeply.")}else throw new TypeError(`Expected Number but got ${g(e)}.`);let s=decodeURIComponent(t);if(/&#/.test(s)){let r=new Set(L),i=[...s.matchAll(X)].reverse();for(let o of i){let[a,c]=o,l;if(/^x[\dA-F]+/i.test(c)?l=parseInt(`0${c}`,16):/^\d+/.test(c)&&(l=parseInt(c)),Number.isInteger(l)){let{index:u}=o,[p,n]=[s.substring(0,u),s.substring(u+a.length)];r.has(l)?(s=`${p}${String.fromCharCode(l)}${n}`,(/#x?$/.test(p)||/^#(?:x(?:00)?[2-7]|\d)/.test(n))&&(s=P(s,++e))):l<256&&(s=`${p}${n}`)}}}return s},te=t=>new Promise((e,s)=>{let r=new V;r.addEventListener("error",()=>s(r.error)),r.addEventListener("abort",()=>e(r.result)),r.addEventListener("load",()=>e(r.result)),r.readAsDataURL(t)}),k=class{#e;constructor(){this.#e=new Set(C)}get(){return[...this.#e]}has(e){return this.#e.has(e)}add(e){if(d(e)){if(j.test(e)||!Q.test(e))throw new Error(`Invalid scheme: ${e}`)}else throw new TypeError(`Expected String but got ${g(e)}.`);return this.#e.add(e),[...this.#e]}remove(e){return this.#e.delete(e)}verify(e){let s;if(d(e))try{let{protocol:r}=new URL(e),i=r.replace(/:$/,""),o=i.split("+");s=!j.test(i)&&J.test(i)||o.every(a=>this.#e.has(a))}catch{s=!1}return!!s}reset(){this.#e.clear();for(let e of C)this.#e.add(e)}};var O=class extends k{#e;#t;constructor(){super(),this.#e=0,this.#t=new Set}replace(e){if(!d(e))throw new TypeError(`Expected String but got ${g(e)}.`);let s=e;if(S.test(s)){let i=[...s.matchAll(q)].reverse();for(let o of i){let[a]=o;D.test(a)&&([a]=D.exec(a)),this.#e++,this.#t.add(a);let c=this.sanitize(a,{allow:["data"]}),{index:l}=o,[u,p]=[s.substring(0,l),s.substring(l+a.length)];c?s=`${u}${c}${p}`:s=`${u}${p}`}}return s}purify(e){if(!d(e))throw new TypeError(`Expected String but got ${g(e)}.`);let s=N.sanitize(decodeURIComponent(e));return s&&S.test(s)&&(s=this.replace(s)),s=s.replace(/(?:#|%23)$/,"").replace(/(?<!(?:#|%23).*)(?:\?|%3F)$/,""),encodeURI(s)}sanitize(e,s){if(this.#e>16)throw this.#e=0,new Error("Data URLs nested too deeply.");let{allow:r,deny:i,only:o}=s??{},a=new Map([["blob",!1],["data",!1],["file",!1],["javascrpt",!1],["vbscript",!1]]),c=new Set,l=!1;if(Array.isArray(o)&&o.length){let p=super.get();for(let m of p)a.set(m,!1);let n=Object.values(o);for(let m of n)if(d(m)&&(m=m.trim(),!A.test(m))){if(super.has(m))a.set(m,!0);else{try{super.add(m)}catch{}super.has(m)&&(a.set(m,!0),c.add(m))}!l&&a.has(m)&&(l=a.get(m))}}else{if(Array.isArray(r)&&r.length){let p=Object.values(r);for(let n of p)if(d(n)&&(n=n.trim(),!A.test(n)))if(super.has(n))a.set(n,!0);else{try{super.add(n)}catch{}super.has(n)&&(a.set(n,!0),c.add(n))}}if(Array.isArray(i)&&i.length){let p=Object.values(i);for(let n of p)d(n)&&(n=n.trim(),n&&a.set(n,!1))}}let u;if(super.verify(e)){let{hash:p,href:n,pathname:m,protocol:U,search:x}=new URL(e),E=U.replace(/:$/,""),G=E.split("+"),_;if(l)_=G.every(y=>a.get(y));else for(let[y,R]of a.entries())if(_=R||E!==y&&G.every(f=>f!==y),!_)break;if(_){let y=G.includes("data"),R,f=n;if(y){let[v,...z]=m.split(","),$=`${z.join(",")}${x}${p}`,T=v.split(";"),I=T[T.length-1]==="base64",h=$;I&&(h=ee($));try{let F=P(h).trim(),{protocol:se}=new URL(F);se.replace(/:$/,"").split("+").some(re=>A.test(re))&&(f="")}catch{}let B=S.test(h);h!==$||B?B?h=this.replace(h):this.#t.has(e)?this.#t.delete(e):R=!0:this.#t.has(e)?this.#t.delete(e):R=!0,(!v||Y.test(v))&&(h=this.purify(h)),f&&h?(I&&h!==$&&T.pop(),f=`${E}:${T.join(";")},${h}`):f=""}else R=!0;if(!y&&M.test(f)){let v=M.exec(f),{index:z}=v;f=f.substring(0,z).replace(/[?&]$/,"")}f?(u=f.replace(/%26/g,Z),R&&(this.#e=0)):this.#e=0}c.size&&c.forEach(y=>{super.remove(y)})}return u||null}parse(e,s){if(!d(e))throw new TypeError(`Expected String but got ${g(e)}.`);let r=new Map([["input",e]]),i;if(this.verify(e)){let{protocol:o}=new URL(e);o==="blob:"?i=e:i=this.sanitize(e,s??{allow:["data","file"]})}if(i){let o=new URL(i),{pathname:a,protocol:c}=o,u=c.replace(/:$/,"").split("+").includes("data");if(r.set("valid",!0),u){let p=new Map,[n,...m]=a.split(","),U=`${m.join(",")}`,x=n.split(";"),E=x[x.length-1]==="base64";E&&x.pop(),p.set("mime",x.join(";")),p.set("base64",E),p.set("data",U),r.set("data",Object.fromEntries(p))}else r.set("data",null);for(let p in o){let n=o[p];d(n)&&r.set(p,n)}}else r.set("valid",!1);return Object.fromEntries(r)}reset(){super.reset(),this.#e=0,this.#t.clear()}},b=new O,ce=async(t,e={allow:[],deny:[],only:[]})=>{let s;if(t&&d(t)){let r;try{let{protocol:i}=new URL(t);r=i.replace(/:$/,"")}catch{}if(r==="blob"){let{allow:i,deny:o,only:a}=e;if(Array.isArray(i)&&i.includes("blob")&&!(Array.isArray(o)&&o.includes("blob"))||Array.isArray(a)&&a.includes("blob")){let c;try{c=await fetch(t).then(l=>l.blob()).then(te)}catch{}if(c){if(Array.isArray(a))a.includes("data")||a.push("data");else if(Array.isArray(i)&&(i.includes("data")||i.push("data"),Array.isArray(o)&&o.includes("data"))){let l=o.indexOf("data");o.splice(l,1)}s=b.sanitize(c,e)}}URL.revokeObjectURL(t)}else r&&(s=b.sanitize(t,e))}return s||null},pe=(t,e)=>{let s;if(t&&d(t)){let r;try{let{protocol:i}=new URL(t);r=i.replace(/:$/,"")}catch{}r==="blob"?URL.revokeObjectURL(t):r&&(s=b.sanitize(t,e))}return s||null},le=async t=>b.parse(t),me=t=>b.parse(t),de=async t=>b.verify(t),fe=t=>b.verify(t),he=b;export{he as default,de as isURI,fe as isURISync,le as parseURL,me as parseURLSync,ce as sanitizeURL,pe as sanitizeURLSync};
|
|
1
|
+
var N={sanitize:(...t)=>{if(globalThis?.DOMPurify)return globalThis.DOMPurify.sanitize(...t);let e=["DOMPurify is not available.","Ensure DOMPurify is exposed globally (e.g., window.DOMPurify)."];throw new Error(e.join(" "))}};var H=/^[\w+/=-]+$/;var S=/data:[\w#&+./;=-]*,/,G=/data:[\w#&+./;=^]*base64,[\w+/=-]+/i,q=/data:[\w#&+./;=-]*,[^\x22]+/g,X=/&#(x(?:00)?[\dA-F]{2}|0?\d{1,3});?/gi,Y=/^(?:application\/(?:[\w#&.;-]+\+)?x|image\/svg\+x|text\/(?:ht|x))ml;?/;var Q=/^[a-z][\da-z+.-]*$/,J=/^(?:ext|web)\+[a-z]+$/,M=/(?:java|vb)script/,A=/(?:java|vb)script|blob/,j=/%(?:22|27|3C|3E)|[\x22\x27<>]/,K=/^%[\dA-F]{2}$/i;var g=t=>Object.prototype.toString.call(t).slice(8,-1),d=t=>typeof t=="string"||t instanceof String;var{FileReader:V}=globalThis;var L=[7,8,9,10,11,12,13,27,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,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,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255];var C=["aaa","aaas","about","acap","acct","acd","acr","adiumxtra","adt","afp","afs","agtp","aim","amss","android","appdata","apt","ar","ari","ark","at","attachment","aw","barion","beshare","bitcoin","bitcoincash","bl","blob","bluetooth","bolo","brid","browserext","cabal","caip","calculator","callto","cap","cast","casts","chrome","chrome-extension","cid","coap","coaps","com-eventbrite-attendee","content","content-type","crid","cstr","cttps","cvs","dab","dat","data","dav","dhttp","diaspora","dict","did","dilithium3","dis","dlna-playcontainer","dlna-playsingle","dnp","dns","dntp","doi","donau","dpp","drm","dtmi","dtn","dvb","dvx","dweb","ed2k","eid","elsi","embedded","ens","esim","ethereum","example","facetime","feed","feedready","fido","file","finger","first-run-pen-experience","fish","fm","ftp","fuchsia-pkg","geo","gg","git","gitoid","gizmoproject","go","gopher","graph","gtalk","h323","ham","hcap","hcp","hs20","http","https","hxxp","hxxps","hydrazone","hyper","i0","iax","ibi","ibi-","icap","icon","ilstring","im","imap","info","iotdisco","ipfs","ipn","ipns","ipp","ipps","irc","irc6","ircs","iris","iris.beep","iris.lwz","iris.xpc","iris.xpcs","isostore","itms","jabber","jar","jms","keyparc","lastfm","lbry","ldap","ldaps","leaptofrogans","lid","linkid","lorawan","lpa","lvlt","machineProvisioningProgressReporter","magnet","mailto","maps","market","matrix","message","microsoft.windows.camera","microsoft.windows.camera.multipicker","microsoft.windows.camera.picker","mid","mms","mongodb","moz","moz-extension","mqtt","mqtts","ms-access","ms-appinstaller","ms-browser-extension","ms-calculator","ms-drive-to","ms-enrollment","ms-excel","ms-eyecontrolspeech","ms-gamebarservices","ms-gamingoverlay","ms-getoffice","ms-help","ms-infopath","ms-inputapp","ms-launchremotedesktop","ms-lockscreencomponent-config","ms-media-stream-id","ms-meetnow","ms-mixedrealitycapture","ms-mobileplans","ms-newsandinterests","ms-officeapp","ms-people","ms-personacard","ms-powerpoint","ms-project","ms-publisher","ms-recall","ms-remotedesktop","ms-remotedesktop-launch","ms-restoretabcompanion","ms-screenclip","ms-screensketch","ms-search","ms-search-repair","ms-secondary-screen-controller","ms-secondary-screen-setup","ms-settings","ms-settings-airplanemode","ms-settings-bluetooth","ms-settings-camera","ms-settings-cellular","ms-settings-cloudstorage","ms-settings-connectabledevices","ms-settings-displays-topology","ms-settings-emailandaccounts","ms-settings-language","ms-settings-location","ms-settings-lock","ms-settings-nfctransactions","ms-settings-notifications","ms-settings-power","ms-settings-privacy","ms-settings-proximity","ms-settings-screenrotation","ms-settings-wifi","ms-settings-workplace","ms-spd","ms-stickers","ms-sttoverlay","ms-transit-to","ms-useractivityset","ms-uup","ms-virtualtouchpad","ms-visio","ms-walk-to","ms-whiteboard","ms-whiteboard-cmd","ms-widgetboard","ms-widgets","ms-word","msnim","msrp","msrps","mss","mt","mtqp","mtrust","mumble","mupdate","mvn","mvrp","mvrps","news","nfs","ni","nih","nntp","notes","num","ocf","oid","onenote","onenote-cmd","opaquelocktoken","openid","openpgp4fpr","otpauth","palm","paparazzi","payto","pkcs11","platform","pop","pres","proxy","psyc","pttp","pwid","qb","query","quic-transport","redis","rediss","reload","res","resource","rmi","rsync","rtmfp","rtmp","rtsp","rtsps","rtspu","sarif","secondlife","secret-token","service","session","sftp","sgn","shc","shelter","sieve","simpleledger","simplex","sip","sips","skype","smb","smp","sms","smtp","snmp","soap.beep","soap.beeps","soldat","spacify","spiffe","spotify","ssb","ssh","starknet","steam","stun","stuns","submit","svn","swh","swid","swidpath","tag","taler","teamspeak","teapot","teapots","tel","teliaeid","telnet","tftp","things","thismessage","tip","tn3270","tool","turn","turns","tv","udp","unreal","upn","urn","ut2004","uuid-in-package","v-event","vemmi","ventrilo","ves","view-source","vnc","vscode","vscode-insiders","vsls","w3","wasm","wasm-js","wcr","web3","webcal","wifi","ws","wss","wtai","wyciwyg","xcompute","xcon","xcon-userid","xfire","xftp","xmlrpc.beep","xmlrpc.beeps","xmpp","xrcp","xri","ymsgr","z39.50r","z39.50s"];var W=t=>{if(!d(t))throw new TypeError(`Expected String but got ${g(t)}.`);let e=[];for(let s of t)e.push(`%${s.charCodeAt(0).toString(16).toUpperCase()}`);return e.join("")},Z=t=>{d(t)&&K.test(t)&&(t=t.toUpperCase());let[e,s,r,i,o,a]=["&","#","<",">",'"',"'"].map(W),c;return t===e?c=`${e}amp;`:t===r?c=`${e}lt;`:t===i?c=`${e}gt;`:t===o?c=`${e}quot;`:t===a?c=`${e}${s}39;`:c=t,c},ee=t=>{if(d(t)){if(!H.test(t))throw new Error(`Invalid base64 data: ${t}`)}else throw new TypeError(`Expected String but got ${g(t)}.`);let e=atob(t),s=Uint8Array.from([...e].map(o=>o.charCodeAt(0))),r=new Set(L),i;return s.every(o=>r.has(o))?i=e.replace(/\s/g,W):i=t,i},P=(t,e=0)=>{if(!d(t))throw new TypeError(`Expected String but got ${g(t)}.`);if(Number.isInteger(e)){if(e>16)throw new Error("Character references nested too deeply.")}else throw new TypeError(`Expected Number but got ${g(e)}.`);let s=decodeURIComponent(t);if(/&#/.test(s)){let r=new Set(L),i=[...s.matchAll(X)].reverse();for(let o of i){let[a,c]=o,l;if(/^x[\dA-F]+/i.test(c)?l=parseInt(`0${c}`,16):/^\d+/.test(c)&&(l=parseInt(c)),Number.isInteger(l)){let{index:u}=o,[p,n]=[s.substring(0,u),s.substring(u+a.length)];r.has(l)?(s=`${p}${String.fromCharCode(l)}${n}`,(/#x?$/.test(p)||/^#(?:x(?:00)?[2-7]|\d)/.test(n))&&(s=P(s,++e))):l<256&&(s=`${p}${n}`)}}}return s},te=t=>new Promise((e,s)=>{let r=new V;r.addEventListener("error",()=>s(r.error)),r.addEventListener("abort",()=>e(r.result)),r.addEventListener("load",()=>e(r.result)),r.readAsDataURL(t)}),k=class{#e;constructor(){this.#e=new Set(C)}get(){return[...this.#e]}has(e){return this.#e.has(e)}add(e){if(d(e)){if(M.test(e)||!Q.test(e))throw new Error(`Invalid scheme: ${e}`)}else throw new TypeError(`Expected String but got ${g(e)}.`);return this.#e.add(e),[...this.#e]}remove(e){return this.#e.delete(e)}verify(e){let s;if(d(e))try{let{protocol:r}=new URL(e),i=r.replace(/:$/,""),o=i.split("+");s=!M.test(i)&&J.test(i)||o.every(a=>this.#e.has(a))}catch{s=!1}return!!s}reset(){this.#e.clear();for(let e of C)this.#e.add(e)}};var O=class extends k{#e;#t=new Set;constructor(){super(),this.#e=0}replace(e){if(!d(e))throw new TypeError(`Expected String but got ${g(e)}.`);let s=e;if(S.test(s)){let i=[...s.matchAll(q)].reverse();for(let o of i){let[a]=o;G.test(a)&&([a]=G.exec(a)),this.#e++,this.#t.add(a);let c=this.sanitize(a,{allow:["data"]}),{index:l}=o,[u,p]=[s.substring(0,l),s.substring(l+a.length)];c?s=`${u}${c}${p}`:s=`${u}${p}`}}return s}purify(e){if(!d(e))throw new TypeError(`Expected String but got ${g(e)}.`);let s=N.sanitize(decodeURIComponent(e));return s&&S.test(s)&&(s=this.replace(s)),s=s.replace(/(?:#|%23)$/,"").replace(/(?<!(?:#|%23).*)(?:\?|%3F)$/,""),encodeURI(s)}sanitize(e,s){if(this.#e>16)throw this.#e=0,new Error("Data URLs nested too deeply.");let{allow:r,deny:i,only:o}=s??{},a=new Map([["blob",!1],["data",!1],["file",!1],["javascrpt",!1],["vbscript",!1]]),c=new Set,l=!1;if(Array.isArray(o)&&o.length){let p=super.get();for(let m of p)a.set(m,!1);let n=Object.values(o);for(let m of n)if(d(m)&&(m=m.trim(),!A.test(m))){if(super.has(m))a.set(m,!0);else{try{super.add(m)}catch{}super.has(m)&&(a.set(m,!0),c.add(m))}!l&&a.has(m)&&(l=a.get(m))}}else{if(Array.isArray(r)&&r.length){let p=Object.values(r);for(let n of p)if(d(n)&&(n=n.trim(),!A.test(n)))if(super.has(n))a.set(n,!0);else{try{super.add(n)}catch{}super.has(n)&&(a.set(n,!0),c.add(n))}}if(Array.isArray(i)&&i.length){let p=Object.values(i);for(let n of p)d(n)&&(n=n.trim(),n&&a.set(n,!1))}}let u;if(super.verify(e)){let{hash:p,href:n,pathname:m,protocol:U,search:x}=new URL(e),E=U.replace(/:$/,""),z=E.split("+"),_;if(l)_=z.every(y=>a.get(y));else for(let[y,R]of a.entries())if(_=R||E!==y&&z.every(f=>f!==y),!_)break;if(_){let y=z.includes("data"),R,f=n;if(y){let[v,...D]=m.split(","),$=`${D.join(",")}${x}${p}`,T=v.split(";"),I=T[T.length-1]==="base64",h=$;I&&(h=ee($));try{let F=P(h).trim(),{protocol:se}=new URL(F);se.replace(/:$/,"").split("+").some(re=>A.test(re))&&(f="")}catch{}let B=S.test(h);h!==$||B?B?h=this.replace(h):this.#t.has(e)?this.#t.delete(e):R=!0:this.#t.has(e)?this.#t.delete(e):R=!0,(!v||Y.test(v))&&(h=this.purify(h)),f&&h?(I&&h!==$&&T.pop(),f=`${E}:${T.join(";")},${h}`):f=""}else R=!0;if(!y&&j.test(f)){let v=j.exec(f),{index:D}=v;f=f.substring(0,D).replace(/[?&]$/,"")}f?(u=f.replace(/%26/g,Z),R&&(this.#e=0)):this.#e=0}c.size&&c.forEach(y=>{super.remove(y)})}return u||null}parse(e,s){if(!d(e))throw new TypeError(`Expected String but got ${g(e)}.`);let r=new Map([["input",e]]),i;if(this.verify(e)){let{protocol:o}=new URL(e);o==="blob:"?i=e:i=this.sanitize(e,s??{allow:["data","file"]})}if(i){let o=new URL(i),{pathname:a,protocol:c}=o,u=c.replace(/:$/,"").split("+").includes("data");if(r.set("valid",!0),u){let p=new Map,[n,...m]=a.split(","),U=`${m.join(",")}`,x=n.split(";"),E=x[x.length-1]==="base64";E&&x.pop(),p.set("mime",x.join(";")),p.set("base64",E),p.set("data",U),r.set("data",Object.fromEntries(p))}else r.set("data",null);for(let p in o){let n=o[p];d(n)&&r.set(p,n)}}else r.set("valid",!1);return Object.fromEntries(r)}reset(){super.reset(),this.#e=0,this.#t.clear()}};var b=new O,ce=async(t,e={allow:[],deny:[],only:[]})=>{let s;if(t&&d(t)){let r;try{let{protocol:i}=new URL(t);r=i.replace(/:$/,"")}catch{}if(r==="blob"){let{allow:i,deny:o,only:a}=e;if(Array.isArray(i)&&i.includes("blob")&&!(Array.isArray(o)&&o.includes("blob"))||Array.isArray(a)&&a.includes("blob")){let c;try{c=await fetch(t).then(l=>l.blob()).then(te)}catch{}if(c){if(Array.isArray(a))a.includes("data")||a.push("data");else if(Array.isArray(i)&&(i.includes("data")||i.push("data"),Array.isArray(o)&&o.includes("data"))){let l=o.indexOf("data");o.splice(l,1)}s=b.sanitize(c,e)}}URL.revokeObjectURL(t)}else r&&(s=b.sanitize(t,e))}return s||null},pe=(t,e)=>{let s;if(t&&d(t)){let r;try{let{protocol:i}=new URL(t);r=i.replace(/:$/,"")}catch{}r==="blob"?URL.revokeObjectURL(t):r&&(s=b.sanitize(t,e))}return s||null},le=async t=>b.parse(t),me=t=>b.parse(t),de=async t=>b.verify(t),fe=t=>b.verify(t),he=b;export{he as default,de as isURI,fe as isURISync,le as parseURL,me as parseURLSync,ce as sanitizeURL,pe as sanitizeURLSync};
|
|
2
2
|
/*!
|
|
3
3
|
* URL Sanitizer
|
|
4
4
|
*
|