tarsen-core 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Tarsen Contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,57 @@
1
+ # tarsen-core
2
+
3
+ Static npm package analysis for [Tarsen](../../README.md). Tarsen checks
4
+ executable npm packages **before** developers or AI agents run them.
5
+
6
+ `tarsen-core` is a pure local analyzer. It **never executes package code**,
7
+ **never runs install scripts**, and **has no cloud connection or telemetry**.
8
+ It turns registry metadata and extracted source files into a stable JSON risk
9
+ report that the CLI (or any other tool) can render.
10
+
11
+ ## What it provides
12
+
13
+ - **Registry metadata parsing** (`parseMetadata`) — normalize a version manifest
14
+ and packument into a typed `PackageMetadata`.
15
+ - **Static file scanning** (`scanContent`, `scanFiles`) — pure string pattern
16
+ detection for child processes, dynamic execution, env/filesystem/network
17
+ access, and obfuscation. Never imports or evaluates the code it scans.
18
+ - **Safe tarball helpers** (`isTraversalAttempt`, `makeSafeFilter`) — reject path
19
+ traversal, drop symlinks/hardlinks, and enforce entry caps during extraction.
20
+ - **Risk scoring** (`scoreSignals`, `riskLevel`, `recommend`) — deterministic
21
+ mapping from signals to a `low | medium | high | unknown` band and a
22
+ recommendation.
23
+ - **Report contract** (`RiskReport`, `analyzePackage`, `unknownReport`) — the
24
+ schema emitted by `tarsen check --json`.
25
+
26
+ ## Detection scope
27
+
28
+ Lifecycle scripts (`preinstall`, `install`, `postinstall`, `prepare`),
29
+ `child_process` / `exec(` / `spawn(` / `execSync(` / `spawnSync(`, `eval(` /
30
+ `Function(`, sensitive `process.env`, `fs.readFile` / `fs.writeFile` / `fs.rm` /
31
+ `fs.unlink`, `os.homedir(`, `fetch(` / `http.request` / `https.request` /
32
+ `axios` / `XMLHttpRequest` / `WebSocket`, large minified files, very long
33
+ lines, base64-like blobs, missing repository/maintainers/description, very new
34
+ packages, and one-edit typosquatting against common package names.
35
+
36
+ ## Usage
37
+
38
+ ```ts
39
+ import { analyzePackage, parseMetadata } from "tarsen-core";
40
+
41
+ const metadata = parseMetadata(manifest, packument);
42
+ const report = analyzePackage(metadata, [
43
+ { path: "index.js", content: "require('child_process').exec('whoami')" },
44
+ ]);
45
+ // report.risk === "high"
46
+ ```
47
+
48
+ ## Safety guarantees
49
+
50
+ This package only ever reads strings. It does not fetch from the network,
51
+ execute code, or write anywhere — those concerns live in `tarsen`. The tar
52
+ helpers are pure predicates and filter factories; the actual extraction is
53
+ driven by the CLI into a temporary directory that it owns and cleans up.
54
+
55
+ ## License
56
+
57
+ Apache-2.0. See [LICENSE](../../LICENSE).
@@ -0,0 +1,28 @@
1
+ import type { PackageMetadata, RiskReport } from "./report.js";
2
+ export { SCHEMA_VERSION } from "./report.js";
3
+ export type { PackageMetadata, Recommendation, RiskLevel, RiskReport, RiskSignal, ScanStats, SignalSeverity, } from "./report.js";
4
+ export { parseMetadata, typosquatSignal, isVeryNew, COMMON_PACKAGE_NAMES } from "./metadata.js";
5
+ export { scanContent, scanFiles } from "./scan.js";
6
+ export { capSignals, scoreSignals, riskLevel, recommend, SEVERITY_WEIGHTS } from "./score.js";
7
+ export { isTraversalAttempt, makeSafeFilter, DEFAULT_EXTRACTION_LIMITS, } from "./tar.js";
8
+ export type { ExtractionLimits, ExtractedFile, WalkResult } from "./tar.js";
9
+ export interface AnalyzeOptions {
10
+ truncated?: boolean;
11
+ }
12
+ /**
13
+ * Combine metadata + scanned-file signals into a finalized report.
14
+ *
15
+ * This is the single entry point the CLI uses after extracting a tarball.
16
+ * It is a pure function of its inputs and safe to call against untrusted data.
17
+ */
18
+ export declare function analyzePackage(metadata: PackageMetadata, files: Array<{
19
+ path: string;
20
+ content: string;
21
+ }>, options?: AnalyzeOptions): RiskReport;
22
+ /**
23
+ * Produce an `unknown` report when metadata fetch or extraction fails. The CLI
24
+ * uses this so `--json` always emits a valid object and a non-zero exit code,
25
+ * rather than crashing or printing a stack trace.
26
+ */
27
+ export declare function unknownReport(packageSpec: string, error: unknown): RiskReport;
28
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,eAAe,EAAE,UAAU,EAAc,MAAM,aAAa,CAAC;AAK3E,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,YAAY,EACV,eAAe,EACf,cAAc,EACd,SAAS,EACT,UAAU,EACV,UAAU,EACV,SAAS,EACT,cAAc,GACf,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,SAAS,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AAChG,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,SAAS,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9F,OAAO,EACL,kBAAkB,EAClB,cAAc,EACd,yBAAyB,GAC1B,MAAM,UAAU,CAAC;AAClB,YAAY,EAAE,gBAAgB,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAE5E,MAAM,WAAW,cAAc;IAC7B,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,QAAQ,EAAE,eAAe,EACzB,KAAK,EAAE,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,EAC/C,OAAO,GAAE,cAAmB,GAC3B,UAAU,CAqBZ;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,WAAW,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,UAAU,CAyB7E"}
package/dist/index.js ADDED
@@ -0,0 +1,74 @@
1
+ // tarsen-core — static npm package analyzer.
2
+ //
3
+ // Tarsen never executes package code during analysis and never runs install
4
+ // scripts. This package only fetches metadata, scans extracted source files as
5
+ // strings, scores the results, and emits a stable JSON report. There is no
6
+ // cloud connection and no telemetry in this package.
7
+ import { metadataSignals } from "./metadata.js";
8
+ import { scanFiles } from "./scan.js";
9
+ import { capSignals, recommend, riskLevel, scoreSignals } from "./score.js";
10
+ export { SCHEMA_VERSION } from "./report.js";
11
+ export { parseMetadata, typosquatSignal, isVeryNew, COMMON_PACKAGE_NAMES } from "./metadata.js";
12
+ export { scanContent, scanFiles } from "./scan.js";
13
+ export { capSignals, scoreSignals, riskLevel, recommend, SEVERITY_WEIGHTS } from "./score.js";
14
+ export { isTraversalAttempt, makeSafeFilter, DEFAULT_EXTRACTION_LIMITS, } from "./tar.js";
15
+ /**
16
+ * Combine metadata + scanned-file signals into a finalized report.
17
+ *
18
+ * This is the single entry point the CLI uses after extracting a tarball.
19
+ * It is a pure function of its inputs and safe to call against untrusted data.
20
+ */
21
+ export function analyzePackage(metadata, files, options = {}) {
22
+ const raw = [...metadataSignals(metadata), ...scanFiles(files)];
23
+ const signals = capSignals(raw);
24
+ const score = scoreSignals(signals);
25
+ const risk = riskLevel(signals, score);
26
+ return {
27
+ schemaVersion: "1.0",
28
+ package: metadata.name,
29
+ version: metadata.version,
30
+ risk,
31
+ score,
32
+ recommendation: recommend(risk),
33
+ signals,
34
+ metadata,
35
+ analyzedAt: new Date().toISOString(),
36
+ stats: {
37
+ filesScanned: files.length,
38
+ bytesScanned: files.reduce((n, f) => n + Buffer.byteLength(f.content), 0),
39
+ truncated: options.truncated ?? false,
40
+ },
41
+ };
42
+ }
43
+ /**
44
+ * Produce an `unknown` report when metadata fetch or extraction fails. The CLI
45
+ * uses this so `--json` always emits a valid object and a non-zero exit code,
46
+ * rather than crashing or printing a stack trace.
47
+ */
48
+ export function unknownReport(packageSpec, error) {
49
+ return {
50
+ schemaVersion: "1.0",
51
+ package: packageSpec,
52
+ version: "unknown",
53
+ risk: "unknown",
54
+ score: 0,
55
+ recommendation: "unknown_ask_user",
56
+ signals: [
57
+ {
58
+ type: "analysis_error",
59
+ severity: "high",
60
+ message: error instanceof Error ? error.message : String(error),
61
+ },
62
+ ],
63
+ metadata: {
64
+ name: packageSpec,
65
+ version: "unknown",
66
+ maintainers: [],
67
+ dependencies: 0,
68
+ scripts: {},
69
+ },
70
+ analyzedAt: new Date().toISOString(),
71
+ stats: { filesScanned: 0, bytesScanned: 0, truncated: false },
72
+ };
73
+ }
74
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,6CAA6C;AAC7C,EAAE;AACF,4EAA4E;AAC5E,+EAA+E;AAC/E,2EAA2E;AAC3E,qDAAqD;AAGrD,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE5E,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAU7C,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,SAAS,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AAChG,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,SAAS,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9F,OAAO,EACL,kBAAkB,EAClB,cAAc,EACd,yBAAyB,GAC1B,MAAM,UAAU,CAAC;AAOlB;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAC5B,QAAyB,EACzB,KAA+C,EAC/C,UAA0B,EAAE;IAE5B,MAAM,GAAG,GAAiB,CAAC,GAAG,eAAe,CAAC,QAAQ,CAAC,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YACjB,OAAO,EAAE,SAAS;YAClB,WAAW,EAAE,EAAE;YACf,YAAY,EAAE,CAAC;YACf,OAAO,EAAE,EAAE;SACZ;QACD,UAAU,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;QACpC,KAAK,EAAE,EAAE,YAAY,EAAE,CAAC,EAAE,YAAY,EAAE,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE;KAC9D,CAAC;AACJ,CAAC"}
@@ -0,0 +1,16 @@
1
+ import type { PackageMetadata, RiskSignal } from "./report.js";
2
+ /** A reasonable allowlist of well-known package names for typosquat checks. */
3
+ export declare const COMMON_PACKAGE_NAMES: string[];
4
+ /** Build normalized metadata from a single version manifest + the packument. */
5
+ export declare function parseMetadata(manifest: Record<string, unknown>, packument?: Record<string, unknown>): PackageMetadata;
6
+ /** Return a typosquat signal if the scoped/unscoped name is one edit from a common package. */
7
+ export declare function typosquatSignal(name: string): RiskSignal | undefined;
8
+ /** True if the package was published within the freshness threshold (default 14 days). */
9
+ export declare function isVeryNew(publishedAt: string | undefined, days?: number): boolean;
10
+ /**
11
+ * Metadata + lifecycle signals. Pure function of the manifest; never touches files.
12
+ * These run even when no source can be extracted, so a publish-only package still
13
+ * gets a meaningful report.
14
+ */
15
+ export declare function metadataSignals(metadata: PackageMetadata): RiskSignal[];
16
+ //# sourceMappingURL=metadata.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metadata.d.ts","sourceRoot":"","sources":["../src/metadata.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAI/D,+EAA+E;AAC/E,eAAO,MAAM,oBAAoB,UAwBhC,CAAC;AAaF,gFAAgF;AAChF,wBAAgB,aAAa,CAC3B,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACjC,SAAS,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,GACtC,eAAe,CA0BjB;AAkBD,+FAA+F;AAC/F,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS,CAcpE;AAED,0FAA0F;AAC1F,wBAAgB,SAAS,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,SAAK,GAAG,OAAO,CAI7E;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,eAAe,GAAG,UAAU,EAAE,CAqCvE"}
@@ -0,0 +1,150 @@
1
+ // Normalize raw npm registry document into PackageMetadata and detect
2
+ // metadata-level risk signals (missing fields, very new package, typosquatting).
3
+ //
4
+ // This module deliberately touches only the registry JSON, never the tarball,
5
+ // so it is safe to run against untrusted manifests.
6
+ const LIFECYCLE_SCRIPTS = ["preinstall", "install", "postinstall", "prepare"];
7
+ /** A reasonable allowlist of well-known package names for typosquat checks. */
8
+ export const COMMON_PACKAGE_NAMES = [
9
+ "typescript",
10
+ "react",
11
+ "react-dom",
12
+ "next",
13
+ "vite",
14
+ "webpack",
15
+ "rollup",
16
+ "esbuild",
17
+ "eslint",
18
+ "prettier",
19
+ "jest",
20
+ "vitest",
21
+ "express",
22
+ "commander",
23
+ "lodash",
24
+ "axios",
25
+ "chalk",
26
+ "npm",
27
+ "pnpm",
28
+ "yarn",
29
+ "create-next-app",
30
+ "create-vite",
31
+ "create-react-app",
32
+ ];
33
+ /** Pull a `name` out of either `{name:"x"}` or `{name:"x",email:"y"}` maintainer shapes. */
34
+ function maintainerName(entry) {
35
+ if (typeof entry === "string")
36
+ return entry;
37
+ if (entry && typeof entry === "object") {
38
+ const { name, email } = entry;
39
+ if (typeof name === "string" && name)
40
+ return name;
41
+ if (typeof email === "string" && email)
42
+ return email;
43
+ }
44
+ return undefined;
45
+ }
46
+ /** Build normalized metadata from a single version manifest + the packument. */
47
+ export function parseMetadata(manifest, packument = {}) {
48
+ const version = String(manifest.version ?? "unknown");
49
+ const repositoryField = manifest.repository;
50
+ const repository = typeof repositoryField === "string"
51
+ ? repositoryField
52
+ : repositoryField && typeof repositoryField === "object"
53
+ ? String(repositoryField.url ?? "")
54
+ : null;
55
+ const maintainers = (manifest.maintainers ?? packument.maintainers ?? []);
56
+ const time = packument.time;
57
+ const dist = (manifest.dist ?? {});
58
+ return {
59
+ name: String(manifest.name ?? "unknown"),
60
+ version,
61
+ description: typeof manifest.description === "string" ? manifest.description : undefined,
62
+ repository: repository || null,
63
+ maintainers: maintainers.map(maintainerName).filter((m) => Boolean(m)),
64
+ publishedAt: time && time[version] ? String(time[version]) : undefined,
65
+ dependencies: Object.keys(manifest.dependencies ?? {}).length,
66
+ scripts: manifest.scripts ?? {},
67
+ tarball: typeof dist.tarball === "string" ? dist.tarball : undefined,
68
+ unpackedSize: typeof dist.unpackedSize === "number" ? dist.unpackedSize : undefined,
69
+ fileCount: typeof dist.fileCount === "number" ? dist.fileCount : undefined,
70
+ bin: manifest.bin,
71
+ };
72
+ }
73
+ /** Levenshtein edit distance, used for one-edit typosquat detection. */
74
+ function editDistance(a, b) {
75
+ const d = Array.from({ length: a.length + 1 }, (_, i) => [i]);
76
+ for (let j = 1; j <= b.length; j++)
77
+ d[0][j] = j;
78
+ for (let i = 1; i <= a.length; i++) {
79
+ for (let j = 1; j <= b.length; j++) {
80
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
81
+ }
82
+ }
83
+ return d[a.length][b.length];
84
+ }
85
+ /** Return a typosquat signal if the scoped/unscoped name is one edit from a common package. */
86
+ export function typosquatSignal(name) {
87
+ const plain = name.replace(/^@[^/]+\//, "");
88
+ if (plain.length < 4)
89
+ return undefined;
90
+ // A well-known package name is never itself a typosquat, even if it happens
91
+ // to be one edit from another common package (e.g. `pnpm` vs `npm`).
92
+ if (COMMON_PACKAGE_NAMES.includes(plain))
93
+ return undefined;
94
+ const target = COMMON_PACKAGE_NAMES.find((item) => editDistance(plain, item) === 1);
95
+ return target
96
+ ? {
97
+ type: "typosquatting",
98
+ severity: "high",
99
+ message: `package name is one edit away from "${target}"`,
100
+ }
101
+ : undefined;
102
+ }
103
+ /** True if the package was published within the freshness threshold (default 14 days). */
104
+ export function isVeryNew(publishedAt, days = 14) {
105
+ if (!publishedAt)
106
+ return false;
107
+ const then = Date.parse(publishedAt);
108
+ return Number.isFinite(then) && Date.now() - then <= days * 24 * 60 * 60 * 1000;
109
+ }
110
+ /**
111
+ * Metadata + lifecycle signals. Pure function of the manifest; never touches files.
112
+ * These run even when no source can be extracted, so a publish-only package still
113
+ * gets a meaningful report.
114
+ */
115
+ export function metadataSignals(metadata) {
116
+ const signals = [];
117
+ for (const script of LIFECYCLE_SCRIPTS) {
118
+ const value = metadata.scripts[script];
119
+ if (value) {
120
+ signals.push({
121
+ type: "lifecycle_script",
122
+ severity: "high",
123
+ message: `${script} script detected`,
124
+ file: "package.json",
125
+ evidence: value,
126
+ });
127
+ }
128
+ }
129
+ if (!metadata.repository) {
130
+ signals.push({ type: "metadata_risk", severity: "medium", message: "repository is missing" });
131
+ }
132
+ if (!metadata.maintainers.length) {
133
+ signals.push({ type: "metadata_risk", severity: "medium", message: "maintainers are missing" });
134
+ }
135
+ if (!metadata.description) {
136
+ signals.push({ type: "metadata_risk", severity: "low", message: "description is missing" });
137
+ }
138
+ if (isVeryNew(metadata.publishedAt)) {
139
+ signals.push({
140
+ type: "metadata_risk",
141
+ severity: "medium",
142
+ message: "package was published very recently",
143
+ });
144
+ }
145
+ const typo = typosquatSignal(metadata.name);
146
+ if (typo)
147
+ signals.push(typo);
148
+ return signals;
149
+ }
150
+ //# sourceMappingURL=metadata.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metadata.js","sourceRoot":"","sources":["../src/metadata.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,iFAAiF;AACjF,EAAE;AACF,8EAA8E;AAC9E,oDAAoD;AAIpD,MAAM,iBAAiB,GAAG,CAAC,YAAY,EAAE,SAAS,EAAE,aAAa,EAAE,SAAS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,EAAE,MAAM;gBAChB,OAAO,EAAE,GAAG,MAAM,kBAAkB;gBACpC,IAAI,EAAE,cAAc;gBACpB,QAAQ,EAAE,KAAK;aAChB,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,IAAI,CAAC,QAAQ,CAAC,UAAU,EAAE,CAAC;QACzB,OAAO,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,eAAe,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,uBAAuB,EAAE,CAAC,CAAC;IAChG,CAAC;IACD,IAAI,CAAC,QAAQ,CAAC,WAAW,CAAC,MAAM,EAAE,CAAC;QACjC,OAAO,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,eAAe,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,yBAAyB,EAAE,CAAC,CAAC;IAClG,CAAC;IACD,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC;QAC1B,OAAO,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,eAAe,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,wBAAwB,EAAE,CAAC,CAAC;IAC9F,CAAC;IACD,IAAI,SAAS,CAAC,QAAQ,CAAC,WAAW,CAAC,EAAE,CAAC;QACpC,OAAO,CAAC,IAAI,CAAC;YACX,IAAI,EAAE,eAAe;YACrB,QAAQ,EAAE,QAAQ;YAClB,OAAO,EAAE,qCAAqC;SAC/C,CAAC,CAAC;IACL,CAAC;IAED,MAAM,IAAI,GAAG,eAAe,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC5C,IAAI,IAAI;QAAE,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAE7B,OAAO,OAAO,CAAC;AACjB,CAAC"}
@@ -0,0 +1,52 @@
1
+ export declare const SCHEMA_VERSION: "1.0";
2
+ /** Overall risk band assigned to a package. */
3
+ export type RiskLevel = "low" | "medium" | "high" | "unknown";
4
+ /** What Tarsen advises the operator to do with the package. */
5
+ export type Recommendation = "safe_to_run" | "ask_user" | "do_not_run_without_user_confirmation" | "unknown_ask_user";
6
+ /** Per-signal severity. `unknown` reports (analysis errors) still use `high`. */
7
+ export type SignalSeverity = "low" | "medium" | "high";
8
+ /** A single risky static pattern detected in the package. */
9
+ export interface RiskSignal {
10
+ type: string;
11
+ severity: SignalSeverity;
12
+ message: string;
13
+ /** Relative path within the extracted tarball (e.g. `index.js`). */
14
+ file?: string;
15
+ /** Human-readable location evidence, e.g. `line 42`. */
16
+ evidence?: string;
17
+ }
18
+ /** Normalized registry metadata used both for scanning and reporting. */
19
+ export interface PackageMetadata {
20
+ name: string;
21
+ version: string;
22
+ description?: string;
23
+ repository?: string | null;
24
+ maintainers: string[];
25
+ publishedAt?: string;
26
+ dependencies: number;
27
+ scripts: Record<string, string>;
28
+ tarball?: string;
29
+ unpackedSize?: number;
30
+ fileCount?: number;
31
+ bin?: string | Record<string, string>;
32
+ }
33
+ /** Stats about the scan itself, useful for interpreting truncation. */
34
+ export interface ScanStats {
35
+ filesScanned: number;
36
+ bytesScanned: number;
37
+ truncated: boolean;
38
+ }
39
+ /** The full report emitted by Tarsen. Serialized verbatim in `--json` mode. */
40
+ export interface RiskReport {
41
+ schemaVersion: typeof SCHEMA_VERSION;
42
+ package: string;
43
+ version: string;
44
+ risk: RiskLevel;
45
+ score: number;
46
+ recommendation: Recommendation;
47
+ signals: RiskSignal[];
48
+ metadata: PackageMetadata;
49
+ analyzedAt: string;
50
+ stats: ScanStats;
51
+ }
52
+ //# sourceMappingURL=report.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"report.d.ts","sourceRoot":"","sources":["../src/report.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,cAAc,EAAG,KAAc,CAAC;AAE7C,+CAA+C;AAC/C,MAAM,MAAM,SAAS,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,SAAS,CAAC;AAE9D,+DAA+D;AAC/D,MAAM,MAAM,cAAc,GACtB,aAAa,G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ACd,cAAc,EAAE,cAAc,CAAC;IAC/B,OAAO,EAAE,UAAU,EAAE,CAAC;IACtB,QAAQ,EAAE,eAAe,CAAC;IAC1B,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,SAAS,CAAC;CAClB"}
package/dist/report.js ADDED
@@ -0,0 +1,7 @@
1
+ // Risk report types and JSON schema contract.
2
+ //
3
+ // These types are the machine-readable contract emitted by `tarsen check --json`
4
+ // and consumed by `tarsen run` and any downstream tooling. They are stable and
5
+ // versioned via `schemaVersion`. See docs/report.schema.json for the JSON Schema.
6
+ export const SCHEMA_VERSION = "1.0";
7
+ //# sourceMappingURL=report.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"report.js","sourceRoot":"","sources":["../src/report.ts"],"names":[],"mappings":"AAAA,8CAA8C;AAC9C,EAAE;AACF,iFAAiF;AACjF,+EAA+E;AAC/E,kFAAkF;AAElF,MAAM,CAAC,MAAM,cAAc,GAAG,KAAc,CAAC"}
package/dist/scan.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ import type { RiskSignal } from "./report.js";
2
+ /**
3
+ * Scan a single file's content. Pure & deterministic given the same input.
4
+ * Returns at most one signal per rule per file (deduplicated by type).
5
+ */
6
+ export declare function scanContent(content: string, file: string): RiskSignal[];
7
+ /** Scan every provided file (already read off disk) and flatten the signals. */
8
+ export declare function scanFiles(files: Array<{
9
+ path: string;
10
+ content: string;
11
+ }>): RiskSignal[];
12
+ //# sourceMappingURL=scan.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scan.d.ts","sourceRoot":"","sources":["../src/scan.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,UAAU,EAAkB,MAAM,aAAa,CAAC;AAgG9D;;;GAGG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,UAAU,EAAE,CA2BvE;AAED,gFAAgF;AAChF,wBAAgB,SAAS,CAAC,KAAK,EAAE,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,GAAG,UAAU,EAAE,CAIvF"}
package/dist/scan.js ADDED
@@ -0,0 +1,128 @@
1
+ // Static file scanning: pure functions that turn file contents into RiskSignals.
2
+ //
3
+ // Safety note: these functions only ever inspect strings. They never execute,
4
+ // import, or evaluate package code, so scanning untrusted tarballs is safe.
5
+ // Lifecycle + install-script hooks are handled in metadata.ts (from package.json).
6
+ // The rules here scan source files for the categories in the detection scope.
7
+ const SCAN_RULES = [
8
+ {
9
+ type: "dangerous_execution",
10
+ severity: "high",
11
+ message: "child process execution detected",
12
+ pattern: /(?:node:)?child_process|\b(?:execSync|spawnSync|execFileSync|execFile|fork)\s*\(|\b(?:exec|spawn)\s*\(/,
13
+ },
14
+ {
15
+ type: "dynamic_execution",
16
+ severity: "high",
17
+ message: "dynamic code execution detected",
18
+ pattern: /\beval\s*\(|new\s+Function\s*\(|\bFunction\s*\(/,
19
+ },
20
+ {
21
+ type: "filesystem_write",
22
+ severity: "medium",
23
+ message: "filesystem write or deletion detected",
24
+ pattern: /(?:\bfs\.|node:fs)[\s\S]{0,60}\b(?:writeFile|writeFileSync|appendFile|rm|rmSync|unlink|unlinkSync|rmdir|chmod|chown|rename|mkdir|copyFile)\b/,
25
+ },
26
+ {
27
+ type: "filesystem_read",
28
+ severity: "low",
29
+ message: "filesystem read or homedir access detected",
30
+ pattern: /(?:\bfs\.|node:fs)[\s\S]{0,60}\b(?:readFile|readFileSync|readdir|readdirSync|createReadStream|createWriteStream)\b|\bos\.homedir\s*\(/,
31
+ },
32
+ {
33
+ type: "network_access",
34
+ severity: "medium",
35
+ message: "network access detected",
36
+ pattern: /\bfetch\s*\(|\bhttps?\.(?:request|get)\s*\(|\baxios\b|XMLHttpRequest|new\s+WebSocket/,
37
+ },
38
+ {
39
+ type: "shell_command",
40
+ severity: "high",
41
+ message: "shell command construction detected",
42
+ pattern: /\bshell\s*:\s*true|\/bin\/(?:ba|z)?sh|cmd\.exe|powershell(?:\.exe)?/i,
43
+ },
44
+ ];
45
+ /** Return the 1-based line number of the first match for a global regex, else undefined. */
46
+ function lineOf(content, pattern) {
47
+ const match = content.match(pattern);
48
+ if (!match || match.index === undefined)
49
+ return undefined;
50
+ return `line ${content.slice(0, match.index).split("\n").length}`;
51
+ }
52
+ /** Sensitive env access: NODE_ENV/DEBUG/CI are common and low risk; anything else is high. */
53
+ function environmentSignals(content, file) {
54
+ const out = [];
55
+ if (/process\.env(?:\[[^\]]+\]|\.(?!NODE_ENV\b|DEBUG\b|CI\b)[A-Za-z_$][\w$]*)/.test(content)) {
56
+ out.push({
57
+ type: "environment_access",
58
+ severity: "high",
59
+ message: "potentially sensitive environment access detected",
60
+ file,
61
+ evidence: lineOf(content, /process\.env/),
62
+ });
63
+ }
64
+ else if (/process\.env\.(?:NODE_ENV|DEBUG|CI)\b/.test(content)) {
65
+ out.push({
66
+ type: "environment_access",
67
+ severity: "low",
68
+ message: "runtime environment mode access detected",
69
+ file,
70
+ evidence: lineOf(content, /process\.env/),
71
+ });
72
+ }
73
+ return out;
74
+ }
75
+ /** Obfuscation heuristics: very long lines and base64-like blobs. */
76
+ function obfuscationSignals(content, file) {
77
+ const lines = content.split("\n");
78
+ if (lines.some((line) => line.length > 2000) || /[A-Za-z0-9+/]{1000,}={0,2}/.test(content)) {
79
+ return [
80
+ {
81
+ type: "obfuscation",
82
+ severity: "medium",
83
+ message: "minified, very long, or encoded content detected",
84
+ file,
85
+ },
86
+ ];
87
+ }
88
+ return [];
89
+ }
90
+ /**
91
+ * Scan a single file's content. Pure & deterministic given the same input.
92
+ * Returns at most one signal per rule per file (deduplicated by type).
93
+ */
94
+ export function scanContent(content, file) {
95
+ const signals = [];
96
+ const seen = new Set();
97
+ const push = (signal) => {
98
+ const key = `${signal.type}:${signal.file ?? ""}`;
99
+ if (seen.has(key))
100
+ return;
101
+ seen.add(key);
102
+ signals.push(signal);
103
+ };
104
+ for (const rule of SCAN_RULES) {
105
+ if (rule.pattern.test(content)) {
106
+ push({
107
+ type: rule.type,
108
+ severity: rule.severity,
109
+ message: rule.message,
110
+ file,
111
+ evidence: lineOf(content, rule.pattern),
112
+ });
113
+ }
114
+ }
115
+ for (const signal of environmentSignals(content, file))
116
+ push(signal);
117
+ for (const signal of obfuscationSignals(content, file))
118
+ push(signal);
119
+ return signals;
120
+ }
121
+ /** Scan every provided file (already read off disk) and flatten the signals. */
122
+ export function scanFiles(files) {
123
+ const out = [];
124
+ for (const { path, content } of files)
125
+ out.push(...scanContent(content, path));
126
+ return out;
127
+ }
128
+ //# sourceMappingURL=scan.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scan.js","sourceRoot":"","sources":["../src/scan.ts"],"names":[],"mappings":"AAAA,iFAAiF;AACjF,EAAE;AACF,8EAA8E;AAC9E,4EAA4E;AAW5E,mFAAmF;AACnF,8EAA8E;AAC9E,MAAM,UAAU,GAAe;IAC7B;QACE,IAAI,EAAE,qBAAqB;QAC3B,QAAQ,EAAE,MAAM;QAChB,OAAO,EAAE,kCAAkC;QAC3C,OAAO,EAAE,wGAAwG;KAClH;IACD;QACE,IAAI,EAAE,mBAAmB;QACzB,QAAQ,EAAE,MAAM;QAChB,OAAO,EAAE,iCAAiC;QAC1C,OAAO,EAAE,iDAAiD;KAC3D;IACD;QACE,IAAI,EAAE,kBAAkB;QACxB,QAAQ,EAAE,QAAQ;QAClB,OAAO,EAAE,uCAAuC;QAChD,OAAO,EAAE,8IAA8I;KACxJ;IACD;QACE,IAAI,EAAE,iBAAiB;QACvB,QAAQ,EAAE,KAAK;QACf,OAAO,EAAE,4CAA4C;QACrD,OAAO,EAAE,uIAAuI;KACjJ;IACD;QACE,IAAI,EAAE,gBAAgB;QACtB,QAAQ,EAAE,QAAQ;QAClB,OAAO,EAAE,yBAAyB;QAClC,OAAO,EAAE,sFAAsF;KAChG;IACD;QACE,IAAI,EAAE,eAAe;QACrB,QAAQ,EAAE,MAAM;QAChB,O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I,CAAC,MAAM,CAAC,CAAC;IACrE,KAAK,MAAM,MAAM,IAAI,kBAAkB,CAAC,OAAO,EAAE,IAAI,CAAC;QAAE,IAAI,CAAC,MAAM,CAAC,CAAC;IAErE,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,gFAAgF;AAChF,MAAM,UAAU,SAAS,CAAC,KAA+C;IACvE,MAAM,GAAG,GAAiB,EAAE,CAAC;IAC7B,KAAK,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,KAAK;QAAE,GAAG,CAAC,IAAI,CAAC,GAAG,WAAW,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC;IAC/E,OAAO,GAAG,CAAC;AACb,CAAC"}
@@ -0,0 +1,12 @@
1
+ import type { Recommendation, RiskLevel, RiskSignal, SignalSeverity } from "./report.js";
2
+ /** Per-severity weight when summing the strongest signal of each type. */
3
+ export declare const SEVERITY_WEIGHTS: Record<SignalSeverity, number>;
4
+ /** Cap duplicate signal types so a chatty detector cannot dominate the report. */
5
+ export declare function capSignals(signals: RiskSignal[], limit?: number): RiskSignal[];
6
+ /** 0-100 score: sum the strongest severity per signal type, capped at 100. */
7
+ export declare function scoreSignals(signals: RiskSignal[]): number;
8
+ /** Map a score + signal distribution to a risk band. */
9
+ export declare function riskLevel(signals: RiskSignal[], score: number): RiskLevel;
10
+ /** Map a risk band to a recommendation. `unknown` is handled by the caller. */
11
+ export declare function recommend(risk: RiskLevel): Recommendation;
12
+ //# sourceMappingURL=score.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"score.d.ts","sourceRoot":"","sources":["../src/score.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAEzF,0EAA0E;AAC1E,eAAO,MAAM,gBAAgB,EAAE,MAAM,CAAC,cAAc,EAAE,MAAM,CAI3D,CAAC;AAIF,kFAAkF;AAClF,wBAAgB,UAAU,CAAC,OAAO,EAAE,UAAU,EAAE,EAAE,KAAK,SAAM,GAAG,UAAU,EAAE,CAa3E;AAED,8EAA8E;AAC9E,wBAAgB,YAAY,CAAC,OAAO,EAAE,UAAU,EAAE,GAAG,MAAM,CAY1D;AAED,wDAAwD;AACxD,wBAAgB,SAAS,CAAC,OAAO,EAAE,UAAU,EAAE,EAAE,KAAK,EAAE,MAAM,GAAG,SAAS,CAMzE;AAED,+EAA+E;AAC/E,wBAAgB,SAAS,CAAC,IAAI,EAAE,SAAS,GAAG,cAAc,CAWzD"}
package/dist/score.js ADDED
@@ -0,0 +1,63 @@
1
+ // Risk scoring and recommendation logic.
2
+ //
3
+ // Pure function of the signal list. Kept separate so it can be unit tested
4
+ // without touching the network or filesystem.
5
+ /** Per-severity weight when summing the strongest signal of each type. */
6
+ export const SEVERITY_WEIGHTS = {
7
+ high: 35,
8
+ medium: 12,
9
+ low: 2,
10
+ };
11
+ const SEVERITY_RANK = { low: 1, medium: 2, high: 3 };
12
+ /** Cap duplicate signal types so a chatty detector cannot dominate the report. */
13
+ export function capSignals(signals, limit = 100) {
14
+ const seen = new Set();
15
+ const counts = new Map();
16
+ const out = [];
17
+ for (const signal of signals) {
18
+ const key = `${signal.type}:${signal.file ?? ""}`;
19
+ if (seen.has(key) || (counts.get(signal.type) ?? 0) >= 5)
20
+ continue;
21
+ seen.add(key);
22
+ counts.set(signal.type, (counts.get(signal.type) ?? 0) + 1);
23
+ out.push(signal);
24
+ if (out.length >= limit)
25
+ break;
26
+ }
27
+ return out;
28
+ }
29
+ /** 0-100 score: sum the strongest severity per signal type, capped at 100. */
30
+ export function scoreSignals(signals) {
31
+ const strongestByType = new Map();
32
+ for (const signal of signals) {
33
+ const current = strongestByType.get(signal.type);
34
+ if (!current || SEVERITY_RANK[signal.severity] > SEVERITY_RANK[current]) {
35
+ strongestByType.set(signal.type, signal.severity);
36
+ }
37
+ }
38
+ return Math.min(100, [...strongestByType.values()].reduce((sum, severity) => sum + SEVERITY_WEIGHTS[severity], 0));
39
+ }
40
+ /** Map a score + signal distribution to a risk band. */
41
+ export function riskLevel(signals, score) {
42
+ const hasHigh = signals.some((signal) => signal.severity === "high");
43
+ const mediumCount = signals.filter((signal) => signal.severity === "medium").length;
44
+ if (hasHigh)
45
+ return "high";
46
+ if (mediumCount > 0 || score >= 10)
47
+ return "medium";
48
+ return "low";
49
+ }
50
+ /** Map a risk band to a recommendation. `unknown` is handled by the caller. */
51
+ export function recommend(risk) {
52
+ switch (risk) {
53
+ case "high":
54
+ return "do_not_run_without_user_confirmation";
55
+ case "medium":
56
+ return "ask_user";
57
+ case "low":
58
+ return "safe_to_run";
59
+ default:
60
+ return "unknown_ask_user";
61
+ }
62
+ }
63
+ //# sourceMappingURL=score.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"score.js","sourceRoot":"","sources":["../src/score.ts"],"names":[],"mappings":"AAAA,yCAAyC;AACzC,EAAE;AACF,2EAA2E;AAC3E,8CAA8C;AAI9C,0EAA0E;AAC1E,MAAM,CAAC,MAAM,gBAAgB,GAAmC;IAC9D,IAAI,EAAE,EAAE;IACR,MAAM,EAAE,EAAE;IACV,GAAG,EAAE,CAAC;CACP,CAAC;AAEF,MAAM,aAAa,GAAmC,EAAE,GAAG,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC;AAErF,kFAAkF;AAClF,MAAM,UAAU,UAAU,CAAC,OAAqB,EAAE,KAAK,GAAG,GAAG;IAC3D,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,MAAM,MAAM,GAAG,IAAI,GAAG,EAAkB,CAAC;IACzC,MAAM,GAAG,GAAiB,EAAE,CAAC;IAC7B,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,MAAM,GAAG,GAAG,GAAG,MAAM,CAAC,IAAI,IAAI,MAAM,CAAC,IAAI,IAAI,EAAE,EAAE,CAAC;QAClD,IAAI,IAAI,CAAC,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,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,KAAK,MAAM,CAAC,CAAC;IACrE,MAAM,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC,MAAM,CAAC;IACpF,IAAI,OAAO;QAAE,OAAO,MAAM,CAAC;IAC3B,IAAI,WAAW,GAAG,CAAC,IAAI,KAAK,IAAI,EAAE;QAAE,OAAO,QAAQ,CAAC;IACpD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,+EAA+E;AAC/E,MAAM,UAAU,SAAS,CAAC,IAAe;IACvC,QAAQ,IAAI,EAAE,CAAC;QACb,KAAK,MAAM;YACT,OAAO,sCAAsC,CAAC;QAChD,KAAK,QAAQ;YACX,OAAO,UAAU,CAAC;QACpB,KAAK,KAAK;YACR,OAAO,aAAa,CAAC;QACvB;YACE,OAAO,kBAAkB,CAAC;IAC9B,CAAC;AACH,CAAC"}
package/dist/tar.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ /** Reject a tarball entry whose resolved path would escape the destination. */
2
+ export declare function isTraversalAttempt(entryPath: string, dest: string): boolean;
3
+ /** Entry filter shared with `tar.x`. Returns `true` to KEEP an entry. */
4
+ export interface ExtractionLimits {
5
+ maxEntries: number;
6
+ }
7
+ /**
8
+ * Build a `tar.x` filter. Counts entries and drops anything that is a link,
9
+ * escapes the destination, or would exceed the entry budget.
10
+ *
11
+ * `tar` passes each entry header as `header` with a `type` flag:
12
+ * 0/"" file, 5 directory, 2 symlink, 1 hardlink, etc.
13
+ */
14
+ export declare function makeSafeFilter(dest: string, limits: ExtractionLimits): (_path: string, entry: {
15
+ type?: string;
16
+ }) => boolean;
17
+ /** Walked file shape used by the analyzer. */
18
+ export interface ExtractedFile {
19
+ path: string;
20
+ content: string;
21
+ }
22
+ export interface WalkResult {
23
+ files: ExtractedFile[];
24
+ truncated: boolean;
25
+ }
26
+ /** Conservative defaults mirroring the CLI's own pipeline. */
27
+ export declare const DEFAULT_EXTRACTION_LIMITS: ExtractionLimits;
28
+ //# sourceMappingURL=tar.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tar.d.ts","sourceRoot":"","sources":["../src/tar.ts"],"names":[],"mappings":"AAYA,+EAA+E;AAC/E,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAQ3E;AAED,yEAAyE;AACzE,MAAM,WAAW,gBAAgB;IAC/B,UAAU,EAAE,MAAM,CAAC;CACpB;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,gBAAgB,IAE3D,OAAO,MAAM,EAAE,OAAO;IAAE,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,aAQhD;AAED,8CAA8C;AAC9C,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,aAAa,EAAE,CAAC;IACvB,SAAS,EAAE,OAAO,CAAC;CACpB;AAED,8DAA8D;AAC9D,eAAO,MAAM,yBAAyB,EAAE,gBAAyC,CAAC"}
package/dist/tar.js ADDED
@@ -0,0 +1,45 @@
1
+ // Safe tarball extraction helpers.
2
+ //
3
+ // These are the hard safety guarantees Tarsen makes during analysis:
4
+ // - tarballs are extracted ONLY into a caller-provided temporary directory
5
+ // - path traversal (entries escaping via `../` or absolute paths) is rejected
6
+ // - symlinks and hardlinks are dropped
7
+ // - entry count and per-archive byte budgets are enforced
8
+ //
9
+ // This module never executes package code and never runs install scripts.
10
+ import { isAbsolute, normalize, relative, sep } from "node:path";
11
+ /** Reject a tarball entry whose resolved path would escape the destination. */
12
+ export function isTraversalAttempt(entryPath, dest) {
13
+ const cleaned = normalize(entryPath);
14
+ if (isAbsolute(cleaned))
15
+ return true;
16
+ if (cleaned.startsWith("..") || cleaned.startsWith(`..${sep}`))
17
+ return true;
18
+ // Belt-and-braces: resolve relative to dest and confirm it stays inside.
19
+ const resolved = normalize(`${dest}${sep}${cleaned}`);
20
+ const rel = relative(dest, resolved);
21
+ return rel.startsWith("..") || isAbsolute(rel);
22
+ }
23
+ /**
24
+ * Build a `tar.x` filter. Counts entries and drops anything that is a link,
25
+ * escapes the destination, or would exceed the entry budget.
26
+ *
27
+ * `tar` passes each entry header as `header` with a `type` flag:
28
+ * 0/"" file, 5 directory, 2 symlink, 1 hardlink, etc.
29
+ */
30
+ export function makeSafeFilter(dest, limits) {
31
+ let entries = 0;
32
+ return (_path, entry) => {
33
+ entries += 1;
34
+ if (entries > limits.maxEntries)
35
+ return false;
36
+ const type = entry.type ?? "";
37
+ // Drop all link types (symlink, hardlink, character/block device).
38
+ if (type === "SymbolicLink" || type === "Link" || type === "2" || type === "1")
39
+ return false;
40
+ return !isTraversalAttempt(_path, dest);
41
+ };
42
+ }
43
+ /** Conservative defaults mirroring the CLI's own pipeline. */
44
+ export const DEFAULT_EXTRACTION_LIMITS = { maxEntries: 10_000 };
45
+ //# sourceMappingURL=tar.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tar.js","sourceRoot":"","sources":["../src/tar.ts"],"names":[],"mappings":"AAAA,mCAAmC;AACnC,EAAE;AACF,qEAAqE;AACrE,6EAA6E;AAC7E,gFAAgF;AAChF,yCAAyC;AACzC,4DAA4D;AAC5D,EAAE;AACF,0EAA0E;AAE1E,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAEjE,+EAA+E;AAC/E,MAAM,UAAU,kBAAkB,CAAC,SAAiB,EAAE,IAAY;IAChE,MAAM,OAAO,GAAG,SAAS,CAAC,SAAS,CAAC,CAAC;IACrC,IAAI,UAAU,CAAC,OAAO,CAAC;QAAE,OAAO,IAAI,CAAC;IACrC,IAAI,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,OAAO,CAAC,UAAU,CAAC,KAAK,GAAG,EAAE,CAAC;QAAE,OAAO,IAAI,CAAC;IAC5E,yEAAyE;IACzE,MAAM,QAAQ,GAAG,SAAS,CAAC,GAAG,IAAI,GAAG,GAAG,GAAG,OAAO,EAAE,CAAC,CAAC;IACtD,MAAM,GAAG,GAAG,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IACrC,OAAO,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;AACjD,CAAC;AAOD;;;;;;GAMG;AACH,MAAM,UAAU,cAAc,CAAC,IAAY,EAAE,MAAwB;IACnE,IAAI,OAAO,GAAG,CAAC,CAAC;IAChB,OAAO,CAAC,KAAa,EAAE,KAAwB,EAAE,EAAE;QACjD,OAAO,IAAI,CAAC,CAAC;QACb,IAAI,OAAO,GAAG,MAAM,CAAC,UAAU;YAAE,OAAO,KAAK,CAAC;QAC9C,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,IAAI,EAAE,CAAC;QAC9B,mEAAmE;QACnE,IAAI,IAAI,KAAK,cAAc,IAAI,IAAI,KAAK,MAAM,IAAI,IAAI,KAAK,GAAG,IAAI,IAAI,KAAK,GAAG;YAAE,OAAO,KAAK,CAAC;QAC7F,OAAO,CAAC,kBAAkB,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IAC1C,CAAC,CAAC;AACJ,CAAC;AAaD,8DAA8D;AAC9D,MAAM,CAAC,MAAM,yBAAyB,GAAqB,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC"}
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "tarsen-core",
3
+ "version": "0.1.0",
4
+ "description": "Static npm package risk analysis for Tarsen.",
5
+ "homepage": "https://github.com/pandapor/tarsen#readme",
6
+ "repository": { "type": "git", "url": "git+https://github.com/pandapor/tarsen.git", "directory": "packages/core" },
7
+ "publishConfig": { "access": "public" },
8
+ "description": "Static npm package analysis, risk scoring, and safe tarball helpers for Tarsen. No cloud, no telemetry.",
9
+ "type": "module",
10
+ "main": "dist/index.js",
11
+ "types": "dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "default": "./dist/index.js"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "README.md",
21
+ "package.json",
22
+ "LICENSE"
23
+ ],
24
+ "engines": {
25
+ "node": ">=20"
26
+ },
27
+ "scripts": {
28
+ "build": "tsc -p tsconfig.json",
29
+ "test": "vitest run"
30
+ },
31
+ "license": "Apache-2.0",
32
+ "devDependencies": {
33
+ "@types/node": "^22.0.0",
34
+ "typescript": "^5.9.0",
35
+ "vitest": "^3.2.0"
36
+ }
37
+ }