ai-install-guard 0.0.0-stage → 0.0.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.
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "ai-install-guard",
3
+ "description": "A pre-install security gate for Claude Code.",
4
+ "owner": {
5
+ "name": "Boaz Ziniman",
6
+ "email": "ziniman@gmail.com",
7
+ "url": "https://github.com/ziniman"
8
+ },
9
+ "plugins": [
10
+ {
11
+ "name": "ai-install-guard",
12
+ "source": "./",
13
+ "version": "0.0.0",
14
+ "description": "Scans plugins, mods, skills and MCP servers without running them, shows a PASS / WARN / FAIL verdict, and installs nothing until you approve.",
15
+ "category": "security",
16
+ "keywords": [
17
+ "security",
18
+ "supply-chain",
19
+ "static-analysis"
20
+ ]
21
+ }
22
+ ]
23
+ }
@@ -0,0 +1,22 @@
1
+ {
2
+ "name": "ai-install-guard",
3
+ "version": "0.0.0",
4
+ "description": "A pre-install security gate for Claude Code: scans plugins, mods, skills and MCP servers without running them, and installs nothing until you approve.",
5
+ "author": {
6
+ "name": "Boaz Ziniman",
7
+ "email": "ziniman@gmail.com",
8
+ "url": "https://github.com/ziniman"
9
+ },
10
+ "homepage": "https://github.com/ziniman/ai-install-guard",
11
+ "repository": "https://github.com/ziniman/ai-install-guard",
12
+ "license": "Apache-2.0",
13
+ "keywords": [
14
+ "security",
15
+ "supply-chain",
16
+ "static-analysis",
17
+ "plugins",
18
+ "skills",
19
+ "mcp",
20
+ "mods"
21
+ ]
22
+ }
package/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # Changelog
2
+
3
+ All notable changes to ai-install-guard. Ordered newest to oldest.
4
+
5
+ ---
6
+
7
+ ## Unreleased
8
+
9
+ **`/guard scan`** - Lists every file of a local folder, reads and hashes each one, records symbolic links with where they land without following them, and prints a SHA-256 tree hash that pins the exact content
10
+
11
+ **`release`** - Versioning, npm publishing and GitHub releases run from CI when a version bump is merged, as in ai-instruct
12
+
13
+ ---
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 [yyyy] [name of copyright owner]
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 CHANGED
@@ -1,3 +1,85 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # AI Install Guard
4
+
5
+ **A security gate for Claude Code. Nothing new gets installed until you have seen what it can do.**
6
+
7
+ [![npm version](https://img.shields.io/npm/v/ai-install-guard?style=for-the-badge&logo=npm&logoColor=white&color=CB3837)](https://www.npmjs.com/package/ai-install-guard)
8
+ [![npm downloads](https://img.shields.io/npm/dm/ai-install-guard?style=for-the-badge&logo=npm&logoColor=white&color=CB3837)](https://www.npmjs.com/package/ai-install-guard)
9
+ [![GitHub stars](https://img.shields.io/github/stars/ziniman/ai-install-guard?style=for-the-badge&logo=github&logoColor=white&color=181717)](https://github.com/ziniman/ai-install-guard/stargazers)
10
+ [![license](https://img.shields.io/badge/license-Apache%202.0-blue?style=for-the-badge)](https://github.com/ziniman/ai-install-guard/blob/main/LICENSE)
11
+ [![last commit](https://img.shields.io/github/last-commit/ziniman/ai-install-guard?style=for-the-badge&logo=github&logoColor=white&color=181717)](https://github.com/ziniman/ai-install-guard/commits/main)
12
+
13
+ ```
14
+ /plugin install ai-install-guard --marketplace ziniman/ai-install-guard
15
+ ```
16
+
17
+ </div>
18
+
19
+ > **Status: early development.** Today the guard can list and hash a local folder with `/guard scan <path>`. The checks, the verdict pane and the install gates below are being built in stages; see [Roadmap](#roadmap).
20
+
21
+ Everything you add to Claude Code runs with your permissions. A plugin can ship shell hooks that run every session, an MCP server can download and launch a package, a mod can read files or auto-approve tools, and a skill can carry hidden instructions the model will follow. The install prompt asks you to trust the author, and an update can change the files after you looked.
22
+
23
+ AI Install Guard is a Claude Code mod that stops every new plugin, mod, skill, MCP server or marketplace, and every update to one, scans it without running any of its code, and installs nothing until you approve it.
24
+
25
+ ## How it works
26
+
27
+ 1. **Fetch without running.** The candidate is fetched at an exact commit into a folder the guard owns. Nothing is installed, built or run.
28
+ 2. **Check every file.** Deterministic checks read the hooks, MCP servers, mod code, skills, scripts, images and manifest.
29
+ 3. **Show a verdict.** A pane shows **Safe to install**, **Install with caution**, **Do not install** or **Could not verify**, a PASS / WARN / FAIL list with file and line evidence, and two buttons: **Install** and **Reject**.
30
+ 4. **Install only what was scanned.** Install is pinned to the scanned commit and content hash. If the source changed since the scan, it is scanned again first.
31
+
32
+ Approvals are remembered by commit and content hash, so the same version is never scanned twice, and an update is reviewed as a diff: anything new since the version you approved is listed and flagged. An optional model review can add warnings but can never clear a failure, so a README that says "this plugin is safe" changes nothing.
33
+
34
+ ## Where it steps in
35
+
36
+ | Layer | Catches | What happens |
37
+ |-------|---------|--------------|
38
+ | Slash command | `/plugin install`, `/plugin update`, `/plugin marketplace add` | Held until you press Install |
39
+ | Claude's own tool calls | `claude plugin install`, `claude mcp add`, copies into skills folders, edits to `.mcp.json` or settings, `npx -y`, `curl \| sh` | Denied, with a note to the model that a scan is pending |
40
+ | Mod loading | Any mod about to load, however it got there | Refused if its files do not match what you approved |
41
+ | First use of a skill | Skills and commands, including ones copied in by hand | Blocked until scanned |
42
+ | Session start | Anything installed while the guard was not running | Scanned, with Keep or Uninstall |
43
+
44
+ ## What it checks
45
+
46
+ | Threat | What gets flagged |
47
+ |--------|-------------------|
48
+ | Code execution | Shell hooks, MCP servers that launch binaries or unpinned `npx` / `uvx` packages, mods that run processes |
49
+ | Data theft | Reads of `~/.ssh`, `~/.aws`, `.env`, keychains or secret env vars, combined with network calls |
50
+ | Prompt injection | Hidden instructions in skills, commands, agents and tool descriptions, including invisible Unicode |
51
+ | Permission escalation | Mods that auto-approve tools, writes to Claude settings or permissions, skills granting broad `Bash` |
52
+ | Persistence | Writes to shell rc files, crontab, launchd, systemd, git hooks |
53
+ | Supply chain | Marketplaces on a moving branch, brand-new repos, look-alike names, committed secrets, binaries, data hidden after the end of images |
54
+ | Sneaky updates | An update that adds capabilities, hooks, domains or servers without saying so |
55
+
56
+ ## Commands
57
+
58
+ | Command | What it does |
59
+ |---------|--------------|
60
+ | `/guard scan <path>` | Scan a local folder without installing it |
61
+
62
+ ## What it is not
63
+
64
+ - **Not a proof of safety.** Static analysis raises the bar and makes every capability visible; a determined attacker can still evade it.
65
+ - **Install it first.** It judges only mods that load after it. For a company, the strongest setup is deploying it through managed settings so it loads first.
66
+ - **No per-plugin block for classic shell hooks.** Claude Code runs them outside mods, so the guard scans before install and uninstalls on reject.
67
+
68
+ ## Roadmap
69
+
70
+ 1. [x] Skeleton mod: `/guard scan <path>` lists and hashes a local folder
71
+ 2. [ ] Checks for structure, mod capabilities, classic hooks, skills, code patterns and committed secrets
72
+ 3. [ ] The verdict pane with Install and Reject
73
+ 4. [ ] Remote fetch pinned to a commit, provenance checks, MCP server checks
74
+ 5. [ ] Gates on `/plugin` and on Claude's own install commands, with approvals
75
+ 6. [ ] Module load gate with hash match, skill gate, session-start reconciliation
76
+ 7. [ ] Update diffs and the optional model review
77
+ 8. [ ] Full documentation
78
+
79
+ ## Contributing
80
+
81
+ Issues and pull requests are welcome. See [.claude/CLAUDE.md](./.claude/CLAUDE.md) for how the repo is laid out, how to run the checks, and how releases work.
82
+
83
+ ## License
84
+
85
+ Apache 2.0 - see [LICENSE](./LICENSE). Free to use, modify, and redistribute.
@@ -0,0 +1 @@
1
+ { "modules": ["./register.tsx"] }
@@ -0,0 +1,31 @@
1
+ import type { EngineInterface } from 'claude-code'
2
+
3
+ import { fromBase64, type Host } from './scan/host'
4
+
5
+ // Windows PowerShell 5.1 answers a link's Target as an array; -join makes it one string.
6
+ const WINDOWS_READLINK = "[Console]::Out.Write(((Get-Item -LiteralPath $env:GUARD_LINK -Force).Target -join ''))"
7
+
8
+ /** The scanner's host inside Claude Code: `$.fs` reads, `$.process` runs. */
9
+ export function modHost($: EngineInterface): Host {
10
+ return {
11
+ list: path => $.fs.list(path),
12
+ stat: (path, options) => $.fs.stat(path, options ?? { resolve: false }),
13
+ readBytes: async path => fromBase64((await $.fs.read(path, { as: 'bytes' })).base64),
14
+ readLink: async path => {
15
+ const posix = await $.process.run(['readlink', path]).catch(() => undefined)
16
+ if (posix !== undefined && posix.exitCode === 0) {
17
+ return posix.stdout.endsWith('\n') ? posix.stdout.slice(0, -1) : posix.stdout
18
+ }
19
+ // Windows has no readlink. The path travels in the environment, never
20
+ // in the command text, so no name can change what PowerShell runs.
21
+ const windows = await $.process
22
+ .run(['powershell', '-NoProfile', '-NonInteractive', '-Command', WINDOWS_READLINK], { env: { GUARD_LINK: path } })
23
+ .catch(() => undefined)
24
+ if (windows !== undefined && windows.exitCode === 0 && windows.stdout.trim() !== '') {
25
+ return windows.stdout.replace(/\r?\n$/, '')
26
+ }
27
+ throw new Error(`could not read the link ${path}`)
28
+ },
29
+ run: (argv, options) => $.process.run(argv, options),
30
+ }
31
+ }
@@ -0,0 +1,63 @@
1
+ import type { Register } from 'claude-code'
2
+
3
+ import { modHost } from './mod-host'
4
+ import type { Host } from './scan/host'
5
+ import { takeInventory } from './scan/inventory'
6
+ import { formatInventory } from './scan/report'
7
+ import { safeLine } from './scan/safe-text'
8
+
9
+ const USAGE = [
10
+ 'Usage:',
11
+ ' /guard scan <path> Scan a local plugin, mod or skill folder without installing it',
12
+ ].join('\n')
13
+
14
+ export const register: Register = on => {
15
+ on('session.start', async ($, e, next) => {
16
+ await $.command.register({
17
+ name: 'guard',
18
+ description: 'Scan a plugin, mod, skill or MCP server without installing it',
19
+ argumentHint: 'scan <path>',
20
+ })
21
+ return next(e)
22
+ })
23
+
24
+ on('command.run', { command: 'guard' }, async ($, e) => {
25
+ const { sub, rest } = splitArgs(e.args)
26
+ if (sub !== 'scan' || rest === '') {
27
+ return { text: USAGE }
28
+ }
29
+ const host = modHost($)
30
+ try {
31
+ const tree = await takeInventory(host, await expandHome(host, rest))
32
+ return { text: formatInventory(rest, tree.inventory) }
33
+ } catch (error) {
34
+ return { text: `Could not verify ${safeLine(rest)}: ${safeLine(reasonOf(error))}` }
35
+ }
36
+ }).catch(() => ({ text: 'AI Install Guard: the command failed before it could answer.' }))
37
+ }
38
+
39
+ /** `scan "my folder"` → `{ sub: 'scan', rest: 'my folder' }`. */
40
+ export function splitArgs(args: string): { sub: string; rest: string } {
41
+ const trimmed = args.trim()
42
+ const space = trimmed.search(/\s/)
43
+ const sub = space === -1 ? trimmed : trimmed.slice(0, space)
44
+ const rest = space === -1 ? '' : trimmed.slice(space).trim()
45
+ const unquoted = /^(["']).*\1$/.test(rest) ? rest.slice(1, -1) : rest
46
+ return { sub: sub.toLowerCase(), rest: unquoted }
47
+ }
48
+
49
+ async function expandHome(host: Host, path: string): Promise<string> {
50
+ if (path !== '~' && !path.startsWith('~/')) {
51
+ return path
52
+ }
53
+ const { exitCode, stdout } = await host.run(['printenv', 'HOME'])
54
+ const home = stdout.trim()
55
+ if (exitCode !== 0 || home === '') {
56
+ throw new Error('could not find the home folder')
57
+ }
58
+ return home + path.slice(1)
59
+ }
60
+
61
+ function reasonOf(error: unknown): string {
62
+ return error instanceof Error ? error.message : String(error)
63
+ }
@@ -0,0 +1,38 @@
1
+ import type { InventoryEntry } from './inventory'
2
+
3
+ const encoder = new TextEncoder()
4
+
5
+ export async function sha256Hex(data: Uint8Array | string): Promise<string> {
6
+ const bytes = typeof data === 'string' ? encoder.encode(data) : data
7
+ const digest = await crypto.subtle.digest('SHA-256', bytes)
8
+ return [...new Uint8Array(digest)].map(b => b.toString(16).padStart(2, '0')).join('')
9
+ }
10
+
11
+ /**
12
+ * One record per entry, sorted by path, each ended by a NUL byte (which no
13
+ * path can hold, so two different trees never share a record list), then
14
+ * hashed:
15
+ *
16
+ * file <sha256 of its bytes> <path>
17
+ * link <sha256 of the target as stored in the link> <path>
18
+ * dir - <path>
19
+ * other - <path>
20
+ *
21
+ * A link counts by its stored target, not where it lands on this machine, so
22
+ * the same tree hashes the same everywhere. Changing this format changes every
23
+ * stored approval.
24
+ */
25
+ export async function treeHash(entries: readonly InventoryEntry[]): Promise<string> {
26
+ const sorted = [...entries].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
27
+ let records = ''
28
+ for (const entry of sorted) {
29
+ if (entry.kind === 'file') {
30
+ records += `file ${entry.sha256} ${entry.path}\0`
31
+ } else if (entry.kind === 'link') {
32
+ records += `link ${await sha256Hex(entry.target)} ${entry.path}\0`
33
+ } else {
34
+ records += `${entry.kind} - ${entry.path}\0`
35
+ }
36
+ }
37
+ return `sha256:${await sha256Hex(records)}`
38
+ }
@@ -0,0 +1,51 @@
1
+ // The scanner's view of the machine. The scan code never touches `$` or Node
2
+ // directly: the mod passes a host built on `$.fs` and `$.process`, and tests
3
+ // pass one that answers from fixtures in memory.
4
+
5
+ export type HostEntryKind = 'file' | 'dir' | 'other'
6
+
7
+ export type HostEntry = {
8
+ name: string
9
+ kind: HostEntryKind
10
+ size: number
11
+ isLink: boolean
12
+ }
13
+
14
+ export type HostStat = {
15
+ kind: HostEntryKind
16
+ size: number
17
+ isLink: boolean
18
+ /** Where the path lands with every link followed; absent when it leads nowhere. */
19
+ realPath?: string
20
+ }
21
+
22
+ export type RunResult = {
23
+ exitCode: number
24
+ stdout: string
25
+ stderr: string
26
+ }
27
+
28
+ export type RunOptions = {
29
+ cwd?: string
30
+ timeoutMs?: number
31
+ /** Variables set over the host's own environment. */
32
+ env?: Record<string, string>
33
+ }
34
+
35
+ export type Host = {
36
+ list: (path: string) => Promise<HostEntry[]>
37
+ stat: (path: string, options?: { resolve: boolean }) => Promise<HostStat>
38
+ readBytes: (path: string) => Promise<Uint8Array>
39
+ /** The target text stored in a symbolic link, as `readlink` prints it. */
40
+ readLink: (path: string) => Promise<string>
41
+ run: (argv: readonly string[], options?: RunOptions) => Promise<RunResult>
42
+ }
43
+
44
+ export function fromBase64(base64: string): Uint8Array {
45
+ const binary = atob(base64)
46
+ const bytes = new Uint8Array(binary.length)
47
+ for (let i = 0; i < binary.length; i += 1) {
48
+ bytes[i] = binary.charCodeAt(i)
49
+ }
50
+ return bytes
51
+ }
@@ -0,0 +1,240 @@
1
+ import { sha256Hex, treeHash } from './hash'
2
+ import type { Host } from './host'
3
+
4
+ /** Past these the scan stops and the verdict is "Could not verify". */
5
+ export const LIMITS = {
6
+ maxEntries: 5000,
7
+ /** Each link costs a `readlink` process, so links have a lower ceiling. */
8
+ maxLinks: 500,
9
+ maxFileBytes: 4 * 1024 * 1024,
10
+ maxTotalBytes: 50 * 1024 * 1024,
11
+ }
12
+
13
+ const READ_CONCURRENCY = 8
14
+ const TEXT_SNIFF_BYTES = 8000
15
+
16
+ export type InventoryFile = {
17
+ kind: 'file'
18
+ path: string
19
+ size: number
20
+ sha256: string
21
+ isText: boolean
22
+ }
23
+
24
+ export type InventoryLink = {
25
+ kind: 'link'
26
+ path: string
27
+ /** The target as stored in the link (what `readlink` prints). */
28
+ target: string
29
+ /**
30
+ * Where it lands: relative to the root when inside it, absolute when
31
+ * outside, absent when it leads nowhere.
32
+ */
33
+ landsAt?: string
34
+ isInside: boolean
35
+ }
36
+
37
+ export type InventoryDir = {
38
+ kind: 'dir'
39
+ path: string
40
+ }
41
+
42
+ export type InventoryOther = {
43
+ kind: 'other'
44
+ path: string
45
+ }
46
+
47
+ export type InventoryEntry = InventoryFile | InventoryLink | InventoryDir | InventoryOther
48
+
49
+ export type Inventory = {
50
+ /** The scanned folder, every link resolved. */
51
+ root: string
52
+ /** Sorted by path. */
53
+ entries: InventoryEntry[]
54
+ totalBytes: number
55
+ treeHash: string
56
+ /** Folders left out on purpose (the root's `.git`). */
57
+ skipped: string[]
58
+ }
59
+
60
+ export type ScannedTree = {
61
+ inventory: Inventory
62
+ /** Each file's bytes by path, for the checks. Never stored. */
63
+ contents: Map<string, Uint8Array>
64
+ }
65
+
66
+ export class ScanError extends Error {
67
+ constructor(message: string) {
68
+ super(message)
69
+ this.name = 'ScanError'
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Lists every entry under `path` and reads and hashes every regular file.
75
+ * A symbolic link is recorded with its target and where it lands, and never
76
+ * followed, so a link to `~/.ssh` is reported, not read.
77
+ */
78
+ export async function takeInventory(host: Host, path: string): Promise<ScannedTree> {
79
+ const rootStat = await host.stat(path, { resolve: true }).catch(() => undefined)
80
+ if (rootStat === undefined) {
81
+ throw new ScanError(`${path} does not exist`)
82
+ }
83
+ if (rootStat.kind !== 'dir' || rootStat.isLink) {
84
+ throw new ScanError(`${path} is not a folder`)
85
+ }
86
+ const root = normalize(rootStat.realPath ?? path)
87
+
88
+ const entries: InventoryEntry[] = []
89
+ const files: { path: string; size: number }[] = []
90
+ const links: string[] = []
91
+ const skipped: string[] = []
92
+ const queue: string[] = ['']
93
+
94
+ while (queue.length > 0) {
95
+ const dir = queue.shift() as string
96
+ const listed = await host.list(dir === '' ? root : `${root}/${dir}`)
97
+ for (const item of listed) {
98
+ const rel = dir === '' ? item.name : `${dir}/${item.name}`
99
+ if (item.isLink) {
100
+ links.push(rel)
101
+ } else if (item.kind === 'dir') {
102
+ if (dir === '' && item.name === '.git') {
103
+ skipped.push(rel)
104
+ } else {
105
+ entries.push({ kind: 'dir', path: rel })
106
+ queue.push(rel)
107
+ }
108
+ } else if (item.kind === 'file') {
109
+ files.push({ path: rel, size: item.size })
110
+ } else {
111
+ entries.push({ kind: 'other', path: rel })
112
+ }
113
+ if (entries.length + files.length + links.length > LIMITS.maxEntries) {
114
+ throw new ScanError(`more than ${LIMITS.maxEntries} files and folders`)
115
+ }
116
+ }
117
+ }
118
+
119
+ if (links.length > LIMITS.maxLinks) {
120
+ throw new ScanError(`more than ${LIMITS.maxLinks} symbolic links`)
121
+ }
122
+ checkSizes(files)
123
+ entries.push(...(await mapLimit(links, READ_CONCURRENCY, rel => describeLink(host, root, rel))))
124
+
125
+ const contents = new Map<string, Uint8Array>()
126
+ let readBytes = 0
127
+ const read = await mapLimit(files, READ_CONCURRENCY, async (file): Promise<InventoryFile> => {
128
+ const full = `${root}/${file.path}`
129
+ await assertPlainFile(host, full, file.path)
130
+ const bytes = await host.readBytes(full)
131
+ readBytes += bytes.length
132
+ checkSizes([{ path: file.path, size: bytes.length }], readBytes)
133
+ contents.set(file.path, bytes)
134
+ return {
135
+ kind: 'file',
136
+ path: file.path,
137
+ size: bytes.length,
138
+ sha256: await sha256Hex(bytes),
139
+ isText: looksLikeText(bytes),
140
+ }
141
+ })
142
+ entries.push(...read)
143
+ entries.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
144
+
145
+ return {
146
+ inventory: {
147
+ root,
148
+ entries,
149
+ totalBytes: readBytes,
150
+ treeHash: await treeHash(entries),
151
+ skipped,
152
+ },
153
+ contents,
154
+ }
155
+ }
156
+
157
+ /** Throws when a file, or all of them together, is over its limit. */
158
+ function checkSizes(files: readonly { path: string; size: number }[], total?: number): void {
159
+ const tooLarge = files.find(file => file.size > LIMITS.maxFileBytes)
160
+ if (tooLarge !== undefined) {
161
+ throw new ScanError(`${tooLarge.path} is ${formatBytes(tooLarge.size)}, over the ${formatBytes(LIMITS.maxFileBytes)} per-file limit`)
162
+ }
163
+ const sum = total ?? files.reduce((acc, file) => acc + file.size, 0)
164
+ if (sum > LIMITS.maxTotalBytes) {
165
+ throw new ScanError(`${formatBytes(sum)} of files, over the ${formatBytes(LIMITS.maxTotalBytes)} limit`)
166
+ }
167
+ }
168
+
169
+ /**
170
+ * Refuses to read a path that is no longer the plain file the listing saw:
171
+ * swapped for a link, or reached through one, it would be read where it lands.
172
+ */
173
+ async function assertPlainFile(host: Host, full: string, rel: string): Promise<void> {
174
+ const stat = await host.stat(full, { resolve: true }).catch(() => undefined)
175
+ const real = stat?.realPath === undefined ? undefined : normalize(stat.realPath)
176
+ if (stat === undefined || stat.isLink || stat.kind !== 'file' || real !== normalize(full)) {
177
+ throw new ScanError(`${rel} changed while it was being scanned`)
178
+ }
179
+ }
180
+
181
+ async function describeLink(host: Host, root: string, rel: string): Promise<InventoryLink> {
182
+ const full = `${root}/${rel}`
183
+ const target = await host.readLink(full).catch(() => {
184
+ throw new ScanError(`could not read where the link ${rel} points`)
185
+ })
186
+ const stat = await host.stat(full, { resolve: true }).catch(() => undefined)
187
+ const real = stat?.realPath === undefined ? undefined : normalize(stat.realPath)
188
+ if (real === undefined) {
189
+ return { kind: 'link', path: rel, target, isInside: false }
190
+ }
191
+ if (real === root || real.startsWith(`${root}/`)) {
192
+ return { kind: 'link', path: rel, target, landsAt: real.slice(root.length + 1) || '.', isInside: true }
193
+ }
194
+ return { kind: 'link', path: rel, target, landsAt: real, isInside: false }
195
+ }
196
+
197
+ /**
198
+ * Drops trailing slashes. Backslashes become slashes only in a Windows path
199
+ * (`C:\...` or `\\server\...`): elsewhere a backslash is part of a name.
200
+ */
201
+ function normalize(path: string): string {
202
+ const isWindows = /^[A-Za-z]:[\\/]/.test(path) || path.startsWith('\\\\')
203
+ const slashed = isWindows ? path.replace(/\\/g, '/') : path
204
+ return slashed.length > 1 ? slashed.replace(/\/+$/, '') : slashed
205
+ }
206
+
207
+ function looksLikeText(bytes: Uint8Array): boolean {
208
+ const end = Math.min(bytes.length, TEXT_SNIFF_BYTES)
209
+ for (let i = 0; i < end; i += 1) {
210
+ if (bytes[i] === 0) return false
211
+ }
212
+ return true
213
+ }
214
+
215
+ /** Runs `fn` over `items`, `limit` at a time; after the first failure no worker starts another item. */
216
+ export async function mapLimit<T, R>(items: readonly T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {
217
+ const results: R[] = new Array(items.length)
218
+ let next = 0
219
+ let hasFailed = false
220
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
221
+ while (!hasFailed && next < items.length) {
222
+ const index = next
223
+ next += 1
224
+ try {
225
+ results[index] = await fn(items[index] as T)
226
+ } catch (error) {
227
+ hasFailed = true
228
+ throw error
229
+ }
230
+ }
231
+ })
232
+ await Promise.all(workers)
233
+ return results
234
+ }
235
+
236
+ export function formatBytes(bytes: number): string {
237
+ if (bytes < 1024) return `${bytes} B`
238
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
239
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
240
+ }
@@ -0,0 +1,41 @@
1
+ import { formatBytes, type Inventory } from './inventory'
2
+ import { safeLine } from './safe-text'
3
+
4
+ const MAX_LISTED = 60
5
+
6
+ /** The plain-text report `/guard scan` prints. */
7
+ export function formatInventory(target: string, inventory: Inventory): string {
8
+ const files = inventory.entries.filter(entry => entry.kind === 'file')
9
+ const links = inventory.entries.filter(entry => entry.kind === 'link')
10
+ const others = inventory.entries.filter(entry => entry.kind === 'other')
11
+ const listed = inventory.entries.filter(entry => entry.kind !== 'dir')
12
+
13
+ const lines = [
14
+ `AI Install Guard: ${safeLine(target)}`,
15
+ `Folder: ${safeLine(inventory.root)}`,
16
+ `Files: ${files.length} (${formatBytes(inventory.totalBytes)}), links: ${links.length}, other: ${others.length}`,
17
+ `Tree hash: ${inventory.treeHash}`,
18
+ ]
19
+ if (inventory.skipped.length > 0) {
20
+ lines.push(`Not read: ${inventory.skipped.map(safeLine).join(', ')}`)
21
+ }
22
+ lines.push('')
23
+
24
+ for (const entry of listed.slice(0, MAX_LISTED)) {
25
+ const path = safeLine(entry.path)
26
+ if (entry.kind === 'file') {
27
+ lines.push(` ${path} ${formatBytes(entry.size)}${entry.isText ? '' : ', binary'}`)
28
+ } else if (entry.kind === 'link') {
29
+ const where = entry.landsAt === undefined ? 'leads nowhere' : entry.isInside ? '' : 'outside the folder'
30
+ lines.push(` ${path} link to ${safeLine(entry.target)}${where === '' ? '' : ` (${where})`}`)
31
+ } else {
32
+ lines.push(` ${path} not a regular file`)
33
+ }
34
+ }
35
+ if (listed.length > MAX_LISTED) {
36
+ lines.push(` ... and ${listed.length - MAX_LISTED} more`)
37
+ }
38
+
39
+ lines.push('', 'No checks run yet: this build lists and hashes the files only.')
40
+ return lines.join('\n')
41
+ }
@@ -0,0 +1,28 @@
1
+ // Text taken from a candidate (file names, excerpts) is untrusted: it may
2
+ // carry terminal escapes or invisible characters meant to hide what it says.
3
+ // Everything a report shows from a candidate goes through `safeText` first.
4
+
5
+ const HIDDEN = new RegExp(
6
+ [
7
+ '[\\u0000-\\u0008\\u000b-\\u001f\\u007f-\\u009f]', // control characters (escapes, NUL, C1)
8
+ '[\\u00ad\\u034f\\u061c\\u115f\\u1160\\u17b4\\u17b5\\u180b-\\u180f]', // invisible marks and fillers
9
+ '[\\u200b-\\u200f\\u2028-\\u202e\\u2060-\\u2069\\u3164\\ufeff\\uffa0\\ufff9-\\ufffb]', // zero-width, line and paragraph separators, bidi controls
10
+ '[\\ufe00-\\ufe0f]', // variation selectors
11
+ '[\\u{e0000}-\\u{e007f}]', // tag characters
12
+ '[\\u{e0100}-\\u{e01ef}]', // variation selectors supplement
13
+ ].join('|'),
14
+ 'gu',
15
+ )
16
+
17
+ /** Shows each hidden or control character as `<U+XXXX>` so it can be seen. */
18
+ export function safeText(text: string): string {
19
+ return text.replace(HIDDEN, char => {
20
+ const code = char.codePointAt(0) as number
21
+ return `<U+${code.toString(16).toUpperCase().padStart(4, '0')}>`
22
+ })
23
+ }
24
+
25
+ /** `safeText` for text that must stay on one line, such as a file name. */
26
+ export function safeLine(text: string): string {
27
+ return safeText(text).replace(/\t/g, '<U+0009>').replace(/\n/g, '<U+000A>')
28
+ }
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "ai-install-guard",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.0",
4
+ "description": "A pre-install security gate for Claude Code: scans plugins, mods, skills and MCP servers without running them, and installs nothing until you approve.",
5
+ "scripts": {
6
+ "build:fixtures": "node scripts/build-fixtures.js",
7
+ "sync:versions": "node scripts/sync-versions.js",
8
+ "validate": "claude plugin validate --strict .",
9
+ "typecheck": "tsc -p .",
10
+ "test": "claude plugin test .",
11
+ "check": "npm run validate && npm run typecheck && npm test",
12
+ "version": "node scripts/sync-versions.js && git add .claude-plugin/"
13
+ },
14
+ "keywords": [
15
+ "claude",
16
+ "claude-code",
17
+ "security",
18
+ "supply-chain",
19
+ "static-analysis",
20
+ "plugins",
21
+ "skills",
22
+ "mcp"
23
+ ],
24
+ "files": [
25
+ ".claude-plugin/plugin.json",
26
+ ".claude-plugin/marketplace.json",
27
+ "hooks/",
28
+ "!hooks/**/*.test.ts",
29
+ "!hooks/test-support/",
30
+ "README.md",
31
+ "CHANGELOG.md",
32
+ "LICENSE"
33
+ ],
34
+ "license": "Apache-2.0",
35
+ "author": "Boaz Ziniman <ziniman@gmail.com> (https://github.com/ziniman)",
36
+ "homepage": "https://github.com/ziniman/ai-install-guard",
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/ziniman/ai-install-guard.git"
40
+ },
41
+ "bugs": "https://github.com/ziniman/ai-install-guard/issues",
42
+ "engines": {
43
+ "node": ">=18"
44
+ },
45
+ "devDependencies": {
46
+ "typescript": "^5.9.3"
47
+ }
48
+ }