@eagleoutice/flowr 2.16.8 → 2.17.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 (94) hide show
  1. package/README.md +16 -10
  2. package/abstract-interpretation/absint-inference.d.ts +17 -1
  3. package/abstract-interpretation/absint-inference.js +118 -3
  4. package/abstract-interpretation/data-frame/arguments.d.ts +11 -1
  5. package/abstract-interpretation/data-frame/arguments.js +12 -0
  6. package/abstract-interpretation/domains/lattice.d.ts +2 -0
  7. package/abstract-interpretation/domains/lattice.js +0 -6
  8. package/abstract-interpretation/domains/multi-value-state-domain.d.ts +2 -1
  9. package/abstract-interpretation/domains/multi-value-state-domain.js +7 -3
  10. package/abstract-interpretation/domains/partial-product-domain.js +2 -1
  11. package/abstract-interpretation/domains/state-abstract-domain.d.ts +6 -3
  12. package/abstract-interpretation/domains/state-abstract-domain.js +13 -7
  13. package/abstract-interpretation/domains/state-domain.d.ts +4 -0
  14. package/config.js +1 -1
  15. package/control-flow/useless-loop.js +10 -8
  16. package/data/r-primitives.generated.d.ts +1 -0
  17. package/data/r-primitives.generated.js +9 -0
  18. package/data/sigdb/sigdb.remote.json +110 -110
  19. package/dataflow/environments/query-fn-props.d.ts +9 -3
  20. package/dataflow/environments/query-fn-props.js +13 -5
  21. package/dataflow/fn/class-declaration.js +1 -8
  22. package/dataflow/graph/df-helper.d.ts +2 -0
  23. package/dataflow/graph/df-helper.js +7 -0
  24. package/documentation/wiki-linter.js +29 -0
  25. package/documentation/wiki-query.js +20 -1
  26. package/linter/linter-executor.js +2 -1
  27. package/linter/linter-rules.d.ts +65 -0
  28. package/linter/linter-rules.js +5 -1
  29. package/linter/rules/cmd-check/global-environment-modification.d.ts +14 -1
  30. package/linter/rules/cmd-check/global-environment-modification.js +15 -7
  31. package/linter/rules/no-leaked-credentials.d.ts +1 -0
  32. package/linter/rules/no-leaked-credentials.js +3 -3
  33. package/linter/rules/process-state-in-session.d.ts +71 -0
  34. package/linter/rules/process-state-in-session.js +267 -0
  35. package/linter/rules/secret-exfiltration.d.ts +80 -0
  36. package/linter/rules/secret-exfiltration.js +183 -0
  37. package/package.json +1 -1
  38. package/project/flowr-analyzer.d.ts +6 -0
  39. package/project/flowr-analyzer.js +4 -0
  40. package/project/plugins/file-plugins/files/flowr-namespace-file.d.ts +2 -0
  41. package/project/plugins/file-plugins/files/flowr-namespace-file.js +22 -3
  42. package/project/sigdb/decompress.d.ts +4 -0
  43. package/project/sigdb/decompress.js +60 -25
  44. package/project/sigdb/manifest.d.ts +1 -1
  45. package/project/sigdb/manifest.js +2 -5
  46. package/project/sigdb/reader.js +15 -6
  47. package/project/sigdb/sigdb-download.d.ts +3 -7
  48. package/project/sigdb/sigdb-download.js +71 -72
  49. package/queries/catalog/taint-query/taint-query-executor.d.ts +7 -0
  50. package/queries/catalog/taint-query/taint-query-executor.js +30 -0
  51. package/queries/catalog/taint-query/taint-query-format.d.ts +29 -0
  52. package/queries/catalog/taint-query/taint-query-format.js +124 -0
  53. package/queries/query.d.ts +12 -1
  54. package/queries/query.js +2 -0
  55. package/taint-analysis/builder/domain.d.ts +14 -0
  56. package/taint-analysis/builder/domain.js +69 -0
  57. package/taint-analysis/builder/report-template.d.ts +50 -0
  58. package/taint-analysis/builder/report-template.js +46 -0
  59. package/taint-analysis/builder/taint-analysis-definition.d.ts +108 -0
  60. package/taint-analysis/builder/taint-analysis-definition.js +128 -0
  61. package/taint-analysis/builder/taint-analysis.d.ts +124 -0
  62. package/taint-analysis/builder/taint-analysis.js +93 -0
  63. package/taint-analysis/builtin-index-bridge.d.ts +20 -0
  64. package/taint-analysis/builtin-index-bridge.js +48 -0
  65. package/taint-analysis/eval/eval.d.ts +1 -0
  66. package/taint-analysis/eval/eval.js +124 -0
  67. package/taint-analysis/eval/instrumentation.d.ts +59 -0
  68. package/taint-analysis/eval/instrumentation.js +124 -0
  69. package/taint-analysis/finite-domain.d.ts +41 -0
  70. package/taint-analysis/finite-domain.js +118 -0
  71. package/taint-analysis/function-categories.d.ts +31 -0
  72. package/taint-analysis/function-categories.js +61 -0
  73. package/taint-analysis/logger.d.ts +1 -0
  74. package/taint-analysis/logger.js +6 -0
  75. package/taint-analysis/predefined/determinism.d.ts +6 -0
  76. package/taint-analysis/predefined/determinism.js +14 -0
  77. package/taint-analysis/predefined/normalization.d.ts +17 -0
  78. package/taint-analysis/predefined/normalization.js +150 -0
  79. package/taint-analysis/predefined/predefined.d.ts +12 -0
  80. package/taint-analysis/predefined/predefined.js +18 -0
  81. package/taint-analysis/predefined/randomness-analysis.d.ts +6 -0
  82. package/taint-analysis/predefined/randomness-analysis.js +124 -0
  83. package/taint-analysis/predefined/secret-analysis.d.ts +77 -0
  84. package/taint-analysis/predefined/secret-analysis.js +165 -0
  85. package/taint-analysis/predefined/security-analysis.d.ts +7 -0
  86. package/taint-analysis/predefined/security-analysis.js +91 -0
  87. package/taint-analysis/taint-mapping.d.ts +86 -0
  88. package/taint-analysis/taint-mapping.js +70 -0
  89. package/taint-analysis/taint-resolve.d.ts +26 -0
  90. package/taint-analysis/taint-resolve.js +86 -0
  91. package/taint-analysis/taint-visitor.d.ts +80 -0
  92. package/taint-analysis/taint-visitor.js +82 -0
  93. package/util/flowr-version.d.ts +1 -1
  94. package/util/flowr-version.js +2 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eagleoutice/flowr",
3
- "version": "2.16.8",
3
+ "version": "2.17.0",
4
4
  "description": "Static Dataflow Analyzer and Program Slicer for the R Programming Language",
5
5
  "engines": {
6
6
  "node": ">=22"
@@ -17,6 +17,7 @@ import { fileProtocol } from '../r-bridge/retriever';
17
17
  import type { FlowrFileProvider } from './context/flowr-file';
18
18
  import type { Tree } from 'web-tree-sitter';
19
19
  import type { CallGraph } from '../dataflow/graph/call-graph';
20
+ import { type TaintAnalysisBuilder } from '../taint-analysis/builder/taint-analysis';
20
21
  import type { InvalidationEvent } from './cache/flowr-cache';
21
22
  import type { GasOverrides } from '../gas';
22
23
  import type { FnInfo } from '../dataflow/environments/query-fn-props';
@@ -160,6 +161,10 @@ export interface ReadonlyFlowrAnalysisProvider<Parser extends KnownParser = Know
160
161
  * @param options - Bounds for this call, see {@link FlowrAnalysisOptions}.
161
162
  */
162
163
  query<Types extends SupportedQueryTypes = SupportedQueryTypes>(query: Queries<Types>, options?: FlowrAnalysisOptions): Promise<QueryResults<Types>>;
164
+ /**
165
+ * Access the taint analysis API for the request.
166
+ */
167
+ taint<Names extends readonly string[] = []>(): TaintAnalysisBuilder<Names>;
163
168
  /**
164
169
  * Run a search on the current analysis.
165
170
  * @param search - The search to run.
@@ -240,6 +245,7 @@ export declare class FlowrAnalyzer<Parser extends KnownParser = KnownParser> imp
240
245
  peekCallGraph(): CallGraph | undefined;
241
246
  query<Types extends SupportedQueryTypes = SupportedQueryTypes>(query: Queries<Types>, options?: FlowrAnalysisOptions): Promise<QueryResults<Types>>;
242
247
  runSearch<Search extends FlowrSearchLike>(search: Search, options?: FlowrAnalysisOptions): Promise<GetSearchElements<SearchOutput<Search>>>;
248
+ taint<Names extends readonly string[] = []>(): TaintAnalysisBuilder<Names>;
243
249
  /**
244
250
  * Free the cached analyses (including any WASM-backed parse trees) and close the parser.
245
251
  * Closing is only required for an RShell/remote engine, but this also frees the cached parse trees.
@@ -8,6 +8,7 @@ const retriever_1 = require("../r-bridge/retriever");
8
8
  const files_1 = require("../util/files");
9
9
  const tree_sitter_normalize_1 = require("../r-bridge/lang-4.x/tree-sitter/tree-sitter-normalize");
10
10
  const tree_sitter_executor_1 = require("../r-bridge/lang-4.x/tree-sitter/tree-sitter-executor");
11
+ const taint_analysis_1 = require("../taint-analysis/builder/taint-analysis");
11
12
  const vertex_1 = require("../dataflow/graph/vertex");
12
13
  const df_helper_1 = require("../dataflow/graph/df-helper");
13
14
  /**
@@ -169,6 +170,9 @@ class FlowrAnalyzer {
169
170
  async runSearch(search, options) {
170
171
  return this.ctx.gas.withGas(options?.gas, () => (0, flowr_search_executor_1.runSearch)(search, this));
171
172
  }
173
+ taint() {
174
+ return taint_analysis_1.TaintAnalysis.create(this);
175
+ }
172
176
  /**
173
177
  * Free the cached analyses (including any WASM-backed parse trees) and close the parser.
174
178
  * Closing is only required for an RShell/remote engine, but this also frees the cached parse trees.
@@ -9,6 +9,8 @@ export interface NamespaceInfo {
9
9
  /**
10
10
  * Names listed by `exportMethods()`: S4 methods the package registered for one of its classes, which is a
11
11
  * different claim than an ordinary export (the package answers a generic, it does not define the function).
12
+ * As R's `loadNamespace`, this keeps only the non-primitive generics: a method on a primitive such as `+` or `[`
13
+ * binds nothing in the namespace, so `pkg::"+"` does not exist and the call stays with base.
12
14
  * Only the context-parsed path ({@link parseNamespaceComplex}) tells these apart; the regex fallback folds
13
15
  * them into {@link exportedFunctions}.
14
16
  */
@@ -14,6 +14,7 @@ const fold_1 = require("../../../../r-bridge/lang-4.x/ast/model/processing/fold"
14
14
  const identifier_1 = require("../../../../dataflow/environments/identifier");
15
15
  const assert_1 = require("../../../../util/assert");
16
16
  const type_1 = require("../../../../r-bridge/lang-4.x/ast/model/type");
17
+ const r_primitives_generated_1 = require("../../../../data/r-primitives.generated");
17
18
  const make_argument_1 = require("../../../../dataflow/internal/process/functions/call/argument/make-argument");
18
19
  const range_1 = require("../../../../util/range");
19
20
  const r_regex_1 = require("../../../../util/r-regex");
@@ -334,9 +335,15 @@ function handleUseDynLibCall(g, args) {
334
335
  }
335
336
  /** `exportClasses(A, B)` / `exportMethods(show, summary)`: a directive may list several names, and each goes to `into`. */
336
337
  function handleS4ExportCall(g, args, into) {
337
- pushUnquotedLexemes(g.current[into], args, r_string_1.RString.unquote);
338
+ const names = [];
339
+ pushUnquotedLexemes(names, args, r_string_1.RString.unquote);
340
+ g.current[into].push(...(into === 'exportedS4Methods' ? exportedGenerics(names) : names));
338
341
  return g;
339
342
  }
343
+ /** The `exportMethods()` names R exports: methods on a primitive generic bind nothing in the namespace. */
344
+ function exportedGenerics(names) {
345
+ return names.filter(n => !r_primitives_generated_1.RPrimitives.has(n));
346
+ }
340
347
  const cleanLineCommentRegex = /^#.*$/gm;
341
348
  /** A namespace that neither exports nor imports anything yet. */
342
349
  function emptyNamespaceInfo() {
@@ -439,9 +446,21 @@ function splitNamespaceArgs(args) {
439
446
  const names = [];
440
447
  let depth = 0;
441
448
  let start = 0;
449
+ let quote;
442
450
  for (let i = 0; i <= args.length; i++) {
443
451
  const c = args[i];
444
- if (c === '(' || c === '[') {
452
+ if (quote !== undefined) {
453
+ if (c === '\\') {
454
+ i++;
455
+ }
456
+ else if (c === quote) {
457
+ quote = undefined;
458
+ }
459
+ }
460
+ else if (c === '"' || c === '\'' || c === '`') {
461
+ quote = c;
462
+ }
463
+ else if (c === '(' || c === '[') {
445
464
  depth++;
446
465
  }
447
466
  else if (c === ')' || c === ']') {
@@ -474,7 +493,7 @@ function parseNamespaceSimple(file) {
474
493
  case 'exportClasses':
475
494
  case 'exportMethods':
476
495
  // a single directive may list several symbols, e.g. `exportMethods(show, summary)`
477
- result.current.exportedFunctions.push(...splitNamespaceArgs(args));
496
+ result.current.exportedFunctions.push(...exportedGenerics(splitNamespaceArgs(args)));
478
497
  break;
479
498
  case 'S3method':
480
499
  {
@@ -20,6 +20,8 @@ export declare function resolveSource(baseDir: string, relPath: string): string;
20
20
  * volume at the cache dir to persist it).
21
21
  */
22
22
  export declare function sigDbCacheDir(override?: string, create?: boolean): string;
23
+ /** a temp path next to `target`, unique even across containers sharing a volume */
24
+ export declare const uniqueTempPath: (target: string, ext: string) => string;
23
25
  /** read the (small) header line of a possibly-compressed bundle without decompressing the whole thing */
24
26
  export declare function readHeaderOf(source: string): Promise<Record<string, unknown> | undefined>;
25
27
  /** where an index for a decompressed source comes from -- a caller-supplied one (e.g. a manifest) or the sibling `.idx` */
@@ -29,6 +31,8 @@ export interface EnsureOptions {
29
31
  index?: SigDbIndex;
30
32
  /** the source is not a seekable bundle (e.g. a shared dictionary file) -- decompress only, write no `.idx` */
31
33
  indexless?: boolean;
34
+ /** the expected decompressed size */
35
+ bytes?: number;
32
36
  }
33
37
  /** whether a compressed source with the given content hash has already been unpacked into its decompressed cache */
34
38
  export declare function isUnpacked(hash: string, cacheDir?: string): boolean;
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.isCompressed = void 0;
6
+ exports.uniqueTempPath = exports.isCompressed = void 0;
7
7
  exports.parseHeader = parseHeader;
8
8
  exports.sigDbStream = sigDbStream;
9
9
  exports.resolveSource = resolveSource;
@@ -20,6 +20,7 @@ exports.ensurePlainSync = ensurePlainSync;
20
20
  */
21
21
  const fs_1 = __importDefault(require("fs"));
22
22
  const os_1 = __importDefault(require("os"));
23
+ const crypto_1 = require("crypto");
23
24
  const path_1 = __importDefault(require("path"));
24
25
  const readline_1 = __importDefault(require("readline"));
25
26
  const promises_1 = require("stream/promises");
@@ -80,19 +81,30 @@ function sigDbCacheDir(override, create = true) {
80
81
  ?? (process.env.LOCALAPPDATA ? path_1.default.join(process.env.LOCALAPPDATA, 'flowr', 'cache') : undefined)
81
82
  ?? path_1.default.join(os_1.default.homedir?.() || os_1.default.tmpdir(), '.cache', 'flowr');
82
83
  const dir = path_1.default.join(base, 'sigdb');
83
- if (!create) {
84
+ const tmp = path_1.default.join(os_1.default.tmpdir(), `flowr-sigdb-cache-${process.getuid?.() ?? os_1.default.userInfo().username}`);
85
+ if (isWritableDir(dir, create) || !(create || fs_1.default.existsSync(tmp))) {
84
86
  return dir;
85
87
  }
88
+ if (create) {
89
+ fs_1.default.mkdirSync(tmp, { recursive: true, mode: 0o700 });
90
+ }
91
+ return tmp;
92
+ }
93
+ function isWritableDir(dir, create) {
86
94
  try {
87
- fs_1.default.mkdirSync(dir, { recursive: true });
88
- return dir;
95
+ if (create) {
96
+ fs_1.default.mkdirSync(dir, { recursive: true });
97
+ }
98
+ fs_1.default.accessSync(dir, fs_1.default.constants.W_OK);
99
+ return true;
89
100
  }
90
101
  catch {
91
- const tmp = path_1.default.join(os_1.default.tmpdir(), 'flowr-sigdb-cache');
92
- fs_1.default.mkdirSync(tmp, { recursive: true });
93
- return tmp;
102
+ return false;
94
103
  }
95
104
  }
105
+ /** a temp path next to `target`, unique even across containers sharing a volume */
106
+ const uniqueTempPath = (target, ext) => `${target}.${process.pid}-${(0, crypto_1.randomBytes)(6).toString('hex')}.${ext}`;
107
+ exports.uniqueTempPath = uniqueTempPath;
96
108
  /** read the (small) header line of a possibly-compressed bundle without decompressing the whole thing */
97
109
  async function readHeaderOf(source) {
98
110
  if (!(0, exports.isCompressed)(source)) {
@@ -138,6 +150,26 @@ function writeCacheIndex(source, idx, index) {
138
150
  }
139
151
  fs_1.default.copyFileSync(srcIdx, idx);
140
152
  }
153
+ function isCachedPlain(plain, idx, opts) {
154
+ try {
155
+ const size = fs_1.default.statSync(plain).size;
156
+ return (opts.bytes === undefined || size === opts.bytes) && (opts.indexless || fs_1.default.existsSync(idx));
157
+ }
158
+ catch {
159
+ return false;
160
+ }
161
+ }
162
+ function commitPlain(source, tmp, plain, idx, opts) {
163
+ const size = fs_1.default.statSync(tmp).size;
164
+ if (opts.bytes !== undefined && size !== opts.bytes) {
165
+ throw new Error(`decompressing ${source} gave ${size} bytes, expected ${opts.bytes}; the file is corrupt or does not match its manifest`);
166
+ }
167
+ fs_1.default.renameSync(tmp, plain);
168
+ if (!opts.indexless) {
169
+ writeCacheIndex(source, idx, opts.index);
170
+ }
171
+ return plain;
172
+ }
141
173
  /**
142
174
  * Ensure a seekable plain `.sigs.ndjson` (+ its `.idx`) exists for `source`, decompressing a `.br`/`.zst`/`.gz`
143
175
  * once into a hash-keyed cache the first time and reusing it on every later startup. The index may be
@@ -149,20 +181,24 @@ async function ensurePlain(source, opts = {}) {
149
181
  }
150
182
  let hash = opts.hash;
151
183
  if (hash === undefined) {
152
- const content = (await readHeaderOf(source))?.content;
153
- hash = content?.hash ?? new hash_1.Hash53().update(source).digest();
184
+ hash = (await readHeaderOf(source))?.content?.hash;
185
+ if (hash === undefined) {
186
+ const { size, mtimeMs } = fs_1.default.statSync(source);
187
+ hash = new hash_1.Hash53().update(`${source}\0${size}\0${mtimeMs}`).digest();
188
+ }
154
189
  }
155
190
  const { plain, idx } = cachePaths(hash, opts.cacheDir);
156
- if (fs_1.default.existsSync(plain) && (opts.indexless || fs_1.default.existsSync(idx))) {
191
+ if (isCachedPlain(plain, idx, opts)) {
157
192
  return plain;
158
193
  }
159
- const tmp = `${plain}.${process.pid}.tmp`;
160
- await (0, promises_1.pipeline)(decompressStream(source), fs_1.default.createWriteStream(tmp));
161
- fs_1.default.renameSync(tmp, plain);
162
- if (!opts.indexless) {
163
- writeCacheIndex(source, idx, opts.index);
194
+ const tmp = (0, exports.uniqueTempPath)(plain, 'tmp');
195
+ try {
196
+ await (0, promises_1.pipeline)(decompressStream(source), fs_1.default.createWriteStream(tmp));
197
+ return commitPlain(source, tmp, plain, idx, opts);
198
+ }
199
+ finally {
200
+ fs_1.default.rmSync(tmp, { force: true });
164
201
  }
165
- return plain;
166
202
  }
167
203
  /** synchronous {@link ensurePlain} (blocking decompression); the supplied `hash` keys the decompress cache */
168
204
  function ensurePlainSync(source, opts) {
@@ -170,17 +206,16 @@ function ensurePlainSync(source, opts) {
170
206
  return source;
171
207
  }
172
208
  const { plain, idx } = cachePaths(opts.hash, opts.cacheDir);
173
- if (fs_1.default.existsSync(plain) && (opts.indexless || fs_1.default.existsSync(idx))) {
209
+ if (isCachedPlain(plain, idx, opts)) {
174
210
  return plain;
175
211
  }
176
- const raw = fs_1.default.readFileSync(source);
177
- const out = (0, codec_1.decompressSyncFor)(source, raw);
178
- const tmp = `${plain}.${process.pid}.tmp`;
179
- fs_1.default.writeFileSync(tmp, out);
180
- fs_1.default.renameSync(tmp, plain);
181
- if (!opts.indexless) {
182
- writeCacheIndex(source, idx, opts.index);
212
+ const tmp = (0, exports.uniqueTempPath)(plain, 'tmp');
213
+ try {
214
+ fs_1.default.writeFileSync(tmp, (0, codec_1.decompressSyncFor)(source, fs_1.default.readFileSync(source)));
215
+ return commitPlain(source, tmp, plain, idx, opts);
216
+ }
217
+ finally {
218
+ fs_1.default.rmSync(tmp, { force: true });
183
219
  }
184
- return plain;
185
220
  }
186
221
  //# sourceMappingURL=decompress.js.map
@@ -59,7 +59,7 @@ export type SigDbScope = 'base' | 'current' | 'full';
59
59
  export declare function sigDbBundleDirs(watched?: [string, number][]): string[];
60
60
  /**
61
61
  * Location of a bundled sigdb **manifest**, found by walking up from several roots (this module,
62
- * `$FLOWR_SIGDB_DIR`, the working directory) across the dev (`src`), build (`dist`), and data-mount
62
+ * `$FLOWR_SIGDB_DIR`) across the dev (`src`), build (`dist`), and data-mount
63
63
  * layouts. With no `scope` it returns the richest available (`full` &gt; `current` &gt; `base`), so a
64
64
  * container that ships the full set uses it automatically while a plain npm install falls back to the
65
65
  * bundled `base`. Node only (needs `fs`); pass `searchRoots` to override where it looks.
@@ -91,7 +91,7 @@ function sigDbBundleDirs(watched) {
91
91
  return [];
92
92
  }
93
93
  }
94
- /** roots to search for a bundled sigdb; extendable via `$FLOWR_SIGDB_DIR` (path-delimiter separated) */
94
+ /** roots to search for a bundled sigdb: this module and `$FLOWR_SIGDB_DIR` (path-delimiter separated) */
95
95
  function sigDbSearchRoots(extra) {
96
96
  const roots = [...(extra ?? [])];
97
97
  const env = typeof process !== 'undefined' ? process.env?.FLOWR_SIGDB_DIR : undefined;
@@ -101,14 +101,11 @@ function sigDbSearchRoots(extra) {
101
101
  if (typeof __dirname !== 'undefined') {
102
102
  roots.push(__dirname);
103
103
  }
104
- if (typeof process !== 'undefined' && typeof process.cwd === 'function') {
105
- roots.push(process.cwd());
106
- }
107
104
  return roots;
108
105
  }
109
106
  /**
110
107
  * Location of a bundled sigdb **manifest**, found by walking up from several roots (this module,
111
- * `$FLOWR_SIGDB_DIR`, the working directory) across the dev (`src`), build (`dist`), and data-mount
108
+ * `$FLOWR_SIGDB_DIR`) across the dev (`src`), build (`dist`), and data-mount
112
109
  * layouts. With no `scope` it returns the richest available (`full` &gt; `current` &gt; `base`), so a
113
110
  * container that ships the full set uses it automatically while a plain npm install falls back to the
114
111
  * bundled `base`. Node only (needs `fs`); pass `searchRoots` to override where it looks.
@@ -31,6 +31,7 @@ const dict_1 = require("./dict");
31
31
  const hash_1 = require("./hash");
32
32
  const manifest_1 = require("./manifest");
33
33
  const arrays_1 = require("../../util/collections/arrays");
34
+ const log_1 = require("../../util/log");
34
35
  /** the run of names one `d` line (`["d", start, payload]`, newline-blob or legacy `string[]` form) adds */
35
36
  function dictLineRun(json) {
36
37
  const [, start, payload] = JSON.parse(json);
@@ -422,7 +423,7 @@ class SigDatabase {
422
423
  if (opts.hash === undefined) {
423
424
  throw new Error('openSyncFrom needs a hash to key the cache for a compressed source');
424
425
  }
425
- plain = (0, decompress_1.ensurePlainSync)(source, { cacheDir: opts.cacheDir, hash: opts.hash, index: opts.index });
426
+ plain = (0, decompress_1.ensurePlainSync)(source, { cacheDir: opts.cacheDir, hash: opts.hash, index: opts.index, bytes: opts.index?.byteCount });
426
427
  }
427
428
  return SigDatabase.openSync(plain, { index: opts.index, strings: opts.strings });
428
429
  }
@@ -742,9 +743,17 @@ class SigDatabaseSet {
742
743
  if (full.format !== manifest_1.SigDbManifestMagic) {
743
744
  throw new Error(`not a ${manifest_1.SigDbManifestMagic} (got ${String(full.format)})`);
744
745
  }
745
- const active = selectShards(full.shards, opts.includeShards, opts.excludeShards);
746
+ const selected = selectShards(full.shards, opts.includeShards, opts.excludeShards);
747
+ const present = (rel) => fs_1.default.existsSync((0, decompress_1.resolveSource)(baseDir, rel));
748
+ const active = selected.filter(s => {
749
+ const dict = s.dict === undefined ? undefined : full.dicts?.find(d => d.id === s.dict);
750
+ return present(s.path) && (dict === undefined || present(dict.path));
751
+ });
752
+ if (active.length < selected.length) {
753
+ log_1.log.warn(`sigdb: ${manifestFile} lacks the files of ${selected.length - active.length} shard(s) (${selected.filter(s => !active.includes(s)).map(s => s.path).join(', ')}), ignoring them; download the bundle again to restore them`);
754
+ }
746
755
  if (active.length === 0) {
747
- throw new Error('openManifest: no shards left after include/exclude filtering');
756
+ throw new Error(`openManifest: no shards left in ${manifestFile} after include/exclude filtering and dropping absent ones`);
748
757
  }
749
758
  return { baseDir, manifest: { ...full, shards: active } };
750
759
  }
@@ -797,7 +806,7 @@ class SigDatabaseSet {
797
806
  if (!ref) {
798
807
  throw new Error(`manifest references unknown dictionary '${dictId}'`);
799
808
  }
800
- const plain = (0, decompress_1.ensurePlainSync)((0, decompress_1.resolveSource)(this.baseDir, ref.path), { cacheDir: this.cacheDir, hash: ref.hash, indexless: true });
809
+ const plain = (0, decompress_1.ensurePlainSync)((0, decompress_1.resolveSource)(this.baseDir, ref.path), { cacheDir: this.cacheDir, hash: ref.hash, indexless: true, bytes: ref.byteCount });
801
810
  let strings;
802
811
  const fd = fs_1.default.openSync(plain, 'r');
803
812
  try {
@@ -840,10 +849,10 @@ class SigDatabaseSet {
840
849
  /** decompress the given shards + their shared dictionaries concurrently, then open them (see {@link preload}) */
841
850
  async warmShards(need) {
842
851
  const dicts = new Set([...need].map(i => this.manifest.shards[i].dict).filter((d) => !!d));
843
- const shardJobs = [...need].map(i => (0, decompress_1.ensurePlain)((0, decompress_1.resolveSource)(this.baseDir, this.manifest.shards[i].path), { cacheDir: this.cacheDir, hash: this.manifest.shards[i].hash, index: this.indices[i] }));
852
+ const shardJobs = [...need].map(i => (0, decompress_1.ensurePlain)((0, decompress_1.resolveSource)(this.baseDir, this.manifest.shards[i].path), { cacheDir: this.cacheDir, hash: this.manifest.shards[i].hash, index: this.indices[i], bytes: this.indices[i]?.byteCount }));
844
853
  const dictJobs = [...dicts].map(id => {
845
854
  const ref = this.manifest.dicts?.find(d => d.id === id);
846
- return ref ? (0, decompress_1.ensurePlain)((0, decompress_1.resolveSource)(this.baseDir, ref.path), { cacheDir: this.cacheDir, hash: ref.hash, indexless: true }) : Promise.resolve('');
855
+ return ref ? (0, decompress_1.ensurePlain)((0, decompress_1.resolveSource)(this.baseDir, ref.path), { cacheDir: this.cacheDir, hash: ref.hash, indexless: true, bytes: ref.byteCount }) : Promise.resolve('');
847
856
  });
848
857
  await Promise.all([...shardJobs, ...dictJobs]);
849
858
  // open each shard now so later synchronous queries never block
@@ -25,7 +25,7 @@ export declare function selectDownloadVariants(names: Iterable<string>): string[
25
25
  export interface SigDbDownloadOptions {
26
26
  /** GitHub `owner/repo` (default `flowr-analysis/flowr`) */
27
27
  readonly repo?: string;
28
- /** release version, i.e. tag `sigdb-v<version>` (default the running flowR version); ignored when the committed `sigdb.remote.json` is present, whose `tag` then drives the download */
28
+ /** an explicit release (tag `<v>`, `v<v>`, or `sigdb-v<v>`), else the pointer's tag */
29
29
  readonly version?: string;
30
30
  /** progress callback (one line per step) */
31
31
  readonly onProgress?: (msg: string) => void;
@@ -69,13 +69,9 @@ export declare const isManifestFile: (name: string) => boolean;
69
69
  * Use the returned {@link SigDbDownloadResult.manifest}, or point `solver.sigdb.additionalPaths` at the dir.
70
70
  */
71
71
  export declare function downloadFullSigDb(opts?: SigDbDownloadOptions): Promise<SigDbDownloadResult>;
72
- /**
73
- * The cache dir a {@link downloadFullSigDb} for the committed link file would populate, or `undefined` if no
74
- * pointer is committed. Lets a caller mount an already-synced bundle via `solver.sigdb.additionalPaths` without
75
- * hitting the network.
76
- */
72
+ /** the cache dir {@link downloadFullSigDb} populates, `undefined` if the pointer is broken */
77
73
  export declare function syncedSigDbDir(): string | undefined;
78
- /** the GitHub release (`{repo, tag, url}`) the committed pointer downloads from, or `undefined` when no pointer is committed */
74
+ /** the GitHub release the pointer downloads from, `undefined` if it is broken */
79
75
  export declare function sigDbRemoteRelease(): {
80
76
  repo: string;
81
77
  tag: string;
@@ -17,7 +17,7 @@ const https_1 = __importDefault(require("https"));
17
17
  const crypto_1 = __importDefault(require("crypto"));
18
18
  const decompress_1 = require("./decompress");
19
19
  const codec_1 = require("./codec");
20
- const version_1 = require("../../util/version");
20
+ const sigdb_remote_json_1 = __importDefault(require("../../data/sigdb/sigdb.remote.json"));
21
21
  const files_1 = require("../../util/files");
22
22
  const secure_mode_1 = require("../../util/secure-mode");
23
23
  /** the GitHub `owner/repo` the full-history bundle is published to (see `scripts/publish-sigdb.mjs`) */
@@ -93,7 +93,7 @@ const mb = (bytes) => `${(bytes / 1e6).toFixed(1)} MB`;
93
93
  const rate = (bytes, ms) => `${(bytes / 1e6 / Math.max(ms / 1000, 0.001)).toFixed(1)} MB/s`;
94
94
  /** Download `url` to `dest` via a temporary file, so a partial or corrupt file never lands there (checked against `sha256`, if given). */
95
95
  async function downloadTo(url, dest, name, progress, expected) {
96
- const part = `${dest}.${process.pid}.part`;
96
+ const part = (0, decompress_1.uniqueTempPath)(dest, 'part');
97
97
  const start = Date.now();
98
98
  try {
99
99
  const res = await httpGet(url, 'application/octet-stream');
@@ -139,26 +139,19 @@ const sha256File = (p) => crypto_1.default.createHash('sha256').update(fs_1.defa
139
139
  exports.sha256File = sha256File;
140
140
  /** the committed link file naming every downloadable shard (base floor + CRAN sets); only this pointer is committed */
141
141
  exports.SigDbRemoteFileName = 'sigdb.remote.json';
142
- /** locate the committed `sigdb.remote.json` link file in the sigdb data dir (dev `src`, built `dist`), or the one `$FLOWR_SIGDB_REMOTE` names */
143
- function findRemotePointer() {
142
+ /** the file `$FLOWR_SIGDB_REMOTE` names, else the committed link file (inlined at build time) */
143
+ function remotePointer() {
144
144
  const override = process.env.FLOWR_SIGDB_REMOTE;
145
- if (override) {
146
- return fs_1.default.existsSync(override) ? override : undefined;
145
+ return override ? readPointerChecked(override) : checkedPointer(sigdb_remote_json_1.default, exports.SigDbRemoteFileName);
146
+ }
147
+ function tryRemotePointer() {
148
+ try {
149
+ return remotePointer();
150
+ }
151
+ catch {
152
+ return undefined;
147
153
  }
148
- const candidates = [
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),
151
- ];
152
- return candidates.find(p => {
153
- try {
154
- return fs_1.default.existsSync(p);
155
- }
156
- catch {
157
- return false;
158
- }
159
- });
160
154
  }
161
- const readPointer = (p) => JSON.parse(fs_1.default.readFileSync(p, 'utf8'));
162
155
  /** the direct release-asset URL, which avoids the REST API rate limit; `$FLOWR_SIGDB_MIRROR` replaces the host */
163
156
  const assetUrl = (repo, tag, name) => `${process.env.FLOWR_SIGDB_MIRROR ?? 'https://github.com'}/${repo}/releases/download/${tag}/${encodeURIComponent(name)}`;
164
157
  /** runtime-decodable variant extensions, most-preferred first, ending in plain (`''`) as a last resort */
@@ -293,17 +286,19 @@ async function syncFiles(tag, repo, planned, opts) {
293
286
  }
294
287
  return { tag, dir, manifest: pickManifest(files), files, downloaded, bytes, ms, stale };
295
288
  }
296
- /** read the committed link file, naming it in the error when it is broken */
297
289
  function readPointerChecked(p) {
298
290
  let remote;
299
291
  try {
300
- remote = readPointer(p);
292
+ remote = JSON.parse(fs_1.default.readFileSync(p, 'utf8'));
301
293
  }
302
294
  catch (e) {
303
295
  throw new Error(`cannot read the signature database link file ${p}: ${e.message}`, { cause: e });
304
296
  }
305
- if (typeof remote.tag !== 'string' || typeof remote.shards !== 'object' || remote.shards === null) {
306
- throw new Error(`the signature database link file ${p} names no tag or shards`);
297
+ return checkedPointer(remote, p);
298
+ }
299
+ function checkedPointer(remote, origin) {
300
+ if (typeof remote?.tag !== 'string' || typeof remote.shards !== 'object' || remote.shards === null) {
301
+ throw new Error(`the signature database link file ${origin} names no tag or shards`);
307
302
  }
308
303
  return remote;
309
304
  }
@@ -313,69 +308,73 @@ function readPointerChecked(p) {
313
308
  * Use the returned {@link SigDbDownloadResult.manifest}, or point `solver.sigdb.additionalPaths` at the dir.
314
309
  */
315
310
  async function downloadFullSigDb(opts = {}) {
316
- const progress = opts.onProgress ?? (() => { });
317
- const pointerPath = findRemotePointer();
318
- if (pointerPath) {
319
- const remote = readPointerChecked(pointerPath);
320
- const repo = opts.repo ?? remote.repo ?? DefaultRepo;
321
- // one variant per logical shard/dictionary -- the best this runtime can decompress (never both codecs)
322
- const planned = selectDownloadVariants(Object.keys(remote.shards)).map(name => ({
323
- name, url: assetUrl(repo, remote.tag, name), expected: remote.shards[name]
324
- }));
325
- return syncFiles(remote.tag, repo, planned, opts);
311
+ if (opts.version !== undefined) {
312
+ return downloadRelease(opts.version, opts);
326
313
  }
327
- // fallback: no committed link file -> list the release via the API and download by size
314
+ const remote = remotePointer();
315
+ const repo = opts.repo ?? remote.repo ?? DefaultRepo;
316
+ // one variant per shard, the best codec this runtime supports
317
+ const planned = selectDownloadVariants(Object.keys(remote.shards)).map(name => ({
318
+ name, url: assetUrl(repo, remote.tag, name), expected: remote.shards[name]
319
+ }));
320
+ return syncFiles(remote.tag, repo, planned, opts);
321
+ }
322
+ function releaseTagCandidates(version) {
323
+ const bare = version.replace(/^(sigdb-)?v/, '');
324
+ return [...new Set([version, `v${bare}`, `sigdb-v${bare}`])];
325
+ }
326
+ async function downloadRelease(version, opts) {
327
+ const progress = opts.onProgress ?? (() => { });
328
328
  const repo = opts.repo ?? DefaultRepo;
329
- const version = opts.version ?? (0, version_1.flowrVersion)().toString();
330
- const tag = `sigdb-v${version}`;
331
- progress(`no sigdb.remote.json found, listing release ${tag} of ${repo}`);
332
- const release = await withRetries(`listing ${tag}`, () => readJson(`https://api.github.com/repos/${repo}/releases/tags/${tag}`), progress);
333
- const assets = (release.assets ?? [])
334
- .filter(a => a.name.endsWith('.br') || a.name.endsWith('.zst') || a.name.endsWith('.manifest.json'));
335
- if (assets.length === 0) {
336
- throw new Error(`release ${tag} in ${repo} has no signature-database assets${typeof release.message === 'string' ? ` (${release.message})` : ''}`);
329
+ const tried = [];
330
+ for (const tag of releaseTagCandidates(version)) {
331
+ progress(`listing release ${tag} of ${repo}`);
332
+ let release;
333
+ try {
334
+ release = await withRetries(`listing ${tag}`, () => readJson(`https://api.github.com/repos/${repo}/releases/tags/${tag}`), progress);
335
+ }
336
+ catch (e) {
337
+ if (!(e instanceof HttpError) || e.retryable) {
338
+ throw e;
339
+ }
340
+ tried.push(`${tag}: ${e.message}`);
341
+ continue;
342
+ }
343
+ const assets = (release.assets ?? [])
344
+ .filter(a => a.name.endsWith('.br') || a.name.endsWith('.zst') || a.name.endsWith('.manifest.json'));
345
+ if (assets.length === 0) {
346
+ tried.push(`${tag}: no signature-database assets`);
347
+ continue;
348
+ }
349
+ const byName = new Map(assets.map(a => [a.name, a]));
350
+ const planned = selectDownloadVariants(byName.keys()).map(name => {
351
+ const a = byName.get(name);
352
+ return { name, url: a.browser_download_url, size: a.size };
353
+ });
354
+ return syncFiles(tag, repo, planned, opts);
337
355
  }
338
- const byName = new Map(assets.map(a => [a.name, a]));
339
- const planned = selectDownloadVariants(byName.keys()).map(name => {
340
- const a = byName.get(name);
341
- return { name, url: a.browser_download_url, size: a.size };
342
- });
343
- return syncFiles(tag, repo, planned, opts);
356
+ throw new Error(`no signature database release for ${version} in ${repo} (${tried.join('; ')})`);
344
357
  }
345
- /**
346
- * The cache dir a {@link downloadFullSigDb} for the committed link file would populate, or `undefined` if no
347
- * pointer is committed. Lets a caller mount an already-synced bundle via `solver.sigdb.additionalPaths` without
348
- * hitting the network.
349
- */
358
+ /** the cache dir {@link downloadFullSigDb} populates, `undefined` if the pointer is broken */
350
359
  function syncedSigDbDir() {
351
- const pointerPath = findRemotePointer();
352
- if (!pointerPath) {
353
- return undefined;
354
- }
355
- return path_1.default.join((0, decompress_1.sigDbCacheDir)(), 'bundles', readPointer(pointerPath).tag);
360
+ const remote = tryRemotePointer();
361
+ return remote && path_1.default.join((0, decompress_1.sigDbCacheDir)(), 'bundles', remote.tag);
356
362
  }
357
- /** the GitHub release (`{repo, tag, url}`) the committed pointer downloads from, or `undefined` when no pointer is committed */
363
+ /** the GitHub release the pointer downloads from, `undefined` if it is broken */
358
364
  function sigDbRemoteRelease() {
359
- const pointerPath = findRemotePointer();
360
- if (!pointerPath) {
361
- return undefined;
362
- }
363
- try {
364
- const remote = readPointer(pointerPath);
365
- const repo = remote.repo ?? DefaultRepo;
366
- return { repo, tag: remote.tag, url: `https://github.com/${repo}/releases/tag/${remote.tag}` };
367
- }
368
- catch {
365
+ const remote = tryRemotePointer();
366
+ if (!remote) {
369
367
  return undefined;
370
368
  }
369
+ const repo = remote.repo ?? DefaultRepo;
370
+ return { repo, tag: remote.tag, url: `https://github.com/${repo}/releases/tag/${remote.tag}` };
371
371
  }
372
372
  function withSelectedShards(f) {
373
- const pointerPath = findRemotePointer();
374
- if (!pointerPath) {
373
+ const remote = tryRemotePointer();
374
+ if (!remote) {
375
375
  return false;
376
376
  }
377
377
  try {
378
- const remote = readPointer(pointerPath);
379
378
  return f(remote, path_1.default.join((0, decompress_1.sigDbCacheDir)(undefined, false), 'bundles', remote.tag), selectDownloadVariants(Object.keys(remote.shards)));
380
379
  }
381
380
  catch {
@@ -0,0 +1,7 @@
1
+ import type { BasicQueryData } from '../../base-query-format';
2
+ import type { TaintQuery, TaintQueryResult } from './taint-query-format';
3
+ import type { AllPredefinedTaintAnalysisNames } from '../../../taint-analysis/predefined/predefined';
4
+ /**
5
+ * Executes the given taint queries using the provided analyzer.
6
+ */
7
+ export declare function executeTaintQuery({ analyzer }: BasicQueryData, queries: readonly TaintQuery[]): Promise<TaintQueryResult<AllPredefinedTaintAnalysisNames>>;
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.executeTaintQuery = executeTaintQuery;
4
+ const log_1 = require("../../../util/log");
5
+ /**
6
+ * Executes the given taint queries using the provided analyzer.
7
+ */
8
+ async function executeTaintQuery({ analyzer }, queries) {
9
+ const flattened = queries.flatMap(q => q.defs);
10
+ const start = Date.now();
11
+ if (flattened.length === 0) {
12
+ log_1.log.warn('Missing taint query definition');
13
+ return {
14
+ results: new Map(),
15
+ '.meta': {
16
+ timing: Date.now() - start
17
+ },
18
+ };
19
+ }
20
+ const analysis = analyzer
21
+ .taint()
22
+ .addPredefined(...flattened);
23
+ return {
24
+ results: await analysis.run(),
25
+ '.meta': {
26
+ timing: Date.now() - start
27
+ },
28
+ };
29
+ }
30
+ //# sourceMappingURL=taint-query-executor.js.map