Skip to content

Commit 07ca56e

Browse files
authored
Polyfill: Support for enforcement in emulated DOM environments (e.g. nodejs + domino).
Build target for npm now exposes `TrustedTypesConfig` and `TrustedTypesEnforcer` objects that allow installing the enforcement on Window-like objects. See `demo/nodejs-domino` for an example usage. Fixes #190.
1 parent 0b900ae commit 07ca56e

24 files changed

+794
-263
lines changed

Diff for: demo/nodejs-domino/.gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
node_modules
2+
lib
3+
*.log

Diff for: demo/nodejs-domino/README.md

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Nodejs domino demo
2+
3+
This example showcases the integration of TT polyfill in nodejs environemnt. We are using TypeScript
4+
on purpose to show our type definitions work. Using TT polyfill on nodejs without enforcement is
5+
possible, but some project emulate DOM on the server side (angular) and this demo shows TT polyfill
6+
can work in those cases, too.
7+
8+
We are emulating DOM using our version of
9+
[domino](https://github.com/Siegrift/domino/tree/configurable), because there is an
10+
[issue](https://github.com/fgnass/domino/issues/171) which prevents us from reconfiguring the DOM
11+
functions defined by domino.
12+
13+
To start enforcing on the emulated DOM object you have two options:
14+
15+
1. Define emulated `window` object on the global scope and create enforcer with a single argument -
16+
enforcement configuration.
17+
2. Pass the emulated `window` object to the enforcer as a second argument. _(You don't need to
18+
expose the object on the global scope)_.
19+
20+
## Running the demos
21+
22+
1. Run `yarn` to install dependencies.
23+
2. There are two demos, which you can run by `yarn run-demo-global` or `yarn run-demo-custom`.
24+
25+
Both demos output a bunch of text to the console. Check the source files to understand the output.

Diff for: demo/nodejs-domino/another.ts

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
// This file shows that the DOM symbols are available in the global scope
2+
console.log('typeof window', typeof window)
3+
console.log('typeof document', typeof document)

Diff for: demo/nodejs-domino/api_only.ts

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
// This file shows how to use the API of trusted types (without any enforcement).
2+
import { trustedTypes } from 'trusted-types'
3+
4+
function acceptOnlyTrustedHTML(html: TrustedHTML) {
5+
if (!trustedTypes.isHTML(html)) console.log('untrusted html', html)
6+
else console.log('trusted html', html)
7+
}
8+
9+
const policy = trustedTypes.createPolicy('app', { createHTML: (s) => s })
10+
acceptOnlyTrustedHTML('str' as any)
11+
acceptOnlyTrustedHTML(policy.createHTML('safe html'))

Diff for: demo/nodejs-domino/custom.ts

+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import domino from 'domino'
2+
import './another'
3+
import {
4+
trustedTypes,
5+
TrustedTypeConfig,
6+
TrustedTypesEnforcer,
7+
} from 'trusted-types'
8+
9+
// create custom DOM API implementation
10+
const win = domino.createWindow()
11+
const doc = win.document
12+
13+
const html = doc.createElement('html')
14+
html.appendChild(doc.createElement('div'))
15+
html.appendChild(doc.createElement('div'))
16+
console.log(html.innerHTML)
17+
18+
// no enforcement yet, assignment should work
19+
html.children[0].innerHTML = 'string'
20+
console.log(html.innerHTML)
21+
22+
// start enforcing mode
23+
const config = new TrustedTypeConfig(
24+
false,
25+
true,
26+
['foo', 'default'],
27+
false,
28+
undefined,
29+
win,
30+
)
31+
const enforcer = new TrustedTypesEnforcer(config)
32+
enforcer.install()
33+
const fooPolicy = trustedTypes.createPolicy('foo', { createHTML: (s) => s })
34+
35+
// we expect string assignment to sink to fail
36+
let caught = false
37+
try {
38+
html.children[0].innerHTML = 'string' // should fail
39+
} catch (err) {
40+
caught = true
41+
}
42+
if (caught) console.log('Caught unsafe write to innerHTML property')
43+
else throw new Error("Didn't catch unsafe write to innerHTML property!")
44+
45+
// trusted value assignment should pass
46+
html.children[0].innerHTML = fooPolicy.createHTML('safeHTML') as any
47+
console.log(html.innerHTML)
48+
49+
// Default policy
50+
trustedTypes.createPolicy('default', { createHTML: (s) => s + '-default' })
51+
52+
// after we uninstall enforcer, raw assignments should work again
53+
enforcer.uninstall()
54+
html.children[0].innerHTML = 'string after uninstall'
55+
console.log(html.innerHTML)
56+
57+
html.children[0].innerHTML = 'string' // should be rewritten to 'string-default'
58+
console.log(html.children[0].innerHTML)
59+
60+
// it should work even with incomplete enforcer
61+
const config2 = new TrustedTypeConfig(
62+
false,
63+
true,
64+
['foo', 'default'],
65+
false,
66+
undefined,
67+
['Element', 'HTMLElement', 'Document', 'Node'].reduce(
68+
(acc, key) => {
69+
acc[key] = (domino as any).impl[key]
70+
return acc
71+
},
72+
{ document: doc } as any,
73+
),
74+
)
75+
const incompleteEnforcer = new TrustedTypesEnforcer(config2)
76+
incompleteEnforcer.install()
77+
incompleteEnforcer.uninstall()

Diff for: demo/nodejs-domino/main.ts

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import domino from 'domino'
2+
import {
3+
trustedTypes,
4+
TrustedTypeConfig,
5+
TrustedTypesEnforcer,
6+
} from 'trusted-types'
7+
8+
// expose DOM API on the global scope
9+
const g = global as any
10+
g.window = domino.createWindow()
11+
g.document = g.window.document
12+
Object.entries((domino as any).impl).forEach(([key, value]) => {
13+
g[key] = value
14+
})
15+
16+
// console logs whether the global DOM symbols
17+
import './another'
18+
19+
const html = document.createElement('html')
20+
html.appendChild(document.createElement('div'))
21+
html.appendChild(document.createElement('div'))
22+
html.appendChild(document.createElement('div'))
23+
console.log(html.innerHTML)
24+
25+
// no enforcement yet, assignment should work
26+
html.children[0].innerHTML = 'string'
27+
console.log(html.innerHTML)
28+
29+
// start enforcing mode
30+
const config = new TrustedTypeConfig(false, true, ['foo', 'default'], false)
31+
const enforcer = new TrustedTypesEnforcer(config)
32+
enforcer.install()
33+
const fooPolicy = trustedTypes.createPolicy('foo', { createHTML: (s) => s })
34+
// we expect string assignment to sink to fail
35+
let caught = false
36+
try {
37+
html.children[0].innerHTML = 'string' // should fail
38+
} catch (err) {
39+
caught = true
40+
}
41+
if (caught) console.log('Caught unsafe write to innerHTML property')
42+
else throw new Error("Didn't catch unsafe write to innerHTML property!")
43+
44+
// trusted value assignment should pass
45+
html.children[0].innerHTML = fooPolicy.createHTML('safeHTML') as any
46+
console.log(html.innerHTML)
47+
48+
// Default policy
49+
trustedTypes.createPolicy('default', { createHTML: (s) => s + '-default' })
50+
51+
// after we uninstall enforcer, raw assignments should work again
52+
enforcer.uninstall()
53+
html.children[0].innerHTML = 'string after uninstall'
54+
console.log(html.innerHTML)

Diff for: demo/nodejs-domino/package.json

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
{
2+
"name": "target",
3+
"version": "1.0.0",
4+
"description": "",
5+
"main": "index.js",
6+
"scripts": {
7+
"run-demo-global": "yarn tsc && node ./lib/main",
8+
"run-demo-custom": "yarn tsc && node ./lib/custom"
9+
},
10+
"author": "",
11+
"license": "ISC",
12+
"dependencies": {
13+
"@types/node": "^14.14.3",
14+
"@types/trusted-types": "^1.0.6",
15+
"domino": "Siegrift/domino#configurable",
16+
"trusted-types": "link:../../",
17+
"typescript": "^4.0.3"
18+
}
19+
}

Diff for: demo/nodejs-domino/tsconfig.json

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
{
2+
"compilerOptions": {
3+
/* Visit https://aka.ms/tsconfig.json to read more about this file */
4+
5+
/* Basic Options */
6+
// "incremental": true, /* Enable incremental compilation */
7+
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
8+
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
9+
// "lib": [], /* Specify library files to be included in the compilation. */
10+
// "allowJs": true, /* Allow javascript files to be compiled. */
11+
// "checkJs": true, /* Report errors in .js files. */
12+
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
13+
// "declaration": true, /* Generates corresponding '.d.ts' file. */
14+
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
15+
// "sourceMap": true, /* Generates corresponding '.map' file. */
16+
// "outFile": "./", /* Concatenate and emit output to single file. */
17+
"outDir": "./lib", /* Redirect output structure to the directory. */
18+
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
19+
// "composite": true, /* Enable project compilation */
20+
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
21+
// "removeComments": true, /* Do not emit comments to output. */
22+
// "noEmit": true, /* Do not emit outputs. */
23+
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
24+
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
25+
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
26+
27+
/* Strict Type-Checking Options */
28+
"strict": true, /* Enable all strict type-checking options. */
29+
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
30+
// "strictNullChecks": true, /* Enable strict null checks. */
31+
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
32+
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
33+
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
34+
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
35+
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
36+
37+
/* Additional Checks */
38+
// "noUnusedLocals": true, /* Report errors on unused locals. */
39+
// "noUnusedParameters": true, /* Report errors on unused parameters. */
40+
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
41+
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
42+
43+
/* Module Resolution Options */
44+
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
45+
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
46+
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
47+
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
48+
// "typeRoots": [], /* List of folders to include type definitions from. */
49+
"types": ["node"], /* Type declaration files to be included in compilation. */
50+
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
51+
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
52+
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
53+
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
54+
55+
/* Source Map Options */
56+
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
57+
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
58+
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
59+
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
60+
61+
/* Experimental Options */
62+
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
63+
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
64+
65+
/* Advanced Options */
66+
"skipLibCheck": true, /* Skip type checking of declaration files. */
67+
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
68+
}
69+
}

Diff for: demo/nodejs-domino/yarn.lock

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
2+
# yarn lockfile v1
3+
4+
5+
"@types/node@^14.14.3":
6+
version "14.14.3"
7+
resolved "https://registry.yarnpkg.com/@types/node/-/node-14.14.3.tgz#e1c09064121f894baaad2bd9f12ce4a41bffb274"
8+
integrity sha512-33/L34xS7HVUx23e0wOT2V1qPF1IrHgQccdJVm9uXGTB9vFBrrzBtkQymT8VskeKOxjz55MSqMv0xuLq+u98WQ==
9+
10+
"@types/trusted-types@^1.0.6":
11+
version "1.0.6"
12+
resolved "https://registry.yarnpkg.com/@types/trusted-types/-/trusted-types-1.0.6.tgz#569b8a08121d3203398290d602d84d73c8dcf5da"
13+
integrity sha512-230RC8sFeHoT6sSUlRO6a8cAnclO06eeiq1QDfiv2FGCLWFvvERWgwIQD4FWqD9A69BN7Lzee4OXwoMVnnsWDw==
14+
15+
domino@Siegrift/domino#configurable:
16+
version "2.1.6"
17+
resolved "https://codeload.github.com/Siegrift/domino/tar.gz/70d427283215ba7ac99083bb4dc2fb41754d684f"
18+
19+
"trusted-types@link:../..":
20+
version "0.0.0"
21+
uid ""
22+
23+
typescript@^4.0.3:
24+
version "4.0.3"
25+
resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.0.3.tgz#153bbd468ef07725c1df9c77e8b453f8d36abba5"
26+
integrity sha512-tEu6DGxGgRJPb/mVPIZ48e69xCn2yRmCgYmDugAVwmJ6o+0u1RI18eO7E7WBTLYLaEVVOhwQmcdhQHweux/WPg==

Diff for: dist/es5/trustedtypes.api_only.build.js.map

+1-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)