@contrast/rewriter 1.1.0 → 1.3.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.
Files changed (3) hide show
  1. package/README.md +4 -10
  2. package/lib/index.js +82 -15
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -1,12 +1,8 @@
1
1
  ## `@contrast/rewriter`
2
2
 
3
- Provides a configured service for rewriting code.
3
+ Rewrite javascript code with custom rewrite transforms.
4
4
 
5
- Basic idea: Enabled features can register rewrite transforms to support their end goal.
6
-
7
- Example: Assess
8
-
9
- Assess will register transforms for `+` -> `contrast_add()` so that it can perform propagation
5
+ For example, Assess will register transforms for `+` -> `contrast_add()` so that it can perform propagation
10
6
  via instrumentation of `contrast_add()`.
11
7
 
12
8
 
@@ -15,7 +11,7 @@ via instrumentation of `contrast_add()`.
15
11
  ```typescript
16
12
  const { Rewriter } = require('.');
17
13
 
18
- const rewriter = new Rewriter({ config, logger });
14
+ const rewriter = new Rewriter({ logger });
19
15
 
20
16
  rewriter.addTransforms({
21
17
  BinaryExpression(path) {
@@ -33,7 +29,5 @@ rewriter.addTransforms({
33
29
  }
34
30
  });
35
31
 
36
- const result = rewriter.rewriteFile({
37
- content: 'function add(x, y) { return x + y; }'
38
- });
32
+ const result = rewriter.rewrite('function add(x, y) { return x + y; }');
39
33
  ```
package/lib/index.js CHANGED
@@ -22,13 +22,13 @@ const { default: generate } = require('@babel/generator');
22
22
  const t = require('@babel/types');
23
23
  const { expression, statement } = require('@babel/template');
24
24
 
25
+
25
26
  /**
26
27
  * factory
27
28
  */
28
29
  module.exports = function(core) {
29
30
  const rewriter = new Rewriter(core);
30
- core.rewriter = rewriter;
31
- return rewriter;
31
+ return core.rewriter = rewriter;
32
32
  };
33
33
 
34
34
 
@@ -54,6 +54,10 @@ class Rewriter {
54
54
  const self = this;
55
55
  this.logger = deps.logger;
56
56
  this.visitors = [];
57
+ this.installedModes = [];
58
+ this.tokens = [];
59
+ this.injections = [];
60
+ this.methodLookups = {};
57
61
  this.rewriteTransforms = {
58
62
  enter(...args) {
59
63
  for (const v of self.visitors) {
@@ -62,7 +66,6 @@ class Rewriter {
62
66
  },
63
67
  Program: function Program(path, state) {
64
68
  if (state.wrap) {
65
-
66
69
  let [prefix, suffix] = Module.wrapper;
67
70
  prefix = prefix.trim();
68
71
  suffix = suffix.trim().replace(/;$/, '.apply(this, arguments);');
@@ -75,25 +78,29 @@ class Rewriter {
75
78
  }
76
79
 
77
80
  if (state.inject) {
78
- path.unshiftContainer('body', [
79
- statement(
80
- 'const ContrastMethods = global.ContrastMethods || (() => { throw new SyntaxError(\'ContrastMethods undefined during compilation\'); })();'
81
- )(),
82
- ]);
81
+ path.unshiftContainer('body', self.injections);
83
82
  }
84
83
  },
85
- CallExpression(path, state) {
84
+ CallExpression(path) {
86
85
  if (path.node.callee.name === 'eval') {
87
86
  path.node.arguments = [
88
87
  t.callExpression(expression('global.ContrastMethods.eval')(), path.node.arguments)
89
88
  ];
90
89
  }
91
- if (path.node.callee.name === 'Function') {
92
- path.node.arguments = [
93
- t.callExpression(expression('global.ContrastMethods.Function')(), path.node.arguments)
94
- ];
95
- }
96
90
  },
91
+ BinaryExpression: function BinaryExpression(path) {
92
+ const method = self.methodLookups[path.node.operator];
93
+ if (method) {
94
+ path.replaceWith(
95
+ t.callExpression(
96
+ expression('ContrastMethods.%%method%%')({ method }), [
97
+ path.node.left,
98
+ path.node.right
99
+ ]
100
+ )
101
+ );
102
+ }
103
+ }
97
104
  };
98
105
  this.unwriteTransforms = {
99
106
  CallExpression(path) {
@@ -103,6 +110,66 @@ class Rewriter {
103
110
  }
104
111
  }
105
112
  };
113
+ this.install = function(mode) {
114
+ self.installedModes.push(mode);
115
+ !self.methodLookups.eval && (self.methodLookups = {
116
+ eval: 'eval'
117
+ });
118
+
119
+ !(self.injections.length === 2) && self.injections.push(
120
+ statement(
121
+ 'const %%id%% = global.%%id%% || (() => { throw new SyntaxError(%%errMessage%%); })();'
122
+ )({
123
+ id: 'ContrastMethods',
124
+ errMessage: t.stringLiteral(
125
+ 'ContrastMethods undefined during compilation'
126
+ )
127
+ }),
128
+ statement(
129
+ 'var %%name%% = global.ContrastMethods.%%id%% || %%name%%;'
130
+ )({ name: 'Function', id: 'Function' }),
131
+ );
132
+
133
+ if (self.installedModes.includes('protect')) {
134
+ // Protect doesn't have anything specific
135
+ // for rewriting that should not be rewritten
136
+ // in Assess (at least for now)
137
+ }
138
+ if (self.installedModes.includes('assess')) {
139
+ Object.assign(self.methodLookups, {
140
+ '+': 'plus',
141
+ '===': 'tripleEqual',
142
+ '!==': 'notTripleEqual',
143
+ '==': 'doubleEqual',
144
+ '!=': 'notDoubleEqual'
145
+ });
146
+ self.injections.push(
147
+ statement(
148
+ 'const %%name%% = global.%%id%% || %%name%%;'
149
+ )({ name: 'JSON', id: 'ContrastJSON' }),
150
+ statement(
151
+ 'const %%name%% = global.%%id%% || %%name%%;'
152
+ )({ name: 'Object', id: 'ContrastObject' }),
153
+ statement(
154
+ 'const %%name%% = global.%%id%% || %%name%%;'
155
+ )({ name: 'Number', id: 'ContrastNumber' })
156
+ );
157
+ Object.assign(self.rewriteTransforms, {
158
+ AssignmentExpression(path) {
159
+ if (path.node.operator !== '+=') return;
160
+ path.replaceWith(
161
+ t.assignmentExpression(
162
+ '=',
163
+ path.node.left,
164
+ t.callExpression(expression('global.ContrastMethods.plus')(), [path.node.left, path.node.right])
165
+ )
166
+ );
167
+ }
168
+ });
169
+ }
170
+
171
+ self.tokens = Object.keys(self.methodLookups);
172
+ };
106
173
  }
107
174
 
108
175
  /**
@@ -129,7 +196,7 @@ class Rewriter {
129
196
  ...opts
130
197
  };
131
198
 
132
- if (state.orig.indexOf('eval') === -1 && state.orig.indexOf('Function') === -1) {
199
+ if (this.tokens.every((token) => state.orig.indexOf(token) === -1)) {
133
200
  return { code: state.orig };
134
201
  }
135
202
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contrast/rewriter",
3
- "version": "1.1.0",
3
+ "version": "1.3.0",
4
4
  "description": "A transpilation tool mainly used for instrumentation",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "author": "Contrast Security <nodejs@contrastsecurity.com> (https://www.contrastsecurity.com)",