asinstalled 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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,3 @@
1
+ asinstalled
2
+ Copyright 2026 Theebbanraj Asokan
3
+ https://github.com/Theebban/asinstalled
package/README.md ADDED
@@ -0,0 +1,165 @@
1
+ # asinstalled
2
+
3
+ **Test your npm package the way your users receive it: packed, installed into a clean project,
4
+ and run on every Node version your `engines` field promises.**
5
+
6
+ The package you test is not the package your users install. You run tests against your source
7
+ tree. Your users get a tarball, filtered by `files`, resolved through `exports` and `bin`,
8
+ running on whatever Node version `engines` admits, often the oldest. Every failure below passes
9
+ the maintainer's own test suite:
10
+
11
+ - an entry point or binary that `files` quietly leaves out of the tarball;
12
+ - a feature newer than the Node version `engines` claims to support;
13
+ - a binary without a `#!` line, so it cannot run as a command;
14
+ - a README that documents a script that no longer exists, or a `git clone <this repo>` placeholder; <!-- asinstalled-ignore -->
15
+ - a published version whose content is not what the tagged source builds.
16
+
17
+ `asinstalled` catches each of them, from the consumer's side.
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ npm install --save-dev asinstalled
23
+ ```
24
+
25
+ Requires Node 22 or newer to run; the package it checks can declare any floor. macOS and Linux.
26
+
27
+ ## Commands
28
+
29
+ ```bash
30
+ npx asinstalled check # pack, install, run on the engines floor and current Node
31
+ npx asinstalled check --run "mycli --help" # also run a binary, and require exit 0
32
+ npx asinstalled check --script smoke.mjs # also run your own smoke script inside the consumer
33
+ npx asinstalled docs # check the Markdown against package.json
34
+ npx asinstalled published # check the registry artifact against a fresh build
35
+ ```
36
+
37
+ Exit status: `0` when every check passed, `1` when any failed, `2` for a usage or setup error.
38
+ Every command takes `--dir <path>` and `--json`.
39
+
40
+ ### `check`
41
+
42
+ 1. Packs the package exactly as `npm publish` would, `prepack` included.
43
+ 2. Confirms every file named in `exports`, `main` and `bin` is actually inside the tarball.
44
+ 3. Installs the tarball into an empty project.
45
+ 4. On each Node version under test, imports every declared entry point (by `import` or `require`,
46
+ as the package declares) and runs the configured binaries and smoke script, all from the
47
+ installed copy and all with that exact Node binary, never the `node` on your `PATH`.
48
+
49
+ **The engines floor.** By default it tests the lowest version your `engines.node` range admits,
50
+ plus the Node you are running. The floor build is downloaded from nodejs.org, checked against
51
+ the SHA-256 in Node's published `SHASUMS256.txt`, and cached. A range whose floor it cannot
52
+ determine (`>20`, `<22`, `lts`) is refused with an error rather than guessed. Choose versions
53
+ explicitly with `--node 20.11.1,22.0.0,current`, or pass a path to a `node` binary.
54
+
55
+ Binaries are only executed when you say how (`--run`); an unknown CLI run with no arguments
56
+ might start a server. Without `--run` they are checked for presence and a `#!` line.
57
+
58
+ ### `docs`
59
+
60
+ Checks every Markdown file for references that no longer match `package.json`:
61
+ `npm run <script>` and `npm test` naming scripts that do not exist, `npx <package>` when that
62
+ binary is not declared, `git clone` with a placeholder instead of a URL, relative links to
63
+ missing files, and a public package whose docs never show how to install it.
64
+
65
+ Only text a reader is told to **run** is checked: fenced code blocks and inline code. A sentence
66
+ describing a removed script is history, not an instruction, and changelogs are checked for
67
+ broken links only.
68
+
69
+ A deliberate exception, such as documentation that quotes a bad command as an example, is
70
+ marked where a reader can see it: `<!-- asinstalled-ignore -->` on the line, or
71
+ `<!-- asinstalled-ignore-next-line -->` above it. Suppressed lines are counted and listed in
72
+ the report.
73
+
74
+ It always reports how many references it checked, so a run that matched nothing cannot pass
75
+ for a clean one.
76
+
77
+ ### `published`
78
+
79
+ For the version in `package.json`, after a release:
80
+
81
+ - **exists**: the exact version is live on the registry;
82
+ - **identical**: its content equals a fresh build of your checkout. The registry tarball is
83
+ first verified against the registry's own `integrity`, then both sides are decompressed and
84
+ compared. The gzip layer is deliberately ignored: the same tarball compresses to different
85
+ bytes under different zlib builds, which says nothing about what users install;
86
+ - **provenance**: a SLSA provenance attestation is attached, and which repository and workflow
87
+ it names;
88
+ - **tag**: the repository has a `v<version>` tag.
89
+
90
+ Provenance is reported as **attached, not cryptographically verified**. For signature
91
+ verification, run `npm audit signatures` in a project that installs the package.
92
+
93
+ ## Security: what running asinstalled executes
94
+
95
+ asinstalled checks a package by doing what a consumer does, so **it runs that package's code**.
96
+ Use it on packages you trust, which normally means your own.
97
+
98
+ - `check` runs `npm pack`, which runs the package's `prepack` and `prepare` scripts in your
99
+ project directory.
100
+ - It then runs `npm install` on the tarball in a temporary project. With npm's default
101
+ configuration that runs the package's `preinstall`, `install` and `postinstall` scripts, and
102
+ those of every dependency. (npm 11 warns about install scripts you have not approved, but runs
103
+ them unless `strict-allow-scripts` is set.) asinstalled uses your npm and your npm
104
+ configuration: if you enforce `ignore-scripts` or `strict-allow-scripts`, so does it, and it
105
+ then models consumers who do the same.
106
+ - It imports every entry point and runs the binaries and smoke script you configure. That is
107
+ code execution, by design.
108
+ - Every child process inherits your environment, including any tokens in it. **In CI, run
109
+ asinstalled in a job that holds no publishing credentials**: not in a job with an npm token,
110
+ and not in one granted `id-token: write`.
111
+ - `published` downloads the registry tarball, then hashes and decompresses it. It does not run it.
112
+ - Node builds are downloaded from nodejs.org and checked against Node's published SHA-256 list.
113
+ The list's GPG signature is not checked.
114
+
115
+ It is not a sandbox, and it does not safely inspect untrusted or malicious packages. For those,
116
+ use a disposable container or VM that holds no credentials, or a dedicated supply-chain scanner.
117
+
118
+ ## Use in CI
119
+
120
+ ```yaml
121
+ consumer-path:
122
+ runs-on: ubuntu-latest
123
+ permissions:
124
+ contents: read # no publishing credentials in this job
125
+ steps:
126
+ - uses: actions/checkout@v4
127
+ - uses: actions/setup-node@v4
128
+ with:
129
+ node-version: 24
130
+ - run: npm ci
131
+ - run: npx asinstalled check --run "mycli --help"
132
+ - run: npx asinstalled docs
133
+ ```
134
+
135
+ ## Where it sits
136
+
137
+ It complements, and does not replace:
138
+
139
+ - **[publint](https://github.com/publint/publint)** and
140
+ **[arethetypeswrong](https://github.com/arethetypeswrong/arethetypeswrong.github.io)**, which
141
+ check your `package.json` and type declarations statically. `asinstalled` executes the
142
+ installed package;
143
+ - **[np](https://github.com/sindresorhus/np)** and **[release-it](https://github.com/release-it/release-it)**,
144
+ which run your release. `asinstalled` checks what that release will deliver, and what it did;
145
+ - **a CI matrix over Node versions**, which usually runs your *source* on each version. That
146
+ can fail where the shipped package works (a source tree that needs a newer runtime flag) and
147
+ pass where it breaks (a file missing from `files`).
148
+
149
+ ## Limits, stated
150
+
151
+ npm only (no Yarn, pnpm or Bun installs yet). macOS and Linux Node builds. The checksum list
152
+ is fetched over HTTPS but its GPG signature is not verified. Native dependencies are installed
153
+ with the current Node and may not match the floor. Executing arbitrary README code blocks is
154
+ out of scope ([doc-detective](https://github.com/doc-detective/doc-detective) does that).
155
+
156
+ ## Development
157
+
158
+ ```bash
159
+ npm install
160
+ npm run check # typecheck, lint and tests
161
+ npm run self-check # asinstalled checks itself as installed, on its own engines floor
162
+ ```
163
+
164
+ Development runs TypeScript directly through Node's type stripping, so it needs Node 22.6 or
165
+ newer; the published package runs on Node 22.0 and newer.
package/dist/check.js ADDED
@@ -0,0 +1,132 @@
1
+ // `asinstalled check`: THE PACKAGE AS A CONSUMER RECEIVES IT.
2
+ //
3
+ // 1. Pack it the way `npm publish` would, `prepack` included.
4
+ // 2. Statically confirm every declared entry point and binary is actually inside the tarball.
5
+ // 3. Install the tarball into a fresh, empty project.
6
+ // 4. On EACH Node version under test, import every declared entry point from that installed
7
+ // copy, run every binary the maintainer told us how to run, and run an optional smoke
8
+ // script, all with that exact Node binary rather than whatever `node` is on PATH.
9
+ //
10
+ // Nothing here reads the source tree after packing. That is the point.
11
+ import { execFileSync, spawnSync } from 'node:child_process';
12
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
13
+ import { tmpdir } from 'node:os';
14
+ import { basename, join } from 'node:path';
15
+ import { readManifest } from "./manifest.js";
16
+ export function packProject(projectDir, destination) {
17
+ const out = execFileSync('npm', ['pack', '--json', '--pack-destination', destination], {
18
+ cwd: projectDir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'],
19
+ });
20
+ // npm prints lifecycle output (prepack) before the JSON array; take the array.
21
+ const json = out.slice(out.indexOf('['));
22
+ const entry = JSON.parse(json)[0];
23
+ if (entry === undefined)
24
+ throw new Error('npm pack produced no tarball');
25
+ return entry;
26
+ }
27
+ /**
28
+ * The part of a failed run's output a reader needs: the error MESSAGE, which Node prints
29
+ * before the stack, rather than the last stack frames, which say where and not what.
30
+ */
31
+ function tail(s) {
32
+ const lines = (s ?? '').trim().split('\n').map((l) => l.trim()).filter((l) => l.length > 0);
33
+ const message = lines.find((l) => /^(\w*Error|Error)\b|: .*Error:|^Error \[/.test(l) || /^\w+Error: /.test(l));
34
+ return (message ?? lines.slice(-2).join(' | ')).slice(0, 400);
35
+ }
36
+ function run(binary, args, cwd) {
37
+ const r = spawnSync(binary, args, { cwd, encoding: 'utf8', timeout: 120_000 });
38
+ if (r.error)
39
+ return { ok: false, detail: r.error.message };
40
+ if (r.status === 0)
41
+ return { ok: true, detail: 'exit 0' };
42
+ return { ok: false, detail: `exit ${r.status ?? r.signal}: ${tail(r.stderr) || tail(r.stdout)}` };
43
+ }
44
+ /** Files an export target or bin path points at, normalised to tarball paths. */
45
+ function declaredFiles(projectDir, m) {
46
+ const pkg = JSON.parse(readFileSync(join(projectDir, 'package.json'), 'utf8'));
47
+ const out = new Set();
48
+ const walk = (v) => {
49
+ if (typeof v === 'string') {
50
+ if (v.startsWith('./') && !v.includes('*'))
51
+ out.add(v.slice(2));
52
+ return;
53
+ }
54
+ if (v !== null && typeof v === 'object')
55
+ for (const x of Object.values(v))
56
+ walk(x);
57
+ };
58
+ if (pkg['exports'] !== undefined)
59
+ walk(pkg['exports']);
60
+ else if (typeof pkg['main'] === 'string')
61
+ out.add(String(pkg['main']).replace(/^\.\//, ''));
62
+ for (const p of Object.values(m.bins))
63
+ out.add(p.replace(/^\.\//, ''));
64
+ out.delete('package.json');
65
+ return [...out];
66
+ }
67
+ export function runCheck(opts) {
68
+ const manifest = readManifest(opts.projectDir);
69
+ const work = mkdtempSync(join(tmpdir(), 'asinstalled-'));
70
+ const findings = [];
71
+ const all = 'all';
72
+ try {
73
+ const packed = packProject(opts.projectDir, work);
74
+ const inTarball = new Set(packed.files.map((f) => f.path));
75
+ for (const f of declaredFiles(opts.projectDir, manifest)) {
76
+ findings.push({
77
+ check: 'packed-contents', node: all, target: f, ok: inTarball.has(f),
78
+ detail: inTarball.has(f) ? 'in the tarball' : 'declared in package.json but NOT in the tarball (check "files" and the build)',
79
+ });
80
+ }
81
+ const consumer = join(work, 'consumer');
82
+ mkdirSync(consumer, { recursive: true });
83
+ writeFileSync(join(consumer, 'package.json'), JSON.stringify({ name: 'asinstalled-consumer', version: '0.0.0', private: true }));
84
+ const install = spawnSync('npm', ['install', join(work, packed.filename), '--no-audit', '--no-fund', '--no-package-lock'], {
85
+ cwd: consumer, encoding: 'utf8', timeout: 600_000,
86
+ });
87
+ const installed = install.status === 0;
88
+ findings.push({ check: 'install', node: all, target: packed.filename, ok: installed,
89
+ detail: installed ? 'installed into an empty project' : `npm install failed: ${tail(install.stderr)}` });
90
+ if (!installed)
91
+ return { manifest, tarball: { filename: packed.filename, integrity: packed.integrity, fileCount: packed.files.length }, findings, workdir: opts.keepWorkdir ? work : null };
92
+ let smoke = null;
93
+ if (opts.smokeScript !== undefined) {
94
+ smoke = join(consumer, basename(opts.smokeScript));
95
+ copyFileSync(opts.smokeScript, smoke);
96
+ }
97
+ for (const n of opts.nodes) {
98
+ for (const e of manifest.entryPoints) {
99
+ const code = e.loader === 'import' ? `await import(${JSON.stringify(e.specifier)})` : `require(${JSON.stringify(e.specifier)})`;
100
+ const args = e.loader === 'import' ? ['--input-type=module', '-e', code] : ['-e', code];
101
+ const r = run(n.binary, args, consumer);
102
+ findings.push({ check: e.loader, node: n.label, target: e.specifier, ...r });
103
+ }
104
+ for (const [bin, rel] of Object.entries(manifest.bins)) {
105
+ const path = join(consumer, 'node_modules', manifest.name, rel);
106
+ if (!existsSync(path)) {
107
+ findings.push({ check: 'bin', node: n.label, target: bin, ok: false, detail: `installed package has no ${rel}` });
108
+ continue;
109
+ }
110
+ const shebang = readFileSync(path, 'utf8').startsWith('#!');
111
+ const args = opts.runBins?.[bin];
112
+ if (args === undefined) {
113
+ findings.push({ check: 'bin', node: n.label, target: bin, ok: shebang,
114
+ detail: shebang ? 'present with a shebang; not executed (no arguments configured)' : `${rel} has no #! line, so it cannot run as a command` });
115
+ continue;
116
+ }
117
+ const r = run(n.binary, [path, ...args], consumer);
118
+ findings.push({ check: 'bin', node: n.label, target: `${bin} ${args.join(' ')}`.trim(), ...r });
119
+ }
120
+ if (smoke !== null) {
121
+ const isTs = smoke.endsWith('.ts');
122
+ const r = run(n.binary, isTs ? ['--experimental-strip-types', smoke] : [smoke], consumer);
123
+ findings.push({ check: 'script', node: n.label, target: basename(smoke), ...r });
124
+ }
125
+ }
126
+ return { manifest, tarball: { filename: packed.filename, integrity: packed.integrity, fileCount: packed.files.length }, findings, workdir: opts.keepWorkdir ? work : null };
127
+ }
128
+ finally {
129
+ if (!opts.keepWorkdir)
130
+ rmSync(work, { recursive: true, force: true });
131
+ }
132
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,170 @@
1
+ #!/usr/bin/env node
2
+ // asinstalled: check a package the way its users receive it.
3
+ //
4
+ // asinstalled check pack, install into a clean project, run on the engines floor and current Node
5
+ // asinstalled docs check the Markdown documentation against the package
6
+ // asinstalled published check the registry artifact against a fresh build, its provenance and its tag
7
+ //
8
+ // Exit status: 0 when every check passed, 1 when any check failed, 2 for a usage or setup error.
9
+ import { readFileSync } from 'node:fs';
10
+ import { resolve } from 'node:path';
11
+ import { readManifest } from "./manifest.js";
12
+ import { enginesFloor } from "./engines.js";
13
+ import { obtainNode } from "./nodeDist.js";
14
+ import { runCheck } from "./check.js";
15
+ import { runDocs } from "./docs.js";
16
+ import { runPublished } from "./published.js";
17
+ const USAGE = `usage:
18
+ asinstalled check [--dir <path>] [--node floor,current,<version>,<path>] [--run "<bin> <args...>"]... [--script <file>] [--keep] [--json]
19
+ asinstalled docs [--dir <path>] [--json]
20
+ asinstalled published [--dir <path>] [--registry <url>] [--no-compare] [--json]`;
21
+ class UsageError extends Error {
22
+ }
23
+ function parse(argv) {
24
+ const a = { command: argv[0] ?? '', dir: '.', nodes: [], runs: [], keep: false, json: false, compare: true };
25
+ for (let i = 1; i < argv.length; i++) {
26
+ const flag = argv[i];
27
+ const value = () => {
28
+ const v = argv[++i];
29
+ if (v === undefined)
30
+ throw new UsageError(`${flag} needs a value`);
31
+ return v;
32
+ };
33
+ switch (flag) {
34
+ case '--dir':
35
+ a.dir = value();
36
+ break;
37
+ case '--node':
38
+ a.nodes.push(...value().split(',').map((s) => s.trim()).filter(Boolean));
39
+ break;
40
+ case '--run':
41
+ a.runs.push(value());
42
+ break;
43
+ case '--script':
44
+ a.script = value();
45
+ break;
46
+ case '--registry':
47
+ a.registry = value();
48
+ break;
49
+ case '--keep':
50
+ a.keep = true;
51
+ break;
52
+ case '--json':
53
+ a.json = true;
54
+ break;
55
+ case '--no-compare':
56
+ a.compare = false;
57
+ break;
58
+ default: throw new UsageError(`unknown argument "${flag}"`);
59
+ }
60
+ }
61
+ return a;
62
+ }
63
+ async function resolveNodes(specs, enginesRange) {
64
+ const wanted = specs.length > 0 ? specs : ['floor', 'current'];
65
+ const out = [];
66
+ const seen = new Set();
67
+ const add = (label, binary, version) => {
68
+ if (seen.has(version))
69
+ return;
70
+ seen.add(version);
71
+ out.push({ label, binary });
72
+ };
73
+ for (const s of wanted) {
74
+ if (s === 'current')
75
+ add(`${process.version.slice(1)} (current)`, process.execPath, process.version.slice(1));
76
+ else if (s === 'floor') {
77
+ const f = enginesFloor(enginesRange);
78
+ if (!f.ok)
79
+ throw new UsageError(`${f.reason}. Pass --node <version> to choose one explicitly.`);
80
+ add(`${f.version} (engines floor)`, await obtainNode(f.version, { log: (l) => console.error(` ${l}`) }), f.version);
81
+ }
82
+ else if (/^v?\d+\.\d+\.\d+$/.test(s)) {
83
+ const v = s.replace(/^v/, '');
84
+ add(v, await obtainNode(v, { log: (l) => console.error(` ${l}`) }), v);
85
+ }
86
+ else {
87
+ add(s, resolve(s), s);
88
+ }
89
+ }
90
+ return out;
91
+ }
92
+ function print(rows, json, asJson) {
93
+ const failed = rows.filter((r) => !r.ok).length;
94
+ if (asJson)
95
+ console.log(JSON.stringify(json, null, 2));
96
+ else {
97
+ for (const r of rows)
98
+ console.log(`${r.ok ? 'PASS' : 'FAIL'} ${r.cols.join(' ')}`);
99
+ console.log(`\n${rows.length - failed} of ${rows.length} checks passed${failed > 0 ? `, ${failed} FAILED` : ''}.`);
100
+ }
101
+ return failed > 0 ? 1 : 0;
102
+ }
103
+ async function main(argv) {
104
+ if (argv[0] === '--help' || argv[0] === '-h' || argv[0] === 'help') {
105
+ console.log(USAGE);
106
+ return 0;
107
+ }
108
+ if (argv[0] === '--version' || argv[0] === '-v') {
109
+ const self = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
110
+ console.log(self.version);
111
+ return 0;
112
+ }
113
+ const args = parse(argv);
114
+ const dir = resolve(args.dir);
115
+ const manifest = readManifest(dir);
116
+ if (args.command === 'check') {
117
+ const runBins = {};
118
+ for (const r of args.runs) {
119
+ const [bin, ...rest] = r.split(/\s+/).filter(Boolean);
120
+ if (bin === undefined)
121
+ throw new UsageError('--run needs "<bin> <args...>"');
122
+ runBins[bin] = rest;
123
+ }
124
+ const nodes = await resolveNodes(args.nodes, manifest.enginesNode);
125
+ if (!args.json)
126
+ console.log(`${manifest.name}@${manifest.version} as installed, on: ${nodes.map((n) => n.label).join(', ')}\n`);
127
+ const r = runCheck({ projectDir: dir, nodes, runBins, keepWorkdir: args.keep, ...(args.script !== undefined ? { smokeScript: resolve(args.script) } : {}) });
128
+ if (!args.json)
129
+ console.log(`tarball ${r.tarball.filename}: ${r.tarball.fileCount} files${r.workdir ? `, kept at ${r.workdir}` : ''}\n`);
130
+ return print(r.findings.map((f) => ({ ok: f.ok, cols: [f.check.padEnd(15), f.node.padEnd(22), f.target, `(${f.detail})`] })), r, args.json);
131
+ }
132
+ if (args.command === 'docs') {
133
+ const r = runDocs(dir, manifest);
134
+ if (!args.json) {
135
+ const c = r.checked;
136
+ console.log(`${r.files.length} Markdown file(s); references checked: ${c.script} script, ${c.bin} binary, ${c.clone} clone, ${c.link} link, ${c.install} install`);
137
+ console.log(r.suppressed.length > 0 ? `${r.suppressed.length} line(s) suppressed by an ignore comment: ${r.suppressed.join(', ')}\n` : '');
138
+ if (r.files.length === 0)
139
+ console.log('no Markdown files found: nothing was checked, which is not the same as clean');
140
+ }
141
+ const total = Object.values(r.checked).reduce((s, n) => s + n, 0);
142
+ const rows = r.findings.map((f) => ({ ok: false, cols: [f.rule.padEnd(8), `${f.file}:${f.line}`, f.detail] }));
143
+ if (args.json)
144
+ console.log(JSON.stringify(r, null, 2));
145
+ else {
146
+ for (const row of rows)
147
+ console.log(`FAIL ${row.cols.join(' ')}`);
148
+ console.log(`\n${total - rows.length} of ${total} references consistent${rows.length > 0 ? `, ${rows.length} FAILED` : ''}.`);
149
+ }
150
+ return rows.length > 0 || r.files.length === 0 ? 1 : 0;
151
+ }
152
+ if (args.command === 'published') {
153
+ const f = await runPublished({ projectDir: dir, manifest, compareLocal: args.compare, ...(args.registry !== undefined ? { registry: args.registry } : {}) });
154
+ if (!args.json)
155
+ console.log(`${manifest.name}@${manifest.version} as published\n`);
156
+ const code = print(f.map((x) => ({ ok: x.ok, cols: [x.check.padEnd(11), x.detail] })), f, args.json);
157
+ if (!args.json)
158
+ console.log('provenance is reported as attached, not cryptographically verified; run `npm audit signatures` in a consumer project for that.');
159
+ return code;
160
+ }
161
+ throw new UsageError(args.command === '' ? 'no command given' : `unknown command "${args.command}"`);
162
+ }
163
+ main(process.argv.slice(2)).then((code) => process.exit(code), (err) => {
164
+ if (err instanceof UsageError) {
165
+ console.error(`asinstalled: ${err.message}\n\n${USAGE}`);
166
+ process.exit(2);
167
+ }
168
+ console.error(`asinstalled: ${err.message}`);
169
+ process.exit(2);
170
+ });
package/dist/docs.js ADDED
@@ -0,0 +1,135 @@
1
+ // `asinstalled docs`: DOES THE DOCUMENTATION DESCRIBE THIS PACKAGE, OR AN EARLIER ONE?
2
+ //
3
+ // Documentation is part of what a consumer receives, and it drifts silently: nothing fails
4
+ // when a README names a script that was deleted. Each rule below exists because it happened:
5
+ //
6
+ // script `npm run <x>` / `npm test` / `npm start` names a script package.json no longer has
7
+ // bin `npx <this package>` when the package does not declare that binary
8
+ // clone a `git clone` whose argument is a placeholder rather than a URL or path
9
+ // link a relative Markdown link to a file that does not exist
10
+ // install a public package whose README never shows the command to install it
11
+ //
12
+ // Command rules apply only where a reader is told to RUN something: fenced code blocks and
13
+ // inline code. A sentence describing a removed script or a past bug is history, not an
14
+ // instruction, and flagging it would punish exactly the honesty a changelog is for. For the
15
+ // same reason, changelogs are checked for broken links only.
16
+ //
17
+ // A deliberate exception is written where a reader can see it: an HTML comment
18
+ // `<!-- asinstalled-ignore -->` on the line, or `<!-- asinstalled-ignore-next-line -->` on the
19
+ // line before. Suppressions are COUNTED and reported, so they can be audited rather than
20
+ // becoming a quiet hole.
21
+ //
22
+ // Subdirectories that contain their own package.json are different packages and are skipped:
23
+ // their scripts are not this package's scripts.
24
+ //
25
+ // Every report states how many references were CHECKED, so a run that matched nothing can
26
+ // never read as a clean result.
27
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
28
+ import { dirname, join, relative } from 'node:path';
29
+ function markdownFiles(projectDir) {
30
+ const out = [];
31
+ const skip = new Set(['node_modules', '.git', 'dist', 'coverage']);
32
+ const walk = (dir) => {
33
+ for (const name of readdirSync(dir)) {
34
+ if (skip.has(name) || name.startsWith('.'))
35
+ continue;
36
+ const p = join(dir, name);
37
+ if (statSync(p).isDirectory()) {
38
+ if (existsSync(join(p, 'package.json')))
39
+ continue; // a nested package is not this package
40
+ walk(p);
41
+ }
42
+ else if (name.toLowerCase().endsWith('.md'))
43
+ out.push(p);
44
+ }
45
+ };
46
+ walk(projectDir);
47
+ return out.sort();
48
+ }
49
+ const NPM_RUN = /\bnpm\s+(?:run|run-script)\s+([A-Za-z0-9:_.-]+)/g;
50
+ const NPM_LIFECYCLE = /\bnpm\s+(test|start|stop|restart)\b(?!\s*[=:])/g;
51
+ const NPX = /\bnpx\s+(?:(?:--no-install|--yes|-y|--package=\S+|-p\s+\S+)\s+)*([@A-Za-z0-9/._-]+)/g;
52
+ const CLONE = /\bgit\s+clone\s+(\S+)/g;
53
+ const LINK = /!?\[[^\]]*\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g;
54
+ const INSTALL = /\b(?:npm\s+(?:install|i|add)|pnpm\s+add|yarn\s+add|bun\s+add)\s+(?:-{1,2}\S+\s+)*([@A-Za-z0-9/._-]+)/g;
55
+ export function runDocs(projectDir, manifest, files = markdownFiles(projectDir)) {
56
+ const findings = [];
57
+ const suppressed = [];
58
+ const checked = { script: 0, bin: 0, clone: 0, link: 0, install: 0 };
59
+ let installsThisPackage = 0;
60
+ for (const file of files) {
61
+ const rel = relative(projectDir, file);
62
+ const lines = readFileSync(file, 'utf8').split('\n');
63
+ const isHistory = /^(changelog|history|changes|releases?)([._-].*)?\.md$/i.test(file.split('/').pop() ?? '');
64
+ let inFence = false;
65
+ lines.forEach((raw, i) => {
66
+ const line = i + 1;
67
+ if (/^\s*(```|~~~)/.test(raw)) {
68
+ inFence = !inFence;
69
+ return;
70
+ }
71
+ // A marker counts only as a real comment, not as text quoting one inside inline code.
72
+ const bare = (t) => t.replace(/`[^`]*`/g, '');
73
+ if (/<!--\s*asinstalled-ignore\s*-->/.test(bare(raw)) || /<!--\s*asinstalled-ignore-next-line\s*-->/.test(bare(lines[i - 1] ?? ''))) {
74
+ suppressed.push(`${rel}:${line}`);
75
+ return;
76
+ }
77
+ // The runnable part of this line: all of it inside a fence, only its inline code outside.
78
+ const text = isHistory ? '' : inFence ? raw : [...raw.matchAll(/`([^`]+)`/g)].map((m) => m[1]).join('\n');
79
+ for (const m of text.matchAll(NPM_RUN)) {
80
+ const name = m[1] ?? '';
81
+ checked.script++;
82
+ if (!(name in manifest.scripts))
83
+ findings.push({ file: rel, line, rule: 'script', detail: `\`npm run ${name}\`: package.json has no "${name}" script` });
84
+ }
85
+ for (const m of text.matchAll(NPM_LIFECYCLE)) {
86
+ const name = m[1] ?? '';
87
+ checked.script++;
88
+ if (!(name in manifest.scripts))
89
+ findings.push({ file: rel, line, rule: 'script', detail: `\`npm ${name}\`: package.json has no "${name}" script` });
90
+ }
91
+ for (const m of text.matchAll(NPX)) {
92
+ const name = m[1] ?? '';
93
+ if (name !== manifest.name)
94
+ continue; // npx of other packages is not ours to judge
95
+ checked.bin++;
96
+ const bare = name.replace(/^@[^/]+\//, '');
97
+ if (!(bare in manifest.bins))
98
+ findings.push({ file: rel, line, rule: 'bin', detail: `\`npx ${name}\`: the package declares no "${bare}" binary` });
99
+ }
100
+ for (const m of text.matchAll(CLONE)) {
101
+ const arg = m[1] ?? '';
102
+ checked.clone++;
103
+ const looksReal = /^(https?:\/\/|git@|ssh:\/\/|file:\/\/|\.{0,2}\/)/.test(arg);
104
+ if (!looksReal)
105
+ findings.push({ file: rel, line, rule: 'clone', detail: `\`git clone ${arg}\` is a placeholder, not something a reader can run` });
106
+ }
107
+ for (const m of inFence ? [] : raw.matchAll(LINK)) {
108
+ const target = m[1] ?? '';
109
+ if (/^[a-z][a-z0-9+.-]*:/i.test(target) || target.startsWith('#'))
110
+ continue;
111
+ const path = decodeURIComponent(target.split('#')[0].split('?')[0]);
112
+ if (path.length === 0)
113
+ continue;
114
+ checked.link++;
115
+ if (!existsSync(join(dirname(file), path)))
116
+ findings.push({ file: rel, line, rule: 'link', detail: `link to "${target}", which does not exist` });
117
+ }
118
+ for (const m of text.matchAll(INSTALL)) {
119
+ const raw = m[1] ?? '';
120
+ // Drop a version or tag suffix: `pkg@1.2.0` -> `pkg`, `@scope/pkg@next` -> `@scope/pkg`.
121
+ const spec = raw.startsWith('@') ? raw.replace(/^(@[^/]+\/[^@]+)@.*$/, '$1') : raw.replace(/@.*$/, '');
122
+ if (spec === manifest.name)
123
+ installsThisPackage++;
124
+ }
125
+ });
126
+ }
127
+ if (!manifest.isPrivate) {
128
+ checked.install++;
129
+ if (installsThisPackage === 0 && files.length > 0) {
130
+ findings.push({ file: relative(projectDir, files[0]), line: 0, rule: 'install',
131
+ detail: `no documentation shows how to install "${manifest.name}" (for example \`npm install ${manifest.name}\`)` });
132
+ }
133
+ }
134
+ return { files: files.map((f) => relative(projectDir, f)), checked, findings, suppressed };
135
+ }
@@ -0,0 +1,58 @@
1
+ // THE ENGINES FLOOR: the lowest Node version a package's `engines.node` field admits.
2
+ //
3
+ // This is the version a package most often breaks on without anyone noticing, because
4
+ // maintainers develop on something newer. A floor that cannot be determined is REFUSED, not
5
+ // guessed: a guessed floor would turn "we tested the version you promised" into "we tested a
6
+ // version we picked", which is the failure this tool exists to catch.
7
+ //
8
+ // Supported forms: `>=X[.Y[.Z]]`, `^X.Y.Z`, `~X.Y.Z`, `X.Y.Z`, `X`, `X.x`, `X.Y.x`, and
9
+ // alternatives joined by `||` (the floor is the lowest alternative). A range with an upper
10
+ // bound only, a `<` or `>` without `=`, or anything else is refused with the reason.
11
+ function parseLoose(v) {
12
+ const m = /^v?(\d+)(?:\.(\d+|x|\*))?(?:\.(\d+|x|\*))?$/.exec(v.trim());
13
+ if (m === null)
14
+ return null;
15
+ const n = (s) => (s === undefined || s === 'x' || s === '*' ? 0 : Number(s));
16
+ return [n(m[1]), n(m[2]), n(m[3])];
17
+ }
18
+ function compare(a, b) {
19
+ return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
20
+ }
21
+ function floorOfComparatorSet(set) {
22
+ // Semver allows a space between an operator and its version: `>= 20.11` means `>=20.11`.
23
+ const parts = set.trim().replace(/(>=|<=|>|<|=|\^|~)\s+/g, '$1').split(/\s+/).filter((p) => p.length > 0);
24
+ if (parts.length === 0)
25
+ return 'empty range';
26
+ let floor = null;
27
+ for (const part of parts) {
28
+ const m = /^(?:>=|\^|~|=)?(.+)$/.exec(part);
29
+ if (m === null)
30
+ return `unsupported comparator "${part}"`;
31
+ if (part.startsWith('<'))
32
+ continue; // an upper bound does not move the floor
33
+ if (part.startsWith('>') && !part.startsWith('>='))
34
+ return `"${part}" has an exclusive lower bound; pass --node explicitly`;
35
+ const t = parseLoose(m[1] ?? '');
36
+ if (t === null)
37
+ return `unsupported version "${part}"`;
38
+ if (floor === null || compare(t, floor) > 0)
39
+ floor = t;
40
+ }
41
+ return floor ?? 'the range has no lower bound';
42
+ }
43
+ export function enginesFloor(range) {
44
+ if (range === null || range.trim() === '' || range.trim() === '*') {
45
+ return { ok: false, reason: 'package.json declares no engines.node, so there is no promised floor to test' };
46
+ }
47
+ let lowest = null;
48
+ for (const alt of range.split('||')) {
49
+ const f = floorOfComparatorSet(alt);
50
+ if (typeof f === 'string')
51
+ return { ok: false, reason: `cannot determine the floor of "${range}": ${f}` };
52
+ if (lowest === null || compare(f, lowest) < 0)
53
+ lowest = f;
54
+ }
55
+ if (lowest === null)
56
+ return { ok: false, reason: `cannot determine the floor of "${range}"` };
57
+ return { ok: true, version: lowest.join('.') };
58
+ }
@@ -0,0 +1,95 @@
1
+ // WHAT THE PACKAGE CLAIMS. Read from package.json exactly as a consumer's tooling reads it.
2
+ //
3
+ // Entry points come from `exports` when present, because that is what Node resolves and what
4
+ // a consumer can import; `main` is used only when there is no `exports`. Binaries come from
5
+ // `bin`, in either of its two shapes.
6
+ import { readFileSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ function isObject(v) {
9
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
10
+ }
11
+ /** Which loaders a single export target supports. A string target is loadable both ways. */
12
+ function loadersOf(target, packageType) {
13
+ const out = new Set();
14
+ if (typeof target === 'string') {
15
+ // A bare path's module kind follows its extension and the package "type".
16
+ if (target.endsWith('.cjs') || (!target.endsWith('.mjs') && packageType !== 'module'))
17
+ out.add('require');
18
+ else
19
+ out.add('import');
20
+ return out;
21
+ }
22
+ if (!isObject(target))
23
+ return out;
24
+ for (const [condition, value] of Object.entries(target)) {
25
+ if (condition === 'types')
26
+ continue;
27
+ if (condition === 'import')
28
+ out.add('import');
29
+ else if (condition === 'require')
30
+ out.add('require');
31
+ else if (condition === 'default' || condition === 'node') {
32
+ for (const l of loadersOf(value, packageType))
33
+ out.add(l);
34
+ }
35
+ }
36
+ return out;
37
+ }
38
+ function entryPointsFrom(pkg, name) {
39
+ const packageType = pkg['type'] === 'module' ? 'module' : 'commonjs';
40
+ const exp = pkg['exports'];
41
+ const entries = [];
42
+ const add = (subpath, target) => {
43
+ // Patterns ("./*") and explicitly blocked subpaths (null) cannot be probed as one specifier.
44
+ if (subpath.includes('*') || target === null)
45
+ return;
46
+ const specifier = subpath === '.' ? name : `${name}/${subpath.replace(/^\.\//, '')}`;
47
+ for (const loader of loadersOf(target, packageType))
48
+ entries.push({ specifier, loader });
49
+ };
50
+ if (exp !== undefined) {
51
+ if (typeof exp === 'string' || (isObject(exp) && !Object.keys(exp).some((k) => k.startsWith('.')))) {
52
+ add('.', exp);
53
+ }
54
+ else if (isObject(exp)) {
55
+ for (const [subpath, target] of Object.entries(exp)) {
56
+ // package.json is a conventional export, not code; loading it proves nothing.
57
+ if (subpath === './package.json')
58
+ continue;
59
+ add(subpath, target);
60
+ }
61
+ }
62
+ return entries;
63
+ }
64
+ if (typeof pkg['main'] === 'string')
65
+ add('.', pkg['main']);
66
+ return entries;
67
+ }
68
+ export function readManifest(dir) {
69
+ const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
70
+ const name = pkg['name'];
71
+ const version = pkg['version'];
72
+ if (typeof name !== 'string' || typeof version !== 'string') {
73
+ throw new Error(`${join(dir, 'package.json')} has no string "name" and "version"`);
74
+ }
75
+ const engines = isObject(pkg['engines']) ? pkg['engines'] : {};
76
+ const rawBin = pkg['bin'];
77
+ const bins = {};
78
+ if (typeof rawBin === 'string')
79
+ bins[name.replace(/^@[^/]+\//, '')] = rawBin;
80
+ else if (isObject(rawBin))
81
+ for (const [k, v] of Object.entries(rawBin))
82
+ if (typeof v === 'string')
83
+ bins[k] = v;
84
+ return {
85
+ name,
86
+ version,
87
+ enginesNode: typeof engines['node'] === 'string' ? engines['node'] : null,
88
+ entryPoints: entryPointsFrom(pkg, name),
89
+ bins,
90
+ scripts: isObject(pkg['scripts'])
91
+ ? Object.fromEntries(Object.entries(pkg['scripts']).filter(([, v]) => typeof v === 'string'))
92
+ : {},
93
+ isPrivate: pkg['private'] === true,
94
+ };
95
+ }
@@ -0,0 +1,78 @@
1
+ // OBTAINING AN EXACT NODE VERSION, verified before it is trusted.
2
+ //
3
+ // The official build is downloaded from the Node.js distribution, its SHA-256 is checked
4
+ // against the checksum list Node publishes beside it, and only then is it extracted. A
5
+ // mismatch is refused, never retried silently: a binary that does not match its published
6
+ // checksum is not the binary the check claims to have run.
7
+ //
8
+ // Limits, stated rather than implied: the checksum list is fetched over HTTPS and its
9
+ // detached GPG signature is NOT verified; Windows builds are not supported; the cache is
10
+ // trusted once written.
11
+ import { createHash } from 'node:crypto';
12
+ import { execFileSync } from 'node:child_process';
13
+ import { existsSync, mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs';
14
+ import { homedir, tmpdir } from 'node:os';
15
+ import { join } from 'node:path';
16
+ export class ChecksumMismatchError extends Error {
17
+ constructor(file, expected, actual) {
18
+ super(`${file}: SHA-256 ${actual} does not match the published ${expected}. Refusing to use it.`);
19
+ this.name = 'ChecksumMismatchError';
20
+ }
21
+ }
22
+ export function defaultCacheDir() {
23
+ return join(process.env['XDG_CACHE_HOME'] ?? join(homedir(), '.cache'), 'asinstalled', 'node');
24
+ }
25
+ function distPlatform(p) {
26
+ if (p === 'darwin' || p === 'linux')
27
+ return p;
28
+ throw new Error(`Node builds for platform "${p}" are not supported by asinstalled`);
29
+ }
30
+ async function fetchBytes(url) {
31
+ const res = await fetch(url);
32
+ if (!res.ok)
33
+ throw new Error(`GET ${url} returned ${res.status}`);
34
+ return Buffer.from(await res.arrayBuffer());
35
+ }
36
+ /** Path to a `node` executable of exactly `version`, downloading and verifying it if needed. */
37
+ export async function obtainNode(version, opts = {}) {
38
+ const v = version.replace(/^v/, '');
39
+ const platform = distPlatform(opts.platform ?? process.platform);
40
+ const arch = opts.arch ?? process.arch;
41
+ const base = (opts.baseUrl ?? 'https://nodejs.org/dist').replace(/\/$/, '');
42
+ const stem = `node-v${v}-${platform}-${arch}`;
43
+ const cacheRoot = opts.cacheDir ?? defaultCacheDir();
44
+ const binary = join(cacheRoot, stem, 'bin', 'node');
45
+ if (existsSync(binary))
46
+ return binary;
47
+ const file = `${stem}.tar.gz`;
48
+ opts.log?.(`downloading Node ${v} (${platform}-${arch})`);
49
+ const [sums, archive] = await Promise.all([
50
+ fetchBytes(`${base}/v${v}/SHASUMS256.txt`),
51
+ fetchBytes(`${base}/v${v}/${file}`),
52
+ ]);
53
+ const expected = sums.toString('utf8').split('\n').map((l) => l.trim().split(/\s+/))
54
+ .find((cols) => cols[1] === file)?.[0];
55
+ if (expected === undefined)
56
+ throw new Error(`${file} is not listed in the published SHASUMS256.txt for v${v}`);
57
+ const actual = createHash('sha256').update(archive).digest('hex');
58
+ if (actual !== expected)
59
+ throw new ChecksumMismatchError(file, expected, actual);
60
+ // Extract into a private temporary directory, then move into place, so a crash can never
61
+ // leave a half-extracted build in the cache that a later run would trust.
62
+ mkdirSync(cacheRoot, { recursive: true });
63
+ const work = mkdtempSync(join(tmpdir(), 'asinstalled-node-'));
64
+ try {
65
+ const tarball = join(work, file);
66
+ writeFileSync(tarball, archive);
67
+ execFileSync('tar', ['-xzf', tarball, '-C', work], { stdio: 'ignore' });
68
+ if (!existsSync(join(work, stem, 'bin', 'node')))
69
+ throw new Error(`${file} did not contain ${stem}/bin/node`);
70
+ if (!existsSync(join(cacheRoot, stem)))
71
+ renameSync(join(work, stem), join(cacheRoot, stem));
72
+ }
73
+ finally {
74
+ rmSync(work, { recursive: true, force: true });
75
+ }
76
+ opts.log?.(`verified and cached Node ${v}`);
77
+ return binary;
78
+ }
@@ -0,0 +1,93 @@
1
+ // `asinstalled published`: IS WHAT THE REGISTRY SERVES WHAT WAS BUILT?
2
+ //
3
+ // After a release, three questions are usually answered by trust:
4
+ // exists is this exact version actually live on the registry?
5
+ // identical are its bytes the bytes a fresh local build produces from this source?
6
+ // provenance does it carry a provenance attestation, and which repository does it name?
7
+ // plus one about the source itself:
8
+ // tag does the repository have the tag this version claims to come from?
9
+ //
10
+ // "identical" compares CONTENT, not the registry's integrity hash. That hash covers the
11
+ // gzip-compressed file, and the same tar stream compresses to different bytes under
12
+ // different zlib builds (for example Node 24 in CI and Node 26 on a laptop). Comparing it
13
+ // would report a difference in the compressor as a difference in the package. So: download
14
+ // the registry tarball, prove it matches the registry's own integrity (the download is
15
+ // authentic), decompress both sides, and compare the tar streams. A remaining difference is
16
+ // a real one: different source, or a build that is not reproducible.
17
+ import { spawnSync } from 'node:child_process';
18
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
19
+ import { createHash } from 'node:crypto';
20
+ import { gunzipSync } from 'node:zlib';
21
+ import { tmpdir } from 'node:os';
22
+ import { join } from 'node:path';
23
+ import { packProject } from "./check.js";
24
+ export async function runPublished(opts) {
25
+ const { manifest } = opts;
26
+ const registry = (opts.registry ?? 'https://registry.npmjs.org').replace(/\/$/, '');
27
+ const url = `${registry}/${manifest.name.replace('/', '%2f')}/${manifest.version}`;
28
+ const findings = [];
29
+ const res = await fetch(url);
30
+ if (!res.ok) {
31
+ findings.push({ check: 'exists', ok: false, detail: `${manifest.name}@${manifest.version} is not on ${registry} (HTTP ${res.status})` });
32
+ return findings;
33
+ }
34
+ const doc = (await res.json());
35
+ findings.push({ check: 'exists', ok: true, detail: `${manifest.name}@${manifest.version} is live on ${registry}` });
36
+ if (opts.compareLocal !== false) {
37
+ const work = mkdtempSync(join(tmpdir(), 'asinstalled-pub-'));
38
+ try {
39
+ const packed = packProject(opts.projectDir, work);
40
+ const localGz = readFileSync(join(work, packed.filename));
41
+ const tarballUrl = doc.dist?.tarball;
42
+ if (tarballUrl === undefined)
43
+ throw new Error('the registry document has no dist.tarball');
44
+ const remoteGz = Buffer.from(await (await fetch(tarballUrl)).arrayBuffer());
45
+ const claimed = doc.dist?.integrity ?? '';
46
+ const actual = `sha512-${createHash('sha512').update(remoteGz).digest('base64')}`;
47
+ if (actual !== claimed) {
48
+ findings.push({ check: 'identical', ok: false, detail: `the downloaded tarball does not match the registry's own integrity ${claimed.slice(0, 24)}...; refusing to compare` });
49
+ }
50
+ else {
51
+ const sha = (b) => createHash('sha256').update(b).digest('hex');
52
+ const same = sha(gunzipSync(localGz)) === sha(gunzipSync(remoteGz));
53
+ const sameCompressed = localGz.equals(remoteGz);
54
+ findings.push({
55
+ check: 'identical', ok: same,
56
+ detail: !same
57
+ ? 'the registry tarball CONTENT differs from a fresh local build (different source, or a build that is not reproducible)'
58
+ : sameCompressed
59
+ ? 'the registry tarball is byte-identical to a fresh local build'
60
+ : 'content identical to a fresh local build; only the gzip layer differs (a different zlib build), which does not change what users install',
61
+ });
62
+ }
63
+ }
64
+ finally {
65
+ rmSync(work, { recursive: true, force: true });
66
+ }
67
+ }
68
+ const attUrl = doc.dist?.attestations?.url;
69
+ if (attUrl === undefined) {
70
+ findings.push({ check: 'provenance', ok: false, detail: 'no provenance attestation is attached to this version' });
71
+ }
72
+ else {
73
+ const bundle = (await (await fetch(attUrl)).json());
74
+ const slsa = bundle.attestations?.find((a) => a.predicateType?.includes('slsa.dev/provenance'));
75
+ let repo = 'unknown repository';
76
+ try {
77
+ const payload = JSON.parse(Buffer.from(slsa?.bundle?.dsseEnvelope?.payload ?? '', 'base64').toString('utf8'));
78
+ const wf = payload.predicate?.buildDefinition?.externalParameters?.workflow;
79
+ if (wf?.repository)
80
+ repo = `${wf.repository} (${wf.path ?? '?'} @ ${wf.ref ?? '?'})`;
81
+ }
82
+ catch { /* reported as unknown below */ }
83
+ findings.push({ check: 'provenance', ok: slsa !== undefined,
84
+ detail: slsa !== undefined ? `SLSA provenance attached, built from ${repo}` : 'an attestation exists but none is SLSA provenance' });
85
+ }
86
+ const tag = `v${manifest.version}`;
87
+ const git = spawnSync('git', ['tag', '-l', tag], { cwd: opts.projectDir, encoding: 'utf8' });
88
+ if (git.status !== 0)
89
+ findings.push({ check: 'tag', ok: false, detail: 'not a git repository, so the source tag cannot be checked' });
90
+ else
91
+ findings.push({ check: 'tag', ok: git.stdout.trim() === tag, detail: git.stdout.trim() === tag ? `git tag ${tag} exists` : `no git tag ${tag} in this repository` });
92
+ return findings;
93
+ }
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "asinstalled",
3
+ "version": "0.1.0",
4
+ "description": "Test your npm package the way users receive it: pack it, install the tarball into a clean project, and run it on every Node version your engines field promises. Also checks your docs against package.json, and the published artifact against the build.",
5
+ "license": "Apache-2.0",
6
+ "author": "Theebbanraj Asokan",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/Theebban/asinstalled.git"
10
+ },
11
+ "homepage": "https://github.com/Theebban/asinstalled#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/Theebban/asinstalled/issues"
14
+ },
15
+ "type": "module",
16
+ "bin": {
17
+ "asinstalled": "dist/cli.js"
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "README.md",
22
+ "LICENSE",
23
+ "NOTICE"
24
+ ],
25
+ "engines": {
26
+ "node": ">=22.0.0"
27
+ },
28
+ "keywords": [
29
+ "npm-pack",
30
+ "package-testing",
31
+ "npm-publish",
32
+ "prepublish",
33
+ "smoke-test",
34
+ "tarball",
35
+ "engines",
36
+ "node-version",
37
+ "packaging",
38
+ "provenance",
39
+ "release",
40
+ "ci"
41
+ ],
42
+ "scripts": {
43
+ "asinstalled": "node --experimental-strip-types src/cli.ts",
44
+ "test": "node --experimental-strip-types --test tests/*.test.ts",
45
+ "typecheck": "tsc --noEmit",
46
+ "lint": "eslint src tests",
47
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
48
+ "check": "npm run typecheck && npm run lint && npm test",
49
+ "prepack": "npm run build",
50
+ "self-check": "node --experimental-strip-types src/cli.ts check --dir . --run \"asinstalled --help\" --script scripts/self-smoke.mjs && node --experimental-strip-types src/cli.ts docs --dir ."
51
+ },
52
+ "devDependencies": {
53
+ "@eslint/js": "^9.39.5",
54
+ "@types/node": "^22.20.4",
55
+ "eslint": "^9.39.5",
56
+ "typescript": "^5.9.3",
57
+ "typescript-eslint": "^8.70.1"
58
+ }
59
+ }