csprefabricate 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 James Toohey
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,33 @@
1
+ # csprefabricate (Work in progress)
2
+
3
+ **Generate a valid CSP with JavaScript. Built with TypeScript.**
4
+
5
+ Content Security Policies (CSPs) are cumbersome strings that are frusting to work with:
6
+
7
+ - Fickle syntax
8
+ - Duplicattion when multiple TLDs are required
9
+ - Easy to allow insecure configuration
10
+
11
+ This project aims to make creating useful and secure CSPs a more pleasant experience.
12
+
13
+ Currently `csprefabricate`:
14
+
15
+ - Validates directive names
16
+ - Supports providing a list of TLDs for a given domain name
17
+
18
+ ```typescript
19
+ import {create} from "csprefabricate";
20
+
21
+ const input = {
22
+ [Directive.DEFAULT_SRC]: ["self"],
23
+ [Directive.IMG_SRC]: ["self", {"*.google": [".com", ".com.au"]}],
24
+ } satisfies ContentSecurityPolicy;
25
+
26
+ const output = create(csp);
27
+ // > "default-src 'self'; img-src 'self' *.google.com *.google.com.au;",
28
+ ```
29
+
30
+ ## Future
31
+
32
+ - Generate baseline recommended CSPs (for example, Google Analytics)
33
+ - Warnings for insecure configurations
@@ -0,0 +1,2 @@
1
+ export declare const isValidDirective: (directive: string) => boolean;
2
+ export declare const formatRule: (rule: string) => string;
@@ -0,0 +1,37 @@
1
+ const validDirectives = [
2
+ "default-src",
3
+ "script-src",
4
+ "style-src",
5
+ "img-src",
6
+ "connect-src",
7
+ "font-src",
8
+ "object-src",
9
+ "media-src",
10
+ "frame-src",
11
+ "sandbox",
12
+ "report-uri",
13
+ "child-src",
14
+ "form-action",
15
+ "frame-ancestors",
16
+ "plugin-types",
17
+ "base-uri",
18
+ "report-to",
19
+ "worker-src",
20
+ "manifest-src",
21
+ "prefetch-src",
22
+ "navigate-to",
23
+ "require-trusted-types-for",
24
+ "trusted-types",
25
+ "upgrade-insecure-requests",
26
+ "block-all-mixed-content",
27
+ ];
28
+ const specialRules = [
29
+ "none",
30
+ "self",
31
+ "unsafe-inline",
32
+ "unsafe-eval",
33
+ "strict-dynamic",
34
+ "unsafe-hashes",
35
+ ];
36
+ export const isValidDirective = (directive) => validDirectives.includes(directive);
37
+ export const formatRule = (rule) => specialRules.includes(rule) ? `'${rule}'` : rule;
@@ -0,0 +1,3 @@
1
+ import { type ContentSecurityPolicy, Directive } from "types";
2
+ import { create } from "utils";
3
+ export { create, type Directive, type ContentSecurityPolicy };
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ import { Directive } from "types";
2
+ import { create } from "utils";
3
+ export { create };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,23 @@
1
+ import { describe, it } from "node:test";
2
+ import assert from "node:assert";
3
+ import { formatRule, isValidDirective } from "../helpers";
4
+ import { Directive } from "../types";
5
+ describe("Helpers tests", () => {
6
+ describe("isValidDirective", () => {
7
+ it("Returns true if directive is valid", () => {
8
+ assert.strictEqual(isValidDirective(Directive.BASE_URI), true);
9
+ assert.strictEqual(isValidDirective("default-src"), true);
10
+ });
11
+ it("Returns false if directive is invalid", () => {
12
+ assert.strictEqual(isValidDirective("some-src"), false);
13
+ });
14
+ });
15
+ describe("formatRule", () => {
16
+ it("Formats special rules with single quotes", () => {
17
+ assert.strictEqual(formatRule("self"), `'self'`);
18
+ });
19
+ it("Returns non-special rules", () => {
20
+ assert.strictEqual(formatRule("google.com"), `google.com`);
21
+ });
22
+ });
23
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,69 @@
1
+ import { describe, it } from "node:test";
2
+ import assert from "node:assert";
3
+ import { create, processRules } from "../utils";
4
+ import { Directive } from "../types";
5
+ describe("Utils tests", () => {
6
+ describe("processRules", () => {
7
+ it("Processes rules provided as an array of strings (simple)", () => {
8
+ const rules = ["self", "*.google.com", "*.google.com.au"];
9
+ assert.strictEqual(processRules(rules), `'self' *.google.com *.google.com.au`);
10
+ });
11
+ it("Processes rules provided a complex list of tlds", () => {
12
+ const rules = ["self", { "*.google": [".com", ".com.au"] }];
13
+ assert.strictEqual(processRules(rules), `'self' *.google.com *.google.com.au`);
14
+ });
15
+ });
16
+ describe("create", () => {
17
+ it("Formats a CSP string with all rules", () => {
18
+ const csp = {
19
+ [Directive.DEFAULT_SRC]: ["self"],
20
+ [Directive.SCRIPT_SRC]: ["self", "js.example.com"],
21
+ [Directive.STYLE_SRC]: ["self", "css.example.com"],
22
+ [Directive.IMG_SRC]: [
23
+ "self",
24
+ { "*.google": [".com", ".com.au"] },
25
+ ],
26
+ [Directive.CONNECT_SRC]: ["self"],
27
+ [Directive.FONT_SRC]: ["self", "font.example.com"],
28
+ [Directive.OBJECT_SRC]: ["none"],
29
+ [Directive.MEDIA_SRC]: ["self", "media.example.com"],
30
+ [Directive.FRAME_SRC]: ["self"],
31
+ [Directive.SANDBOX]: ["allow-scripts"],
32
+ [Directive.REPORT_URI]: ["/my-report-uri"],
33
+ [Directive.CHILD_SRC]: ["self"],
34
+ [Directive.FORM_ACTION]: ["self"],
35
+ [Directive.FRAME_ANCESTORS]: ["none"],
36
+ [Directive.PLUGIN_TYPES]: ["application/pdf"],
37
+ [Directive.BASE_URI]: ["self"],
38
+ [Directive.REPORT_TO]: ["myGroupName"],
39
+ [Directive.WORKER_SRC]: ["none"],
40
+ [Directive.MANIFEST_SRC]: ["none"],
41
+ [Directive.PREFETCH_SRC]: ["none"],
42
+ [Directive.NAVIGATE_TO]: ["example.com"],
43
+ [Directive.REQUIRE_TRUSTED_TYPES_FOR]: ["script"],
44
+ [Directive.TRUSTED_TYPES]: ["none"],
45
+ [Directive.UPGRADE_INSECURE_REQUESTS]: null,
46
+ [Directive.BLOCK_ALL_MIXED_CONTENT]: null,
47
+ };
48
+ const cspString = create(csp);
49
+ assert.strictEqual(cspString, "default-src 'self'; script-src 'self' js.example.com; style-src 'self' css.example.com; img-src 'self' *.google.com *.google.com.au; connect-src 'self'; font-src 'self' font.example.com; object-src 'none'; media-src 'self' media.example.com; frame-src 'self'; sandbox allow-scripts; report-uri /my-report-uri; child-src 'self'; form-action 'self'; frame-ancestors 'none'; plugin-types application/pdf; base-uri 'self'; report-to myGroupName; worker-src 'none'; manifest-src 'none'; prefetch-src 'none'; navigate-to example.com; require-trusted-types-for script; trusted-types 'none'; upgrade-insecure-requests; block-all-mixed-content;");
50
+ });
51
+ it("Handles blank directives", () => {
52
+ const csp = {
53
+ [Directive.SANDBOX]: [],
54
+ };
55
+ const cspString = create(csp);
56
+ assert.strictEqual(cspString, "sandbox;");
57
+ });
58
+ it("Ignores invalid directives", () => {
59
+ const csp = {
60
+ [Directive.DEFAULT_SRC]: ["self"],
61
+ // @ts-expect-error deliberate testing of invalid directive
62
+ ["invalid-directive"]: ["self"],
63
+ [Directive.IMG_SRC]: ["my.domain.com"]
64
+ };
65
+ const cspString = create(csp);
66
+ assert.strictEqual(cspString, "default-src 'self'; img-src my.domain.com;");
67
+ });
68
+ });
69
+ });
@@ -0,0 +1,58 @@
1
+ declare enum Directive {
2
+ DEFAULT_SRC = "default-src",
3
+ SCRIPT_SRC = "script-src",
4
+ STYLE_SRC = "style-src",
5
+ IMG_SRC = "img-src",
6
+ CONNECT_SRC = "connect-src",
7
+ FONT_SRC = "font-src",
8
+ OBJECT_SRC = "object-src",
9
+ MEDIA_SRC = "media-src",
10
+ FRAME_SRC = "frame-src",
11
+ SANDBOX = "sandbox",
12
+ REPORT_URI = "report-uri",
13
+ CHILD_SRC = "child-src",
14
+ FORM_ACTION = "form-action",
15
+ FRAME_ANCESTORS = "frame-ancestors",
16
+ PLUGIN_TYPES = "plugin-types",
17
+ BASE_URI = "base-uri",
18
+ REPORT_TO = "report-to",
19
+ WORKER_SRC = "worker-src",
20
+ MANIFEST_SRC = "manifest-src",
21
+ PREFETCH_SRC = "prefetch-src",
22
+ NAVIGATE_TO = "navigate-to",
23
+ REQUIRE_TRUSTED_TYPES_FOR = "require-trusted-types-for",
24
+ TRUSTED_TYPES = "trusted-types",
25
+ UPGRADE_INSECURE_REQUESTS = "upgrade-insecure-requests",
26
+ BLOCK_ALL_MIXED_CONTENT = "block-all-mixed-content"
27
+ }
28
+ type BasicDirectiveRule = Array<string | Record<string, Array<string>>>;
29
+ type BlankDirectiveRule = null;
30
+ type Rules = BasicDirectiveRule | BlankDirectiveRule;
31
+ interface ContentSecurityPolicy {
32
+ [Directive.DEFAULT_SRC]?: BasicDirectiveRule;
33
+ [Directive.SCRIPT_SRC]?: BasicDirectiveRule;
34
+ [Directive.STYLE_SRC]?: BasicDirectiveRule;
35
+ [Directive.IMG_SRC]?: BasicDirectiveRule;
36
+ [Directive.CONNECT_SRC]?: BasicDirectiveRule;
37
+ [Directive.FONT_SRC]?: BasicDirectiveRule;
38
+ [Directive.OBJECT_SRC]?: BasicDirectiveRule;
39
+ [Directive.MEDIA_SRC]?: BasicDirectiveRule;
40
+ [Directive.FRAME_SRC]?: BasicDirectiveRule;
41
+ [Directive.SANDBOX]?: BasicDirectiveRule;
42
+ [Directive.REPORT_URI]?: BasicDirectiveRule;
43
+ [Directive.CHILD_SRC]?: BasicDirectiveRule;
44
+ [Directive.FORM_ACTION]?: BasicDirectiveRule;
45
+ [Directive.FRAME_ANCESTORS]?: BasicDirectiveRule;
46
+ [Directive.PLUGIN_TYPES]?: BasicDirectiveRule;
47
+ [Directive.BASE_URI]?: BasicDirectiveRule;
48
+ [Directive.REPORT_TO]?: BasicDirectiveRule;
49
+ [Directive.WORKER_SRC]?: BasicDirectiveRule;
50
+ [Directive.MANIFEST_SRC]?: BasicDirectiveRule;
51
+ [Directive.PREFETCH_SRC]?: BasicDirectiveRule;
52
+ [Directive.NAVIGATE_TO]?: BasicDirectiveRule;
53
+ [Directive.REQUIRE_TRUSTED_TYPES_FOR]?: BasicDirectiveRule;
54
+ [Directive.TRUSTED_TYPES]?: BasicDirectiveRule;
55
+ [Directive.UPGRADE_INSECURE_REQUESTS]?: BlankDirectiveRule;
56
+ [Directive.BLOCK_ALL_MIXED_CONTENT]?: BlankDirectiveRule;
57
+ }
58
+ export { type ContentSecurityPolicy, type Rules, Directive };
package/dist/types.js ADDED
@@ -0,0 +1,29 @@
1
+ var Directive;
2
+ (function (Directive) {
3
+ Directive["DEFAULT_SRC"] = "default-src";
4
+ Directive["SCRIPT_SRC"] = "script-src";
5
+ Directive["STYLE_SRC"] = "style-src";
6
+ Directive["IMG_SRC"] = "img-src";
7
+ Directive["CONNECT_SRC"] = "connect-src";
8
+ Directive["FONT_SRC"] = "font-src";
9
+ Directive["OBJECT_SRC"] = "object-src";
10
+ Directive["MEDIA_SRC"] = "media-src";
11
+ Directive["FRAME_SRC"] = "frame-src";
12
+ Directive["SANDBOX"] = "sandbox";
13
+ Directive["REPORT_URI"] = "report-uri";
14
+ Directive["CHILD_SRC"] = "child-src";
15
+ Directive["FORM_ACTION"] = "form-action";
16
+ Directive["FRAME_ANCESTORS"] = "frame-ancestors";
17
+ Directive["PLUGIN_TYPES"] = "plugin-types";
18
+ Directive["BASE_URI"] = "base-uri";
19
+ Directive["REPORT_TO"] = "report-to";
20
+ Directive["WORKER_SRC"] = "worker-src";
21
+ Directive["MANIFEST_SRC"] = "manifest-src";
22
+ Directive["PREFETCH_SRC"] = "prefetch-src";
23
+ Directive["NAVIGATE_TO"] = "navigate-to";
24
+ Directive["REQUIRE_TRUSTED_TYPES_FOR"] = "require-trusted-types-for";
25
+ Directive["TRUSTED_TYPES"] = "trusted-types";
26
+ Directive["UPGRADE_INSECURE_REQUESTS"] = "upgrade-insecure-requests";
27
+ Directive["BLOCK_ALL_MIXED_CONTENT"] = "block-all-mixed-content";
28
+ })(Directive || (Directive = {}));
29
+ export { Directive };
@@ -0,0 +1,3 @@
1
+ import { type ContentSecurityPolicy } from "types";
2
+ export declare const processRules: (rules: Array<string> | Array<string | Record<string, Array<string>>>) => string;
3
+ export declare const create: (obj: ContentSecurityPolicy) => string;
package/dist/utils.js ADDED
@@ -0,0 +1,27 @@
1
+ import { formatRule, isValidDirective } from "helpers";
2
+ import { Directive } from "types";
3
+ export const processRules = (rules) => {
4
+ return rules
5
+ .map((rule) => {
6
+ if (typeof rule === "object") {
7
+ return Object.entries(rule).map(([domain, tlds]) => tlds.map((tld) => `${domain}${tld}`).join(" "));
8
+ }
9
+ else {
10
+ return formatRule(rule);
11
+ }
12
+ })
13
+ .join(" ");
14
+ };
15
+ export const create = (obj) => {
16
+ const entries = Object.entries(obj);
17
+ const cspString = entries
18
+ .filter(([directive, _rules]) => {
19
+ const isValid = isValidDirective(directive);
20
+ if (!isValid) {
21
+ console.warn(`"${directive}" is not a valid CSP directive and has been ignored.`);
22
+ }
23
+ return isValid;
24
+ })
25
+ .map(([directive, rules]) => `${directive}${rules && rules.length > 0 ? " " + processRules(rules) : ""}`);
26
+ return `${cspString.join("; ")};`;
27
+ };
package/package.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "csprefabricate",
3
+ "version": "0.2.0",
4
+ "packageManager": "yarn@4.5.3",
5
+ "type": "module",
6
+ "devDependencies": {
7
+ "@tsconfig/node-lts": "^22.0.1",
8
+ "@types/node": "^22.13.5",
9
+ "prettier": "^3.5.2",
10
+ "tsx": "^4.19.3",
11
+ "typescript": "^5.7.3"
12
+ },
13
+ "main": "dist/index.js",
14
+ "files": [
15
+ "dist/"
16
+ ],
17
+ "scripts": {
18
+ "build": "tsc",
19
+ "pack": "npm pack",
20
+ "prepack": "yarn typecheck && yarn test && yarn build",
21
+ "prettier": "prettier . --write",
22
+ "prepublish": "yarn version check",
23
+ "publish": "yarn npm publish",
24
+ "test": "tsx --test src/test/**/*test.ts",
25
+ "typecheck": "tsc --noEmit"
26
+ }
27
+ }