@stacksjs/malware 0.0.0-stage → 0.75.730

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.md ADDED
@@ -0,0 +1,21 @@
1
+ # MIT License
2
+
3
+ Copyright (c) 2023 Open Web Foundation
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,423 @@
1
- # Temporary Holding Version
1
+ ![Social Card of Stacks](./public/images/social.png)
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
+ # Rapid App & Library Development
4
+
5
+ [![npm version](https://img.shields.io/npm/v/stacks?style=flat-square)](https://npmjs.com/package/stacks)
6
+ [![GitHub Actions](https://img.shields.io/github/actions/workflow/status/stacksjs/stacks/ci.yml?style=flat-square&branch=main)](https://github.com/stacksjs/stacks/actions?query=workflow%3Aci)
7
+ [![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/)
8
+ [![npm downloads](https://img.shields.io/npm/dm/stacks?style=flat-square)](https://npmjs.com/package/stacks)
9
+ <!-- [![Codecov][codecov-src]][codecov-href] -->
10
+
11
+ > [!NOTE]
12
+ > Stacks is in active development and usable today — every section below
13
+ > is real, runnable functionality. Expect occasional breaking changes
14
+ > while we cut the official 1.0. Feedback and issue reports are welcome.
15
+
16
+ Stacks is a rapid development framework, where the goal is to _help you_ create & maintain frontends, backends, and clouds—without having to worry about the boilerplate. _An all-in-one toolkit that meets all your full stack needs._
17
+
18
+ <a href="https://stacksjs.com/docs/diagrams/stacks-runtime">
19
+ <picture>
20
+ <source media="(prefers-color-scheme: dark)" srcset="./docs/public/diagrams/stacks-runtime/dark.png">
21
+ <img alt="Stacks runtime architecture: developer to Buddy CLI to Stacks Cloud, and web or desktop client through rpx to stx, router, actions, ORM, and database" src="./docs/public/diagrams/stacks-runtime/light.png">
22
+ </picture>
23
+ </a>
24
+
25
+ _[Open the interactive diagram](https://stacksjs.com/docs/diagrams/stacks-runtime) for a theme toggle, node search, route tracing, presentation mode, and SVG, PNG, JPEG, WebP and share-card exports._
26
+
27
+ - Web & Desktop Applications _(including system tray apps)_
28
+ - Serverless & Traditional APIs
29
+ - Cloud Infrastructure Creation & Maintenance
30
+ - Interactive CLIs
31
+ - Framework-agnostic Component & Function Libraries
32
+ - Deployment & Release Manager _(CI & CD)_
33
+
34
+ ## Convention Over Configuration
35
+
36
+ As a developer, Stacks helps you every step along the way—in beginner & expert-friendly ways, allowing you to focus on the _what & why_ of your project, all while enabling you to stay in control & ownership of your _(& your users’)_ data.
37
+
38
+ > “It is the framework’s responsibility to remove patterns that lead to boilerplate code. And Stacks is really good at that.” _- Chris_
39
+
40
+ <!-- ![Atomic UI & FX Design](./docs/assets/diagram.png) -->
41
+
42
+ ## Prerequisites
43
+
44
+ Stacks uses [Pantry](https://pantry.dev) to provision Bun, Git, SQLite, and the project-specific tools declared by the framework. You'll need:
45
+
46
+ - **Pantry** - install it with `curl -fsSL https://pantry.dev | bash`, then run `pantry bootstrap` once to configure your shell.
47
+ - **macOS, Linux, or WSL** - Windows-native support is on the roadmap. The current toolchain assumes a POSIX shell.
48
+
49
+ Pantry installs and pins Bun 1.4.4 for this Stacks workspace, then keeps the rest of the machine and project dependencies in sync. Features such as PostgreSQL, Redis, and cloud deployment add their requirements through the same Pantry manifest where possible, with feature-specific configuration documented alongside them.
50
+
51
+ Stacks pins Pantry [`v0.11.50`](https://github.com/pantry-pm/pantry/tree/v0.11.50)
52
+ as an external toolchain contract. Resolution sources, lockfile and integrity
53
+ rules, lifecycle trust, registry routes, authentication, storage, and failure
54
+ modes are documented in the source-linked whitepaper references for the
55
+ [package manager](https://whitepaper.stacksjs.com/reference/package-manager) and
56
+ [registry](https://whitepaper.stacksjs.com/reference/registry). Stacks does not
57
+ redefine those behaviors.
58
+
59
+ ## Get Started
60
+
61
+ ### In the browser
62
+
63
+ [![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/stacksjs/stacks)
64
+
65
+ The root `.devcontainer/` configures GitHub Codespaces and the VS Code Dev
66
+ Containers extension. It provisions Pantry, installs dependencies, runs
67
+ `buddy setup` and forwards the dev ports so `./buddy dev` works on first open.
68
+
69
+ ### On your machine
70
+
71
+ The fastest path after Pantry is installed:
72
+
73
+ ```bash
74
+ panx buddy new my-project
75
+ ```
76
+
77
+ Pantry executes Buddy in an isolated environment and provisions the generated project's declared toolchain during setup.
78
+
79
+ From there: the [documentation](https://stacksjs.com/docs/guide/intro), the [Buddy command reference](https://stacksjs.com/docs/guide/buddy/commands), and the [agent skills](https://stacksjs.com/docs/skills) that teach Claude Code, Codex, and Cursor how each subsystem works.
80
+
81
+ For frontend experiments in the browser, open the live stx starter:
82
+
83
+ [![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/fork/github/stacksjs/stackblitz?title=Stacks%20Starter)
84
+
85
+ ## Usage
86
+
87
+ Stacks ships with `buddy`, a single CLI for everything you'll do day to day. The handful below covers the common workflows; the full reference is collapsed underneath.
88
+
89
+ ```bash
90
+ buddy dev # start the dev server (frontend, API, dashboard, …)
91
+ buddy build # build for production (CLI prompts for what to build)
92
+ buddy test # run tests
93
+ buddy migrate # run database migrations
94
+ buddy make:action UpdateUser # scaffold a new Action (also: model, view, job, …)
95
+ buddy --help # show every available command
96
+ ```
97
+
98
+ For the full command reference, see the collapsible section below or the [Buddy CLI documentation](https://stacksjs.com/docs/guide/buddy/commands).
99
+
100
+ <details>
101
+ <summary>View the complete Buddy Toolkit</summary>
102
+
103
+ ```bash
104
+ buddy --version # get the Stacks version
105
+ buddy --help # view help menu
106
+ # please note: you may suffix any command with the
107
+ # `command --help` flag to review the help menu
108
+
109
+ buddy new my-project # creates a new Stacks project
110
+ buddy install # installs dependencies
111
+ buddy add calendar # pulls a registered project-shaped stack into this project
112
+ buddy fresh # fresh reinstall of all deps (--force skips the confirmation)
113
+ buddy clean # removes all deps (--force skips the confirmation)
114
+ buddy setup # sets up the project initially
115
+ buddy setup:oh-my-zsh # optional: sets up Oh My Zsh with auto-completions & "aliases"
116
+
117
+ buddy upgrade # upgrades the Stacks framework (alias: buddy update)
118
+ buddy upgrade:dependencies # auto-upgrades package.json deps
119
+ buddy upgrade:shell # upgrades the shell integration
120
+ buddy upgrade:binary # upgrades the `stacks` binary
121
+ buddy upgrade:bun # upgrades to latest project-defined Bun version
122
+ buddy upgrade:all # auto-upgrades all of the above
123
+
124
+ # if you need any more info on any command listed here, you may suffix
125
+ # any of them via the "help option", i.e. `buddy ... --help`
126
+
127
+ buddy dev # starts the dev servers (frontend, api & docs)
128
+ buddy dev -i # prompts you to select which dev server to start
129
+ buddy dev:api # starts the API dev server
130
+ buddy dev:dashboard # starts the Admin/Dashboard dev server
131
+ buddy dev:desktop # starts the Desktop dev server
132
+ buddy dev:views # starts frontend dev server
133
+ buddy dev:components # starts component dev server
134
+ buddy dev:docs # starts local docs dev server
135
+ buddy dev docs # also starts the local docs dev server (dev takes the server name as an argument)
136
+
137
+ buddy share # creates a sharable link to your local project
138
+
139
+ # production servers (the same entries the deploy target runs as services)
140
+ buddy serve # starts the production HTTP server (STX views + /api proxy)
141
+ buddy serve:api # starts the production API server
142
+
143
+ # building for production (e.g. AWS, Google Cloud, npm, Vercel, Netlify, et al.)
144
+ buddy build # select a specific build (follow CLI prompts)
145
+ buddy build:frontend # builds the frontend (aliases: build:views, build:pages)
146
+ buddy build:desktop # builds Desktop application
147
+ buddy build:mobile # builds both native iOS and Android applications
148
+ buddy build:ios # builds the native iOS application
149
+ buddy build:android # builds the native Android application
150
+ buddy build:functions # builds function library
151
+ buddy build:components # builds the STX component library and Web Component library
152
+ buddy build:web-components # builds framework agnostic Web Component library (i.e. Custom Elements)
153
+ buddy build:cli # builds the Buddy CLI binary
154
+ buddy build:server # builds the Stacks cloud server (Docker image)
155
+ buddy build:docs # builds the documentation site
156
+
157
+ # `buddy build:*` aliases
158
+ buddy prod:components # alias for build:components
159
+ buddy prod:desktop # alias for build:desktop
160
+ buddy prod:mobile # alias for build:mobile
161
+ buddy prod:ios # alias for build:ios
162
+ buddy prod:android # alias for build:android
163
+ buddy prod:web-components # alias for build:web-components
164
+ buddy prod:frontend # alias for build:frontend
165
+ buddy prod:cli # alias for build:cli
166
+ buddy prod:server # alias for build:server
167
+ buddy prod:docs # alias for build:docs
168
+ buddy prod:frontend-static # alias for build:frontend-static
169
+
170
+ # sets your application key
171
+ buddy key:generate
172
+
173
+ buddy make:component HelloWorld # bootstraps a HelloWorld component
174
+ buddy make:function hello-world # bootstraps a hello-world function
175
+ buddy make:view hello-world # bootstraps a hello-word page
176
+ buddy make:model Car # bootstraps a Car model
177
+ buddy make:database cars # prints guidance: tables come from models + migrations, there is no separate create step
178
+ buddy make:migration create_cars_table # creates a cars migration file
179
+ buddy make:factory cars # creates a Car factory file
180
+ buddy make:notification welcome-email # bootstraps a welcome-email notification
181
+ buddy make:lang de # bootstraps a lang/de.yml language file
182
+ buddy make:stack my-plugin # scaffolds a project-shaped registry stack (new project? use `panx buddy new`)
183
+
184
+ buddy migrate # runs database migrations
185
+ buddy migrate:fresh # drops all tables & re-runs migrations (destroys all data; --seed reseeds)
186
+ buddy dns:pull # prints the live zone as a ./config/dns.ts block
187
+ buddy seed # runs database seeders
188
+
189
+ buddy dns example.com # list all DNS records for example.com
190
+ buddy dns example.com --type MX # list MX records for example.com
191
+
192
+ buddy http example.com/api/hello # sends a GET request & prints the response
193
+ buddy http -v example.com/api/get # same, with verbose output
194
+
195
+ buddy lint # runs linter
196
+ buddy lint:fix # runs linter and fixes issues
197
+ buddy format # formats your project codebase
198
+ buddy format:check # checks formatting without making changes
199
+
200
+ buddy commit # follow CLI prompts for committing staged changes
201
+ buddy release # creates the releases for the stack & triggers the Release Action (workflow)
202
+ buddy changelog # generates CHANGELOG.md
203
+
204
+ # when deploying your app/s to a remote server or cloud provider
205
+ buddy deploy # select a specific deployment (follow CLI prompts)
206
+ buddy undeploy # be careful: "undeploys" removes/deletes your deployed resources (--yes skips the confirmation)
207
+
208
+ buddy cloud:remove # removes cloud setup
209
+ buddy cloud:cleanup # removes cloud setup & cleans up all potentially leftover resources
210
+ buddy cloud:add --jump-box # adds a jump box to your cloud setup
211
+
212
+ # you likely won’t need to run these commands as they are auto-triggered, but they are available
213
+ buddy generate # prompts you to select which generator to run
214
+ buddy generate:types # generates types for your components, functions, & views
215
+ buddy generate:entries # generates entry files for components, functions, & views
216
+ buddy generate:web-types # generates Web Component types
217
+ buddy generate:vscode-custom-data # generates VSCode custom data
218
+ buddy generate:ide-helpers # generates IDE helpers
219
+ buddy generate:component-meta # generates component meta
220
+
221
+ # generates your application key
222
+ buddy key:generate # generates your application key
223
+
224
+ # manage your environment variables
225
+ buddy env:get # get an environment variable
226
+ buddy env:set # set an environment variable
227
+ buddy env:encrypt # encrypt an environment variable
228
+ buddy env:decrypt # decrypt an environment variable
229
+ buddy env:keypair # generate a keypair
230
+ buddy env:rotate # rotate a keypair
231
+
232
+ # generate your TypeScript declarations
233
+ buddy types:generate # generates types for your components, functions, & views
234
+ buddy types:fix # auto-fixes types for your components, functions, & views
235
+
236
+ buddy domains:add stacksjs.com # adds a domain
237
+ buddy domains:remove stacksjs.com # removes a domain
238
+ buddy domains:purchase stacksjs.com # purchase a new domain
239
+
240
+ # handy utilities
241
+ buddy doctor # runs health checks on your Stacks installation
242
+ buddy list # lists all available Buddy commands
243
+ buddy route:list # lists your routes
244
+ buddy ports # checks your project for port issues & misconfigurations
245
+ buddy outdated # lists outdated project dependencies
246
+ buddy env:check # checks your environment configuration & validates setup
247
+ buddy tinker # interactive REPL with the Stacks framework preloaded
248
+ buddy down # puts the app into maintenance mode
249
+ buddy up # brings the app out of maintenance mode
250
+
251
+ # test your stack
252
+ buddy test # runs your test suite
253
+ buddy test:unit # runs unit tests
254
+ buddy test:feature # runs feature tests
255
+ buddy test:types # runs typecheck
256
+
257
+ # the published @stacksjs/buddy package ships
258
+ # `buddy`, `bud`, & `stx` bins; inside this repo
259
+ # the CLI is invoked as ./buddy
260
+ ./buddy fresh
261
+ ```
262
+
263
+ </details>
264
+
265
+ Read more about the Buddy CLI in the [official docs](https://stacksjs.com/docs/guide/buddy/commands): every command, every flag, every prompt explained.
266
+
267
+ ## Features
268
+
269
+ The Stacks framework is a harmony of several “engines” to build any web and/or desktop application, in highly scalable & privacy-friendly ways. It consists of the following engines:
270
+
271
+ ### Frontend Development
272
+
273
+ _Develop dynamic UIs with helpers for atomic design, and much more._
274
+
275
+ - 🧩 **Components** _primitive to develop user interfaces_
276
+ - 🤖 **Functions** _primitive to develop business logic (and grant your UI superpowers)_
277
+ - 🎨 **UI Kit** _modern & deeply-integrated components_
278
+ - 🌐 **Web** _“a routing & templating engine that makes sense”_
279
+ - 🖥️ **Desktop** _transforms your web app into a desktop app, plus more_
280
+ - 📝 **Documentation** _markdown-based documentation, auto-generated_
281
+ - 📚 **Library** _auto-builds & manages component & function libraries_
282
+ - ⚡️ Powered by Bun, Craft, Headwind
283
+
284
+ ### Backend Development
285
+
286
+ _Develop serverless (or server) functions with countless helpers to build scalable & fast APIs._
287
+
288
+ - 🪄 **AI** _deep AI integrations to simplify building agentic workflow_
289
+ - 🤖 **APIs** _scalability & maintainability built-in_
290
+ - 🏎️ **Cache** _unified caching for DynamoDB, Redis and more_
291
+ - ⚙️ **CLIs** _create beautiful CLIs for Linux, Windows, and Mac (dependency-free binaries)_
292
+ - 🛍️ **Commerce** _own & grow your own online business with ease (SaaS-optimized)_
293
+ - 📀 **Database** _DynamoDB, SQLite, MySQL, Postgres, and more_
294
+ - 👾 **Errors** _native type-safe error handling_
295
+ - 🗓️ **Events** _functional event (front & backend) communication_
296
+ - 📢 **Notifications** _emails, SMSs, direct, and push notifications & webhooks_
297
+ - 🗺️ **ORM** _automated schemas for scale & a pretty API_
298
+ - 💳 **Payments** _unified API for one-off & subscription billing methods for Stripe_
299
+ - ⚙️ **Queues** _run any heavy workload in the background_
300
+ - 🛠️ **Query Builder** _powerful, type-safe SQL query builder_
301
+ - 💬 **Realtime** _“everything you need to build dynamic real-time apps”_
302
+ - 🧭 **Router** _smart routing, file-based or Laravel-like_
303
+ - 🔎 **Search Engine** _smart searching, advanced filtering & sorting, pagination, headless UI_
304
+ - 💾 **Storage** _a secure-by-default File API that feels right_
305
+ - 🧪 **Tinker** _a powerful TypeScript REPL_
306
+ - 🌪️ **Validation** _e2e type-safety (true frontend & backend harmony)_
307
+
308
+ ### Cloud Development
309
+
310
+ _Develop & maintain cloud infrastructure with ease. “Imagine Vercel, Vapor and Forge having been unified.”_
311
+
312
+ - ☁️ **Server** _local development server & production-ready servers out-of-the-box_
313
+ - ⛅️ **Serverless** _on-demand, auto-scaling, zero maintenance_
314
+ - ⏰ **Alarms** _built-in cloud infrastructure monitoring to avoid surprises_
315
+ - 🚏 **CDN** _zero-config, low-latency, request life-cycle hooks, optimized request compressions (Brotli & gzip)_
316
+ - 🔀 **Domain** _version-controlled & zero-config domain management (e.g. DNS management)_
317
+ - 🤖 **AI** _fine-tune a foundational model using your application data_
318
+ - 📧 **Email** _secure & zero-setup <easy-peasy@custom-domains.com> mailboxes_
319
+ - 🔐 **Firewall** _native web application firewall support_
320
+ - 📦 **Storage** _unlimited cloud storage & automatic backups_
321
+ - 🚜 **Maintenance** _maintain your cloud infrastructure with ease using Buddy & Stacks_
322
+ - 🚦 **Infrastructure as Code** _version-controlled cloud infrastructure (AWS, Google next?)_
323
+
324
+ ### CI/CD
325
+
326
+ _Focus on coding, not publishing._
327
+
328
+ - 🚀 **Deployment Manager** _takes the sweat out of production deployments—zero-setup push-to-deploy_
329
+ - 0️⃣ **Zero Downtime** _deploy with confidence using a zero-downtime deployment strategy_
330
+ - 📫 **Release Manager** _libraries (component & function) auto-published to npm, git helpers, and more_
331
+
332
+ ### Developer Experience (DX)
333
+
334
+ Convention over configuration, while staying wholly configurable. _No more boilerplate._
335
+
336
+ - 🧠 **LLM-Friendly Authoring** _models generate compact application intent instead of repeating framework glue or reading `node_modules`_
337
+ - 💎 **Automated Upgrades** _no need to worry about upgrading to the latest versions, Stacks upgrades you_
338
+ - 🦋 **Pretty Dev URLs** _your-project.localhost instead of localhost:3000_
339
+ - 💡 **IDE Integration** _auto-completions, inline docs & a powerful IDE setup_
340
+ - 🪄 **Zero-Config** _yet highly configurable—convention over configuration_
341
+ - 💅 **Linter & Formatter** _auto-configured & built into your IDE_
342
+ - 💪🏼 **Type Strong** _built-in e2e type-safety_
343
+ - ✨ **Git Workflows** _committing with ease_
344
+ - 🚗 **Auto Imports** _your components & functions, including date, string, array, & object helpers_
345
+ - ⏩ **Code Snippets** _goodbye to the boilerplate code—thank you Sarah Drasner_
346
+ - 🔤 **Spell Checker** _be notified once there are typos_
347
+ - 🛠️ **Essential Utilities** _powers at your fingertips. Collections, STX composables, and more_
348
+ - 👥 **Team Management** _manage your team & their permissions_
349
+ - 🧪 **Streamlined Testing** _unit, feature & component tests powered by Bun & very-happy-dom_
350
+
351
+ No matter whether you are a beginner or an expert, the approachable Stacks design allows you to learn at your own pace, using our thorough documentation covering every aspect of the framework. Stacks is extremely beginner & expert-friendly.
352
+
353
+ Develop beautiful, reactive, composable UIs without learning a new set of languages. HTML, CSS, and minimal JavaScript—that’s all you need to dive in now! _Or TypeScript ✌🏼_
354
+
355
+ > _An actual rapid application development framework for all Full Stack needs. Next-level simplicity & DX._
356
+
357
+ ## Testing
358
+
359
+ ```bash
360
+ ./buddy test
361
+ ```
362
+
363
+ ## Changelog
364
+
365
+ Please see our [releases](https://github.com/stacksjs/stacks/releases) page for more information on what has changed recently.
366
+
367
+ ## Contributing
368
+
369
+ Please see the [Contributing Guide](https://github.com/stacksjs/contributing) for details.
370
+
371
+ ## Community
372
+
373
+ For help, discussion about best practices, or any other conversation that would benefit from being searchable:
374
+
375
+ [Discussions on GitHub](https://github.com/stacksjs/stacks/discussions)
376
+
377
+ For casual chit-chat with others using this package:
378
+
379
+ [Join the Stacks Discord Server](https://stacksjs.com/discord)
380
+
381
+ To hear when 1.0 lands, leave your email at [stacksjs.com](https://stacksjs.com). The site is in
382
+ its pre-launch state, so that signup is currently the shortest path to being told when
383
+ something changes.
384
+
385
+ ## Postcardware
386
+
387
+ “Software that is free, but hopes for a postcard.” We love receiving postcards from around the world showing where Stacks is being used! We showcase them on our website too.
388
+
389
+ Our address: Stacks.js, 12665 Village Ln #2306, Playa Vista, CA 90094, United States 🌎
390
+
391
+ ## Sponsors
392
+
393
+ We would like to extend our thanks to the following sponsors for funding Stacks development. If you are interested in becoming a sponsor, please reach out to us.
394
+
395
+ - [JetBrains](https://www.jetbrains.com/)
396
+ - [The Solana Foundation](https://solana.com/)
397
+
398
+ ## Credits
399
+
400
+ - [Laravel](https://laravel.com) _many thanks to their community_
401
+ - [Chris Breuer](https://github.com/chrisbbreuer)
402
+ - [All Contributors](../../contributors)
403
+
404
+ And a special thanks to [Dan Scanlon](https://twitter.com/danscan) for donating the `stacks` name on npm ✨
405
+
406
+ ## License
407
+
408
+ The MIT License (MIT). Please see [LICENSE](LICENSE.md) for more information.
409
+
410
+ Made with 💙
411
+
412
+ <!-- Badges -->
413
+ [npm-version-src]: https://img.shields.io/npm/v/stacks?style=flat-square
414
+ [npm-version-href]: https://npmjs.com/package/stacks
415
+
416
+ [npm-downloads-src]: https://img.shields.io/npm/dm/stacks?style=flat-square
417
+ [npm-downloads-href]: https://npmjs.com/package/stacks
418
+
419
+ [github-actions-src]: https://img.shields.io/github/actions/workflow/status/stacksjs/stacks/ci.yml?style=flat-square&branch=main
420
+ [github-actions-href]: https://github.com/stacksjs/stacks/actions?query=workflow%3Aci
421
+
422
+ <!-- [codecov-src]: https://img.shields.io/codecov/c/gh/stacksjs/stacks/main?style=flat-square
423
+ [codecov-href]: https://codecov.io/gh/stacksjs/buddy -->
@@ -0,0 +1,26 @@
1
+ import type { MalwareConfig, MalwareSurface } from '@stacksjs/types';
2
+ /**
3
+ * The effective malware config: framework defaults, then `config/malware.ts`,
4
+ * then anything set with {@link configureMalware}. Nested objects merge; they
5
+ * are never replaced whole.
6
+ */
7
+ export declare function malwareConfig(): ResolvedMalwareConfig;
8
+ /**
9
+ * Override the malware config at runtime, merged over `config/malware.ts`.
10
+ * Mostly for tests: `configureMalware({ driver: 'eicar' })`.
11
+ */
12
+ export declare function configureMalware(options: Partial<MalwareConfig>): void;
13
+ /** Drop every runtime override and cached driver. */
14
+ export declare function resetMalwareConfig(): void;
15
+ /** @internal Called when the config changes, so cached drivers are rebuilt. */
16
+ export declare function onMalwareConfigChange(listener: () => void): void;
17
+ /** Whether a surface scans. A surface left out of `surfaces` scans. */
18
+ export declare function scanEnabled(surface: MalwareSurface): boolean;
19
+ export declare interface ResolvedMalwareConfig extends MalwareConfig {
20
+ failClosed: boolean
21
+ maxScanBytes: number
22
+ timeoutMs: number
23
+ quarantine: { enabled: boolean, path: string }
24
+ staging: { prefix: string }
25
+ surfaces: Partial<Record<MalwareSurface, boolean>>
26
+ }
package/dist/config.js ADDED
@@ -0,0 +1 @@
1
+ import{config}from"@stacksjs/config";const DEFAULTS={driver:"auto",failClosed:true,maxScanBytes:512*1024*1024,timeoutMs:30000,quarantine:{enabled:true,path:"storage/quarantine"},staging:{prefix:"incoming/"},surfaces:{}};let overrides=null;let listeners=[];function appConfig(){try{return config.malware??{}}catch{return{}}}export function malwareConfig(){const app=appConfig();const runtime=overrides??{};return{...DEFAULTS,...app,...runtime,clamd:{...app.clamd,...runtime.clamd},guardian:{...app.guardian,...runtime.guardian},quarantine:{...DEFAULTS.quarantine,...app.quarantine,...runtime.quarantine},staging:{...DEFAULTS.staging,...app.staging,...runtime.staging},surfaces:{...app.surfaces,...runtime.surfaces},driver:runtime.driver??app.driver??DEFAULTS.driver,failClosed:runtime.failClosed??app.failClosed??DEFAULTS.failClosed,maxScanBytes:runtime.maxScanBytes??app.maxScanBytes??DEFAULTS.maxScanBytes,timeoutMs:runtime.timeoutMs??app.timeoutMs??DEFAULTS.timeoutMs}}export function configureMalware(options){overrides={...overrides,...options};for(const listener of listeners)listener()}export function resetMalwareConfig(){overrides=null;for(const listener of listeners)listener()}export function onMalwareConfigChange(listener){listeners=[...listeners,listener]}export function scanEnabled(surface){return malwareConfig().surfaces[surface]!==false}
@@ -0,0 +1,17 @@
1
+ import type { DriverScanContext, DriverScanResult, MalwareDriver, MalwareHealth } from './types';
2
+ export declare function describeEndpoint(endpoint: ClamdEndpoint): string;
3
+ /**
4
+ * Read a clamd reply line. `stream: OK`, `stream: <name> FOUND`, or anything
5
+ * ending in `ERROR`. Heuristic and PUA matches are `suspicious`, not `infected`.
6
+ */
7
+ export declare function parseScanReply(reply: string): DriverScanResult;
8
+ /** Send one `z`-prefixed command and return the reply. */
9
+ export declare function command(endpoint: ClamdEndpoint, name: 'PING' | 'VERSION', timeoutMs?: number): Promise<string>;
10
+ export declare function instream(endpoint: ClamdEndpoint, chunks: AsyncIterable<Uint8Array>, context: DriverScanContext): Promise<DriverScanResult>;
11
+ export declare function pingHealth(name: string, endpoint: ClamdEndpoint): Promise<MalwareHealth>;
12
+ export declare function clamdDriver(endpoint: ClamdEndpoint, name?: string): MalwareDriver;
13
+ export declare interface ClamdEndpoint {
14
+ socket?: string
15
+ host?: string
16
+ port?: number
17
+ }
@@ -0,0 +1 @@
1
+ import{createConnection}from"node:net";export function describeEndpoint(endpoint){if(endpoint.socket)return endpoint.socket;return`${endpoint.host??"127.0.0.1"}:${endpoint.port??3310}`}function connect(endpoint,timeoutMs){return new Promise((resolve,reject)=>{const socket=endpoint.socket?createConnection({path:endpoint.socket}):createConnection({host:endpoint.host??"127.0.0.1",port:endpoint.port??3310});const fail=(error)=>{socket.destroy();reject(error)};socket.setTimeout(timeoutMs,()=>fail(new Error(`connection to ${describeEndpoint(endpoint)} timed out`)));socket.once("error",fail);socket.once("connect",()=>{socket.off("error",fail);resolve(socket)})})}function collectReply(socket){return new Promise((resolve,reject)=>{const parts=[];let settled=false;const finish=()=>{if(settled)return;settled=true;resolve(Buffer.concat(parts).toString("utf8").replace(/[\0\r\n]+$/g,"").replace(/\0/g,""))};socket.on("data",(chunk)=>{parts.push(chunk);if(chunk.includes(0))finish()});socket.once("end",finish);socket.once("close",finish);socket.once("error",(error)=>{if(parts.length>0)finish();else if(!settled){settled=true;reject(error)}})})}function write(socket,bytes){return new Promise((resolve,reject)=>{if(socket.destroyed){reject(new Error("scanner closed the connection"));return}const ok=socket.write(bytes,(error)=>{if(error)reject(error)});if(ok){resolve();return}const onDrain=()=>{cleanup();resolve()};const onClose=()=>{cleanup();reject(new Error("scanner closed the connection"))};const cleanup=()=>{socket.off("drain",onDrain);socket.off("close",onClose)};socket.once("drain",onDrain);socket.once("close",onClose)})}export function parseScanReply(reply){const line=reply.trim();const body=line.replace(/^(?:\d+: )?stream: ?/,"");if(body==="OK")return{verdict:"clean"};const found=/^(.*) FOUND$/.exec(body);if(found){const signature=(found[1]??"").trim();const suspicious=/^(?:Heuristics?|PUA)\./i.test(signature);return{verdict:suspicious?"suspicious":"infected",signature}}if(/ERROR$/.test(body))return{verdict:"error",error:body.replace(/\s*ERROR$/,"")||"scanner error"};return{verdict:"error",error:line?`unexpected scanner reply: ${line.slice(0,120)}`:"scanner closed the connection without a verdict"}}export async function command(endpoint,name,timeoutMs=5000){const socket=await connect(endpoint,timeoutMs);try{const reply=collectReply(socket);await write(socket,new TextEncoder().encode(`z${name}\x00`));return await reply}finally{socket.destroy()}}export async function instream(endpoint,chunks,context){let socket;try{socket=await connect(endpoint,context.timeoutMs)}catch(error){return{verdict:"error",error:`scanner unreachable at ${describeEndpoint(endpoint)}: ${error.message}`}}let bytes=0;let timedOut=false;socket.setTimeout(context.timeoutMs,()=>{timedOut=true;socket.destroy()});const reply=collectReply(socket).catch((error)=>`${error.message} ERROR`);try{await write(socket,new TextEncoder().encode("zINSTREAM\x00"));const header=new Uint8Array(4);const view=new DataView(header.buffer);for await(const chunk of chunks){bytes+=chunk.byteLength;if(bytes>context.maxScanBytes){socket.destroy();return{verdict:"error",bytes,error:`input exceeds maxScanBytes (${context.maxScanBytes})`}}view.setUint32(0,chunk.byteLength);await write(socket,header.slice());await write(socket,chunk)}await write(socket,new Uint8Array(4))}catch(error){if(timedOut){socket.destroy();return{verdict:"error",bytes,error:`scan timed out after ${context.timeoutMs} ms idle`}}const early=await Promise.race([reply,new Promise((r)=>setTimeout(()=>r(""),50))]);socket.destroy();if(early)return{...parseScanReply(early),bytes};return{verdict:"error",bytes,error:error.message}}const text=await reply;socket.destroy();if(timedOut)return{verdict:"error",bytes,error:`scan timed out after ${context.timeoutMs} ms idle`};return{...parseScanReply(text),bytes}}export async function pingHealth(name,endpoint){const where=describeEndpoint(endpoint);try{const pong=await command(endpoint,"PING");if(pong!=="PONG")return{ok:false,driver:name,endpoint:where,error:`unexpected PING reply: ${pong.slice(0,60)}`};const version=await command(endpoint,"VERSION").catch(()=>{return});return{ok:true,driver:name,endpoint:where,version}}catch(error){return{ok:false,driver:name,endpoint:where,error:error.message}}}export function clamdDriver(endpoint,name="clamd"){return{name,scan:(chunks,context)=>instream(endpoint,chunks,context),health:()=>pingHealth(name,endpoint)}}
@@ -0,0 +1,19 @@
1
+ import { describeEndpoint } from './clamd';
2
+ import type { MalwareDriver, MalwareHealth } from './types';
3
+ import type { ResolvedMalwareConfig } from '../config';
4
+ /**
5
+ * Register a custom driver, then select it with `driver: '<name>'` in
6
+ * `config/malware.ts`. Built-in names cannot be replaced.
7
+ */
8
+ export declare function registerMalwareDriver(name: string, factory: () => MalwareDriver): void;
9
+ /** The driver the current config selects, built once and reused. */
10
+ export declare function currentDriver(config: ResolvedMalwareConfig): Promise<MalwareDriver>;
11
+ export declare function driverHealth(config: ResolvedMalwareConfig): Promise<MalwareHealth>;
12
+ /** Where zavd listens when `guardian.socket` is not set. */
13
+ export declare const DEFAULT_ZAVD_SOCKET: '/run/zavd/zavd.sock';
14
+ /**
15
+ * Sockets `auto` tries, zavd first, then the usual clamd locations.
16
+ * @defaultValue `['/var/run/zavd/zavd.sock', '/var/run/clamav/clamd.ctl', '/run/clamav/clamd.ctl', '/var/run/clamd.scan/clamd.sock', '/opt/homebrew/var/run/clamav/clamd.sock', '/usr/local/var/run/clamav/clamd.sock', '/tmp/clamd.socket']`
17
+ */
18
+ export declare const PROBED_SOCKETS: (unknown | string)[];
19
+ export { describeEndpoint };
@@ -0,0 +1 @@
1
+ import{existsSync}from"node:fs";import{log}from"@stacksjs/logging";import{onMalwareConfigChange}from"../config";import{clamdDriver,command,describeEndpoint}from"./clamd";import{eicarDriver,noneDriver}from"./simple";export const DEFAULT_ZAVD_SOCKET="/run/zavd/zavd.sock";export const PROBED_SOCKETS=[DEFAULT_ZAVD_SOCKET,"/var/run/zavd/zavd.sock","/var/run/clamav/clamd.ctl","/run/clamav/clamd.ctl","/var/run/clamd.scan/clamd.sock","/opt/homebrew/var/run/clamav/clamd.sock","/usr/local/var/run/clamav/clamd.sock","/tmp/clamd.socket"];const custom=new Map;let cached=null;const AUTO_NONE_RETRY_MS=60000;const warned=new Set;onMalwareConfigChange(()=>{cached=null});function warnOnce(key,message){if(warned.has(key))return;warned.add(key);Promise.resolve(log.warn(message)).catch(()=>{})}export function registerMalwareDriver(name,factory){if(["auto","guardian","clamd","eicar","none"].includes(name))throw new Error(`[malware] '${name}' is a built-in driver`);custom.set(name,factory);cached=null}function clamdEndpoint(config){const c=config.clamd??{};if(c.socket)return{socket:c.socket};if(c.port||c.host)return{host:c.host??"127.0.0.1",port:c.port??3310};return{socket:"/var/run/clamav/clamd.ctl"}}async function answers(endpoint){try{return await command(endpoint,"PING",1500)==="PONG"}catch{return false}}async function resolveAuto(config){const candidates=[];if(config.guardian?.socket)candidates.push({socket:config.guardian.socket});if(config.clamd?.socket)candidates.push({socket:config.clamd.socket});if(config.clamd?.port||config.clamd?.host)candidates.push({host:config.clamd.host??"127.0.0.1",port:config.clamd.port??3310});for(const socket of PROBED_SOCKETS){if(existsSync(socket))candidates.push({socket})}candidates.push({host:"127.0.0.1",port:3310});for(const endpoint of candidates){if(await answers(endpoint))return clamdDriver(endpoint,"auto:clamd")}warnOnce("auto-none","[malware] no zavd or clamd scanner answered; uploads are NOT scanned. Run zavd or clamd, or set `driver` in config/malware.ts (`none` to silence this).");return{...noneDriver(),name:"auto:none"}}function build(name,config){switch(name){case"none":warnOnce("none","[malware] scanning is disabled (driver: none)");return Promise.resolve(noneDriver());case"eicar":warnOnce("eicar","[malware] driver `eicar` only detects the EICAR test file; it is not protection");return Promise.resolve(eicarDriver());case"clamd":return Promise.resolve(clamdDriver(clamdEndpoint(config)));case"guardian":return Promise.resolve(clamdDriver({socket:config.guardian?.socket??DEFAULT_ZAVD_SOCKET},"guardian"));case"auto":return resolveAuto(config);default:{const factory=custom.get(name);if(!factory)throw new Error(`[malware] unknown driver '${name}'`);return Promise.resolve(factory())}}}export function currentDriver(config){const key=JSON.stringify([config.driver,config.clamd,config.guardian,[...custom.keys()]]);if(!cached||cached.key!==key||Date.now()>cached.expiresAt){const driver=build(config.driver,config);const entry={key,driver,expiresAt:Number.POSITIVE_INFINITY};cached=entry;driver.then((d)=>{if(d.name==="auto:none")entry.expiresAt=Date.now()+AUTO_NONE_RETRY_MS},()=>{});driver.catch(()=>{if(cached?.driver===driver)cached=null})}return cached.driver}export async function driverHealth(config){try{const driver=await currentDriver(config);return await driver.health()}catch(error){return{ok:false,driver:String(config.driver),error:error.message}}}export{describeEndpoint};
@@ -0,0 +1,16 @@
1
+ import type { MalwareDriver } from './types';
2
+ /** The EICAR test file as bytes, for tests. */
3
+ export declare function eicarBytes(): Uint8Array;
4
+ /**
5
+ * Detects the EICAR string anywhere in the input, across chunk boundaries,
6
+ * and nothing else. Meant for test suites and local development without a
7
+ * daemon: it is not protection.
8
+ */
9
+ export declare function eicarDriver(): MalwareDriver;
10
+ /** Always clean. Consumes the input so a stream tee is never left blocked. */
11
+ export declare function noneDriver(): MalwareDriver;
12
+ /**
13
+ * The 68-byte EICAR anti-malware test file. Every scanner reports it as
14
+ * `Eicar-Test-Signature` (or a close variant), and it is harmless.
15
+ */
16
+ export declare const EICAR: 'X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*';
@@ -0,0 +1 @@
1
+ export const EICAR="X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*";const EICAR_BYTES=new TextEncoder().encode(EICAR);export function eicarBytes(){return EICAR_BYTES.slice()}export function eicarDriver(){return{name:"eicar",async scan(chunks,context){const needle=EICAR_BYTES;const overlap=needle.byteLength-1;let tail=new Uint8Array(0);let bytes=0;let found=false;for await(const chunk of chunks){bytes+=chunk.byteLength;if(bytes>context.maxScanBytes)return{verdict:"error",bytes,error:`input exceeds maxScanBytes (${context.maxScanBytes})`};if(found)continue;const window=new Uint8Array(tail.byteLength+chunk.byteLength);window.set(tail,0);window.set(chunk,tail.byteLength);if(Buffer.from(window.buffer,window.byteOffset,window.byteLength).indexOf(needle)!==-1)found=true;tail=window.slice(Math.max(0,window.byteLength-overlap))}return found?{verdict:"infected",signature:"Eicar-Test-Signature",bytes}:{verdict:"clean",bytes}},health:async()=>({ok:true,driver:"eicar"})}}export function noneDriver(){return{name:"none",async scan(chunks){let bytes=0;for await(const chunk of chunks)bytes+=chunk.byteLength;return{verdict:"clean",bytes}},health:async()=>({ok:true,driver:"none",error:"scanning is disabled"})}}
@@ -0,0 +1,20 @@
1
+ import type { MalwareScanResult } from '@stacksjs/types';
2
+ export declare interface DriverScanContext {
3
+ maxScanBytes: number
4
+ timeoutMs: number
5
+ }
6
+ export declare interface MalwareHealth {
7
+ ok: boolean
8
+ driver: string
9
+ version?: string
10
+ endpoint?: string
11
+ error?: string
12
+ }
13
+ /** A scanner backend. Register custom ones with `registerMalwareDriver()`. */
14
+ export declare interface MalwareDriver {
15
+ readonly name: string
16
+ scan: (chunks: AsyncIterable<Uint8Array>, context: DriverScanContext) => Promise<DriverScanResult>
17
+ health: () => Promise<MalwareHealth>
18
+ }
19
+ /** What a driver reports. `scan()` adds the duration and the driver name. */
20
+ export type DriverScanResult = Omit<MalwareScanResult, 'durationMs' | 'driver'>;
File without changes
@@ -0,0 +1,33 @@
1
+ import type { MalwareScanResult, MalwareSurface } from '@stacksjs/types';
2
+ /** Either refusal from the scanner. */
3
+ export declare function isMalwareRefusal(error: unknown): error is MalwareDetectedError | MalwareScanError;
4
+ /**
5
+ * A scan found malware (`infected` or `suspicious`). The message is neutral
6
+ * on purpose: it is safe to show to an anonymous caller. The signature name
7
+ * is on `signature` and `result` for logs, never in `message`.
8
+ */
9
+ export declare class MalwareDetectedError extends Error {
10
+ /** @defaultValue 'MALWARE_DETECTED' */
11
+ readonly code: string;
12
+ /** @defaultValue 422 */
13
+ readonly status: number;
14
+ readonly signature: string | undefined;
15
+ readonly result: MalwareScanResult;
16
+ readonly surface: MalwareSurface | undefined;
17
+ readonly quarantineId: string | undefined;
18
+ readonly intendedPath: string | undefined;
19
+ constructor(result: MalwareScanResult, options?: { surface?: MalwareSurface, quarantineId?: string, intendedPath?: string });
20
+ }
21
+ /**
22
+ * The scanner could not answer (unreachable, timed out, input too large) and
23
+ * `failClosed` is on, so the input is treated as not clean.
24
+ */
25
+ export declare class MalwareScanError extends Error {
26
+ /** @defaultValue 'MALWARE_SCAN_FAILED' */
27
+ readonly code: string;
28
+ /** @defaultValue 503 */
29
+ readonly status: number;
30
+ readonly result: MalwareScanResult;
31
+ readonly surface: MalwareSurface | undefined;
32
+ constructor(result: MalwareScanResult, options?: { surface?: MalwareSurface });
33
+ }
package/dist/errors.js ADDED
@@ -0,0 +1 @@
1
+ export class MalwareDetectedError extends Error{code="MALWARE_DETECTED";status=422;signature;result;surface;quarantineId;intendedPath;constructor(result,options={}){super("The file was rejected by the malware scanner.");this.name="MalwareDetectedError";this.result=result;this.signature=result.signature;this.surface=options.surface;this.quarantineId=options.quarantineId;this.intendedPath=options.intendedPath}}export class MalwareScanError extends Error{code="MALWARE_SCAN_FAILED";status=503;result;surface;constructor(result,options={}){super("The file could not be checked for malware. Try again later.");this.name="MalwareScanError";this.result=result;this.surface=options.surface}}export function isMalwareRefusal(error){return error instanceof MalwareDetectedError||error instanceof MalwareScanError||typeof error==="object"&&error!==null&&["MALWARE_DETECTED","MALWARE_SCAN_FAILED"].includes(error.code??"")}
@@ -0,0 +1,21 @@
1
+ export type { DriverScanContext, DriverScanResult, MalwareDriver, MalwareHealth } from './drivers/types';
2
+ export type { MalwareConfig, MalwareDriverName, MalwareScanResult, MalwareSurface, MalwareVerdict } from '@stacksjs/types';
3
+ /**
4
+ * `@stacksjs/malware`: one `scan()` call for every Stacks upload surface.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * import { assertClean, scan } from '@stacksjs/malware'
9
+ *
10
+ * const result = await scan(bytes) // { verdict: 'clean' | 'infected' | 'suspicious' | 'error', ... }
11
+ * await assertClean(bytes, { surface: 'storage', originalName: file.name }) // throws unless clean
12
+ * ```
13
+ */
14
+ export { configureMalware, malwareConfig, resetMalwareConfig, scanEnabled, type ResolvedMalwareConfig } from './config';
15
+ export { clamdDriver, parseScanReply, type ClamdEndpoint } from './drivers/clamd';
16
+ export { DEFAULT_ZAVD_SOCKET, PROBED_SOCKETS, registerMalwareDriver } from './drivers/resolve';
17
+ export { EICAR, eicarBytes, eicarDriver, noneDriver } from './drivers/simple';
18
+ export { isMalwareRefusal, MalwareDetectedError, MalwareScanError } from './errors';
19
+ export { FRAME_BYTES, toChunks, type ScanInput } from './input';
20
+ export { deleteQuarantined, listQuarantine, quarantine, quarantineRoot, type QuarantineMeta, type QuarantineRecord } from './quarantine';
21
+ export { assertClean, health, isClean, malwareScanCount, rememberedVerdict, rememberVerdict, scan, type AssertCleanOptions, type CleanVerdict, type ScanOptions } from './scan';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export{configureMalware,malwareConfig,resetMalwareConfig,scanEnabled}from"./config";export{clamdDriver,parseScanReply}from"./drivers/clamd";export{DEFAULT_ZAVD_SOCKET,PROBED_SOCKETS,registerMalwareDriver}from"./drivers/resolve";export{EICAR,eicarBytes,eicarDriver,noneDriver}from"./drivers/simple";export{isMalwareRefusal,MalwareDetectedError,MalwareScanError}from"./errors";export{FRAME_BYTES,toChunks}from"./input";export{deleteQuarantined,listQuarantine,quarantine,quarantineRoot}from"./quarantine";export{assertClean,health,isClean,malwareScanCount,rememberedVerdict,rememberVerdict,scan}from"./scan";
@@ -0,0 +1,28 @@
1
+ /** Turn any {@link ScanInput} into chunks no larger than {@link FRAME_BYTES}. */
2
+ export declare function toChunks(input: ScanInput): AsyncIterable<Uint8Array>;
3
+ /** Largest frame a driver sends in one piece. clamd reads 4-byte-length frames. */
4
+ export declare const FRAME_BYTES: number;
5
+ /**
6
+ * Normalise every input `scan()` accepts into an async stream of chunks, so a
7
+ * driver only ever sees one shape and nothing is buffered whole that did not
8
+ * arrive whole.
9
+ */
10
+ /**
11
+ * What `scan()` accepts.
12
+ *
13
+ * - bytes (`Uint8Array`, `Buffer`, `ArrayBuffer`)
14
+ * - a `Blob` or `File`
15
+ * - a `ReadableStream<Uint8Array>`, read chunk by chunk
16
+ * - a file path, as a string or `{ path }`
17
+ * - an open file descriptor, as `{ fd }`
18
+ *
19
+ * A bare string is a path, never content: encode text with `TextEncoder` to
20
+ * scan it.
21
+ */
22
+ export type ScanInput = | Uint8Array
23
+ | ArrayBuffer
24
+ | Blob
25
+ | ReadableStream<Uint8Array>
26
+ | string
27
+ | { path: string }
28
+ | { fd: number }
package/dist/input.js ADDED
@@ -0,0 +1 @@
1
+ export const FRAME_BYTES=64*1024;function isReadableStream(value){return typeof value==="object"&&value!==null&&typeof value.getReader==="function"}async function*splitBytes(bytes){for(let offset=0;offset<bytes.byteLength;offset+=FRAME_BYTES)yield bytes.subarray(offset,Math.min(offset+FRAME_BYTES,bytes.byteLength))}async function*readStream(stream){const reader=stream.getReader();let finished=false;try{while(true){const{done,value}=await reader.read();if(done){finished=true;return}if(!value||value.byteLength===0)continue;if(value.byteLength>FRAME_BYTES)yield*splitBytes(value);else yield value}}finally{if(!finished)await reader.cancel().catch(()=>{});reader.releaseLock()}}export function toChunks(input){if(input instanceof Uint8Array)return splitBytes(input);if(input instanceof ArrayBuffer)return splitBytes(new Uint8Array(input));if(isReadableStream(input))return readStream(input);if(input instanceof Blob)return readStream(input.stream());if(typeof input==="string")return readStream(Bun.file(input).stream());if(typeof input==="object"&&input!==null&&"path"in input)return readStream(Bun.file(input.path).stream());if(typeof input==="object"&&input!==null&&"fd"in input)return readStream(Bun.file(input.fd).stream());throw new TypeError("scan() accepts bytes, a Blob, a ReadableStream, a path or { fd }")}
@@ -0,0 +1,29 @@
1
+ import type { MalwareScanResult, MalwareSurface } from '@stacksjs/types';
2
+ import type { ScanInput } from './input';
3
+ export declare function quarantineRoot(): string;
4
+ /**
5
+ * Store a refused file in quarantine. Returns `null` when quarantine is
6
+ * disabled. A stream that has already been read cannot be quarantined: pass
7
+ * bytes, a Blob or a path.
8
+ */
9
+ export declare function quarantine(input: ScanInput, result: MalwareScanResult, meta?: QuarantineMeta): Promise<QuarantineRecord | null>;
10
+ /** Every quarantined file, newest first. */
11
+ export declare function listQuarantine(): Promise<QuarantineRecord[]>;
12
+ /** Delete a quarantined file and its metadata for good. */
13
+ export declare function deleteQuarantined(id: string): Promise<boolean>;
14
+ export declare interface QuarantineMeta {
15
+ surface?: MalwareSurface
16
+ originalName?: string
17
+ intendedPath?: string
18
+ context?: Record<string, unknown>
19
+ }
20
+ export declare interface QuarantineRecord extends QuarantineMeta {
21
+ id: string
22
+ quarantinedAt: string
23
+ verdict: MalwareScanResult['verdict']
24
+ signature?: string
25
+ driver: string
26
+ bytes: number
27
+ sha256: string
28
+ file: string
29
+ }
@@ -0,0 +1,2 @@
1
+ import{chmod,mkdir,readdir,readFile,rm}from"node:fs/promises";import{isAbsolute,join,resolve}from"node:path";import process from"node:process";import{malwareConfig}from"./config";import{toChunks}from"./input";export function quarantineRoot(){const path=malwareConfig().quarantine.path;return isAbsolute(path)?path:resolve(process.cwd(),path)}export async function quarantine(input,result,meta={}){const config=malwareConfig();if(!config.quarantine.enabled)return null;const now=new Date;const id=`${now.toISOString().replace(/[-:.TZ]/g,"").slice(0,14)}-${crypto.randomUUID().slice(0,8)}`;const dir=join(quarantineRoot(),now.toISOString().slice(0,10));await mkdir(dir,{recursive:true,mode:448});const file=join(dir,`${id}.quarantined`);const hasher=new Bun.CryptoHasher("sha256");const sink=Bun.file(file).writer();let bytes=0;try{for await(const chunk of toChunks(input)){hasher.update(chunk);bytes+=chunk.byteLength;sink.write(chunk);await sink.flush()}}finally{await sink.end()}await chmod(file,384);const record={id,quarantinedAt:now.toISOString(),verdict:result.verdict,signature:result.signature,driver:result.driver,bytes,sha256:hasher.digest("hex"),file,...meta};const metaFile=join(dir,`${id}.json`);await Bun.write(metaFile,`${JSON.stringify(record,null,2)}
2
+ `);await chmod(metaFile,384);return record}export async function listQuarantine(){const root=quarantineRoot();let days;try{days=await readdir(root)}catch{return[]}const records=[];for(const day of days.sort().reverse()){let entries;try{entries=await readdir(join(root,day))}catch{continue}for(const entry of entries.filter((e)=>e.endsWith(".json")).sort().reverse()){try{records.push(JSON.parse(await readFile(join(root,day,entry),"utf8")))}catch{}}}return records}export async function deleteQuarantined(id){if(!/^[\w-]+$/.test(id))return false;const record=(await listQuarantine()).find((r)=>r.id===id);if(!record)return false;await rm(record.file,{force:true});await rm(record.file.replace(/\.quarantined$/,".json"),{force:true});return true}
package/dist/scan.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ import { quarantine } from './quarantine';
2
+ import type { MalwareDriverName, MalwareScanResult, MalwareSurface } from '@stacksjs/types';
3
+ import type { MalwareHealth } from './drivers/types';
4
+ import type { QuarantineMeta } from './quarantine';
5
+ import type { ScanInput } from './input';
6
+ /**
7
+ * Remember a verdict for an upload object (an `UploadedFile`, a `File`), so
8
+ * validation and storage scan it once between them.
9
+ */
10
+ export declare function rememberVerdict(file: object, result: MalwareScanResult): void;
11
+ /** The verdict remembered for an upload object, if any. */
12
+ export declare function rememberedVerdict(file: object): MalwareScanResult | undefined;
13
+ /** How many scans this process has run. For tests asserting "scanned once". */
14
+ export declare function malwareScanCount(): number;
15
+ /**
16
+ * Scan bytes, a Blob, a stream, a path or a file descriptor.
17
+ *
18
+ * Never throws for a scanner problem: an unreachable or failing scanner is
19
+ * `{ verdict: 'error' }`. Use {@link isClean} to decide, or
20
+ * {@link assertClean} to throw.
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * const result = await scan(await file.bytes())
25
+ * if (result.verdict === 'infected') console.log(result.signature)
26
+ * ```
27
+ */
28
+ export declare function scan(input: ScanInput, options?: ScanOptions): Promise<MalwareScanResult>;
29
+ /**
30
+ * Whether a verdict lets the input through. `error` counts as not clean
31
+ * unless `failClosed` is off.
32
+ */
33
+ export declare function isClean(result: MalwareScanResult, failClosed?: boolean): boolean;
34
+ /**
35
+ * Scan and throw unless clean: {@link MalwareDetectedError} for a detection
36
+ * (after quarantining the file), {@link MalwareScanError} when the scanner
37
+ * could not answer and `failClosed` is on. Returns the verdict otherwise.
38
+ *
39
+ * The signature is logged server side; the thrown message never names it.
40
+ */
41
+ export declare function assertClean(input: ScanInput, options?: AssertCleanOptions): Promise<CleanVerdict>;
42
+ /** Ask the configured scanner whether it is up, for the dashboard and `buddy doctor`. */
43
+ export declare function health(): Promise<MalwareHealth>;
44
+ export declare interface ScanOptions {
45
+ driver?: MalwareDriverName | string
46
+ maxScanBytes?: number
47
+ timeoutMs?: number
48
+ }
49
+ export declare interface AssertCleanOptions extends ScanOptions, QuarantineMeta {
50
+ surface?: MalwareSurface
51
+ file?: object
52
+ quarantine?: boolean
53
+ }
54
+ export declare interface CleanVerdict extends MalwareScanResult {
55
+ skipped?: boolean
56
+ }
package/dist/scan.js ADDED
@@ -0,0 +1 @@
1
+ import{log}from"@stacksjs/logging";import{malwareConfig,scanEnabled}from"./config";import{currentDriver,driverHealth}from"./drivers/resolve";import{MalwareDetectedError,MalwareScanError}from"./errors";import{toChunks}from"./input";import{quarantine}from"./quarantine";let scanCount=0;const verdicts=new WeakMap;export function rememberVerdict(file,result){if(result.verdict!=="error")verdicts.set(verdictKey(file),result)}export function rememberedVerdict(file){return verdicts.get(verdictKey(file))}function verdictKey(file){const inner=file.file;return inner instanceof Blob?inner:file}export function malwareScanCount(){return scanCount}export async function scan(input,options={}){const config=malwareConfig();const started=performance.now();scanCount++;try{const driver=await currentDriver(options.driver?{...config,driver:options.driver}:config);const result=await driver.scan(toChunks(input),{maxScanBytes:options.maxScanBytes??config.maxScanBytes,timeoutMs:options.timeoutMs??config.timeoutMs});return{...result,driver:driver.name,durationMs:Math.round(performance.now()-started)}}catch(error){return{verdict:"error",error:error.message,driver:String(options.driver??config.driver),durationMs:Math.round(performance.now()-started)}}}export function isClean(result,failClosed=malwareConfig().failClosed){if(result.verdict==="clean")return true;if(result.verdict==="error")return!failClosed;return false}function rereadable(input){return!(typeof input==="object"&&input!==null&&typeof input.getReader==="function")}export async function assertClean(input,options={}){if(options.surface&&!scanEnabled(options.surface))return{verdict:"clean",driver:"skipped",durationMs:0,skipped:true};const remembered=options.file?rememberedVerdict(options.file):undefined;const result=remembered??await scan(input,options);if(options.file&&!remembered)rememberVerdict(options.file,result);if(result.verdict==="clean")return result;if(result.verdict==="error"){if(!malwareConfig().failClosed){Promise.resolve(log.warn(`[malware] scan failed, allowing the file because failClosed is off: ${result.error}`)).catch(()=>{});return result}Promise.resolve(log.error(`[malware] scan failed${options.surface?` on ${options.surface}`:""}: ${result.error}`)).catch(()=>{});throw new MalwareScanError(result,{surface:options.surface})}let quarantineId;if(options.quarantine!==false&&!remembered&&rereadable(input)){try{const record=await quarantine(input,result,{surface:options.surface,originalName:options.originalName,intendedPath:options.intendedPath,context:options.context});quarantineId=record?.id}catch(error){Promise.resolve(log.error(`[malware] could not quarantine a detected file: ${error.message}`)).catch(()=>{})}}Promise.resolve(log.warn(`[malware] refused ${options.originalName?`'${options.originalName}' `:""}on ${options.surface??"scan"}: ${result.signature??result.verdict}${quarantineId?` (quarantine ${quarantineId})`:""}`)).catch(()=>{});throw new MalwareDetectedError(result,{surface:options.surface,quarantineId,intendedPath:options.intendedPath})}export function health(){return driverHealth(malwareConfig())}
@@ -0,0 +1,5 @@
1
+ {
2
+ "compilerOptions": {
3
+ "paths": {}
4
+ }
5
+ }
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@stacksjs/malware",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "type": "module",
4
+ "sideEffects": false,
5
+ "version": "0.75.730",
6
+ "description": "Malware scanning for Stacks apps: one scan() call over the Guardian engine, zavd or clamd, with fail-closed defaults and quarantine.",
7
+ "author": "Chris Breuer",
8
+ "contributors": [
9
+ "Chris Breuer <chris@stacksjs.com>"
10
+ ],
11
+ "license": "MIT",
12
+ "funding": "https://github.com/sponsors/chrisbbreuer",
13
+ "homepage": "https://github.com/stacksjs/stacks/tree/main/storage/framework/core/malware#readme",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/stacksjs/stacks.git",
17
+ "directory": "storage/framework/core/malware"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/stacksjs/stacks/issues"
21
+ },
22
+ "keywords": [
23
+ "malware",
24
+ "antivirus",
25
+ "clamd",
26
+ "zavd",
27
+ "guardian",
28
+ "upload scanning",
29
+ "stacks"
30
+ ],
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.ts",
34
+ "import": "./dist/index.js",
35
+ "default": "./dist/index.js"
36
+ }
37
+ },
38
+ "module": "dist/index.js",
39
+ "types": "dist/index.d.ts",
40
+ "files": [
41
+ "README.md",
42
+ "dist"
43
+ ],
44
+ "scripts": {
45
+ "build": "bun build.ts",
46
+ "test": "bun test ./tests",
47
+ "typecheck": "bun tsc --noEmit",
48
+ "prepublishOnly": "bun run build"
49
+ },
50
+ "dependencies": {
51
+ "@stacksjs/config": "0.75.730",
52
+ "@stacksjs/logging": "0.75.730",
53
+ "@stacksjs/types": "0.75.730"
54
+ },
55
+ "devDependencies": {
56
+ "better-dx": "^0.2.39"
57
+ }
58
+ }