@eagleoutice/flowr 2.16.0 → 2.16.1

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 (49) 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/extractor.js +14 -5
  20. package/dataflow/fn/frame-reflection.js +14 -2
  21. package/dataflow/internal/control-flow.d.ts +11 -0
  22. package/dataflow/internal/control-flow.js +15 -0
  23. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.js +4 -10
  24. package/dataflow/internal/process/functions/call/built-in/built-in-function-definition.js +1 -1
  25. package/dataflow/internal/process/functions/call/built-in/transitive-side-effects.js +8 -7
  26. package/dataflow/internal/process/functions/call/deferred.js +6 -1
  27. package/dataflow/internal/process/functions/call/named-call-handling.js +10 -1
  28. package/documentation/doc-capabilities.js +4 -1
  29. package/documentation/wiki-interface.js +4 -0
  30. package/engines.js +11 -3
  31. package/linter/linter-executor.js +19 -1
  32. package/linter/rules/file-path-validity.js +4 -1
  33. package/linter/rules/seeded-randomness.js +3 -1
  34. package/package.json +1 -1
  35. package/project/plugins/file-plugins/files/flowr-rda-file.d.ts +14 -5
  36. package/project/plugins/file-plugins/files/flowr-rda-file.js +35 -24
  37. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.js +2 -1
  38. package/project/sigdb/decompress.js +3 -1
  39. package/project/sigdb/sigdb-download.js +9 -6
  40. package/queries/catalog/config-query/config-query-executor.js +9 -2
  41. package/r-bridge/shell-executor.js +2 -0
  42. package/r-bridge/shell.js +2 -0
  43. package/slicing/static/static-slicer.js +14 -9
  44. package/util/files.d.ts +6 -0
  45. package/util/files.js +12 -0
  46. package/util/parallel.js +2 -0
  47. package/util/secure-mode.d.ts +42 -0
  48. package/util/secure-mode.js +70 -0
  49. package/util/version.js +2 -2
@@ -165,6 +165,15 @@ export declare enum SerializationFormat {
165
165
  Ascii = "ASCII",
166
166
  Binary = "BINARY"
167
167
  }
168
+ /** The parts of the (untyped) `bzip2` package we use. */
169
+ export interface Bzip2 {
170
+ array(bytes: Uint8Array): unknown;
171
+ header(bits: unknown): number;
172
+ /** decompresses the next block (stopping after `len` bytes), `-1` after the last one */
173
+ decompress(bits: unknown, size: number, len?: number): Uint8Array | -1;
174
+ }
175
+ /** Decompresses a bzip2 stream block by block, throwing a `RangeError` if it would yield more than `limit` bytes. */
176
+ export declare function bunzip(bzip2: Bzip2, content: Buffer, limit?: number): Buffer;
168
177
  /**
169
178
  * Parser for RDA files.
170
179
  * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c | R source: serialize.c}
@@ -176,7 +185,6 @@ export declare class RDAParser {
176
185
  private buffer;
177
186
  private currentDepth;
178
187
  private static readonly INITIAL_DEPTH;
179
- private lastName;
180
188
  private offset;
181
189
  private static readonly R_CODE_SET_MAX;
182
190
  private RWeakRefs;
@@ -250,15 +258,16 @@ export declare class RDAParser {
250
258
  * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L2117-L2121 | R source: ReadItem}
251
259
  */
252
260
  readItem(): RObject;
253
- /** Runs `code` in R and answers an `EnvSxp`, `value` set to {@link RValues.GlobalEnv} when the result names it. Shared by {@link R_FindNamespace} and {@link R_FindNamespace1}. */
254
- private runNamespaceLookup;
255
261
  /**
256
- * Resolves a namespace reference by name via `getNamespace()` in R. Simpler variant of {@link R_FindNamespace1}.
262
+ * Resolves a namespace reference by name. Simpler variant of {@link R_FindNamespace1}.
263
+ * R would load the namespace (`getNamespace()`), but flowR analyzes R code and data without running it: the name comes
264
+ * from the (untrusted) file, and loading a namespace runs the package's code. Hence, this answers an `EnvSxp` standing
265
+ * for the (unknown) namespace environment without consulting R.
257
266
  * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/envir.c#L3795-L3804 | R source: R_FindNamespace}
258
267
  */
259
268
  R_FindNamespace(info: RObjectData): RObjectData;
260
269
  /**
261
- * Resolves a serialized namespace reference by executing R at runtime. See {@link R_FindNamespace} for the result shape.
270
+ * Resolves a serialized namespace reference, see {@link R_FindNamespace} for why this does not ask R.
262
271
  * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L1785-L1796 | R source: R_FindNamespace1}
263
272
  */
264
273
  R_FindNamespace1(info: RObjectData): RObjectData;
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.RDAParser = exports.SerializationFormat = exports.SexpType = exports.SerializationTypeTag = exports.CompressionType = exports.FlowrRDAFile = void 0;
7
+ exports.bunzip = bunzip;
7
8
  exports.attributeOf = attributeOf;
8
9
  exports.stringsOf = stringsOf;
9
10
  exports.namesOf = namesOf;
@@ -12,8 +13,8 @@ const flowr_file_1 = require("../../../context/flowr-file");
12
13
  const fs_1 = __importDefault(require("fs"));
13
14
  const assert_1 = require("../../../../util/assert");
14
15
  const r_fun_tab_1 = require("./r-fun-tab");
15
- const shell_executor_1 = require("../../../../r-bridge/shell-executor");
16
16
  const log_1 = require("../../../../util/log");
17
+ const secure_mode_1 = require("../../../../util/secure-mode");
17
18
  const rdaLog = log_1.log.getSubLogger({ name: 'flowr-rda-file' });
18
19
  /**
19
20
  * This decorates a text file and provides access to its content in the format of an {@link RObjectData}.
@@ -227,6 +228,21 @@ const SpecialValueSxps = new Map([
227
228
  [SexpType.MissingArgSxp, { value: RValues.MissingArg, type: SexpType.EnvSxp }],
228
229
  [SexpType.BaseNamespaceSxp, { value: RValues.BaseNamespace, type: SexpType.EnvSxp }],
229
230
  ]);
231
+ /** Decompresses a bzip2 stream block by block, throwing a `RangeError` if it would yield more than `limit` bytes. */
232
+ function bunzip(bzip2, content, limit = Infinity) {
233
+ const bits = bzip2.array(content);
234
+ const size = bzip2.header(bits);
235
+ const chunks = [];
236
+ let total = 0;
237
+ for (let chunk = bzip2.decompress(bits, size, limit - total + 1); chunk !== -1; chunk = bzip2.decompress(bits, size, limit - total + 1)) {
238
+ total += chunk.byteLength;
239
+ if (total > limit) {
240
+ throw new RangeError(`Refusing to decompress more than ${limit} bytes`);
241
+ }
242
+ chunks.push(chunk);
243
+ }
244
+ return Buffer.concat(chunks);
245
+ }
230
246
  /**
231
247
  * Parser for RDA files.
232
248
  * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c | R source: serialize.c}
@@ -238,7 +254,6 @@ class RDAParser {
238
254
  buffer;
239
255
  currentDepth = 0;
240
256
  static INITIAL_DEPTH = 1;
241
- lastName = undefined;
242
257
  offset = 0;
243
258
  static R_CODE_SET_MAX = 2 ** 6 - 1;
244
259
  RWeakRefs = null;
@@ -290,27 +305,29 @@ class RDAParser {
290
305
  /** Decompresses `fileContent` per the {@link detectCompression} result `compressionType`. Throws error for unsupported compression types. */
291
306
  decompress(fileContent, compressionType) {
292
307
  let buffer;
308
+ // the file belongs to the (possibly hostile) project, so the secure mode bounds what it may decompress to
309
+ const limit = secure_mode_1.SecureMode.decompressionLimit();
293
310
  switch (compressionType) {
294
311
  case CompressionType.CompGz: {
295
312
  // eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/no-unsafe-assignment
296
313
  const zlib = require('zlib');
297
314
  try {
298
315
  // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
299
- buffer = zlib.gunzipSync(fileContent);
316
+ buffer = zlib.gunzipSync(fileContent, { maxOutputLength: limit });
300
317
  }
301
- catch {
318
+ catch (e) {
319
+ if (e.code === 'ERR_BUFFER_TOO_LARGE') {
320
+ throw e;
321
+ }
302
322
  // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
303
- buffer = zlib.inflateSync(fileContent);
323
+ buffer = zlib.inflateSync(fileContent, { maxOutputLength: limit });
304
324
  }
305
325
  break;
306
326
  }
307
327
  case CompressionType.CompBz: {
308
- // eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/no-unsafe-assignment
328
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
309
329
  const bzip2 = require('bzip2');
310
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
311
- const decompressed = bzip2.simple(bzip2.array(fileContent));
312
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
313
- buffer = Buffer.from(decompressed);
330
+ buffer = bunzip(bzip2, fileContent, limit);
314
331
  break;
315
332
  }
316
333
  case CompressionType.CompXz:
@@ -614,26 +631,23 @@ class RDAParser {
614
631
  const flags = this.assertInteger(this.inInteger());
615
632
  return this.readItemRecursive(flags);
616
633
  }
617
- /** Runs `code` in R and answers an `EnvSxp`, `value` set to {@link RValues.GlobalEnv} when the result names it. Shared by {@link R_FindNamespace} and {@link R_FindNamespace1}. */
618
- runNamespaceLookup(code) {
619
- const shell = new shell_executor_1.RShellExecutor();
620
- const result = shell.run(code);
621
- shell.close();
622
- return result === '<environment: R_GlobalEnv>' ? { type: SexpType.EnvSxp, value: RValues.GlobalEnv } : { type: SexpType.EnvSxp };
623
- }
624
634
  /**
625
- * Resolves a namespace reference by name via `getNamespace()` in R. Simpler variant of {@link R_FindNamespace1}.
635
+ * Resolves a namespace reference by name. Simpler variant of {@link R_FindNamespace1}.
636
+ * R would load the namespace (`getNamespace()`), but flowR analyzes R code and data without running it: the name comes
637
+ * from the (untrusted) file, and loading a namespace runs the package's code. Hence, this answers an `EnvSxp` standing
638
+ * for the (unknown) namespace environment without consulting R.
626
639
  * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/envir.c#L3795-L3804 | R source: R_FindNamespace}
627
640
  */
628
641
  R_FindNamespace(info) {
629
- return this.runNamespaceLookup(`getNamespace("${info.value.name}")`);
642
+ rdaLog.trace(`Not loading namespace ${JSON.stringify(info.value?.name)} of a serialized object`);
643
+ return { type: SexpType.EnvSxp };
630
644
  }
631
645
  /**
632
- * Resolves a serialized namespace reference by executing R at runtime. See {@link R_FindNamespace} for the result shape.
646
+ * Resolves a serialized namespace reference, see {@link R_FindNamespace} for why this does not ask R.
633
647
  * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L1785-L1796 | R source: R_FindNamespace1}
634
648
  */
635
649
  R_FindNamespace1(info) {
636
- return this.runNamespaceLookup(`..getNamespace("${info.value[0].name}", "${this.lastName}")`);
650
+ return this.R_FindNamespace({ ...info, value: info.value?.[0] });
637
651
  }
638
652
  /**
639
653
  * Deserializes a single SEXP node, dispatching on its encoded {@link SexpType}.
@@ -1076,9 +1090,6 @@ class RDAParser {
1076
1090
  this.currentDepth++;
1077
1091
  s.attributes = hasAttr ? [this.shortcut ? this.skipItem() : this.assertRObjectData(this.readItem())] : undefined;
1078
1092
  s.tag = hasTag ? this.readItem() : RValues.NilValue;
1079
- if (hasTag && this.currentDepth == RDAParser.INITIAL_DEPTH && typeof s.tag === 'object') {
1080
- this.lastName = s.tag.name;
1081
- }
1082
1093
  s.car = this.shortcut ? this.skipItem() : this.readItem();
1083
1094
  this.currentDepth--;
1084
1095
  if (sFirst === null) {
@@ -55,6 +55,7 @@ const r_version_1 = require("../../../util/r-version");
55
55
  const r_base_packages_1 = require("../../../util/r-base-packages");
56
56
  const defaultmap_1 = require("../../../util/collections/defaultmap");
57
57
  const arrays_1 = require("../../../util/collections/arrays");
58
+ const secure_mode_1 = require("../../../util/secure-mode");
58
59
  /** the plugin's instance name (pass to `unregisterPlugins` to disable the default sigdb resolver) */
59
60
  exports.SigDbPluginName = 'flowr-analyzer-package-versions-sigdb-plugin';
60
61
  /** a resolved source's compressed extension as a codec name for display, a file without one is `plain` */
@@ -171,7 +172,7 @@ class FlowrAnalyzerPackageVersionsSigDbPlugin extends flowr_analyzer_package_ver
171
172
  if (ctx.config.solver.sigdb.warmInBackground) {
172
173
  this.startBackgroundWarm();
173
174
  }
174
- if (ctx.config.solver.sigdb.autoSync) {
175
+ if (ctx.config.solver.sigdb.autoSync && !secure_mode_1.SecureMode.isEnabled()) {
175
176
  this.startBackgroundSync(ctx);
176
177
  }
177
178
  if (ctx.config.solver.sigdb.versionSelection === config_1.VersionSelection.System) {
@@ -27,6 +27,7 @@ const schema_1 = require("./schema");
27
27
  const index_format_1 = require("./index-format");
28
28
  const hash_1 = require("../../util/hash");
29
29
  const codec_1 = require("./codec");
30
+ const files_1 = require("../../util/files");
30
31
  /** whether a bundle path is a compressed (`.br`/`.zst`/`.gz`) source that must be decompressed to be seekable */
31
32
  const isCompressed = (f) => (0, codec_1.isCompressedExt)(f);
32
33
  exports.isCompressed = isCompressed;
@@ -117,7 +118,8 @@ async function readHeaderOf(source) {
117
118
  }
118
119
  }
119
120
  function cachePaths(hash, cacheDir) {
120
- const plain = path_1.default.join(sigDbCacheDir(cacheDir), `sigdb-${hash}${schema_1.SigDbExt}`);
121
+ // the hash may come from the header of a project-supplied bundle
122
+ const plain = (0, files_1.joinUntrustedSegment)(sigDbCacheDir(cacheDir), `sigdb-${hash}${schema_1.SigDbExt}`);
121
123
  return { plain, idx: `${plain}.idx` };
122
124
  }
123
125
  /** whether a compressed source with the given content hash has already been unpacked into its decompressed cache */
@@ -18,6 +18,8 @@ const crypto_1 = __importDefault(require("crypto"));
18
18
  const decompress_1 = require("./decompress");
19
19
  const codec_1 = require("./codec");
20
20
  const version_1 = require("../../util/version");
21
+ const files_1 = require("../../util/files");
22
+ const secure_mode_1 = require("../../util/secure-mode");
21
23
  /** the GitHub `owner/repo` the full-history bundle is published to (see `scripts/publish-sigdb.mjs`) */
22
24
  const DefaultRepo = 'flowr-analysis/flowr';
23
25
  /** GitHub request headers; the token (used only for the API's rate limit and private repos) is attached only when `withAuth` */
@@ -39,6 +41,7 @@ class HttpError extends Error {
39
41
  }
40
42
  /** GET following redirects (GitHub asset URLs redirect to a storage host); resolves the final response for streaming */
41
43
  function httpGet(url, accept, redirects = 5, withAuth = true) {
44
+ secure_mode_1.SecureMode.guard('network access', url);
42
45
  return new Promise((resolve, reject) => {
43
46
  const req = (url.startsWith('http:') ? http_1.default : https_1.default).get(url, { headers: ghHeaders(accept, withAuth) }, res => {
44
47
  const status = res.statusCode ?? 0;
@@ -143,9 +146,8 @@ function findRemotePointer() {
143
146
  return fs_1.default.existsSync(override) ? override : undefined;
144
147
  }
145
148
  const candidates = [
146
- path_1.default.join(__dirname, '../../data/sigdb', exports.SigDbRemoteFileName), // src/ and dist/src/ layouts (same depth)
147
- path_1.default.join(process.cwd(), 'src/data/sigdb', exports.SigDbRemoteFileName),
148
- path_1.default.join(process.cwd(), 'dist/src/data/sigdb', exports.SigDbRemoteFileName),
149
+ // src/ and dist/src/ layouts (same depth); never the working directory, which may be the analyzed (untrusted) project
150
+ path_1.default.join(__dirname, '../../data/sigdb', exports.SigDbRemoteFileName),
149
151
  ];
150
152
  return candidates.find(p => {
151
153
  try {
@@ -238,10 +240,11 @@ function isCached(dest, file) {
238
240
  async function syncFiles(tag, repo, planned, opts) {
239
241
  const progress = opts.onProgress ?? (() => { });
240
242
  const start = Date.now();
241
- const dir = path_1.default.join((0, decompress_1.sigDbCacheDir)(), 'bundles', tag);
243
+ // tag and file names come from the (remote) pointer and release listing
244
+ const dir = (0, files_1.joinUntrustedSegment)(path_1.default.join((0, decompress_1.sigDbCacheDir)(), 'bundles'), tag);
242
245
  fs_1.default.mkdirSync(dir, { recursive: true });
243
246
  const ordered = [...planned.filter(p => !(0, exports.isManifestFile)(p.name)), ...planned.filter(p => (0, exports.isManifestFile)(p.name))];
244
- const missing = ordered.filter(p => opts.force || !isCached(path_1.default.join(dir, p.name), p));
247
+ const missing = ordered.filter(p => opts.force || !isCached((0, files_1.joinUntrustedSegment)(dir, p.name), p));
245
248
  const toFetch = missing.reduce((sum, p) => sum + (p.expected?.bytes ?? p.size ?? 0), 0);
246
249
  progress(`signature database ${tag} from ${repo}: ${ordered.length} file(s), ${ordered.length - missing.length} up to date, ${missing.length} to fetch (${mb(toFetch)}) into ${dir}`);
247
250
  const files = [];
@@ -249,7 +252,7 @@ async function syncFiles(tag, repo, planned, opts) {
249
252
  const failed = [];
250
253
  let bytes = 0;
251
254
  for (const file of ordered) {
252
- const dest = path_1.default.join(dir, file.name);
255
+ const dest = (0, files_1.joinUntrustedSegment)(dir, file.name);
253
256
  if (!missing.includes(file)) {
254
257
  files.push(dest);
255
258
  continue;
@@ -4,6 +4,7 @@ exports.executeConfigQuery = executeConfigQuery;
4
4
  const log_1 = require("../../../util/log");
5
5
  const config_query_format_1 = require("./config-query-format");
6
6
  const assert_1 = require("../../../util/assert");
7
+ const config_1 = require("../../../config");
7
8
  /**
8
9
  * Executes the given configuration queries using the provided analyzer.
9
10
  */
@@ -17,12 +18,18 @@ function executeConfigQuery({ analyzer }, queries) {
17
18
  }
18
19
  // validate here too (not only in the repl parser), so a programmatic / JSON-API update cannot merge an unknown
19
20
  // key or a wrong-typed value; the update then lands via `updateConfig`, which invalidates the analysis cache
20
- for (const update of updates) {
21
- const err = (0, config_query_format_1.validateConfigUpdate)(update);
21
+ for (const given of updates) {
22
+ const err = (0, config_query_format_1.validateConfigUpdate)(given);
22
23
  if (err !== undefined) {
23
24
  log_1.log.warn(`ignoring invalid config update: ${err}`);
24
25
  continue;
25
26
  }
27
+ // queries may come from clients of the server, so they must not choose what flowR executes, loads, or downloads
28
+ const update = structuredClone(given);
29
+ const dropped = config_1.FlowrConfig.dropUntrusted(update);
30
+ if (dropped.length > 0) {
31
+ log_1.log.warn(`ignoring untrusted options in config update: ${dropped.join(', ')}`);
32
+ }
26
33
  analyzer.updateConfig(update);
27
34
  }
28
35
  const specialization = analyzer.inspectContext().configSpecialization();
@@ -12,6 +12,7 @@ const log_1 = require("../util/log");
12
12
  const init_1 = require("./init");
13
13
  const convert_values_1 = require("./lang-4.x/convert-values");
14
14
  const retriever_1 = require("./retriever");
15
+ const secure_mode_1 = require("../util/secure-mode");
15
16
  const executorLog = log_1.log.getSubLogger({ name: 'RShellExecutor' });
16
17
  /**
17
18
  * This is a synchronous alternative to the {@link RShell}.
@@ -69,6 +70,7 @@ class RShellExecutor {
69
70
  run(command, returnErr = false) {
70
71
  command += ';base::quit()';
71
72
  (0, log_1.expensiveTrace)(executorLog, () => `> ${JSON.stringify(command)}`);
73
+ secure_mode_1.SecureMode.guard('starting R', this.options.pathToRExecutable);
72
74
  const returns = (0, child_process_1.spawnSync)(this.options.pathToRExecutable, this.options.commandLineOptions, {
73
75
  env: this.options.env,
74
76
  cwd: this.options.cwd,
package/r-bridge/shell.js CHANGED
@@ -48,6 +48,7 @@ const fs_1 = __importDefault(require("fs"));
48
48
  const init_1 = require("./init");
49
49
  const convert_values_1 = require("./lang-4.x/convert-values");
50
50
  const retriever_1 = require("./retriever");
51
+ const secure_mode_1 = require("../util/secure-mode");
51
52
  exports.DEFAULT_OUTPUT_COLLECTOR_CONFIGURATION = {
52
53
  from: 'stdout',
53
54
  postamble: `🐧${'-'.repeat(5)}🐧`,
@@ -302,6 +303,7 @@ class RShellSession {
302
303
  collectionTimeout;
303
304
  requestQueue = Promise.resolve();
304
305
  constructor(options, log) {
306
+ secure_mode_1.SecureMode.guard('starting R', options.pathToRExecutable);
305
307
  this.bareSession = (0, child_process_1.spawn)(options.pathToRExecutable, options.commandLineOptions, {
306
308
  env: options.env,
307
309
  cwd: options.cwd,
@@ -18,6 +18,7 @@ const slice_direction_1 = require("../../util/slice-direction");
18
18
  const model_1 = require("../../r-bridge/lang-4.x/ast/model/model");
19
19
  const r_function_definition_1 = require("../../r-bridge/lang-4.x/ast/model/nodes/r-function-definition");
20
20
  const r_expression_list_1 = require("../../r-bridge/lang-4.x/ast/model/nodes/r-expression-list");
21
+ const r_argument_1 = require("../../r-bridge/lang-4.x/ast/model/nodes/r-argument");
21
22
  exports.slicerLogger = log_1.log.getSubLogger({ name: 'slicer' });
22
23
  /**
23
24
  * Computes the node ids to include in a static slice, starting from the given seed ids.
@@ -57,9 +58,7 @@ function staticSlice(options) {
57
58
  // retrieve the minimum nesting of all nodes to only add control dependencies if they are "part" of the current execution
58
59
  minNesting = Math.min(minNesting, idMap.get(startId)?.info.nest ?? minNesting);
59
60
  sliceSeedIds.add(startId);
60
- if (trackCallees) {
61
- openBodiesAround(startId);
62
- }
61
+ openBodiesAround(startId);
63
62
  }
64
63
  /* include all the implicit side effects that we have to consider as we are unable to narrow them down */
65
64
  for (const id of graph.unknownSideEffects) {
@@ -91,7 +90,7 @@ function staticSlice(options) {
91
90
  const strictlyEnclosing = model_1.RNode.strictlyEnclosingFunction(id, idMap);
92
91
  if (!enclosingHandled.has(strictlyEnclosing)) {
93
92
  enclosingHandled.add(strictlyEnclosing);
94
- definitionWithHolders(strictlyEnclosing, idMap, graph).forEach(outer => enqueue(outer, emptyEnv, basePrint));
93
+ definitionWithHolders(strictlyEnclosing, idMap, graph, trackCallees ? undefined : openedBodies).forEach(outer => enqueue(outer, emptyEnv, basePrint));
95
94
  }
96
95
  // includeCallees: note the enclosing function definition (if any) so its callees can be considered once the body slice is complete
97
96
  if (trackCallees) {
@@ -100,9 +99,11 @@ function staticSlice(options) {
100
99
  pendingCalleeBoundaries.set(enclosingFnDef, [baseEnvironment, baseEnvFingerprint]);
101
100
  }
102
101
  }
103
- /* control dependencies count only in a different call or at least at the nesting of the seeds */
102
+ /* control dependencies count only in a different call or at least at the nesting of the seeds; a read or a constant
103
+ is the same value whether or not its promise is forced, only what runs within one depends on its call */
104
104
  const topLevel = graph.isRoot(id) || sliceSeedIds.has(id);
105
- for (const cd of currentVertex.cds?.filter(({ id }) => !queue.hasId(id)) ?? []) {
105
+ const plain = vertex_1.DfgVertex.isUse(currentVertex) || vertex_1.DfgVertex.isValue(currentVertex);
106
+ for (const cd of currentVertex.cds?.filter(cd => !(plain && cd.byPromise) && !queue.hasId(cd.id)) ?? []) {
106
107
  if (!topLevel || (idMap.get(cd.id)?.info.nest ?? 0) >= minNesting) {
107
108
  queue.add(cd.id, baseEnvironment, baseEnvFingerprint, false);
108
109
  }
@@ -181,15 +182,19 @@ function outputWithinCallees(seeds, graph) {
181
182
  }
182
183
  return found;
183
184
  }
184
- /** The function `definition` and what holds it, up to its statement, as a body only runs as part of its definition. */
185
- function definitionWithHolders(definition, idMap, graph) {
185
+ /**
186
+ * The function `definition` and what holds it, up to its statement, as a body only runs as part of its definition.
187
+ * The `opened` bodies the slice starts in stop at an argument holding them or handed to a call of them: that call is a caller.
188
+ */
189
+ function definitionWithHolders(definition, idMap, graph, opened) {
186
190
  const definitionNode = definition === undefined ? undefined : idMap.get(definition);
187
191
  if (definitionNode === undefined) {
188
192
  return [];
189
193
  }
190
194
  const outer = [definitionNode.info.id];
191
195
  for (const node of model_1.RNode.iterateParents(definitionNode, idMap)) {
192
- if (r_function_definition_1.RFunctionDefinition.is(node) || (r_expression_list_1.RExpressionList.is(node) && node.grouping?.[0].lexeme !== '(')) {
196
+ if (r_function_definition_1.RFunctionDefinition.is(node) || (r_expression_list_1.RExpressionList.is(node) && node.grouping?.[0].lexeme !== '(')
197
+ || (opened !== undefined && r_argument_1.RArgument.is(node) && (opened.has(definitionNode.info.id) || (0, frame_reflection_1.edgeTargets)(graph, node.info.parent ?? '', edge_1.EdgeType.Calls).some(fn => opened.has(fn))))) {
193
198
  break;
194
199
  }
195
200
  if (graph.hasVertex(node.info.id)) {
package/util/files.d.ts CHANGED
@@ -47,6 +47,12 @@ export declare function readLineByLine(filePath: string, onLine: (line: Buffer,
47
47
  * See {@link readLineByLine} for an asynchronous version.
48
48
  */
49
49
  export declare function readLineByLineSync(filePath: string, onLine: (line: Buffer, lineNumber: number) => void, maxLines?: number): boolean;
50
+ /**
51
+ * Joins `base` with a single path segment taken from an untrusted source (e.g., a file name, release tag, or hash read
52
+ * from a downloaded or project-supplied file), refusing every segment that could name anything outside `base`.
53
+ * @throws if the segment is empty, `.` or `..`, or contains a path separator or NUL
54
+ */
55
+ export declare function joinUntrustedSegment(base: string, segment: string): string;
50
56
  /**
51
57
  * Chops off the last part of the given directory path after a path separator, essentially returning the path's parent directory.
52
58
  * If an absolute path is passed, the returned path is also absolute.
package/util/files.js CHANGED
@@ -42,6 +42,7 @@ exports.getAllFilesSync = getAllFilesSync;
42
42
  exports.allRFiles = allRFiles;
43
43
  exports.readLineByLine = readLineByLine;
44
44
  exports.readLineByLineSync = readLineByLineSync;
45
+ exports.joinUntrustedSegment = joinUntrustedSegment;
45
46
  exports.getParentDirectory = getParentDirectory;
46
47
  exports.commonDirectory = commonDirectory;
47
48
  exports.relativeTo = relativeTo;
@@ -190,6 +191,17 @@ function readLineByLineSync(filePath, onLine, maxLines = Infinity) {
190
191
  }
191
192
  return true;
192
193
  }
194
+ /**
195
+ * Joins `base` with a single path segment taken from an untrusted source (e.g., a file name, release tag, or hash read
196
+ * from a downloaded or project-supplied file), refusing every segment that could name anything outside `base`.
197
+ * @throws if the segment is empty, `.` or `..`, or contains a path separator or NUL
198
+ */
199
+ function joinUntrustedSegment(base, segment) {
200
+ if (segment === '' || segment === '.' || segment === '..' || /[/\\\0]/.test(segment) || path_1.default.isAbsolute(segment)) {
201
+ throw new Error(`Refusing the untrusted path segment ${JSON.stringify(segment)}`);
202
+ }
203
+ return path_1.default.join(base, segment);
204
+ }
193
205
  /**
194
206
  * Chops off the last part of the given directory path after a path separator, essentially returning the path's parent directory.
195
207
  * If an absolute path is passed, the returned path is also absolute.
package/util/parallel.js CHANGED
@@ -43,6 +43,7 @@ const cp = __importStar(require("child_process"));
43
43
  const log_1 = require("./log");
44
44
  const assert_1 = require("./assert");
45
45
  const json_1 = require("./json");
46
+ const secure_mode_1 = require("./secure-mode");
46
47
  /**
47
48
  * This is not really generic but written especially for the benchmarking script.
48
49
  * It offers a work stealing thread pool executor.
@@ -93,6 +94,7 @@ class LimitedThreadPool {
93
94
  (0, assert_1.guard)(args !== undefined, () => `arguments should not be undefined in ${JSON.stringify(this.workingQueue)}`);
94
95
  this.currentlyRunning.add(args);
95
96
  console.log(`[${this.counter}/${this.limit}] Running next, currently running: ${this.currentlyRunning.size}, queue: ${this.workingQueue.length} [args: ${args.join(' ')}]`);
97
+ secure_mode_1.SecureMode.guard('starting a process', this.module);
96
98
  const child = cp.fork(this.module, args);
97
99
  child.on('exit', this.onChildExit(args));
98
100
  let timeout;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * flowR's secure mode, for analyzing untrusted code (e.g., on a server that accepts arbitrary projects).
3
+ *
4
+ * Once enabled, it stays enabled for the lifetime of the process: there is deliberately no way to disable it.
5
+ * Instead of trying to find every path that may lead to a dangerous operation, the operations themselves
6
+ * (starting R or any other process, accessing the network, using the clipboard) check {@link SecureMode.guard}, so
7
+ * code added later is covered as well. Configuration is restricted on top (see {@link FlowrConfig.fromFile}).
8
+ *
9
+ * Enable it with `--secure` on the command line, the environment variable {@link SecureMode.EnvVar}, or {@link SecureMode.enable}.
10
+ */
11
+ /** What the secure mode forbids, named in the error it throws. */
12
+ export type SecureModeOperation = 'starting R' | 'starting a process' | 'network access' | 'clipboard access';
13
+ /** Thrown by {@link SecureMode.guard} if a forbidden operation is attempted in secure mode. */
14
+ export declare class SecureModeError extends Error {
15
+ readonly operation: SecureModeOperation;
16
+ constructor(operation: SecureModeOperation, detail?: string);
17
+ }
18
+ /** Whether `value` (of an environment variable) switches something on. */
19
+ export declare function isTruthyEnvValue(value: string | undefined): boolean;
20
+ /**
21
+ * The process-wide secure mode, see the module documentation.
22
+ * @helper security
23
+ */
24
+ export declare const SecureMode: {
25
+ readonly EnvVar: "FLOWR_SECURE_MODE";
26
+ /** Enables the secure mode for the rest of the process's lifetime (there is no way back). */
27
+ readonly enable: (this: void) => void;
28
+ /**
29
+ * In secure mode, decompressing a file of the analyzed project must not yield more than this many bytes,
30
+ * so a decompression bomb cannot exhaust the memory. Use {@link SecureMode.decompressionLimit}.
31
+ */
32
+ readonly MaxDecompressedBytes: number;
33
+ /** The maximum number of bytes decompressing a project file may yield, `undefined` (no limit) outside the secure mode. */
34
+ readonly decompressionLimit: (this: void) => number | undefined;
35
+ /** Whether the secure mode is enabled. */
36
+ readonly isEnabled: (this: void) => boolean;
37
+ /**
38
+ * Call this right before performing the given operation.
39
+ * @throws a {@link SecureModeError} if the secure mode is enabled
40
+ */
41
+ readonly guard: (this: void, operation: SecureModeOperation, detail?: string) => void;
42
+ };
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ /**
3
+ * flowR's secure mode, for analyzing untrusted code (e.g., on a server that accepts arbitrary projects).
4
+ *
5
+ * Once enabled, it stays enabled for the lifetime of the process: there is deliberately no way to disable it.
6
+ * Instead of trying to find every path that may lead to a dangerous operation, the operations themselves
7
+ * (starting R or any other process, accessing the network, using the clipboard) check {@link SecureMode.guard}, so
8
+ * code added later is covered as well. Configuration is restricted on top (see {@link FlowrConfig.fromFile}).
9
+ *
10
+ * Enable it with `--secure` on the command line, the environment variable {@link SecureMode.EnvVar}, or {@link SecureMode.enable}.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.SecureMode = exports.SecureModeError = void 0;
14
+ exports.isTruthyEnvValue = isTruthyEnvValue;
15
+ /** Environment variable that enables {@link SecureMode} when flowR is loaded. */
16
+ const EnvVar = 'FLOWR_SECURE_MODE';
17
+ /** Thrown by {@link SecureMode.guard} if a forbidden operation is attempted in secure mode. */
18
+ class SecureModeError extends Error {
19
+ operation;
20
+ constructor(operation, detail) {
21
+ super(`flowR runs in secure mode, which forbids ${operation}${detail ? ` (${detail})` : ''}`);
22
+ this.operation = operation;
23
+ this.name = 'SecureModeError';
24
+ }
25
+ }
26
+ exports.SecureModeError = SecureModeError;
27
+ /** Whether `value` (of an environment variable) switches something on. */
28
+ function isTruthyEnvValue(value) {
29
+ const v = value?.trim().toLowerCase();
30
+ return v !== undefined && v !== '' && v !== '0' && v !== 'false' && v !== 'no' && v !== 'off';
31
+ }
32
+ let enabled = typeof process !== 'undefined' && isTruthyEnvValue(process.env?.[EnvVar]);
33
+ /**
34
+ * The process-wide secure mode, see the module documentation.
35
+ * @helper security
36
+ */
37
+ exports.SecureMode = {
38
+ EnvVar,
39
+ /** Enables the secure mode for the rest of the process's lifetime (there is no way back). */
40
+ enable() {
41
+ enabled = true;
42
+ if (typeof process !== 'undefined' && process.env) {
43
+ // inherited by every child process flowR may (legitimately) start before, e.g., a worker
44
+ process.env[EnvVar] = '1';
45
+ }
46
+ },
47
+ /**
48
+ * In secure mode, decompressing a file of the analyzed project must not yield more than this many bytes,
49
+ * so a decompression bomb cannot exhaust the memory. Use {@link SecureMode.decompressionLimit}.
50
+ */
51
+ MaxDecompressedBytes: 512 * 1024 * 1024,
52
+ /** The maximum number of bytes decompressing a project file may yield, `undefined` (no limit) outside the secure mode. */
53
+ decompressionLimit() {
54
+ return enabled ? exports.SecureMode.MaxDecompressedBytes : undefined;
55
+ },
56
+ /** Whether the secure mode is enabled. */
57
+ isEnabled() {
58
+ return enabled;
59
+ },
60
+ /**
61
+ * Call this right before performing the given operation.
62
+ * @throws a {@link SecureModeError} if the secure mode is enabled
63
+ */
64
+ guard(operation, detail) {
65
+ if (enabled) {
66
+ throw new SecureModeError(operation, detail);
67
+ }
68
+ }
69
+ };
70
+ //# sourceMappingURL=secure-mode.js.map
package/util/version.js CHANGED
@@ -42,9 +42,9 @@ const assert_1 = require("./assert");
42
42
  const sigdb_download_1 = require("../project/sigdb/sigdb-download");
43
43
  const doc_files_1 = require("../documentation/doc-util/doc-files");
44
44
  // this is automatically replaced with the current version by release-it
45
- const version = '2.16.0';
45
+ const version = '2.16.1';
46
46
  // this is automatically replaced with the release date by release-it (scripts/bump-version.ts)
47
- const versionDate = '2026-10-14T08:59:37Z';
47
+ const versionDate = '2026-10-15T16:13:39Z';
48
48
  /**
49
49
  * Retrieves the current flowR version as a new {@link SemVer} object.
50
50
  */