@eagleoutice/flowr 2.16.0 → 2.16.2

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 (80) hide show
  1. package/README.md +9 -9
  2. package/cli/flowr-main-options.d.ts +15 -0
  3. package/cli/flowr-main-options.js +18 -0
  4. package/cli/flowr.d.ts +18 -0
  5. package/cli/flowr.js +13 -2
  6. package/cli/repl/commands/repl-clipboard.js +2 -1
  7. package/cli/repl/commands/repl-commands.js +2 -0
  8. package/cli/repl/commands/repl-main.d.ts +5 -0
  9. package/cli/repl/commands/repl-signature.js +2 -0
  10. package/cli/repl/core.d.ts +7 -1
  11. package/cli/repl/core.js +17 -8
  12. package/cli/repl/execute.js +2 -0
  13. package/cli/repl/server/connection.js +2 -1
  14. package/cli/repl/server/net.d.ts +10 -0
  15. package/cli/repl/server/net.js +34 -1
  16. package/cli/slicer-app.js +2 -1
  17. package/config.d.ts +12 -2
  18. package/config.js +91 -14
  19. package/dataflow/environments/built-in-props.d.ts +5 -2
  20. package/dataflow/environments/built-in-props.js +6 -3
  21. package/dataflow/environments/default-builtin-config.d.ts +197 -11
  22. package/dataflow/environments/default-builtin-config.js +62 -42
  23. package/dataflow/environments/identifier.d.ts +1 -0
  24. package/dataflow/environments/query-fn-props.d.ts +3 -0
  25. package/dataflow/environments/query-fn-props.js +8 -0
  26. package/dataflow/environments/resolve-by-name.js +11 -4
  27. package/dataflow/eval/resolve/resolve-argument.js +5 -1
  28. package/dataflow/extractor.js +14 -5
  29. package/dataflow/fn/frame-reflection.js +14 -2
  30. package/dataflow/graph/graph.js +12 -0
  31. package/dataflow/internal/control-flow.d.ts +11 -0
  32. package/dataflow/internal/control-flow.js +15 -0
  33. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.js +4 -10
  34. package/dataflow/internal/process/functions/call/built-in/built-in-function-definition.js +1 -1
  35. package/dataflow/internal/process/functions/call/built-in/built-in-purrr-formula.js +9 -0
  36. package/dataflow/internal/process/functions/call/built-in/transitive-side-effects.js +8 -7
  37. package/dataflow/internal/process/functions/call/deferred.js +6 -1
  38. package/dataflow/internal/process/functions/call/named-call-handling.js +70 -9
  39. package/documentation/doc-capabilities.js +4 -1
  40. package/documentation/wiki-interface.js +4 -0
  41. package/engines.js +11 -3
  42. package/linter/linter-executor.js +19 -1
  43. package/linter/linter-rules.d.ts +8 -3
  44. package/linter/rules/file-path-validity.js +4 -1
  45. package/linter/rules/function-finder-util.d.ts +1 -1
  46. package/linter/rules/function-finder-util.js +1 -3
  47. package/linter/rules/network-functions.d.ts +4 -3
  48. package/linter/rules/network-functions.js +14 -12
  49. package/linter/rules/no-leaked-credentials.d.ts +8 -3
  50. package/linter/rules/no-leaked-credentials.js +133 -35
  51. package/linter/rules/problematic-inputs.d.ts +1 -1
  52. package/linter/rules/problematic-inputs.js +20 -14
  53. package/linter/rules/seeded-randomness.js +3 -1
  54. package/linter/rules/unescaped-arguments.d.ts +13 -2
  55. package/linter/rules/unescaped-arguments.js +100 -12
  56. package/package.json +1 -1
  57. package/project/plugins/file-plugins/files/flowr-rda-file.d.ts +14 -5
  58. package/project/plugins/file-plugins/files/flowr-rda-file.js +35 -24
  59. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.js +2 -1
  60. package/project/sigdb/decompress.js +3 -1
  61. package/project/sigdb/sigdb-download.js +9 -6
  62. package/queries/catalog/call-context-query/call-context-query-executor.js +2 -1
  63. package/queries/catalog/config-query/config-query-executor.js +9 -2
  64. package/queries/catalog/input-sources-query/input-source-functions.d.ts +6 -4
  65. package/queries/catalog/input-sources-query/input-source-functions.js +11 -6
  66. package/queries/catalog/input-sources-query/input-sources-query-executor.js +1 -1
  67. package/queries/catalog/input-sources-query/input-sources-query-format.d.ts +1 -1
  68. package/queries/catalog/input-sources-query/input-sources-query-format.js +9 -2
  69. package/queries/catalog/input-sources-query/simple-input-classifier.d.ts +12 -4
  70. package/queries/catalog/input-sources-query/simple-input-classifier.js +227 -29
  71. package/r-bridge/shell-executor.js +2 -0
  72. package/r-bridge/shell.js +2 -0
  73. package/search/search-executor/search-enrichers.js +5 -3
  74. package/slicing/static/static-slicer.js +14 -9
  75. package/util/files.d.ts +6 -0
  76. package/util/files.js +12 -0
  77. package/util/parallel.js +2 -0
  78. package/util/secure-mode.d.ts +42 -0
  79. package/util/secure-mode.js +70 -0
  80. package/util/version.js +2 -2
package/README.md CHANGED
@@ -38,7 +38,7 @@ It offers a wide variety of features, for example:
38
38
 
39
39
  ```shell
40
40
  $ docker run -it --rm eagleoutice/flowr # or npm run flowr
41
- flowR repl v2.15.10, R grammar v14 (tree-sitter engine)
41
+ flowR repl v2.16.0, R grammar v14 (tree-sitter engine)
42
42
  R> :query @linter "read.csv(\"/root/x.txt\")"
43
43
  ```
44
44
 
@@ -46,7 +46,7 @@ It offers a wide variety of features, for example:
46
46
  <summary style='color:gray'>Output</summary>
47
47
 
48
48
  ```text
49
- Query: linter (28 ms)
49
+ Query: linter (11 ms)
50
50
  ╰ Deprecated Functions (deprecated-functions): no findings
51
51
  ╰ File Path Validity (file-path-validity): no findings
52
52
  ╰ Seeded Randomness (seeded-randomness): no findings
@@ -65,7 +65,7 @@ It offers a wide variety of features, for example:
65
65
  ╰ Unclosed Connection (unclosed-connection): no findings
66
66
  ╰ Unescaped Arguments (unescaped-arguments): no findings
67
67
  ╰ Namespace Access Validity (namespace-access): no findings
68
- All queries together required ≈28 ms (1ms accuracy, total 28 ms)
68
+ All queries together required ≈12 ms (1ms accuracy, total 12 ms)
69
69
  ```
70
70
 
71
71
  The linter will analyze the code and return any issues found.
@@ -79,7 +79,7 @@ It offers a wide variety of features, for example:
79
79
 
80
80
  _Results (prettified and summarized):_
81
81
 
82
- Query: **linter** (48 ms)\
82
+ Query: **linter** (13 ms)\
83
83
  &nbsp;&nbsp;&nbsp;╰ **Deprecated Functions** (deprecated-functions): _no findings_\
84
84
  &nbsp;&nbsp;&nbsp;╰ **File Path Validity** (file-path-validity):\
85
85
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;╰ certain:\
@@ -102,7 +102,7 @@ It offers a wide variety of features, for example:
102
102
  &nbsp;&nbsp;&nbsp;╰ **Unclosed Connection** (unclosed-connection): _no findings_\
103
103
  &nbsp;&nbsp;&nbsp;╰ **Unescaped Arguments** (unescaped-arguments): _no findings_\
104
104
  &nbsp;&nbsp;&nbsp;╰ **Namespace Access Validity** (namespace-access): _no findings_\
105
- _All queries together required ≈49 ms (1ms accuracy, total 49 ms)_
105
+ _All queries together required ≈13 ms (1ms accuracy, total 13 ms)_
106
106
 
107
107
  <details> <summary style="color:gray">Show Detailed Results as Json</summary>
108
108
 
@@ -193,7 +193,7 @@ It offers a wide variety of features, for example:
193
193
 
194
194
  ```shell
195
195
  $ docker run -it --rm eagleoutice/flowr # or npm run flowr
196
- flowR repl v2.15.10, R grammar v14 (tree-sitter engine)
196
+ flowR repl v2.16.0, R grammar v14 (tree-sitter engine)
197
197
  R> :query @static-slice (11@sum) file://test/testfiles/example.R
198
198
  ```
199
199
 
@@ -206,7 +206,7 @@ It offers a wide variety of features, for example:
206
206
  N <- 10
207
207
  for(i in 1:(N-1)) sum <- sum + i + w
208
208
  sum
209
- All queries together required ≈24 ms (1ms accuracy, total 24 ms)
209
+ All queries together required ≈4 ms (1ms accuracy, total 4 ms)
210
210
  ```
211
211
 
212
212
  </details>
@@ -214,7 +214,7 @@ It offers a wide variety of features, for example:
214
214
  </details>
215
215
 
216
216
  * 🚀 **fast call-graph, data-, and control-flow graphs**\
217
- Within just [<i><span title="This measurement is automatically fetched from the latest benchmark!">115 ms</span></i> (as of Oct 4, 2026)](https://flowr-analysis.github.io/flowr/wiki/stats/benchmark),
217
+ Within just [<i><span title="This measurement is automatically fetched from the latest benchmark!">85.8 ms</span></i> (as of Oct 14, 2026)](https://flowr-analysis.github.io/flowr/wiki/stats/benchmark),
218
218
  _flowR_ can analyze the data- and control-flow of the average real-world R&nbsp;script. See the [benchmarks](https://flowr-analysis.github.io/flowr/wiki/stats/benchmark) for more information,
219
219
  and consult the [wiki pages](https://github.com/flowr-analysis/flowr/wiki/Dataflow-Graph) for more details on the [dataflow graphs](https://github.com/flowr-analysis/flowr/wiki/Dataflow-Graph) as well as [call graphs](https://github.com/flowr-analysis/flowr/wiki/Dataflow-Graph#perspectives-cg).
220
220
  (&nbsp;[▶&nbsp;Explore in Browser](https://flowr-analysis.github.io/flowr/wiki/playground/#c=zDYSwRgTghhCeAUATADsWECUAoLBnAxlMAKYD6ALgPakC2UAHgAQA8AtIwGYCuAdvuSEo949DIyYB6RnXojsWaAHdGKlW0aIo5KADoO0GsXghEjALyMAjAC4AbABpGANyJdi5xvngBmRwA5HAHZHACZHAE5HABYMbHwSKB5VdQ4QYHJiCHglRxdgN0YAPkYQuISeABICImJTdWqSCmoZeHjiRIq8t3lcLho6OFJcbXJcFnZe-pgQXCM2xMdDRI8l4Qba2KxeLlnEJu1gNQm%2B7KhFTtdieUUIEAydfFwneEmB2CGR3EcAIleYWAeT2%2B2FQlHIrXKVUIJEQIMoIB4owh7UqJgwQA&p=13:1 "run this script in flowR's playground, no setup")&nbsp;)
@@ -245,7 +245,7 @@ It offers a wide variety of features, for example:
245
245
 
246
246
  ```shell
247
247
  $ docker run -it --rm eagleoutice/flowr # or npm run flowr
248
- flowR repl v2.15.10, R grammar v14 (tree-sitter engine)
248
+ flowR repl v2.16.0, R grammar v14 (tree-sitter engine)
249
249
  R> :dataflow* test/testfiles/example.R
250
250
  ```
251
251
 
@@ -7,6 +7,11 @@ export declare const flowrMainOptionDefinitions: [{
7
7
  readonly type: StringConstructor;
8
8
  readonly description: "The name of the configuration file to use";
9
9
  readonly multiple: false;
10
+ }, {
11
+ readonly name: "trust-config";
12
+ readonly type: BooleanConstructor;
13
+ readonly description: "Keep the security-sensitive options (e.g., the R executable) of the flowr.json found in the working directory or a parent. Only use this for projects you trust.";
14
+ readonly multiple: false;
10
15
  }, {
11
16
  readonly name: "config-json";
12
17
  readonly type: StringConstructor;
@@ -43,6 +48,11 @@ export declare const flowrMainOptionDefinitions: [{
43
48
  readonly type: StringConstructor;
44
49
  readonly description: "The path to the R executable to use. Defaults to your PATH. This option is being phased out in favor of the engine configuration option \"engine.r-shell.r-path\", which should be used instead.";
45
50
  readonly multiple: false;
51
+ }, {
52
+ readonly name: "secure";
53
+ readonly type: BooleanConstructor;
54
+ readonly description: "Run in secure mode for analyzing untrusted code: flowR does not start R (or any other process), does not access the network, does not search for project configs, and ignores security-sensitive options in every config. Cannot be disabled once enabled. Can also be enabled with the environment variable {italic FLOWR_SECURE_MODE=1}.";
55
+ readonly multiple: false;
46
56
  }, {
47
57
  readonly name: "r-session-access";
48
58
  readonly type: BooleanConstructor;
@@ -74,6 +84,11 @@ export declare const flowrMainOptionDefinitions: [{
74
84
  readonly name: "ws";
75
85
  readonly type: BooleanConstructor;
76
86
  readonly description: "If the server flag is set, use websocket for messaging";
87
+ }, {
88
+ readonly name: "ws-allow-origin";
89
+ readonly type: StringConstructor;
90
+ readonly description: "An origin (e.g., {italic https://example.org}) whose web pages may connect to the websocket server, in addition to local pages and clients that are no browser. Can be given multiple times, {italic *} allows all origins.";
91
+ readonly multiple: true;
77
92
  }, {
78
93
  readonly name: "engine.r-shell.disabled";
79
94
  readonly type: BooleanConstructor;
@@ -16,6 +16,12 @@ function getScriptsText() {
16
16
  }
17
17
  exports.flowrMainOptionDefinitions = [
18
18
  { name: 'config-file', type: String, description: 'The name of the configuration file to use', multiple: false },
19
+ {
20
+ name: 'trust-config',
21
+ type: Boolean,
22
+ description: 'Keep the security-sensitive options (e.g., the R executable) of the flowr.json found in the working directory or a parent. Only use this for projects you trust.',
23
+ multiple: false
24
+ },
19
25
  {
20
26
  name: 'config-json',
21
27
  type: String,
@@ -59,6 +65,12 @@ exports.flowrMainOptionDefinitions = [
59
65
  description: 'The path to the R executable to use. Defaults to your PATH. This option is being phased out in favor of the engine configuration option "engine.r-shell.r-path", which should be used instead.',
60
66
  multiple: false
61
67
  },
68
+ {
69
+ name: 'secure',
70
+ type: Boolean,
71
+ description: 'Run in secure mode for analyzing untrusted code: flowR does not start R (or any other process), does not access the network, does not search for project configs, and ignores security-sensitive options in every config. Cannot be disabled once enabled. Can also be enabled with the environment variable {italic FLOWR_SECURE_MODE=1}.',
72
+ multiple: false
73
+ },
62
74
  {
63
75
  name: 'r-session-access',
64
76
  type: Boolean,
@@ -92,6 +104,12 @@ exports.flowrMainOptionDefinitions = [
92
104
  description: 'Provide information about the version of flowR as well as its underlying R system and exit.'
93
105
  },
94
106
  { name: 'ws', type: Boolean, description: 'If the server flag is set, use websocket for messaging' },
107
+ {
108
+ name: 'ws-allow-origin',
109
+ type: String,
110
+ description: 'An origin (e.g., {italic https://example.org}) whose web pages may connect to the websocket server, in addition to local pages and clients that are no browser. Can be given multiple times, {italic *} allows all origins.',
111
+ multiple: true
112
+ },
95
113
  {
96
114
  name: 'engine.r-shell.disabled',
97
115
  type: Boolean,
package/cli/flowr.d.ts CHANGED
@@ -9,10 +9,12 @@ export declare const toolName = "flowr";
9
9
  export interface FlowrCliOptions {
10
10
  'config-file': string;
11
11
  'config-json': string;
12
+ 'trust-config': boolean;
12
13
  'no-ansi': boolean;
13
14
  'no-fs': boolean;
14
15
  'r-path': string | undefined;
15
16
  'r-session-access': boolean;
17
+ secure: boolean;
16
18
  execute: string | undefined;
17
19
  help: boolean;
18
20
  port: number;
@@ -21,6 +23,7 @@ export interface FlowrCliOptions {
21
23
  verbose: boolean;
22
24
  version: boolean;
23
25
  ws: boolean;
26
+ 'ws-allow-origin': string[] | undefined;
24
27
  'default-engine': string;
25
28
  'engine.r-shell.disabled': boolean;
26
29
  'engine.r-shell.r-path': string | undefined;
@@ -45,6 +48,11 @@ export declare const optionHelp: ({
45
48
  readonly type: StringConstructor;
46
49
  readonly description: "The name of the configuration file to use";
47
50
  readonly multiple: false;
51
+ }, {
52
+ readonly name: "trust-config";
53
+ readonly type: BooleanConstructor;
54
+ readonly description: "Keep the security-sensitive options (e.g., the R executable) of the flowr.json found in the working directory or a parent. Only use this for projects you trust.";
55
+ readonly multiple: false;
48
56
  }, {
49
57
  readonly name: "config-json";
50
58
  readonly type: StringConstructor;
@@ -81,6 +89,11 @@ export declare const optionHelp: ({
81
89
  readonly type: StringConstructor;
82
90
  readonly description: "The path to the R executable to use. Defaults to your PATH. This option is being phased out in favor of the engine configuration option \"engine.r-shell.r-path\", which should be used instead.";
83
91
  readonly multiple: false;
92
+ }, {
93
+ readonly name: "secure";
94
+ readonly type: BooleanConstructor;
95
+ readonly description: "Run in secure mode for analyzing untrusted code: flowR does not start R (or any other process), does not access the network, does not search for project configs, and ignores security-sensitive options in every config. Cannot be disabled once enabled. Can also be enabled with the environment variable {italic FLOWR_SECURE_MODE=1}.";
96
+ readonly multiple: false;
84
97
  }, {
85
98
  readonly name: "r-session-access";
86
99
  readonly type: BooleanConstructor;
@@ -112,6 +125,11 @@ export declare const optionHelp: ({
112
125
  readonly name: "ws";
113
126
  readonly type: BooleanConstructor;
114
127
  readonly description: "If the server flag is set, use websocket for messaging";
128
+ }, {
129
+ readonly name: "ws-allow-origin";
130
+ readonly type: StringConstructor;
131
+ readonly description: "An origin (e.g., {italic https://example.org}) whose web pages may connect to the websocket server, in addition to local pages and clients that are no browser. Can be given multiple times, {italic *} allows all origins.";
132
+ readonly multiple: true;
115
133
  }, {
116
134
  readonly name: "engine.r-shell.disabled";
117
135
  readonly type: BooleanConstructor;
package/cli/flowr.js CHANGED
@@ -63,6 +63,7 @@ const fs_1 = __importDefault(require("fs"));
63
63
  const path_1 = __importDefault(require("path"));
64
64
  const engines_1 = require("../engines");
65
65
  const flowr_analyzer_builder_1 = require("../project/flowr-analyzer-builder");
66
+ const secure_mode_1 = require("../util/secure-mode");
66
67
  exports.toolName = 'flowr';
67
68
  exports.optionHelp = [
68
69
  {
@@ -88,6 +89,13 @@ const options = (0, command_line_args_1.default)(flowr_main_options_1.flowrMainO
88
89
  log_1.log.updateSettings(l => l.settings.minLevel = options.verbose ? 1 /* LogLevel.Trace */ : 5 /* LogLevel.Error */);
89
90
  log_1.log.debug(`flowR ${(0, version_1.flowrVersion)().toString()}, node ${process.version}, ${process.platform}/${process.arch}`);
90
91
  log_1.log.info('running with options', options);
92
+ if (options.secure) {
93
+ secure_mode_1.SecureMode.enable();
94
+ }
95
+ if (secure_mode_1.SecureMode.isEnabled() && options['r-session-access']) {
96
+ console.error('The secure mode forbids --r-session-access, as it would run R code');
97
+ process.exit(1);
98
+ }
91
99
  if (options['no-ansi'] || (process.env.NO_COLOR !== undefined && process.env.NO_COLOR !== '')) {
92
100
  log_1.log.info('disabling ansi colors');
93
101
  (0, ansi_1.setFormatter)(ansi_1.voidFormatter);
@@ -113,7 +121,10 @@ function createConfig() {
113
121
  process.exit(1);
114
122
  }
115
123
  }
116
- config = config_1.FlowrConfig.fromFile(options['config-file'] ?? flowr_main_options_1.defaultConfigFile);
124
+ // a file named by the user is trusted, a flowr.json found in the analyzed project is not
125
+ config = options['config-file']
126
+ ? config_1.FlowrConfig.fromFile(path_1.default.resolve(options['config-file']))
127
+ : config_1.FlowrConfig.fromFile(flowr_main_options_1.defaultConfigFile, process.cwd(), options['trust-config']);
117
128
  }
118
129
  }
119
130
  // for all options that we manually supply that have a config equivalent, set them in the config
@@ -233,7 +244,7 @@ async function mainServer(useWebSocket) {
233
244
  // so the common one-shot analysis path does not pay for evaluating it
234
245
  const { FlowRServer } = await Promise.resolve().then(() => __importStar(require('./repl/server/server')));
235
246
  const { NetServer, WebSocketServerWrapper } = await Promise.resolve().then(() => __importStar(require('./repl/server/net')));
236
- const backend = useWebSocket ? new WebSocketServerWrapper() : new NetServer();
247
+ const backend = useWebSocket ? new WebSocketServerWrapper(options['ws-allow-origin']) : new NetServer();
237
248
  await new FlowRServer(engines.engines, engines.default, options['r-session-access'], config, backend).start(options.port);
238
249
  }
239
250
  async function main() {
@@ -34,6 +34,7 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.ReplClipboard = void 0;
37
+ const secure_mode_1 = require("../../../util/secure-mode");
37
38
  /**
38
39
  * Output that the user most likely wants on their clipboard as well.
39
40
  * @helper output
@@ -43,7 +44,7 @@ exports.ReplClipboard = {
43
44
  /** Prints `text` and, if the output allows it, copies it to the clipboard and reports `note` afterwards. */
44
45
  async print(output, text, note) {
45
46
  output.stdout(text);
46
- if (output.allowClipboard !== false) {
47
+ if (output.allowClipboard !== false && !secure_mode_1.SecureMode.isEnabled()) {
47
48
  try {
48
49
  const clipboard = await Promise.resolve().then(() => __importStar(require('clipboardy')));
49
50
  clipboard.default.writeSync(text);
@@ -186,6 +186,8 @@ function getReplCommands() {
186
186
  description,
187
187
  aliases: [],
188
188
  script: true,
189
+ // master scripts run as separate processes with client-controlled arguments (e.g., output files)
190
+ localOnly: true,
189
191
  usageExample: `:${script} --help`,
190
192
  isCodeCommand: false,
191
193
  fn: async ({ output, remainingLine, analyzer }) => {
@@ -54,6 +54,11 @@ export interface ReplBaseCommand {
54
54
  script: boolean;
55
55
  /** Example of how to use the command, for example `:slicer --help` */
56
56
  usageExample: string;
57
+ /**
58
+ * Commands that may act beyond analyzing code, e.g., spawn processes, write files, or change the user's global state,
59
+ * are only available to the local user and refused for remote clients of the server (see {@link replProcessAnswer}).
60
+ */
61
+ localOnly?: boolean;
57
62
  }
58
63
  export interface ReplCommand extends ReplBaseCommand {
59
64
  isCodeCommand: false;
@@ -136,6 +136,8 @@ exports.signatureCommand = {
136
136
  usageExample: ':signature <query|add|download> ...',
137
137
  aliases: ['sig'],
138
138
  script: false,
139
+ // `add` mounts arbitrary local files and `download` fetches from the network and persists into the global config
140
+ localOnly: true,
139
141
  argsParser: parseArgs,
140
142
  fn: async ({ output, analyzer, remainingArgs }) => {
141
143
  const [sub = 'help', ...rest] = remainingArgs.filter(a => a.length > 0);
@@ -27,6 +27,11 @@ export interface CommandCompletions {
27
27
  }
28
28
  /** Labels a completion with what it does, see {@link CommandCompletions#labels|labels}. */
29
29
  export declare function describeCompletion(insert: string, describe: string): string;
30
+ /**
31
+ * Every completion for `line`, the fragment of it they replace, the labels saying what each does, and the
32
+ * display-only hints; {@link replCompleter} and {@link completionSuggestion} are the two views the terminal needs.
33
+ */
34
+ export declare function computeCompletions(line: string, config: FlowrConfig): [string[], string, ReadonlyMap<string, string>?, (readonly string[])?];
30
35
  /**
31
36
  * Used by the repl to provide automatic completions for a given (partial) input line. Returns every matching
32
37
  * option, so Tab shows the full menu and only completes when a single option remains (standard readline behavior).
@@ -63,8 +68,9 @@ export declare function startWatching(watchPath: string, output: ReplOutput, onF
63
68
  * @param output - Defines two methods that every function in the repl uses to output its data.
64
69
  * @param expr - The expression to process.
65
70
  * @param allowRSessionAccess - If true, allows the execution of arbitrary R code.
71
+ * @param remote - If true, the expression comes from a (untrusted) client of the server, which may not use {@link ReplBaseCommand#localOnly} commands.
66
72
  */
67
- export declare function replProcessAnswer(analyzer: FlowrAnalyzer, output: ReplOutput, expr: string, allowRSessionAccess: boolean): Promise<void>;
73
+ export declare function replProcessAnswer(analyzer: FlowrAnalyzer, output: ReplOutput, expr: string, allowRSessionAccess: boolean, remote?: boolean): Promise<void>;
68
74
  /**
69
75
  * Options for the {@link repl} function.
70
76
  */
package/cli/repl/core.js CHANGED
@@ -37,6 +37,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.describeCompletion = describeCompletion;
40
+ exports.computeCompletions = computeCompletions;
40
41
  exports.replCompleter = replCompleter;
41
42
  exports.completionSuggestion = completionSuggestion;
42
43
  exports.makeDefaultReplReadline = makeDefaultReplReadline;
@@ -84,6 +85,10 @@ const defaultHistoryFile = path_1.default.join(os_1.default.tmpdir(), '.flowrhis
84
85
  function describeCompletion(insert, describe) {
85
86
  return `${insert} ${ansi_1.ansiFormatter.format(describe, { style: 2 /* FontStyles.Faint */ })}`;
86
87
  }
88
+ /**
89
+ * Every completion for `line`, the fragment of it they replace, the labels saying what each does, and the
90
+ * display-only hints; {@link replCompleter} and {@link completionSuggestion} are the two views the terminal needs.
91
+ */
87
92
  function computeCompletions(line, config) {
88
93
  const splitLine = (0, args_1.splitAtEscapeSensitive)(line);
89
94
  // did we just type a space (and are starting a new arg right now)?
@@ -241,7 +246,7 @@ function startWatching(watchPath, output, onFire, watchImpl = fs_1.default.watch
241
246
  output.stdout(faint(`Watching ${isDir ? 'folder' : 'file'} '${watchPath}'. Press Ctrl+C or enter another command to stop.`));
242
247
  return watcher;
243
248
  }
244
- async function executeStatement(output, statement, analyzer, allowRSessionAccess) {
249
+ async function executeStatement(output, statement, analyzer, allowRSessionAccess, remote) {
245
250
  const time = Date.now();
246
251
  const heatMap = new Map();
247
252
  if (analyzer.inspectContext().config.repl.dfProcessorHeat) {
@@ -258,7 +263,10 @@ async function executeStatement(output, statement, analyzer, allowRSessionAccess
258
263
  };
259
264
  try {
260
265
  const processor = (0, repl_commands_1.getCommand)(command);
261
- if (processor) {
266
+ if (processor?.localOnly && remote) {
267
+ output.stderr(`the command '${command}' is only available in a local session, not to clients of the server\n`);
268
+ }
269
+ else if (processor) {
262
270
  await (0, query_1.genericWrapReplFailIfNoRequest)(async () => {
263
271
  const remainingLine = statement.slice(command.length + 2).trim();
264
272
  if (processor.isCodeCommand) {
@@ -330,17 +338,17 @@ async function executeStatement(output, statement, analyzer, allowRSessionAccess
330
338
  }
331
339
  }
332
340
  }
333
- async function replProcessStatement(output, statement, analyzer, allowRSessionAccess) {
341
+ async function replProcessStatement(output, statement, analyzer, allowRSessionAccess, remote) {
334
342
  stopWatching(output, !statement.includes(path_input_1.watchProtocol));
335
343
  if (statement.includes(path_input_1.watchProtocol)) {
336
344
  const watchPath = extractWatchPath(statement);
337
345
  const effective = toFileStatement(statement);
338
- await executeStatement(output, effective, analyzer, allowRSessionAccess);
346
+ await executeStatement(output, effective, analyzer, allowRSessionAccess, remote);
339
347
  if (watchPath) {
340
348
  try {
341
349
  activeWatcher = startWatching(watchPath, output, () => {
342
350
  analyzer.context().files.getFileByPath(watchPath)?.invalidate();
343
- void executeStatement(output, effective, analyzer, allowRSessionAccess);
351
+ void executeStatement(output, effective, analyzer, allowRSessionAccess, remote);
344
352
  });
345
353
  activeWatcher.unref();
346
354
  activeWatcher.on('error', (err) => {
@@ -354,7 +362,7 @@ async function replProcessStatement(output, statement, analyzer, allowRSessionAc
354
362
  }
355
363
  return;
356
364
  }
357
- await executeStatement(output, statement, analyzer, allowRSessionAccess);
365
+ await executeStatement(output, statement, analyzer, allowRSessionAccess, remote);
358
366
  }
359
367
  /**
360
368
  * This function interprets the given `expr` as a REPL command (see {@link repl} for more on the semantics).
@@ -362,11 +370,12 @@ async function replProcessStatement(output, statement, analyzer, allowRSessionAc
362
370
  * @param output - Defines two methods that every function in the repl uses to output its data.
363
371
  * @param expr - The expression to process.
364
372
  * @param allowRSessionAccess - If true, allows the execution of arbitrary R code.
373
+ * @param remote - If true, the expression comes from a (untrusted) client of the server, which may not use {@link ReplBaseCommand#localOnly} commands.
365
374
  */
366
- async function replProcessAnswer(analyzer, output, expr, allowRSessionAccess) {
375
+ async function replProcessAnswer(analyzer, output, expr, allowRSessionAccess, remote = false) {
367
376
  const statements = (0, args_1.splitAtEscapeSensitive)(expr, false, /^;\s*:/);
368
377
  for (const statement of statements) {
369
- await replProcessStatement(output, statement.trim(), analyzer, allowRSessionAccess);
378
+ await replProcessStatement(output, statement.trim(), analyzer, allowRSessionAccess, remote);
370
379
  }
371
380
  }
372
381
  /**
@@ -10,6 +10,7 @@ const readline_1 = __importDefault(require("readline"));
10
10
  const assert_1 = require("../../util/assert");
11
11
  const log_1 = require("../../util/log");
12
12
  const proc_1 = require("../../util/proc");
13
+ const secure_mode_1 = require("../../util/secure-mode");
13
14
  /**
14
15
  * Simply captures the output of the script executed by {@link waitOnScript}.
15
16
  * @param stdio - The standard io tuple provided by {@link waitOnScript}
@@ -45,6 +46,7 @@ function stdioCaptureProcessor(stdio, onStdOutLine, onStdErrLine) {
45
46
  */
46
47
  async function waitOnScript(module, args, io, exitOnError = false) {
47
48
  log_1.log.info(`starting script ${module} with args ${JSON.stringify(args)}`);
49
+ secure_mode_1.SecureMode.guard('starting a process', module);
48
50
  const child = child_process_1.default.fork(module, args, {
49
51
  silent: io !== undefined
50
52
  });
@@ -335,7 +335,8 @@ class FlowRServerConnection {
335
335
  formatter: request.ansi ? ansi_1.ansiFormatter : ansi_1.voidFormatter,
336
336
  stdout: msg => out('stdout', msg),
337
337
  stderr: msg => out('stderr', msg)
338
- }, request.expression, this.allowRSessionAccess);
338
+ }, request.expression, this.allowRSessionAccess,
339
+ /* remote */ true);
339
340
  (0, send_1.sendMessage)(this.socket, {
340
341
  type: 'end-repl-execution',
341
342
  id: request.id
@@ -12,9 +12,19 @@ export interface Server {
12
12
  onConnect(handler: OnConnect): void;
13
13
  start(port: number): void;
14
14
  }
15
+ /**
16
+ * Whether a WebSocket client with the given `Origin` header may connect.
17
+ * Browsers send the origin of the page that opens the connection, so this keeps arbitrary web pages from talking to a
18
+ * local server (cross-site WebSocket hijacking). Clients that are no browser usually send no origin and are allowed,
19
+ * as are pages served from this machine and the origins in `allowed` (`*` allows all).
20
+ */
21
+ export declare function isAllowedWebSocketOrigin(origin: string | undefined, allowed?: readonly string[]): boolean;
15
22
  export declare class WebSocketServerWrapper implements Server {
23
+ private readonly allowedOrigins;
16
24
  private server;
17
25
  private connectHandler;
26
+ /** @param allowedOrigins - additional origins (besides the local ones) whose pages may connect, see {@link isAllowedWebSocketOrigin} */
27
+ constructor(allowedOrigins?: readonly string[]);
18
28
  onConnect(handler: OnConnect): void;
19
29
  start(port: number): void;
20
30
  }
@@ -4,20 +4,53 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.NetServer = exports.WebSocketWrapper = exports.WebSocketServerWrapper = void 0;
7
+ exports.isAllowedWebSocketOrigin = isAllowedWebSocketOrigin;
7
8
  /**
8
9
  * This is just a simple layer to allow me to mock the server's behavior in tests.
9
10
  */
10
11
  const net_1 = __importDefault(require("net"));
11
12
  const ws_1 = require("ws");
12
13
  const server_1 = require("./server");
14
+ /**
15
+ * Whether a WebSocket client with the given `Origin` header may connect.
16
+ * Browsers send the origin of the page that opens the connection, so this keeps arbitrary web pages from talking to a
17
+ * local server (cross-site WebSocket hijacking). Clients that are no browser usually send no origin and are allowed,
18
+ * as are pages served from this machine and the origins in `allowed` (`*` allows all).
19
+ */
20
+ function isAllowedWebSocketOrigin(origin, allowed = []) {
21
+ if (origin === undefined || allowed.includes('*') || allowed.includes(origin)) {
22
+ return true;
23
+ }
24
+ try {
25
+ return ['localhost', '127.0.0.1', '[::1]'].includes(new URL(origin).hostname);
26
+ }
27
+ catch {
28
+ return false;
29
+ }
30
+ }
13
31
  class WebSocketServerWrapper {
32
+ allowedOrigins;
14
33
  server;
15
34
  connectHandler;
35
+ /** @param allowedOrigins - additional origins (besides the local ones) whose pages may connect, see {@link isAllowedWebSocketOrigin} */
36
+ constructor(allowedOrigins = []) {
37
+ this.allowedOrigins = allowedOrigins;
38
+ }
16
39
  onConnect(handler) {
17
40
  this.connectHandler = handler;
18
41
  }
19
42
  start(port) {
20
- this.server = new ws_1.WebSocketServer({ port, maxPayload: 1024 * 1024 * 1024 * 1024 });
43
+ this.server = new ws_1.WebSocketServer({
44
+ port,
45
+ maxPayload: 1024 * 1024 * 1024 * 1024,
46
+ verifyClient: ({ origin }) => {
47
+ const allowed = isAllowedWebSocketOrigin(origin, this.allowedOrigins);
48
+ if (!allowed) {
49
+ server_1.serverLog.warn(`Refusing a WebSocket connection from origin ${origin}, allow it with --ws-allow-origin`);
50
+ }
51
+ return allowed;
52
+ }
53
+ });
21
54
  this.server.on('error', (e) => reportListenFailure(port, e));
22
55
  server_1.serverLog.info('WebSocket-Server wrapper is active!');
23
56
  this.server.on('connection', c => this.connectHandler?.(new WebSocketWrapper(c)));
package/cli/slicer-app.js CHANGED
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const fs_1 = __importDefault(require("fs"));
7
+ const path_1 = __importDefault(require("path"));
7
8
  const assert_1 = require("../util/assert");
8
9
  const log_1 = require("../util/log");
9
10
  const process_1 = require("../benchmark/summarizer/first-phase/process");
@@ -32,7 +33,7 @@ async function getSlice() {
32
33
  (0, assert_1.guard)(options.input !== undefined, 'input must be given');
33
34
  (0, assert_1.guard)(options.criterion !== undefined, 'a slicing criterion must be given');
34
35
  const config = (options['config-json'] ? config_1.FlowrConfig.parse(options['config-json']) : undefined)
35
- ?? config_1.FlowrConfig.fromFile(options['config-file']);
36
+ ?? config_1.FlowrConfig.fromFile(options['config-file'] && path_1.default.resolve(options['config-file']));
36
37
  await slicer.init(options['input-is-text']
37
38
  ? { request: 'text', content: options.input.replaceAll('\\n', '\n') }
38
39
  : { request: 'file', content: options.input }, config, options['no-magic-comments'] ? auto_select_defaults_1.doNotAutoSelect : (0, magic_comments_1.makeMagicCommentHandler)(auto_select_defaults_1.doNotAutoSelect), undefined, options.inline, options['include-callees'], options['inline-full'] ? (options['inline-banner'] ? 'banner' : true) : undefined);
package/config.d.ts CHANGED
@@ -349,7 +349,15 @@ export declare const FlowrConfig: {
349
349
  /**
350
350
  * Parses the given JSON string as a flowR config file, returning the resulting config object if the parsing and validation were successful, or `undefined` if there was an error.
351
351
  */
352
- readonly parse: (this: void, jsonString: string) => FlowrConfig | undefined;
352
+ readonly parse: (this: void, jsonString: string, trusted?: boolean) => FlowrConfig | undefined;
353
+ /** Paths (`*` matching any key) of all {@link securitySensitive} options, also within `specializeConfig`. */
354
+ readonly securitySensitivePaths: (this: void) => readonly (readonly string[])[];
355
+ /** Paths of all {@link regexOption} options, see {@link FlowrConfig.securitySensitivePaths}. */
356
+ readonly regexPaths: (this: void) => readonly (readonly string[])[];
357
+ /** Removes all {@link FlowrConfig.securitySensitivePaths} from the raw config (in place), returns the removed paths. */
358
+ readonly dropSecuritySensitive: (this: void, raw: unknown) => string[];
359
+ /** Like {@link FlowrConfig.dropSecuritySensitive}, but in {@link SecureMode} also drops the {@link FlowrConfig.regexPaths}. */
360
+ readonly dropUntrusted: (this: void, raw: unknown) => string[];
353
361
  /**
354
362
  * Creates a new flowr config that has the updated values.
355
363
  */
@@ -363,8 +371,10 @@ export declare const FlowrConfig: {
363
371
  * Please note that you can also use this without a path parameter to
364
372
  * infer the config from flowR's default locations.
365
373
  * This is mostly useful for user-facing features.
374
+ * A relative `configFile` is searched for in the working directory and its parents. That file belongs to the analyzed
375
+ * project, so its {@link securitySensitive} options are dropped unless `trustProjectConfig` is set.
366
376
  */
367
- readonly fromFile: (this: void, configFile?: string, configWorkingDirectory?: string) => FlowrConfig;
377
+ readonly fromFile: (this: void, configFile?: string, configWorkingDirectory?: string, trustProjectConfig?: boolean) => FlowrConfig;
368
378
  /**
369
379
  * Resolves the configuration for the given {@link ProjectKind} by applying the matching
370
380
  * {@link FlowrConfig.specializeConfig} entry to every key it names. What you configured wins over the entry, which in