@eagleoutice/flowr 2.17.0 → 2.17.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 (67) hide show
  1. package/README.md +8 -8
  2. package/config.d.ts +32 -0
  3. package/config.js +22 -2
  4. package/dataflow/environments/built-in-props.d.ts +16 -2
  5. package/dataflow/environments/built-in-props.js +23 -3
  6. package/dataflow/environments/built-in.js +13 -3
  7. package/dataflow/environments/default-builtin-config.d.ts +268 -7
  8. package/dataflow/environments/default-builtin-config.js +72 -13
  9. package/dataflow/environments/identifier.d.ts +7 -1
  10. package/dataflow/extractor.js +49 -14
  11. package/dataflow/fn/function-semantics.d.ts +1 -0
  12. package/linter/rules/network-functions.js +10 -2
  13. package/linter/rules/unused-import.js +11 -1
  14. package/package.json +1 -1
  15. package/project/cache/flowr-analyzer-cache.d.ts +4 -0
  16. package/project/cache/flowr-analyzer-cache.js +11 -0
  17. package/project/context/flowr-analyzer-dependencies-context.d.ts +3 -0
  18. package/project/context/flowr-analyzer-dependencies-context.js +6 -0
  19. package/project/context/flowr-file.d.ts +2 -2
  20. package/project/context/flowr-file.js +2 -2
  21. package/project/plugins/file-plugins/files/flowr-manifest-files.d.ts +39 -4
  22. package/project/plugins/file-plugins/files/flowr-manifest-files.js +134 -30
  23. package/project/plugins/file-plugins/files/flowr-rmarkdown-file.js +1 -1
  24. package/project/plugins/file-plugins/flowr-analyzer-manifest-file-plugin.d.ts +7 -0
  25. package/project/plugins/file-plugins/flowr-analyzer-manifest-file-plugin.js +14 -1
  26. package/project/plugins/file-plugins/flowr-analyzer-virtualenv-file-plugin.d.ts +1 -1
  27. package/project/plugins/file-plugins/flowr-analyzer-virtualenv-file-plugin.js +3 -3
  28. package/project/plugins/package-version-plugins/flowr-analyzer-meta-manifest-file-plugin.d.ts +18 -5
  29. package/project/plugins/package-version-plugins/flowr-analyzer-meta-manifest-file-plugin.js +43 -15
  30. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-lockfile-plugin.d.ts +12 -0
  31. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-lockfile-plugin.js +31 -2
  32. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-on-demand-plugin.d.ts +58 -0
  33. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-on-demand-plugin.js +237 -0
  34. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-plugin.d.ts +8 -0
  35. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-plugin.js +8 -0
  36. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.d.ts +7 -0
  37. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.js +24 -18
  38. package/project/plugins/plugin-registry.d.ts +5 -4
  39. package/project/plugins/plugin-registry.js +6 -0
  40. package/project/plugins/project-discovery/flowr-analyzer-project-discovery-plugin.js +4 -4
  41. package/project/sigdb/decode.js +13 -3
  42. package/project/sigdb/memory-source.d.ts +6 -4
  43. package/project/sigdb/memory-source.js +6 -5
  44. package/project/sigdb/on-demand/fetch.d.ts +18 -0
  45. package/project/sigdb/on-demand/fetch.js +127 -0
  46. package/project/sigdb/on-demand/package-sources.d.ts +40 -0
  47. package/project/sigdb/on-demand/package-sources.js +263 -0
  48. package/project/sigdb/on-demand/recoverer.d.ts +40 -0
  49. package/project/sigdb/on-demand/recoverer.js +169 -0
  50. package/project/sigdb/on-demand/remote-sources.d.ts +72 -0
  51. package/project/sigdb/on-demand/remote-sources.js +132 -0
  52. package/project/sigdb/on-demand/tar.d.ts +19 -0
  53. package/project/sigdb/on-demand/tar.js +119 -0
  54. package/queries/catalog/dependencies-query/function-info/derived-functions.d.ts +5 -0
  55. package/queries/catalog/dependencies-query/function-info/derived-functions.js +17 -1
  56. package/queries/catalog/dependencies-query/function-info/read-functions.js +3 -1
  57. package/queries/catalog/dependencies-query/function-info/write-functions.js +11 -1
  58. package/r-bridge/data/data.d.ts +29 -0
  59. package/r-bridge/data/data.js +23 -0
  60. package/r-bridge/lang-4.x/tree-sitter/tree-sitter-executor.d.ts +4 -0
  61. package/r-bridge/lang-4.x/tree-sitter/tree-sitter-executor.js +8 -0
  62. package/taint-analysis/predefined/secret-analysis.js +7 -2
  63. package/taint-analysis/taint-mapping.d.ts +5 -2
  64. package/taint-analysis/taint-mapping.js +17 -6
  65. package/util/flowr-version.d.ts +1 -1
  66. package/util/flowr-version.js +2 -2
  67. package/util/r-version.js +4 -2
@@ -0,0 +1,127 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.RefusedUrlError = exports.TooLargeError = void 0;
7
+ exports.isLocalHost = isLocalHost;
8
+ exports.checkedUrl = checkedUrl;
9
+ exports.httpsFetcher = httpsFetcher;
10
+ const https_1 = __importDefault(require("https"));
11
+ const net_1 = __importDefault(require("net"));
12
+ const secure_mode_1 = require("../../../util/secure-mode");
13
+ /** an archive bigger than its source was allowed to be */
14
+ class TooLargeError extends Error {
15
+ constructor(url, max) {
16
+ super(`${url} is larger than ${Math.round(max / 1024 / 1024)} MiB`);
17
+ this.name = 'TooLargeError';
18
+ }
19
+ }
20
+ exports.TooLargeError = TooLargeError;
21
+ /** a URL the on-demand fetch refuses: anything but `https`, or a host on the local machine or network */
22
+ class RefusedUrlError extends Error {
23
+ constructor(url, why) {
24
+ super(`refusing ${url}: ${why}`);
25
+ this.name = 'RefusedUrlError';
26
+ }
27
+ }
28
+ exports.RefusedUrlError = RefusedUrlError;
29
+ /** whether `host` is this machine or an address of a private network, which a redirect must never lead to */
30
+ function isLocalHost(host) {
31
+ const bare = host.replace(/^\[|\]$/g, '').toLowerCase();
32
+ if (bare === 'localhost' || bare.endsWith('.localhost') || bare.endsWith('.local') || bare.endsWith('.internal')) {
33
+ return true;
34
+ }
35
+ if (net_1.default.isIPv4(bare)) {
36
+ const [a, b] = bare.split('.').map(Number);
37
+ return a === 0 || a === 10 || a === 127 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || a >= 224;
38
+ }
39
+ if (net_1.default.isIPv6(bare)) {
40
+ return bare === '::' || bare === '::1' || /^(fc|fd|fe8|fe9|fea|feb)/.test(bare) || bare.startsWith('::ffff:');
41
+ }
42
+ return false;
43
+ }
44
+ /** the URL, if the fetch may go there. `trusted` hosts (the mirrors a trusted configuration names) may be local */
45
+ function checkedUrl(url, trusted = new Set()) {
46
+ let parsed;
47
+ try {
48
+ parsed = new URL(url);
49
+ }
50
+ catch {
51
+ throw new RefusedUrlError(url, 'no URL');
52
+ }
53
+ if (parsed.protocol !== 'https:') {
54
+ throw new RefusedUrlError(url, 'only https is allowed');
55
+ }
56
+ if (parsed.username || parsed.password) {
57
+ throw new RefusedUrlError(url, 'no credentials in URLs');
58
+ }
59
+ if (isLocalHost(parsed.hostname) && !trusted.has(parsed.host)) {
60
+ throw new RefusedUrlError(url, 'a local or private host');
61
+ }
62
+ return parsed;
63
+ }
64
+ const IdleTimeoutMs = 30_000;
65
+ const MaxRedirects = 5;
66
+ function get(url, redirects, trusted) {
67
+ secure_mode_1.SecureMode.guard('network access', url);
68
+ const target = checkedUrl(url, trusted);
69
+ return new Promise((resolve, reject) => {
70
+ /* no token or cookie ever goes out: these are public sources */
71
+ const req = https_1.default.get(target, { headers: { 'User-Agent': 'flowr', Accept: '*/*' } }, res => {
72
+ const status = res.statusCode ?? 0;
73
+ if (status >= 300 && status < 400 && res.headers.location) {
74
+ res.resume();
75
+ if (redirects <= 0) {
76
+ reject(new Error(`GET ${url}: too many redirects`));
77
+ return;
78
+ }
79
+ /* every hop is checked again, so a redirect cannot lead to plain http or into the local network */
80
+ get(new URL(res.headers.location, target).toString(), redirects - 1, trusted).then(resolve, reject);
81
+ }
82
+ else if (status >= 200 && status < 300) {
83
+ resolve(res);
84
+ }
85
+ else {
86
+ res.resume();
87
+ if (status === 404 || status === 410) {
88
+ resolve(undefined);
89
+ }
90
+ else {
91
+ reject(new Error(`GET ${url} -> HTTP ${status}`));
92
+ }
93
+ }
94
+ });
95
+ req.setTimeout(IdleTimeoutMs, () => req.destroy(new Error(`GET ${url} -> no data for ${IdleTimeoutMs / 1000}s`)));
96
+ req.on('error', reject);
97
+ });
98
+ }
99
+ /**
100
+ * {@link FetchBytes} over HTTPS, see {@link checkedUrl}. A 404 (or 410) means the server does not have it.
101
+ * @param trusted - the hosts (with port) that may be local, as a company mirror is
102
+ */
103
+ function httpsFetcher(trusted = new Set()) {
104
+ return async (url, maxBytes) => {
105
+ const res = await get(url, MaxRedirects, trusted);
106
+ if (res === undefined) {
107
+ return undefined;
108
+ }
109
+ const announced = Number(res.headers['content-length'] ?? NaN);
110
+ if (announced > maxBytes) {
111
+ res.destroy();
112
+ throw new TooLargeError(url, maxBytes);
113
+ }
114
+ const chunks = [];
115
+ let total = 0;
116
+ for await (const chunk of res) {
117
+ total += chunk.length;
118
+ if (total > maxBytes) {
119
+ res.destroy();
120
+ throw new TooLargeError(url, maxBytes);
121
+ }
122
+ chunks.push(chunk);
123
+ }
124
+ return Buffer.concat(chunks);
125
+ };
126
+ }
127
+ //# sourceMappingURL=fetch.js.map
@@ -0,0 +1,40 @@
1
+ import type Parser from 'web-tree-sitter';
2
+ import type { DecodedFunction } from '../decode';
3
+ /**
4
+ * What flowR recovers of a package from its sources: the exports its `NAMESPACE` states (an `exportPattern`
5
+ * matched against the names the code defines) and the formals of every function its `R/` files define at the
6
+ * top level. This is what an on-demand signature source serves for a package no database knows.
7
+ */
8
+ export interface RecoveredPackage {
9
+ readonly name: string;
10
+ readonly version?: string;
11
+ /** where the sources came from, like `github:masurp/ggmirt` */
12
+ readonly origin: string;
13
+ readonly exported: readonly string[];
14
+ readonly s4Classes: readonly string[];
15
+ readonly functions: readonly DecodedFunction[];
16
+ }
17
+ /** The R files of a package source, the way `R CMD build` picks them: `R/*.R` (and `.r`, `.S`, `.s`, `.q`), not the platform subdirectories. */
18
+ export declare function isPackageCodeFile(path: string): boolean;
19
+ /** the files of a package source the recovery reads */
20
+ export declare function isRecoveredFile(path: string): boolean;
21
+ /**
22
+ * Recovers a package from the files of its source (`DESCRIPTION`, `NAMESPACE`, `R/*.R`, paths relative to its
23
+ * root), parsing the code with `parse`. `undefined` if the files are no R package (no `DESCRIPTION` naming one).
24
+ * Without a `NAMESPACE`, as old packages have, every name not starting with a dot is exported, as R does.
25
+ */
26
+ export declare function recoverPackage(files: ReadonlyMap<string, string>, parse: (code: string) => Parser.Tree, origin: string): RecoveredPackage | undefined;
27
+ /** the most names, functions, and parameters a recovered package may state, so a crafted one cannot bloat the analysis */
28
+ export declare const RecoveredLimits: {
29
+ readonly names: 20000;
30
+ readonly parameters: 256;
31
+ readonly nameLength: 256;
32
+ };
33
+ /**
34
+ * What of a recovered package (fresh from its sources, or read back from the cache, both of which an attacker
35
+ * may have shaped) flowR is willing to use: package and bindable names only, a version that is one, bounded
36
+ * sizes, and no properties beyond the ones the recovery itself states. Names in `shielded` are dropped from the
37
+ * exports: a package nobody vetted must not take over a call flowR knows to be security relevant, like `system`,
38
+ * which would hide that call from every analysis looking for it. `undefined` for something that is no package.
39
+ */
40
+ export declare function sanitizeRecovered(value: unknown, shielded?: ReadonlySet<string>): RecoveredPackage | undefined;
@@ -0,0 +1,263 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RecoveredLimits = void 0;
4
+ exports.isPackageCodeFile = isPackageCodeFile;
5
+ exports.isRecoveredFile = isRecoveredFile;
6
+ exports.recoverPackage = recoverPackage;
7
+ exports.sanitizeRecovered = sanitizeRecovered;
8
+ const flowr_file_1 = require("../../context/flowr-file");
9
+ const flowr_description_file_1 = require("../../plugins/file-plugins/files/flowr-description-file");
10
+ const schema_1 = require("../schema");
11
+ const built_in_props_1 = require("../../../dataflow/environments/built-in-props");
12
+ const r_regex_1 = require("../../../util/r-regex");
13
+ const arrays_1 = require("../../../util/collections/arrays");
14
+ const tree_sitter_types_1 = require("../../../r-bridge/lang-4.x/tree-sitter/tree-sitter-types");
15
+ /** The R files of a package source, the way `R CMD build` picks them: `R/*.R` (and `.r`, `.S`, `.s`, `.q`), not the platform subdirectories. */
16
+ function isPackageCodeFile(path) {
17
+ return /^R\/[^/]+\.[RrSsq]$/.test(path);
18
+ }
19
+ /** the files of a package source the recovery reads */
20
+ function isRecoveredFile(path) {
21
+ return path === 'DESCRIPTION' || path === 'NAMESPACE' || isPackageCodeFile(path);
22
+ }
23
+ const AssignLeft = new Set(['<-', '=', '<<-', ':=']);
24
+ const AssignRight = new Set(['->', '->>']);
25
+ /** the name a definition binds, without the quotes or backticks it may be written with */
26
+ function boundName(node) {
27
+ if (node.type === tree_sitter_types_1.TreeSitterType.Identifier) {
28
+ return node.text.startsWith('`') && node.text.endsWith('`') && node.text.length > 1 ? node.text.slice(1, -1) : node.text;
29
+ }
30
+ else if (node.type === tree_sitter_types_1.TreeSitterType.String) {
31
+ return node.childForFieldName('content')?.text ?? '';
32
+ }
33
+ return undefined;
34
+ }
35
+ function shortened(text) {
36
+ return text.length > schema_1.MaxDefaultLength ? `${text.slice(0, schema_1.MaxDefaultLength)}…` : text;
37
+ }
38
+ function signatureOf(definition) {
39
+ const parameters = definition.childForFieldName('parameters')?.namedChildren.filter(p => p.type === tree_sitter_types_1.TreeSitterType.Parameter) ?? [];
40
+ return parameters.flatMap(p => {
41
+ const name = p.childForFieldName('name');
42
+ if (name === null) {
43
+ return [];
44
+ }
45
+ const value = p.childForFieldName('default');
46
+ const param = name.type === tree_sitter_types_1.TreeSitterType.Dots ? '...' : boundName(name) ?? name.text;
47
+ return [value === null
48
+ ? { name: param, props: param === '...' ? 0 : built_in_props_1.ArgProp.NoDefault }
49
+ : { name: param, props: 0, default: shortened(value.text) }];
50
+ });
51
+ }
52
+ /** the expression within parentheses, `(function(x) x)` is a function as well */
53
+ function unwrapped(node) {
54
+ while (node.type === tree_sitter_types_1.TreeSitterType.ParenthesizedExpression && node.namedChildren.length === 1) {
55
+ node = node.namedChildren[0];
56
+ }
57
+ return node;
58
+ }
59
+ /** the name an assignment binds and the value it binds it to, `undefined` for another operator or a target that is no name (`x$a <- 1`) */
60
+ function assignment(node) {
61
+ if (node.type !== tree_sitter_types_1.TreeSitterType.BinaryOperator) {
62
+ return undefined;
63
+ }
64
+ const operator = node.childForFieldName('operator')?.type ?? '';
65
+ const [target, value] = AssignLeft.has(operator) ? [node.childForFieldName('lhs'), node.childForFieldName('rhs')]
66
+ : AssignRight.has(operator) ? [node.childForFieldName('rhs'), node.childForFieldName('lhs')] : [null, null];
67
+ const name = target === null ? undefined : boundName(target);
68
+ return name === undefined || value === null ? undefined : { name, value };
69
+ }
70
+ /** the string a call's first argument is, like the `"show"` of `setGeneric("show", ...)` */
71
+ function firstStringArgument(call) {
72
+ const first = call.childForFieldName('arguments')?.namedChildren.find(a => a.type === tree_sitter_types_1.TreeSitterType.Argument);
73
+ const value = first?.childForFieldName('value');
74
+ return value?.type === tree_sitter_types_1.TreeSitterType.String ? boundName(value) : undefined;
75
+ }
76
+ /** the definitions a top-level expression makes, looking into blocks and branches (`if(getRversion() >= "4.0") f <- ...`) but not into functions */
77
+ function collect(node, file, into, exportedFrom) {
78
+ switch (node.type) {
79
+ case tree_sitter_types_1.TreeSitterType.BinaryOperator: {
80
+ const assigned = assignment(node);
81
+ if (assigned === undefined) {
82
+ return;
83
+ }
84
+ into.names.push(assigned.name);
85
+ /* `f <- g <- function(x) x` defines both */
86
+ collect(assigned.value, file, into, exportedFrom);
87
+ let value = unwrapped(assigned.value);
88
+ for (let inner = assignment(value); inner !== undefined; inner = assignment(value)) {
89
+ value = unwrapped(inner.value);
90
+ }
91
+ if (value.type === tree_sitter_types_1.TreeSitterType.FunctionDefinition) {
92
+ into.functions.push({ name: assigned.name, file, line: node.startPosition.row + 1, exported: exportedFrom(assigned.name), props: [], signature: signatureOf(value), callees: [] });
93
+ }
94
+ return;
95
+ }
96
+ case tree_sitter_types_1.TreeSitterType.Call: {
97
+ const callee = node.childForFieldName('function')?.text;
98
+ if (callee === 'setGeneric' || callee === 'methods::setGeneric') {
99
+ const name = firstStringArgument(node);
100
+ const definition = node.childForFieldName('arguments')?.namedChildren
101
+ .map(a => a.childForFieldName('value')).find(v => v?.type === tree_sitter_types_1.TreeSitterType.FunctionDefinition);
102
+ if (name !== undefined) {
103
+ into.names.push(name);
104
+ if (definition) {
105
+ into.functions.push({ name, file, line: node.startPosition.row + 1, exported: exportedFrom(name), props: ['generic'], signature: signatureOf(definition), callees: [] });
106
+ }
107
+ }
108
+ }
109
+ return;
110
+ }
111
+ case tree_sitter_types_1.TreeSitterType.BracedExpression:
112
+ case tree_sitter_types_1.TreeSitterType.Program:
113
+ for (const child of node.namedChildren) {
114
+ collect(child, file, into, exportedFrom);
115
+ }
116
+ return;
117
+ case tree_sitter_types_1.TreeSitterType.IfStatement:
118
+ for (const field of ['consequence', 'alternative']) {
119
+ const branch = node.childForFieldName(field);
120
+ if (branch) {
121
+ collect(branch, file, into, exportedFrom);
122
+ }
123
+ }
124
+ return;
125
+ default:
126
+ return;
127
+ }
128
+ }
129
+ /** the directives of a `NAMESPACE`, read as the R code it is, so a directive spanning lines or a conditional one counts as well */
130
+ function namespaceDirectives(root) {
131
+ const found = { exports: [], patterns: [], classes: [] };
132
+ const visit = (node) => {
133
+ if (node.type === tree_sitter_types_1.TreeSitterType.Call) {
134
+ const args = node.childForFieldName('arguments')?.namedChildren.filter(a => a.type === tree_sitter_types_1.TreeSitterType.Argument && a.childForFieldName('name') === null)
135
+ .flatMap(a => {
136
+ const value = a.childForFieldName('value');
137
+ return value === null ? [] : [boundName(value)].filter(v => v !== undefined);
138
+ }) ?? [];
139
+ const directive = node.childForFieldName('function')?.text;
140
+ const into = directive === 'export' ? found.exports : directive === 'exportPattern' ? found.patterns
141
+ : directive === 'exportClasses' || directive === 'exportClass' ? found.classes : undefined;
142
+ into?.push(...args);
143
+ }
144
+ else {
145
+ node.namedChildren.forEach(visit);
146
+ }
147
+ };
148
+ visit(root);
149
+ return found;
150
+ }
151
+ /**
152
+ * Recovers a package from the files of its source (`DESCRIPTION`, `NAMESPACE`, `R/*.R`, paths relative to its
153
+ * root), parsing the code with `parse`. `undefined` if the files are no R package (no `DESCRIPTION` naming one).
154
+ * Without a `NAMESPACE`, as old packages have, every name not starting with a dot is exported, as R does.
155
+ */
156
+ function recoverPackage(files, parse, origin) {
157
+ const descriptionText = files.get('DESCRIPTION');
158
+ if (descriptionText === undefined) {
159
+ return undefined;
160
+ }
161
+ const description = new flowr_description_file_1.FlowrDescriptionFile(new flowr_file_1.FlowrInlineTextFile('DESCRIPTION', descriptionText));
162
+ const name = description.packageName();
163
+ if (name === undefined || !/^[A-Za-z][A-Za-z0-9.]*$/.test(name)) {
164
+ return undefined;
165
+ }
166
+ const namespaceText = files.get('NAMESPACE');
167
+ const namespace = namespaceText === undefined ? undefined : namespaceDirectives(parse(namespaceText).rootNode);
168
+ const stated = new Set(namespace?.exports ?? []);
169
+ const patterns = namespace?.patterns.map(r_regex_1.parseRRegexPattern) ?? [];
170
+ const exportedFrom = namespace === undefined ? (n) => !n.startsWith('.') : (n) => stated.has(n) || patterns.some(p => p.test(n));
171
+ const definitions = { names: [], functions: [] };
172
+ /* the collation order decides which of two definitions of one name wins, alphabetical by default */
173
+ const collate = description.collate()?.map(f => `R/${f}`);
174
+ const code = [...files.keys()].filter(isPackageCodeFile).sort();
175
+ const ordered = collate === undefined ? code : (0, arrays_1.uniqueArray)([...collate.filter(f => files.has(f)), ...code]);
176
+ for (const file of ordered) {
177
+ collect(parse(files.get(file) ?? '').rootNode, file, definitions, exportedFrom);
178
+ }
179
+ const latest = new Map(definitions.functions.map(f => [f.name, f]));
180
+ const exported = (0, arrays_1.uniqueArray)([...stated, ...definitions.names.filter(exportedFrom)]);
181
+ return {
182
+ name,
183
+ version: versionField(descriptionText) ?? description.version()?.str,
184
+ origin,
185
+ exported,
186
+ s4Classes: namespace?.classes ?? [],
187
+ functions: [...latest.values()]
188
+ };
189
+ }
190
+ /** the `Version` field as written, for one semver cannot read (`1.2-3`) */
191
+ function versionField(description) {
192
+ return /^Version:\s*(\S+)/m.exec(description)?.[1];
193
+ }
194
+ /** the most names, functions, and parameters a recovered package may state, so a crafted one cannot bloat the analysis */
195
+ exports.RecoveredLimits = { names: 20_000, parameters: 256, nameLength: 256 };
196
+ /** whether the code unit is a control character (below space, or DEL) */
197
+ const isControl = (code) => code < 0x20 || code === 0x7f;
198
+ function hasControlChar(text) {
199
+ for (let i = 0; i < text.length; i++) {
200
+ if (isControl(text.charCodeAt(i))) {
201
+ return true;
202
+ }
203
+ }
204
+ return false;
205
+ }
206
+ function withoutControlChars(text) {
207
+ return Array.from(text, c => isControl(c.charCodeAt(0)) ? ' ' : c).join('');
208
+ }
209
+ /** a name R may bind: not empty, not too long, no control characters, and nothing that names an object prototype */
210
+ function isBindableName(name) {
211
+ return typeof name === 'string' && name.length > 0 && name.length <= exports.RecoveredLimits.nameLength && !hasControlChar(name) && name !== '__proto__';
212
+ }
213
+ function sanitizedParameter(p) {
214
+ const param = p;
215
+ if (typeof param !== 'object' || param === null || !isBindableName(param.name)) {
216
+ return undefined;
217
+ }
218
+ /* whether a parameter has a default is all the sources say, every other bit is flowR's to state, never a package's */
219
+ const props = typeof param.props === 'number' ? param.props & built_in_props_1.ArgProp.NoDefault : 0;
220
+ const value = typeof param.default === 'string' ? shortened(withoutControlChars(param.default)) : undefined;
221
+ return value === undefined ? { name: param.name, props } : { name: param.name, props, default: value };
222
+ }
223
+ function sanitizedFunction(f) {
224
+ const fn = f;
225
+ if (typeof fn !== 'object' || fn === null || !isBindableName(fn.name) || !Array.isArray(fn.signature)) {
226
+ return undefined;
227
+ }
228
+ return {
229
+ name: fn.name,
230
+ file: typeof fn.file === 'string' && isPackageCodeFile(fn.file) ? fn.file : undefined,
231
+ line: Number.isInteger(fn.line) && fn.line > 0 ? fn.line : 0,
232
+ exported: fn.exported === true,
233
+ props: Array.isArray(fn.props) && fn.props.includes('generic') ? ['generic'] : [],
234
+ signature: fn.signature.slice(0, exports.RecoveredLimits.parameters).map(sanitizedParameter).filter(p => p !== undefined),
235
+ callees: []
236
+ };
237
+ }
238
+ /**
239
+ * What of a recovered package (fresh from its sources, or read back from the cache, both of which an attacker
240
+ * may have shaped) flowR is willing to use: package and bindable names only, a version that is one, bounded
241
+ * sizes, and no properties beyond the ones the recovery itself states. Names in `shielded` are dropped from the
242
+ * exports: a package nobody vetted must not take over a call flowR knows to be security relevant, like `system`,
243
+ * which would hide that call from every analysis looking for it. `undefined` for something that is no package.
244
+ */
245
+ function sanitizeRecovered(value, shielded = new Set()) {
246
+ const pkg = value;
247
+ if (typeof pkg !== 'object' || pkg === null || typeof pkg.name !== 'string' || !/^[A-Za-z][A-Za-z0-9.]*$/.test(pkg.name)
248
+ || !Array.isArray(pkg.exported) || !Array.isArray(pkg.functions) || !Array.isArray(pkg.s4Classes)) {
249
+ return undefined;
250
+ }
251
+ const exported = (0, arrays_1.uniqueArray)(pkg.exported.filter(isBindableName).filter(n => !shielded.has(n))).slice(0, exports.RecoveredLimits.names);
252
+ const isExported = new Set(exported);
253
+ return {
254
+ name: pkg.name,
255
+ version: typeof pkg.version === 'string' && /^[0-9][0-9.-]{0,40}$/.test(pkg.version) ? pkg.version : undefined,
256
+ origin: typeof pkg.origin === 'string' && !hasControlChar(pkg.origin) ? pkg.origin.slice(0, 200) : 'unknown',
257
+ exported,
258
+ s4Classes: (0, arrays_1.uniqueArray)(pkg.s4Classes.filter(isBindableName)).slice(0, exports.RecoveredLimits.names),
259
+ functions: pkg.functions.slice(0, exports.RecoveredLimits.names).map(sanitizedFunction).filter(f => f !== undefined)
260
+ .map(f => ({ ...f, exported: f.exported && isExported.has(f.name) }))
261
+ };
262
+ }
263
+ //# sourceMappingURL=package-sources.js.map
@@ -0,0 +1,40 @@
1
+ import type Parser from 'web-tree-sitter';
2
+ import type { FlowrConfig } from '../../../config';
3
+ import type { FetchBytes, OnDemandSource, PackageRequest } from './remote-sources';
4
+ import { type RecoveredPackage } from './package-sources';
5
+ export declare const onDemandLog: import("tslog").Logger<import("tslog").ILogObj>;
6
+ /** what `solver.sigdb.onDemand` configures */
7
+ export type OnDemandOptions = NonNullable<FlowrConfig['solver']['sigdb']['onDemand']>;
8
+ /** what a {@link OnDemandRecoverer} works with, injectable so a test needs no network */
9
+ export interface OnDemandRecovererArgs {
10
+ readonly sources: readonly OnDemandSource[];
11
+ readonly fetch: FetchBytes;
12
+ readonly parse: (code: string) => Parser.Tree;
13
+ readonly cacheDir: string;
14
+ readonly now?: () => number;
15
+ }
16
+ /**
17
+ * Recovers packages no signature database knows from their sources: asks each {@link OnDemandSource} in turn for
18
+ * archives, reads `DESCRIPTION`, `NAMESPACE`, and `R/` from the first one that holds the package, and caches the
19
+ * result (or that no source had it) as one JSON file per package, so later analyses need no network.
20
+ */
21
+ export declare class OnDemandRecoverer {
22
+ private readonly options;
23
+ private readonly args;
24
+ private readonly now;
25
+ constructor(options: OnDemandOptions, args: OnDemandRecovererArgs);
26
+ private cacheFile;
27
+ private readEntry;
28
+ private writeEntry;
29
+ /** The package as fetched before, `undefined` if it never was or no source had it. */
30
+ cached(name: string): RecoveredPackage | undefined;
31
+ /** whether the cache answers `request`, with the package or with a recent miss */
32
+ private settled;
33
+ /**
34
+ * Fetches the packages of `requests` the cache does not answer yet, at most `maxPackages` of them, and returns
35
+ * those it recovered. A failing source is logged and the next one tried, so this never throws.
36
+ */
37
+ recover(requests: readonly PackageRequest[]): Promise<RecoveredPackage[]>;
38
+ private recoverOne;
39
+ private fromArchive;
40
+ }
@@ -0,0 +1,169 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.OnDemandRecoverer = exports.onDemandLog = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const remote_sources_1 = require("./remote-sources");
10
+ const package_sources_1 = require("./package-sources");
11
+ const tar_1 = require("./tar");
12
+ const log_1 = require("../../../util/log");
13
+ exports.onDemandLog = log_1.log.getSubLogger({ name: 'sigdb-on-demand' });
14
+ /** the version of the cache entries, a different one is fetched again */
15
+ const CacheSchema = 1;
16
+ /** how many packages are fetched at once */
17
+ const Parallel = 4;
18
+ function isCacheEntry(value, name) {
19
+ const entry = value;
20
+ const pkg = entry?.package;
21
+ return typeof entry === 'object' && entry !== null && entry.schema === CacheSchema && entry.name === name && typeof entry.at === 'number'
22
+ && (pkg === undefined || (pkg.name === name && Array.isArray(pkg.exported) && Array.isArray(pkg.functions) && Array.isArray(pkg.s4Classes)));
23
+ }
24
+ /** whether what was asked for back then answers what is asked now */
25
+ function answers(entry, request) {
26
+ return (request.version === undefined || entry.request.version === request.version)
27
+ && (request.github === undefined || entry.request.github === request.github);
28
+ }
29
+ /**
30
+ * Recovers packages no signature database knows from their sources: asks each {@link OnDemandSource} in turn for
31
+ * archives, reads `DESCRIPTION`, `NAMESPACE`, and `R/` from the first one that holds the package, and caches the
32
+ * result (or that no source had it) as one JSON file per package, so later analyses need no network.
33
+ */
34
+ class OnDemandRecoverer {
35
+ options;
36
+ args;
37
+ now;
38
+ constructor(options, args) {
39
+ this.options = options;
40
+ this.args = args;
41
+ this.now = args.now ?? Date.now;
42
+ }
43
+ cacheFile(name) {
44
+ return path_1.default.join(this.args.cacheDir, `${name}.json`);
45
+ }
46
+ readEntry(name) {
47
+ if (!(0, remote_sources_1.isPackageName)(name)) {
48
+ return undefined;
49
+ }
50
+ try {
51
+ const entry = JSON.parse(fs_1.default.readFileSync(this.cacheFile(name), 'utf8'));
52
+ return isCacheEntry(entry, name) ? entry : undefined;
53
+ }
54
+ catch {
55
+ return undefined;
56
+ }
57
+ }
58
+ writeEntry(entry) {
59
+ try {
60
+ fs_1.default.mkdirSync(this.args.cacheDir, { recursive: true });
61
+ const file = this.cacheFile(entry.name);
62
+ const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.part`;
63
+ fs_1.default.writeFileSync(tmp, JSON.stringify(entry));
64
+ fs_1.default.renameSync(tmp, file);
65
+ }
66
+ catch (e) {
67
+ exports.onDemandLog.warn(`cannot cache ${entry.name} in ${this.args.cacheDir}: ${e.message}`);
68
+ }
69
+ }
70
+ /** The package as fetched before, `undefined` if it never was or no source had it. */
71
+ cached(name) {
72
+ const found = (0, package_sources_1.sanitizeRecovered)(this.readEntry(name)?.package);
73
+ return found?.name === name ? found : undefined;
74
+ }
75
+ /** whether the cache answers `request`, with the package or with a recent miss */
76
+ settled(request) {
77
+ const entry = this.readEntry(request.name);
78
+ if (entry === undefined || !answers(entry, request)) {
79
+ return false;
80
+ }
81
+ const retry = (this.options.retryAfterHours ?? 24) * 60 * 60 * 1000;
82
+ return entry.package !== undefined || this.now() - entry.at < retry;
83
+ }
84
+ /**
85
+ * Fetches the packages of `requests` the cache does not answer yet, at most `maxPackages` of them, and returns
86
+ * those it recovered. A failing source is logged and the next one tried, so this never throws.
87
+ */
88
+ async recover(requests) {
89
+ if (this.options.offline) {
90
+ return [];
91
+ }
92
+ const wanted = requests.filter(r => (0, remote_sources_1.isPackageName)(r.name) && !this.settled(r)).slice(0, this.options.maxPackages ?? 25);
93
+ const recovered = [];
94
+ for (let i = 0; i < wanted.length; i += Parallel) {
95
+ const batch = await Promise.all(wanted.slice(i, i + Parallel).map(r => this.recoverOne(r)));
96
+ recovered.push(...batch.filter(p => p !== undefined));
97
+ }
98
+ return recovered;
99
+ }
100
+ async recoverOne(request) {
101
+ const failures = [];
102
+ const tryArchive = async (archive) => {
103
+ try {
104
+ const found = await this.fromArchive(request, archive);
105
+ if (found !== undefined) {
106
+ exports.onDemandLog.info(`recovered ${found.name}${found.version ? ` ${found.version}` : ''} from ${archive.url}`);
107
+ this.writeEntry({ schema: CacheSchema, name: request.name, request: { version: request.version, github: request.github }, at: this.now(), package: found });
108
+ }
109
+ return found;
110
+ }
111
+ catch (e) {
112
+ failures.push(`${archive.url}: ${e.message}`);
113
+ return undefined;
114
+ }
115
+ };
116
+ /* in the order of the sources, but every sure archive before any fallback */
117
+ const fallbacks = [];
118
+ for (const source of this.args.sources) {
119
+ let archives;
120
+ try {
121
+ archives = await source.archives(request, this.args.fetch);
122
+ }
123
+ catch (e) {
124
+ failures.push(`${source.name}: ${e.message}`);
125
+ continue;
126
+ }
127
+ for (const archive of archives) {
128
+ if (archive.fallback) {
129
+ fallbacks.push(archive);
130
+ continue;
131
+ }
132
+ const found = await tryArchive(archive);
133
+ if (found !== undefined) {
134
+ return found;
135
+ }
136
+ }
137
+ }
138
+ for (const archive of fallbacks) {
139
+ const found = await tryArchive(archive);
140
+ if (found !== undefined) {
141
+ return found;
142
+ }
143
+ }
144
+ if (failures.length > 0) {
145
+ /* a failure may be the network's rather than the package's, so the next analysis asks again */
146
+ exports.onDemandLog.warn(`cannot recover ${request.name}: ${failures.join(', ')}`);
147
+ return undefined;
148
+ }
149
+ exports.onDemandLog.info(`cannot recover ${request.name}: no source has it`);
150
+ this.writeEntry({ schema: CacheSchema, name: request.name, request: { version: request.version, github: request.github }, at: this.now(), missing: 'no source has it' });
151
+ return undefined;
152
+ }
153
+ async fromArchive(request, archive) {
154
+ const maxBytes = (this.options.maxArchiveMb ?? 32) * 1024 * 1024;
155
+ const bytes = await this.args.fetch(archive.url, maxBytes);
156
+ if (bytes === undefined) {
157
+ return undefined;
158
+ }
159
+ const prefix = archive.subdir === undefined ? '' : `${archive.subdir.replace(/\/$/, '')}/`;
160
+ /* what an archive unpacks to is held in memory at once, so it gets a bound of its own */
161
+ const entries = (0, tar_1.readTarEntries)(bytes, p => p.startsWith(prefix) && (0, package_sources_1.isRecoveredFile)(p.slice(prefix.length)), { ...tar_1.DefaultTarLimits, maxArchiveBytes: Math.min(3 * maxBytes, tar_1.DefaultTarLimits.maxArchiveBytes) });
162
+ const files = new Map([...entries].map(([p, b]) => [p.slice(prefix.length), b.toString('utf8')]));
163
+ const found = (0, package_sources_1.sanitizeRecovered)((0, package_sources_1.recoverPackage)(files, this.args.parse, archive.origin));
164
+ /* a mirror may hold another package under that name, a repository one named differently */
165
+ return found?.name === request.name ? found : undefined;
166
+ }
167
+ }
168
+ exports.OnDemandRecoverer = OnDemandRecoverer;
169
+ //# sourceMappingURL=recoverer.js.map