1 | /*
|
---|
2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
---|
3 | Author Ivan Kopeykin @vankop
|
---|
4 | */
|
---|
5 |
|
---|
6 | "use strict";
|
---|
7 |
|
---|
8 | /** @typedef {import("./Resolver")} Resolver */
|
---|
9 | /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
|
---|
10 |
|
---|
11 | const slashCode = "/".charCodeAt(0);
|
---|
12 | const backslashCode = "\\".charCodeAt(0);
|
---|
13 |
|
---|
14 | /**
|
---|
15 | * @param {string} path path
|
---|
16 | * @param {string} parent parent path
|
---|
17 | * @returns {boolean} true, if path is inside of parent
|
---|
18 | */
|
---|
19 | const isInside = (path, parent) => {
|
---|
20 | if (!path.startsWith(parent)) return false;
|
---|
21 | if (path.length === parent.length) return true;
|
---|
22 | const charCode = path.charCodeAt(parent.length);
|
---|
23 | return charCode === slashCode || charCode === backslashCode;
|
---|
24 | };
|
---|
25 |
|
---|
26 | module.exports = class RestrictionsPlugin {
|
---|
27 | /**
|
---|
28 | * @param {string | ResolveStepHook} source source
|
---|
29 | * @param {Set<string | RegExp>} restrictions restrictions
|
---|
30 | */
|
---|
31 | constructor(source, restrictions) {
|
---|
32 | this.source = source;
|
---|
33 | this.restrictions = restrictions;
|
---|
34 | }
|
---|
35 |
|
---|
36 | /**
|
---|
37 | * @param {Resolver} resolver the resolver
|
---|
38 | * @returns {void}
|
---|
39 | */
|
---|
40 | apply(resolver) {
|
---|
41 | resolver
|
---|
42 | .getHook(this.source)
|
---|
43 | .tapAsync("RestrictionsPlugin", (request, resolveContext, callback) => {
|
---|
44 | if (typeof request.path === "string") {
|
---|
45 | const path = request.path;
|
---|
46 | for (const rule of this.restrictions) {
|
---|
47 | if (typeof rule === "string") {
|
---|
48 | if (!isInside(path, rule)) {
|
---|
49 | if (resolveContext.log) {
|
---|
50 | resolveContext.log(
|
---|
51 | `${path} is not inside of the restriction ${rule}`
|
---|
52 | );
|
---|
53 | }
|
---|
54 | return callback(null, null);
|
---|
55 | }
|
---|
56 | } else if (!rule.test(path)) {
|
---|
57 | if (resolveContext.log) {
|
---|
58 | resolveContext.log(
|
---|
59 | `${path} doesn't match the restriction ${rule}`
|
---|
60 | );
|
---|
61 | }
|
---|
62 | return callback(null, null);
|
---|
63 | }
|
---|
64 | }
|
---|
65 | }
|
---|
66 |
|
---|
67 | callback();
|
---|
68 | });
|
---|
69 | }
|
---|
70 | };
|
---|