Initial commit

This commit is contained in:
Sander Declerck 2025-07-11 17:14:52 +02:00
parent dd51a48435
commit 5eaf6ac3b3
No known key found for this signature in database
51 changed files with 10087 additions and 1 deletions

141
.gitignore vendored Normal file
View file

@ -0,0 +1,141 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.DS_Store
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.*
!.env.example
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Sveltekit cache directory
.svelte-kit/
# vitepress build output
**/.vitepress/dist
# vitepress cache directory
**/.vitepress/cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# Firebase cache directory
.firebase/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v3
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions
# Vite logs files
vite.config.js.timestamp-*
vite.config.ts.timestamp-*

674
LICENSE Normal file
View file

@ -0,0 +1,674 @@
This program is offered under a commercial and under the AGPL license.
You can be released from the requirements of the AGPL license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving Zen by Aikido software without
disclosing the source code of your own applications. These activities include
but are not limited to: offering paid services to customers in a web application
or shipping Aikido with a closed source product.
For more information, please contact Aikido Security at this
address: support@aikido.dev or create an account at https://app.aikido.dev.
For AGPL licensing, see below.
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

View file

@ -1 +1,70 @@
# safe-chain # Aikido Safe Chain
The Aikido Safe Chain **prevents developers from installing malware** on their workstations through npm, npx, or yarn.
The Aikido Safe Chain wraps around the [npm cli](https://github.com/npm/cli), [npx](https://github.com/npm/cli/blob/latest/docs/content/commands/npx.md), and [yarn](https://yarnpkg.com/) to provide extra checks before installing new packages. This tool will detect when a package contains malware and prompt you to exit, preventing npm, npx, or yarn from downloading or running the malware.
![demo](https://aikido-production-staticfiles-public.s3.eu-west-1.amazonaws.com/safe-pkg.gif)
Aikido Safe Chain works on Node.js version 18 and above and supports the following package managers:
- ✅ **npm**
- ✅ **npx**
- ✅ **yarn**
- 🚧 **pnpm** Coming soon
# Usage
## Installation
Installing the Aikido Safe Chain is easy. You just need 3 simple steps:
1. **Install the Aikido Safe Chain package globally** using npm:
```shell
npm install -g @aikidosec/safe-chain
```
2. **Setup the shell integration** by running:
```shell
safe-chain setup
```
3. **❗Restart your terminal** to start using the Aikido Safe Chain.
- This step is crucial as it ensures that the shell aliases for npm, npx, and yarn are loaded correctly. If you do not restart your terminal, the aliases will not be available.
4. **Verify the installation** by running:
```shell
npm install eslint-js
```
- The output should show that Aikido Safe Chain is blocking the installation of this package as it is flagged as malware.
When running `npm`, `npx`, or `yarn` commands, the Aikido Safe Chain will automatically check for malware in the packages you are trying to install. If any malware is detected, it will prompt you to exit the command.
## How it works
The Aikido Safe Chain works by intercepting the npm, npx, and yarn commands and verifying the packages against **[Aikido Intel - Open Sources Threat Intelligence](https://intel.aikido.dev/?tab=malware)**.
The Aikido Safe Chain integrates with your shell to provide a seamless experience when using npm, npx, and yarn commands. It sets up aliases for these commands so that they are wrapped by the Aikido Safe Chain commands, which perform malware checks before executing the original commands. We currently support:
- ✅ **Bash**
- ✅ **Zsh**
- ✅ **Fish**
- ✅ **PowerShell**
- ✅ **PowerShell Core**
More information about the shell integration can be found in the [shell integration documentation](docs/shell-integration.md).
## Uninstallation
To uninstall the Aikido Safe Chain, you can run the following command:
1. **Remove all aliases from your shell** by running:
```shell
safe-chain teardown
```
2. **Uninstall the Aikido Safe Chain package** using npm:
```shell
npm uninstall -g @aikidosec/safe-chain
```
3. **❗Restart your terminal** to remove the aliases.
# Usage in CI/CD
🚧 Support for CI/CD environments is coming soon...

8
bin/aikido-npm.js Executable file
View file

@ -0,0 +1,8 @@
#!/usr/bin/env node
import { main } from "../src/main.js";
import { initializePackageManager } from "../src/packagemanager/currentPackageManager.js";
const packageManagerName = "npm";
initializePackageManager(packageManagerName, process.versions.node);
await main(process.argv.slice(2));

8
bin/aikido-npx.js Executable file
View file

@ -0,0 +1,8 @@
#!/usr/bin/env node
import { main } from "../src/main.js";
import { initializePackageManager } from "../src/packagemanager/currentPackageManager.js";
const packageManagerName = "npx";
initializePackageManager(packageManagerName, process.versions.node);
await main(process.argv.slice(2));

8
bin/aikido-yarn.js Executable file
View file

@ -0,0 +1,8 @@
#!/usr/bin/env node
import { main } from "../src/main.js";
import { initializePackageManager } from "../src/packagemanager/currentPackageManager.js";
const packageManagerName = "yarn";
initializePackageManager(packageManagerName, process.versions.node);
await main(process.argv.slice(2));

57
bin/safe-chain.js Executable file
View file

@ -0,0 +1,57 @@
#!/usr/bin/env node
import chalk from "chalk";
import { ui } from "../src/environment/userInteraction.js";
import { setup } from "../src/shell-integration/setup.js";
import { teardown } from "../src/shell-integration/teardown.js";
if (process.argv.length < 3) {
ui.writeError("No command provided. Please provide a command to execute.");
ui.emptyLine();
writeHelp();
process.exit(1);
}
const command = process.argv[2];
if (command === "help" || command === "--help" || command === "-h") {
writeHelp();
process.exit(0);
}
if (command === "setup") {
setup();
} else if (command === "teardown") {
teardown();
} else {
ui.writeError(`Unknown command: ${command}.`);
ui.emptyLine();
writeHelp();
process.exit(1);
}
function writeHelp() {
ui.writeInformation(
chalk.bold("Usage: ") + chalk.cyan("safe-chain <command>")
);
ui.emptyLine();
ui.writeInformation(
`Available commands: ${chalk.cyan("setup")}, ${chalk.cyan(
"teardown"
)}, ${chalk.cyan("help")}`
);
ui.emptyLine();
ui.writeInformation(
`- ${chalk.cyan(
"safe-chain setup"
)}: This will setup your shell to wrap safe-chain around npm, npx and yarn.`
);
ui.writeInformation(
`- ${chalk.cyan(
"safe-chain teardown"
)}: This will remove safe-chain aliases from your shell configuration.`
);
ui.emptyLine();
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

108
docs/shell-integration.md Normal file
View file

@ -0,0 +1,108 @@
# Shell Integration
## Overview
The shell integration automatically wraps common package manager commands (`npm`, `npx`, `yarn`) with Aikido's security scanning functionality. This is achieved by adding shell aliases that redirect these commands to their Aikido-wrapped equivalents.
## Supported Shells
Aikido Safe Chain supports integration with the following shells.
| Shell | Startup File | Alias Format |
| ---------------------- | ---------------------------- | -------------------------- |
| **Bash** | `~/.bashrc` | `alias npm='aikido-npm'` |
| **Zsh** | `~/.zshrc` | `alias npm='aikido-npm'` |
| **Fish** | `~/.config/fish/config.fish` | `alias npm "aikido-npm"` |
| **PowerShell Core** | `$PROFILE` | `Set-Alias npm aikido-npm` |
| **Windows PowerShell** | `$PROFILE` | `Set-Alias npm aikido-npm` |
## Commands
### Setup Shell Integration
```bash
safe-chain setup
```
This command:
- Detects all supported shells on your system
- Adds aliases for `npm`, `npx`, and `yarn` to each shell's startup file
❗ After running this command, **you must restart your terminal** for the changes to take effect. This ensures that the aliases are loaded correctly.
### Remove Shell Integration
```bash
safe-chain teardown
```
This command:
- Detects all supported shells on your system
- Removes Aikido aliases from each shell's startup file
❗ After running this command, **you must restart your terminal** to restore the original commands.
## File Locations
The system modifies the following files based on your shell configuration:
### Unix/Linux/macOS
- **Bash**: `~/.bashrc`
- **Zsh**: `~/.zshrc`
- **Fish**: `~/.config/fish/config.fish`
- **PowerShell Core**: `$PROFILE` (usually `~/.config/powershell/profile.ps1`)
### Windows
- **PowerShell**: Determined by `$PROFILE` variable
- **PowerShell Core**: Also determined by `$PROFILE` variable
## Troubleshooting
### Common Issues
**Aliases not working after setup:**
- Make sure to restart your terminal
- Check that the startup file was actually modified
- Verify your shell is reading the correct startup file
**Getting 'command not found: aikido-npm' error:**
This means the aliases are working but the Aikido commands aren't installed or available in your PATH:
- Make sure Aikido Safe Chain is properly installed on your system
- Verify the `aikido-npm`, `aikido-npx`, and `aikido-yarn` commands exist
- Check that these commands are in your system's PATH
### Manual Verification
To verify the integration is working, follow these steps:
1. **Check if aliases were added to your shell startup file:**
- **For Bash**: Open `~/.bashrc` in your text editor
- **For Zsh**: Open `~/.zshrc` in your text editor
- **For Fish**: Open `~/.config/fish/config.fish` in your text editor
- **For PowerShell**: Open your PowerShell profile file (run `$PROFILE` in PowerShell to see the path)
Look for lines like:
- `alias npm='aikido-npm'` (Bash/Zsh)
- `alias npm "aikido-npm"` (Fish)
- `Set-Alias npm aikido-npm` (PowerShell)
2. **Test that aliases are active in your terminal:**
After restarting your terminal, run these commands:
- `which npm` - Should show the path to `aikido-npm` instead of the original npm
- `npm --version` - Should show output from the Aikido-wrapped version
- `type npm` - Alternative way to check what command `npm` resolves to
3. **If you need to remove aliases manually:**
Edit the same startup file from step 1 and delete any lines containing `aikido-npm`, `aikido-npx`, or `aikido-yarn`.

25
eslint.config.js Normal file
View file

@ -0,0 +1,25 @@
import js from "@eslint/js";
import { defineConfig } from "@eslint/config-helpers";
import globals from "globals";
import importPlugin from "eslint-plugin-import";
export default defineConfig([
{
files: ["**/*.{js,mjs,cjs,ts}"],
plugins: { js },
extends: ["js/recommended"],
},
{
files: ["**/*.{js,mjs,cjs,ts}"],
languageOptions: { globals: globals.node },
},
importPlugin.flatConfigs.recommended,
{
files: ["**/*.{js,mjs,cjs}"],
languageOptions: {
ecmaVersion: "latest",
sourceType: "module",
},
rules: {},
},
]);

5796
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

44
package.json Normal file
View file

@ -0,0 +1,44 @@
{
"name": "@aikidosec/safe-chain",
"version": "1.0.0",
"scripts": {
"test": "node --test --experimental-test-module-mocks **/*.spec.js",
"test:watch": "node --test --watch --experimental-test-module-mocks **/*.spec.js",
"lint": "eslint ."
},
"repository": {
"type": "git",
"url": "git+https://github.com/AikidoSec/safe-chain.git"
},
"bin": {
"aikido-npm": "bin/aikido-npm.js",
"aikido-npx": "bin/aikido-npx.js",
"aikido-yarn": "bin/aikido-yarn.js",
"safe-chain": "bin/safe-chain.js"
},
"type": "module",
"keywords": [],
"author": "Aikido Security",
"license": "AGPL-3.0-or-later",
"description": "The Aikido Safe Chain wraps around the [npm cli](https://github.com/npm/cli), [npx](https://github.com/npm/cli/blob/latest/docs/content/commands/npx.md), [yarn](https://yarnpkg.com/), [pnpm](https://pnpm.io/), and [pnpx](https://pnpm.io/cli/dlx) to provide extra checks before installing new packages. This tool will detect when a package contains malware and prompt you to exit, preventing npm, npx, yarn, pnpm, or pnpx from downloading or running the malware.",
"dependencies": {
"@inquirer/prompts": "^7.4.1",
"abbrev": "^3.0.1",
"chalk": "^5.4.1",
"npm-registry-fetch": "^18.0.2",
"ora": "^8.2.0",
"semver": "^7.7.2"
},
"devDependencies": {
"@eslint/js": "^9.26.0",
"eslint": "^9.26.0",
"eslint-plugin-import": "^2.31.0",
"globals": "^16.1.0",
"typescript-eslint": "^8.32.0"
},
"main": "eslint.config.js",
"bugs": {
"url": "https://github.com/AikidoSec/safe-chain/issues"
},
"homepage": "https://github.com/AikidoSec/safe-chain#readme"
}

31
src/api/aikido.js Normal file
View file

@ -0,0 +1,31 @@
const malwareDatabaseUrl =
"https://malware-list.aikido.dev/malware_predictions.json";
export async function fetchMalwareDatabase() {
const response = await fetch(malwareDatabaseUrl);
if (!response.ok) {
throw new Error(`Error fetching malware database: ${response.statusText}`);
}
try {
let malwareDatabase = await response.json();
return {
malwareDatabase: malwareDatabase,
version: response.headers.get("etag") || undefined,
};
} catch (error) {
throw new Error(`Error parsing malware database: ${error.message}`);
}
}
export async function fetchMalwareDatabaseVersion() {
const response = await fetch(malwareDatabaseUrl, {
method: "HEAD",
});
if (!response.ok) {
throw new Error(
`Error fetching malware database version: ${response.statusText}`
);
}
return response.headers.get("etag") || undefined;
}

46
src/api/npmApi.js Normal file
View file

@ -0,0 +1,46 @@
import * as semver from "semver";
import * as npmFetch from "npm-registry-fetch";
export async function resolvePackageVersion(packageName, versionRange) {
if (!versionRange) {
versionRange = "latest";
}
if (semver.valid(versionRange)) {
// The version is a fixed version, no need to resolve
return versionRange;
}
const packageInfo = await getPackageInfo(packageName);
if (!packageInfo) {
// It is possible that no version is found (could be a private package, or a package that doesn't exist)
// In this case, we return null to indicate that we couldn't resolve the version
return null;
}
const distTags = packageInfo["dist-tags"];
if (distTags && distTags[versionRange]) {
// If the version range is a dist-tag, return the version associated with that tag
// e.g., "latest", "next", etc.
return distTags[versionRange];
}
// If the version range is not a dist-tag, we need to resolve the highest version matching the range.
// This is useful for ranges like "^1.0.0" or "~2.3.4".
const availableVersions = Object.keys(packageInfo.versions);
const resolvedVersion = semver.maxSatisfying(availableVersions, versionRange);
if (resolvedVersion) {
return resolvedVersion;
}
// Nothing matched the range, return null
return null;
}
async function getPackageInfo(packageName) {
try {
return await npmFetch.json(packageName);
} catch {
return null;
}
}

91
src/config/configFile.js Normal file
View file

@ -0,0 +1,91 @@
import fs from "fs";
import path from "path";
import os from "os";
import { ui } from "../environment/userInteraction.js";
export function getScanTimeout() {
const config = readConfigFile();
return (
parseInt(process.env.AIKIDO_SCAN_TIMEOUT_MS) || config.scanTimeout || 10000 // Default to 10 seconds
);
}
export function writeDatabaseToLocalCache(data, version) {
try {
const databasePath = getDatabasePath();
const versionPath = getDatabaseVersionPath();
fs.writeFileSync(databasePath, JSON.stringify(data));
fs.writeFileSync(versionPath, version.toString());
} catch {
ui.writeWarning(
"Failed to write malware database to local cache, next time the database will be fetched from the server again."
);
}
}
export function readDatabaseFromLocalCache() {
try {
const databasePath = getDatabasePath();
if (!fs.existsSync(databasePath)) {
return {
malwareDatabase: null,
version: null,
};
}
const data = fs.readFileSync(databasePath, "utf8");
const malwareDatabase = JSON.parse(data);
const versionPath = getDatabaseVersionPath();
let version = null;
if (fs.existsSync(versionPath)) {
version = fs.readFileSync(versionPath, "utf8").trim();
}
return {
malwareDatabase: malwareDatabase,
version: version,
};
} catch {
ui.writeWarning(
"Failed to read malware database from local cache. Continuing without local cache."
);
return {
malwareDatabase: null,
version: null,
};
}
}
function readConfigFile() {
const configFilePath = getConfigFilePath();
if (!fs.existsSync(configFilePath)) {
return {};
}
const data = fs.readFileSync(configFilePath, "utf8");
return JSON.parse(data);
}
function getDatabasePath() {
const aikidoDir = getAikidoDirectory();
return path.join(aikidoDir, "malwareDatabase.json");
}
function getDatabaseVersionPath() {
const aikidoDir = getAikidoDirectory();
return path.join(aikidoDir, "version.txt");
}
function getConfigFilePath() {
return path.join(getAikidoDirectory(), "config.json");
}
function getAikidoDirectory() {
const homeDir = os.homedir();
const aikidoDir = path.join(homeDir, ".aikido");
if (!fs.existsSync(aikidoDir)) {
fs.mkdirSync(aikidoDir, { recursive: true });
}
return aikidoDir;
}

View file

@ -0,0 +1,14 @@
export function isCi() {
const ciEnvironments = [
"CI",
"TF_BUILD", // Azure devops does not set CI, but TF_BUILD
];
for (const env of ciEnvironments) {
if (process.env[env]) {
return true;
}
}
return false;
}

View file

@ -0,0 +1,79 @@
import chalk from "chalk";
import ora from "ora";
import { confirm as inquirerConfirm } from "@inquirer/prompts";
import { isCi } from "./environment.js";
function emptyLine() {
writeInformation("");
}
function writeInformation(message, ...optionalParams) {
console.log(message, ...optionalParams);
}
function writeWarning(message, ...optionalParams) {
if (!isCi()) {
message = chalk.yellow(message);
}
console.warn(message, ...optionalParams);
}
function writeError(message, ...optionalParams) {
if (!isCi()) {
message = chalk.red(message);
}
console.error(message, ...optionalParams);
}
function startProcess(message) {
if (isCi()) {
return {
succeed: (message) => {
writeInformation(message);
},
fail: (message) => {
writeError(message);
},
stop: () => {},
setText: (message) => {
writeInformation(message);
},
};
} else {
const spinner = ora(message).start();
return {
succeed: (message) => {
spinner.succeed(message);
},
fail: (message) => {
spinner.fail(message);
},
stop: () => {
spinner.stop();
},
setText: (message) => {
spinner.text = message;
},
};
}
}
async function confirm(config) {
if (isCi()) {
return Promise.resolve(config.default);
} else {
return inquirerConfirm({
message: config.message,
default: config.default,
});
}
}
export const ui = {
writeInformation,
writeWarning,
writeError,
emptyLine,
startProcess,
confirm,
};

18
src/main.js Normal file
View file

@ -0,0 +1,18 @@
#!/usr/bin/env node
import { scanCommand, shouldScanCommand } from "./scanning/index.js";
import { ui } from "./environment/userInteraction.js";
import { getPackageManager } from "./packagemanager/currentPackageManager.js";
export async function main(args) {
try {
if (shouldScanCommand(args)) {
await scanCommand(args);
}
} catch (error) {
ui.writeError("Failed to check for malicious packages:", error.message);
}
var result = getPackageManager().runCommand(args);
process.exit(result.status);
}

View file

@ -0,0 +1,28 @@
import { createNpmPackageManager } from "./npm/createPackageManager.js";
import { createNpxPackageManager } from "./npx/createPackageManager.js";
import { createYarnPackageManager } from "./yarn/createPackageManager.js";
const state = {
packageManagerName: null,
};
export function initializePackageManager(packageManagerName, version) {
if (packageManagerName === "npm") {
state.packageManagerName = createNpmPackageManager(version);
} else if (packageManagerName === "npx") {
state.packageManagerName = createNpxPackageManager();
} else if (packageManagerName === "yarn") {
state.packageManagerName = createYarnPackageManager();
} else {
throw new Error("Unsupported package manager: " + packageManagerName);
}
return state.packageManagerName;
}
export function getPackageManager() {
if (!state.packageManagerName) {
throw new Error("Package manager not initialized.");
}
return state.packageManagerName;
}

View file

@ -0,0 +1,83 @@
import { commandArgumentScanner } from "./dependencyScanner/commandArgumentScanner.js";
import { dryRunScanner } from "./dependencyScanner/dryRunScanner.js";
import { nullScanner } from "./dependencyScanner/nullScanner.js";
import { runNpm } from "./runNpmCommand.js";
import {
getNpmCommandForArgs,
npmInstallCommand,
npmCiCommand,
npmInstallTestCommand,
npmInstallCiTestCommand,
npmUpdateCommand,
npmAuditCommand,
npmExecCommand,
} from "./utils/npmCommands.js";
export function createNpmPackageManager(version) {
const supportedScanners =
getMajorVersion(version) >= 22
? npm22AndAboveSupportedScanners
: npm21AndBelowSupportedScanners;
function isSupportedCommand(args) {
const scanner = findDependencyScannerForCommand(supportedScanners, args);
return scanner.shouldScan(args);
}
function getDependencyUpdatesForCommand(args) {
const scanner = findDependencyScannerForCommand(supportedScanners, args);
return scanner.scan(args);
}
return {
getWarningMessage: () => warnForLimitedSupport(version),
runCommand: runNpm,
isSupportedCommand,
getDependencyUpdatesForCommand,
};
}
const npm22AndAboveSupportedScanners = {
[npmInstallCommand]: dryRunScanner(),
[npmUpdateCommand]: dryRunScanner(),
[npmCiCommand]: dryRunScanner(),
[npmAuditCommand]: dryRunScanner({
skipScanWhen: (args) => !args.includes("fix"),
}),
[npmExecCommand]: commandArgumentScanner({ ignoreDryRun: true }), // exec command doesn't support dry-run
// Running dry-run on install-test and install-ci-test will install & run tests.
// We only want to know if there are changes in the dependencies.
// So we run change the dry-run command to only check the install.
[npmInstallTestCommand]: dryRunScanner({ dryRunCommand: npmInstallCommand }),
[npmInstallCiTestCommand]: dryRunScanner({ dryRunCommand: npmCiCommand }),
};
const npm21AndBelowSupportedScanners = {
[npmInstallCommand]: commandArgumentScanner(),
[npmUpdateCommand]: commandArgumentScanner(),
[npmExecCommand]: commandArgumentScanner({ ignoreDryRun: true }), // exec command doesn't support dry-run
};
function warnForLimitedSupport(version) {
if (getMajorVersion(version) >= 22) {
return null;
}
return `Aikido-npm will only scan the arguments of the install command for Node.js version prior to version 22.
Please update your Node.js version to 22 or higher for full coverage. Current version: v${version}`;
}
function getMajorVersion(version) {
return parseInt(version.split(".")[0]);
}
function findDependencyScannerForCommand(scanners, args) {
const command = getNpmCommandForArgs(args);
if (!command) {
return nullScanner();
}
const scanner = scanners[command];
return scanner ? scanner : nullScanner();
}

View file

@ -0,0 +1,37 @@
import { resolvePackageVersion } from "../../../api/npmApi.js";
import { parsePackagesFromInstallArgs } from "../parsing/parsePackagesFromInstallArgs.js";
import { hasDryRunArg } from "../utils/npmCommands.js";
export function commandArgumentScanner(opts) {
const ignoreDryRun = opts?.ignoreDryRun ?? false;
return {
scan: (args) => scanDependencies(args),
shouldScan: (args) => shouldScanDependencies(args, ignoreDryRun),
};
}
function scanDependencies(args) {
return checkChangesFromArgs(args);
}
function shouldScanDependencies(args, ignoreDryRun) {
return ignoreDryRun || !hasDryRunArg(args);
}
export async function checkChangesFromArgs(args) {
const changes = [];
const packageUpdates = parsePackagesFromInstallArgs(args);
for (const packageUpdate of packageUpdates) {
var exactVersion = await resolvePackageVersion(
packageUpdate.name,
packageUpdate.version
);
if (exactVersion) {
packageUpdate.version = exactVersion;
}
changes.push({ ...packageUpdate, type: "add" });
}
return changes;
}

View file

@ -0,0 +1,50 @@
import { ui } from "../../../environment/userInteraction.js";
import { parseDryRunOutput } from "../parsing/parseNpmInstallDryRunOutput.js";
import { dryRunNpmCommandAndOutput } from "../runNpmCommand.js";
import { hasDryRunArg } from "../utils/npmCommands.js";
export function dryRunScanner(scannerOptions) {
return {
scan: (args) => scanDependencies(scannerOptions, args),
shouldScan: (args) => shouldScanDependencies(scannerOptions, args),
};
}
function scanDependencies(scannerOptions, args) {
let dryRunArgs = args;
if (scannerOptions?.dryRunCommand) {
// Replace the first argument with the dryRunCommand (eg: "install" instead of "install-test")
dryRunArgs = [scannerOptions.dryRunCommand, ...args.slice(1)];
}
return checkChangesWithDryRun(dryRunArgs);
}
function shouldScanDependencies(scannerOptions, args) {
if (hasDryRunArg(args)) {
return false;
}
if (scannerOptions?.skipScanWhen && scannerOptions.skipScanWhen(args)) {
return false;
}
return true;
}
function checkChangesWithDryRun(args) {
const dryRunOutput = dryRunNpmCommandAndOutput(args);
// Dry-run can return a non-zero status code in some cases
// e.g., when running "npm audit fix --dry-run", it returns exit code 1
// when there are vulnurabilities that can be fixed.
if (dryRunOutput.status !== 0 && !dryRunOutput.output) {
ui.writeError("Detecting changes failed.");
return [];
}
const parsedOutput = parseDryRunOutput(dryRunOutput.output);
// reverse the array to have the top-level packages first
return parsedOutput.reverse();
}

View file

@ -0,0 +1,6 @@
export function nullScanner() {
return {
scan: () => [],
shouldScan: () => false,
};
}

View file

@ -0,0 +1,57 @@
export function parseDryRunOutput(output) {
const lines = output.split(/\r?\n/);
const packageChanges = [];
for (const line of lines) {
if (line.startsWith("add ")) {
packageChanges.push(parseAdd(line));
} else if (line.startsWith("remove ")) {
packageChanges.push(parseRemove(line));
} else if (line.startsWith("change ")) {
packageChanges.push(parseChange(line));
}
}
return packageChanges;
}
function parseAdd(line) {
const splitLine = getLineParts(line);
const packageName = splitLine[1];
const packageVersion = splitLine[splitLine.length - 1];
return addedPackage(packageName, packageVersion);
}
function addedPackage(name, version) {
return { type: "add", name, version };
}
function parseRemove(line) {
const splitLine = getLineParts(line);
const packageName = splitLine[1];
const packageVersion = splitLine[splitLine.length - 1];
return removedPackage(packageName, packageVersion);
}
function removedPackage(name, version) {
return { type: "remove", name, version };
}
function parseChange(line) {
const splitLine = getLineParts(line);
const packageName = splitLine[1];
const packageVersion = splitLine[splitLine.length - 1];
const oldVersion = splitLine[2];
return changedPackage(packageName, packageVersion, oldVersion);
}
function getLineParts(line) {
return line
.split(" ")
.map((part) => part.trim())
.filter((part) => part !== "");
}
function changedPackage(name, version, oldVersion) {
return { type: "change", name, version, oldVersion };
}

View file

@ -0,0 +1,134 @@
import { describe, it } from "node:test";
import assert from "node:assert";
import { parseDryRunOutput } from "./parseNpmInstallDryRunOutput.js";
describe("parseNpmInstallDryRunOutput", () => {
it("should parse added packages", () => {
const output = `
add @jest/transform 29.7.0
add @jest/test-result 29.7.0
add @jest/reporters 29.7.0
add @jest/console 29.7.0
add jest-cli 29.7.0
add import-local 3.2.0
add @jest/types 29.6.3
add @jest/core 29.7.0
add jest 29.7.0
added 267 packages in 831ms
32 packages are looking for funding
run \`npm fund\` for details`;
const expected = [
{ name: "@jest/transform", version: "29.7.0", type: "add" },
{ name: "@jest/test-result", version: "29.7.0", type: "add" },
{ name: "@jest/reporters", version: "29.7.0", type: "add" },
{ name: "@jest/console", version: "29.7.0", type: "add" },
{ name: "jest-cli", version: "29.7.0", type: "add" },
{ name: "import-local", version: "3.2.0", type: "add" },
{ name: "@jest/types", version: "29.6.3", type: "add" },
{ name: "@jest/core", version: "29.7.0", type: "add" },
{ name: "jest", version: "29.7.0", type: "add" },
];
const result = parseDryRunOutput(output);
assert.deepEqual(result, expected);
});
it("should parse removed packages", () => {
const output = `
remove react 19.1.0
removed 1 package in 115ms`;
const expected = [{ name: "react", version: "19.1.0", type: "remove" }];
const result = parseDryRunOutput(output);
assert.deepEqual(result, expected);
});
it("should parse changed packages", () => {
const output = `
change react 19.0.0 => 19.1.0
changed 1 package in 204ms`;
const expected = [
{
name: "react",
version: "19.1.0",
oldVersion: "19.0.0",
type: "change",
},
];
const result = parseDryRunOutput(output);
assert.deepEqual(result, expected);
});
it("should parse mixed package changes", () => {
const output = `
add @jest/transform 29.7.0
add @jest/test-result 29.7.0
add @jest/reporters 29.7.0
add @jest/console 29.7.0
add jest-cli 29.7.0
add import-local 3.2.0
add @jest/types 29.6.3
add @jest/core 29.7.0
add jest 29.7.0
remove react 19.1.0
change lodash 4.17.0 => 4.18.0
removed 1 package in 115ms`;
const expected = [
{ name: "@jest/transform", version: "29.7.0", type: "add" },
{ name: "@jest/test-result", version: "29.7.0", type: "add" },
{ name: "@jest/reporters", version: "29.7.0", type: "add" },
{ name: "@jest/console", version: "29.7.0", type: "add" },
{ name: "jest-cli", version: "29.7.0", type: "add" },
{ name: "import-local", version: "3.2.0", type: "add" },
{ name: "@jest/types", version: "29.6.3", type: "add" },
{ name: "@jest/core", version: "29.7.0", type: "add" },
{ name: "jest", version: "29.7.0", type: "add" },
{ name: "react", version: "19.1.0", type: "remove" },
{
name: "lodash",
version: "4.18.0",
oldVersion: "4.17.0",
type: "change",
},
];
const result = parseDryRunOutput(output);
assert.deepEqual(result, expected);
});
it("should work with npm v22.0.0", () => {
const output = `
add @jest/types 29.6.3
add @jest/core 29.7.0
add jest 29.7.0
added 257 packages in 791ms
44 packages are looking for funding
run \`npm fund\` for details`;
const expected = [
{ name: "@jest/types", version: "29.6.3", type: "add" },
{ name: "@jest/core", version: "29.7.0", type: "add" },
{ name: "jest", version: "29.7.0", type: "add" },
];
const result = parseDryRunOutput(output);
assert.deepEqual(result, expected);
});
});

View file

@ -0,0 +1,109 @@
export function parsePackagesFromInstallArgs(args) {
const changes = [];
let defaultTag = "latest";
// Skip first argument (install command)
for (let i = 1; i < args.length; i++) {
const arg = args[i];
const npmOption = getNpmOption(arg);
if (npmOption) {
// If the option has a parameter, skip the next argument as well
i += npmOption.numberOfParameters;
// it a tag is specified, set the default tag
if (npmOption.name === "--tag") {
defaultTag = args[i];
}
continue;
}
const packageDetails = parsePackagename(arg);
if (packageDetails) {
changes.push(packageDetails);
continue;
}
}
for (const change of changes) {
if (!change.version) {
change.version = defaultTag;
}
}
return changes;
}
function getNpmOption(arg) {
if (isNpmOptionWithParameter(arg)) {
return {
name: arg,
numberOfParameters: 1,
};
}
// Arguments starting with "-" or "--" are considered npm options
if (arg.startsWith("-")) {
return {
name: arg,
numberOfParameters: 0,
};
}
return undefined;
}
function isNpmOptionWithParameter(arg) {
const optionsWithParameters = [
"--access",
"--auth-type",
"--cache",
"--fetch-retries",
"--fetch-retry-mintimeout",
"--fetch-retry-maxtimeout",
"--fetch-retry-factor",
"--fetch-timeout",
"--https-proxy",
"--include",
"--location",
"--lockfile-version",
"--loglevel",
"--omit",
"--proxy",
"--registry",
"--replace-registry-host",
"--tag",
"--user-config",
"--workspace",
];
return optionsWithParameters.includes(arg);
}
function parsePackagename(arg) {
arg = removeAlias(arg);
const lastAtIndex = arg.lastIndexOf("@");
let name, version;
if (lastAtIndex !== -1) {
name = arg.slice(0, lastAtIndex);
version = arg.slice(lastAtIndex + 1);
} else {
name = arg;
version = null;
}
return {
name,
version,
};
}
function removeAlias(arg) {
const aliasIndex = arg.indexOf("@npm:");
if (aliasIndex !== -1) {
return arg.slice(aliasIndex + 5);
}
return arg;
}

View file

@ -0,0 +1,176 @@
import { describe, it } from "node:test";
import assert from "node:assert";
import { parsePackagesFromInstallArgs } from "./parsePackagesFromInstallArgs.js";
describe("parsePackagesFromInstallArgs", () => {
it("should return an empty array for no changes", () => {
const args = ["install"];
const result = parsePackagesFromInstallArgs(args);
assert.deepEqual(result, []);
});
it("should return an array of changes for one package", () => {
const args = ["install", "@jest/transform@29.7.0"];
const result = parsePackagesFromInstallArgs(args);
assert.deepEqual(result, [{ name: "@jest/transform", version: "29.7.0" }]);
});
it("should return an array of changes for multiple packages", () => {
const args = ["install", "express@4.17.1", "lodash@4.17.21"];
const result = parsePackagesFromInstallArgs(args);
assert.deepEqual(result, [
{ name: "express", version: "4.17.1" },
{ name: "lodash", version: "4.17.21" },
]);
});
it("should ignore options and return an array of changes", () => {
const args = [
"install",
"--save-dev",
"express@4.17.1",
"--save-exact",
"lodash@4.17.21",
];
const result = parsePackagesFromInstallArgs(args);
assert.deepEqual(result, [
{ name: "express", version: "4.17.1" },
{ name: "lodash", version: "4.17.21" },
]);
});
it("should ignore options with parameters and return an array of changes", () => {
const args = [
"install",
"--save-dev",
"express@4.17.1",
"--loglevel",
"error",
"lodash@4.17.21",
];
const result = parsePackagesFromInstallArgs(args);
assert.deepEqual(result, [
{ name: "express", version: "4.17.1" },
{ name: "lodash", version: "4.17.21" },
]);
});
it("should not ignore the next argument if it is passed directly with the option", () => {
const args = [
"install",
"--save-dev",
"express@4.17.1",
"--loglevel=error",
"lodash@4.17.21",
];
const result = parsePackagesFromInstallArgs(args);
assert.deepEqual(result, [
{ name: "express", version: "4.17.1" },
{ name: "lodash", version: "4.17.21" },
]);
});
it("should set the default tag for packages", () => {
const args = ["install", "express", "lodash@4.17.21"];
const result = parsePackagesFromInstallArgs(args);
assert.deepEqual(result, [
{ name: "express", version: "latest" },
{ name: "lodash", version: "4.17.21" },
]);
});
it("should set the default tag for packages with a specific tag", () => {
const args = ["install", "express", "lodash@4.17.21", "--tag", "beta"];
const result = parsePackagesFromInstallArgs(args);
assert.deepEqual(result, [
{ name: "express", version: "beta" },
{ name: "lodash", version: "4.17.21" },
]);
});
it("should ignore alias", () => {
const args = ["install", "express@npm:express@4.17.1"];
const result = parsePackagesFromInstallArgs(args);
assert.deepEqual(result, [{ name: "express", version: "4.17.1" }]);
});
it("should parse version even for aliased packages", () => {
const args = ["install", "express@npm:express@4.17.1"];
const result = parsePackagesFromInstallArgs(args);
assert.deepEqual(result, [{ name: "express", version: "4.17.1" }]);
});
it("should parse scoped packages", () => {
const args = ["install", "@scope/package@1.0.0"];
const result = parsePackagesFromInstallArgs(args);
assert.deepEqual(result, [{ name: "@scope/package", version: "1.0.0" }]);
});
it("should parse packages with version ranges", () => {
const args = ["install", "express@^4.17.1"];
const result = parsePackagesFromInstallArgs(args);
assert.deepEqual(result, [{ name: "express", version: "^4.17.1" }]);
});
it("should parse package folders", () => {
const args = ["install", "./local-package"];
const result = parsePackagesFromInstallArgs(args);
assert.deepEqual(result, [{ name: "./local-package", version: "latest" }]);
});
it("should parse tarballs", () => {
const args = ["install", "file:./local-package.tgz"];
const result = parsePackagesFromInstallArgs(args);
assert.deepEqual(result, [
{ name: "file:./local-package.tgz", version: "latest" },
]);
});
it("should parse tarball URLs", () => {
const args = ["install", "https://example.com/local-package.tgz"];
const result = parsePackagesFromInstallArgs(args);
assert.deepEqual(result, [
{ name: "https://example.com/local-package.tgz", version: "latest" },
]);
});
it("should parse git URLs", () => {
const args = ["install", "git://github.com/npm/cli.git"];
const result = parsePackagesFromInstallArgs(args);
assert.deepEqual(result, [
{ name: "git://github.com/npm/cli.git", version: "latest" },
]);
});
});

View file

@ -0,0 +1,33 @@
import { execSync } from "child_process";
import { ui } from "../../environment/userInteraction.js";
export function runNpm(args) {
try {
const npmCommand = `npm ${args.join(" ")}`;
execSync(npmCommand, { stdio: "inherit" });
} catch (error) {
if (error.status) {
return { status: error.status };
} else {
ui.writeError("Error executing command:", error.message);
return { status: 1 };
}
}
return { status: 0 };
}
export function dryRunNpmCommandAndOutput(args) {
try {
const npmCommand = `npm ${args.join(" ")} --dry-run`;
const output = execSync(npmCommand, { stdio: "pipe" });
return { status: 0, output: output.toString() };
} catch (error) {
if (error.status) {
const output = error.stdout ? error.stdout.toString() : "";
return { status: error.status, output };
} else {
ui.writeError("Error executing command:", error.message);
return { status: 1 };
}
}
}

View file

@ -0,0 +1,171 @@
// Based on https://github.com/npm/cli/blob/latest/lib/utils/cmd-list.js
import abbrev from "abbrev";
const commands = [
"access",
"adduser",
"audit",
"bugs",
"cache",
"ci",
"completion",
"config",
"dedupe",
"deprecate",
"diff",
"dist-tag",
"docs",
"doctor",
"edit",
"exec",
"explain",
"explore",
"find-dupes",
"fund",
"get",
"help",
"help-search",
"init",
"install",
"install-ci-test",
"install-test",
"link",
"ll",
"login",
"logout",
"ls",
"org",
"outdated",
"owner",
"pack",
"ping",
"pkg",
"prefix",
"profile",
"prune",
"publish",
"query",
"rebuild",
"repo",
"restart",
"root",
"run",
"sbom",
"search",
"set",
"shrinkwrap",
"star",
"stars",
"start",
"stop",
"team",
"test",
"token",
"undeprecate",
"uninstall",
"unpublish",
"unstar",
"update",
"version",
"view",
"whoami",
];
// These must resolve to an entry in commands
const aliases = {
// aliases
author: "owner",
home: "docs",
issues: "bugs",
info: "view",
show: "view",
find: "search",
add: "install",
unlink: "uninstall",
remove: "uninstall",
rm: "uninstall",
r: "uninstall",
// short names for common things
un: "uninstall",
rb: "rebuild",
list: "ls",
ln: "link",
create: "init",
i: "install",
it: "install-test",
cit: "install-ci-test",
up: "update",
c: "config",
s: "search",
se: "search",
tst: "test",
t: "test",
ddp: "dedupe",
v: "view",
"run-script": "run",
"clean-install": "ci",
"clean-install-test": "install-ci-test",
x: "exec",
why: "explain",
la: "ll",
verison: "version",
ic: "ci",
// typos
innit: "init",
// manually abbrev so that install-test doesn't make insta stop working
in: "install",
ins: "install",
inst: "install",
insta: "install",
instal: "install",
isnt: "install",
isnta: "install",
isntal: "install",
isntall: "install",
"install-clean": "ci",
"isntall-clean": "ci",
hlep: "help",
"dist-tags": "dist-tag",
upgrade: "update",
udpate: "update",
rum: "run",
sit: "install-ci-test",
urn: "run",
ogr: "org",
"add-user": "adduser",
};
export function deref(c) {
if (!c) {
return;
}
// Translate camelCase to snake-case (i.e. installTest to install-test)
if (c.match(/[A-Z]/)) {
c = c.replace(/([A-Z])/g, (m) => "-" + m.toLowerCase());
}
// if they asked for something exactly we are done
if (commands.includes(c)) {
return c;
}
// if they asked for a direct alias
if (aliases[c]) {
return aliases[c];
}
const abbrevs = abbrev(commands.concat(Object.keys(aliases)));
// first deref the abbrev, if there is one
// then resolve any aliases
// so `npm install-cl` will resolve to `install-clean` then to `ci`
let a = abbrevs[c];
while (aliases[a]) {
a = aliases[a];
}
return a;
}

View file

@ -0,0 +1,26 @@
import { deref } from "./cmd-list.js";
export function getNpmCommandForArgs(args) {
if (args.length === 0) {
return null;
}
const argCommand = deref(args[0]);
if (!argCommand) {
return null;
}
return argCommand;
}
export function hasDryRunArg(args) {
return args.some((arg) => arg === "--dry-run");
}
export const npmInstallCommand = "install";
export const npmCiCommand = "ci";
export const npmInstallTestCommand = "install-test";
export const npmInstallCiTestCommand = "install-ci-test";
export const npmUpdateCommand = "update";
export const npmAuditCommand = "audit";
export const npmExecCommand = "exec";

View file

@ -0,0 +1,13 @@
import { commandArgumentScanner } from "./dependencyScanner/commandArgumentScanner.js";
import { runNpx } from "./runNpxCommand.js";
export function createNpxPackageManager() {
const scanner = commandArgumentScanner();
return {
getWarningMessage: () => null,
runCommand: runNpx,
isSupportedCommand: (args) => scanner.shouldScan(args),
getDependencyUpdatesForCommand: (args) => scanner.scan(args),
};
}

View file

@ -0,0 +1,31 @@
import { resolvePackageVersion } from "../../../api/npmApi.js";
import { parsePackagesFromArguments } from "../parsing/parsePackagesFromArguments.js";
export function commandArgumentScanner() {
return {
scan: (args) => scanDependencies(args),
shouldScan: () => true, // all npx commands need to be scanned, npx doesn't have dry-run
};
}
function scanDependencies(args) {
return checkChangesFromArgs(args);
}
export async function checkChangesFromArgs(args) {
const changes = [];
const packageUpdates = parsePackagesFromArguments(args);
for (const packageUpdate of packageUpdates) {
var exactVersion = await resolvePackageVersion(
packageUpdate.name,
packageUpdate.version
);
if (exactVersion) {
packageUpdate.version = exactVersion;
}
changes.push({ ...packageUpdate, type: "add" });
}
return changes;
}

View file

@ -0,0 +1,106 @@
export function parsePackagesFromArguments(args) {
let defaultTag = "latest";
for (let i = 0; i < args.length; i++) {
const arg = args[i];
const option = getOption(arg);
if (option) {
// If the option has a parameter, skip the next argument as well
i += option.numberOfParameters;
continue;
}
const packageDetails = parsePackagename(arg, defaultTag);
if (packageDetails) {
return [packageDetails];
}
}
return [];
}
function getOption(arg) {
if (isOptionWithParameter(arg)) {
return {
name: arg,
numberOfParameters: 1,
};
}
// Arguments starting with "-" or "--" are considered options
// except for "--package=" which contains the package name
if (arg.startsWith("-") && !arg.startsWith("--package=")) {
return {
name: arg,
numberOfParameters: 0,
};
}
return undefined;
}
function isOptionWithParameter(arg) {
const optionsWithParameters = [
"--access",
"--auth-type",
"--cache",
"--fetch-retries",
"--fetch-retry-mintimeout",
"--fetch-retry-maxtimeout",
"--fetch-retry-factor",
"--fetch-timeout",
"--https-proxy",
"--include",
"--location",
"--lockfile-version",
"--loglevel",
"--omit",
"--proxy",
"--registry",
"--replace-registry-host",
"--tag",
"--user-config",
"--workspace",
];
return optionsWithParameters.includes(arg);
}
function parsePackagename(arg, defaultTag) {
// format can be --package=name@version
// in that case, we need to remove the --package= part
if (arg.startsWith("--package=")) {
arg = arg.slice(10);
}
arg = removeAlias(arg);
// Split at the last "@" to separate the package name and version
const lastAtIndex = arg.lastIndexOf("@");
let name, version;
if (lastAtIndex !== -1) {
name = arg.slice(0, lastAtIndex);
version = arg.slice(lastAtIndex + 1);
} else {
name = arg;
version = defaultTag; // No tag specified (eg: "http-server"), use the default tag
}
return {
name,
version,
};
}
function removeAlias(arg) {
// removes the alias.
// Eg.: server@npm:http-server@latest becomes http-server@latest
const aliasIndex = arg.indexOf("@npm:");
if (aliasIndex !== -1) {
return arg.slice(aliasIndex + 5);
}
return arg;
}

View file

@ -0,0 +1,147 @@
import { describe, it } from "node:test";
import assert from "node:assert";
import { parsePackagesFromArguments } from "./parsePackagesFromArguments.js";
describe("parsePackagesFromArguments", () => {
it("should return an empty array for no changes", () => {
const args = [];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, []);
});
it("should return an array of changes for one package", () => {
const args = ["http-server@14.1.1"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [{ name: "http-server", version: "14.1.1" }]);
});
it("should return the package with latest tag if absent", () => {
const args = ["http-server"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [{ name: "http-server", version: "latest" }]);
});
it("should ignore double --", () => {
const args = ["--", "http-server"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [{ name: "http-server", version: "latest" }]);
});
it("should only return the first package", () => {
const args = ["http-server", "jest"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [{ name: "http-server", version: "latest" }]);
});
it("should return package with -p option", () => {
const args = ["-p", "http-server"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [{ name: "http-server", version: "latest" }]);
});
it("should return package with --package option", () => {
const args = ["--package", "http-server"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [{ name: "http-server", version: "latest" }]);
});
it("should return package with --package=x option", () => {
const args = ["--package=http-server"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [{ name: "http-server", version: "latest" }]);
});
it("should return package with --package=x@version option", () => {
const args = ["--package=http-server@1.0.0"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [{ name: "http-server", version: "1.0.0" }]);
});
it("should ignore options with parameters and return an array of changes", () => {
const args = ["--loglevel", "error", "http-server@14.1.1"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [{ name: "http-server", version: "14.1.1" }]);
});
it("should parse version even for aliased packages", () => {
const args = ["server@npm:http-server@14.1.1"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [{ name: "http-server", version: "14.1.1" }]);
});
it("should parse scoped packages", () => {
const args = ["@scope/package@1.0.0"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [{ name: "@scope/package", version: "1.0.0" }]);
});
it("should parse packages with version ranges", () => {
const args = ["http-server@^14.1.1"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [{ name: "http-server", version: "^14.1.1" }]);
});
it("should parse package folders", () => {
const args = ["./local-package"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [{ name: "./local-package", version: "latest" }]);
});
it("should parse tarballs", () => {
const args = ["file:./local-package.tgz"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [
{ name: "file:./local-package.tgz", version: "latest" },
]);
});
it("should parse tarball URLs", () => {
const args = ["https://example.com/local-package.tgz"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [
{ name: "https://example.com/local-package.tgz", version: "latest" },
]);
});
it("should parse git URLs", () => {
const args = ["git://github.com/http-party/http-server"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [
{ name: "git://github.com/http-party/http-server", version: "latest" },
]);
});
});

View file

@ -0,0 +1,17 @@
import { execSync } from "child_process";
import { ui } from "../../environment/userInteraction.js";
export function runNpx(args) {
try {
const npxCommand = `npx ${args.join(" ")}`;
execSync(npxCommand, { stdio: "inherit" });
} catch (error) {
if (error.status) {
return { status: error.status };
} else {
ui.writeError("Error executing command:", error.message);
return { status: 1 };
}
}
return { status: 0 };
}

View file

@ -0,0 +1,34 @@
import { commandArgumentScanner } from "./dependencyScanner/commandArgumentScanner.js";
import { runYarnCommand } from "./runYarnCommand.js";
const scanner = commandArgumentScanner();
export function createYarnPackageManager() {
return {
getWarningMessage: () => null,
runCommand: runYarnCommand,
isSupportedCommand: (args) =>
matchesCommand(args, "add") ||
matchesCommand(args, "global", "add") ||
matchesCommand(args, "install") ||
matchesCommand(args, "up") ||
matchesCommand(args, "upgrade") ||
matchesCommand(args, "global", "upgrade") ||
matchesCommand(args, "dlx"),
getDependencyUpdatesForCommand: (args) => scanner.scan(args),
};
}
function matchesCommand(args, ...commandArgs) {
if (args.length < commandArgs.length) {
return false;
}
for (var i = 0; i < commandArgs.length; i++) {
if (args[i].toLowerCase() !== commandArgs[i].toLowerCase()) {
return false;
}
}
return true;
}

View file

@ -0,0 +1,28 @@
import { resolvePackageVersion } from "../../../api/npmApi.js";
import { parsePackagesFromArguments } from "../parsing/parsePackagesFromArguments.js";
export function commandArgumentScanner() {
return {
scan: (args) => scanDependencies(args),
shouldScan: () => true, // There's no dry run for yarn, so we always scan
};
}
async function scanDependencies(args) {
const changes = [];
const packageUpdates = parsePackagesFromArguments(args);
for (const packageUpdate of packageUpdates) {
var exactVersion = await resolvePackageVersion(
packageUpdate.name,
packageUpdate.version
);
if (exactVersion) {
packageUpdate.version = exactVersion;
}
changes.push({ ...packageUpdate, type: "add" });
}
return changes;
}

View file

@ -0,0 +1,102 @@
export function parsePackagesFromArguments(args) {
const changes = [];
let defaultTag = "latest";
for (let i = 1; i < args.length; i++) {
const arg = args[i];
const option = getOption(arg);
if (option) {
// If the option has a parameter, skip the next argument as well
i += option.numberOfParameters;
continue;
}
const packageDetails = parsePackagename(arg, defaultTag);
if (packageDetails) {
changes.push(packageDetails);
}
}
return changes;
}
function getOption(arg) {
if (isOptionWithParameter(arg)) {
return {
name: arg,
numberOfParameters: 1,
};
}
// Arguments starting with "-" or "--" are considered options
// except for "--package=" which contains the package name
if (arg.startsWith("-")) {
return {
name: arg,
numberOfParameters: 0,
};
}
return undefined;
}
function isOptionWithParameter(arg) {
const optionsWithParameters = [
"--use-yarnrc",
"--link-folder",
"--global-folder",
"--modules-folder",
"--preferred-cache-folder",
"--cache-folder",
"--mutex",
"--cwd",
"--proxy",
"--https-proxy",
"--registry",
"--network-concurrency",
"--network-timeout",
"--scripts-prepend-node-path",
"--otp",
];
return optionsWithParameters.includes(arg);
}
function parsePackagename(arg, defaultTag) {
// format can be --package=name@version
// in that case, we need to remove the --package= part
if (arg.startsWith("--package=")) {
arg = arg.slice(10);
}
arg = removeAlias(arg);
// Split at the last "@" to separate the package name and version
const lastAtIndex = arg.lastIndexOf("@");
let name, version;
if (lastAtIndex !== -1) {
name = arg.slice(0, lastAtIndex);
version = arg.slice(lastAtIndex + 1);
} else {
name = arg;
version = defaultTag; // No tag specified (eg: "http-server"), use the default tag
}
return {
name,
version,
};
}
function removeAlias(arg) {
// removes the alias.
// Eg.: server@npm:http-server@latest becomes http-server@latest
const aliasIndex = arg.indexOf("@npm:");
if (aliasIndex !== -1) {
return arg.slice(aliasIndex + 5);
}
return arg;
}

View file

@ -0,0 +1,126 @@
import { describe, it } from "node:test";
import assert from "node:assert";
import { parsePackagesFromArguments } from "./parsePackagesFromArguments.js";
describe("standardYarnArgumentParser", () => {
it("should return an empty array for no changes", () => {
const args = ["add"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, []);
});
it("should return an array of changes for one package", () => {
const args = ["add", "axios@1.9.0"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [{ name: "axios", version: "1.9.0" }]);
});
it("should return the package with latest tag if absent", () => {
const args = ["add", "axios"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [{ name: "axios", version: "latest" }]);
});
it("should only return all packages", () => {
const args = ["add", "axios", "jest"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [
{ name: "axios", version: "latest" },
{ name: "jest", version: "latest" },
]);
});
it("should ignore options with parameters and return an array of changes", () => {
const args = ["add", "--proxy", "http://localhost", "axios@1.9.0"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [{ name: "axios", version: "1.9.0" }]);
});
it("should parse version even for aliased packages", () => {
const args = ["add", "server@npm:axios@1.9.0"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [{ name: "axios", version: "1.9.0" }]);
});
it("should parse scoped packages", () => {
const args = ["add", "@scope/package@1.0.0"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [{ name: "@scope/package", version: "1.0.0" }]);
});
it("should parse packages with version ranges", () => {
const args = ["add", "axios@^1.9.0"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [{ name: "axios", version: "^1.9.0" }]);
});
it("should parse package folders", () => {
const args = ["add", "./local-package"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [{ name: "./local-package", version: "latest" }]);
});
it("should parse tarballs", () => {
const args = ["add", "file:./local-package.tgz"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [
{ name: "file:./local-package.tgz", version: "latest" },
]);
});
it("should parse tarball URLs", () => {
const args = ["add", "https://example.com/local-package.tgz"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [
{ name: "https://example.com/local-package.tgz", version: "latest" },
]);
});
it("should parse git URLs", () => {
const args = ["add", "git://github.com/http-party/http-server"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [
{ name: "git://github.com/http-party/http-server", version: "latest" },
]);
});
it("should parse packages with -p {packageName}", () => {
const args = ["dlx", "-p", "axios@1.9.0"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [{ name: "axios", version: "1.9.0" }]);
});
it("should parse packages with --package {packageName}", () => {
const args = ["dlx", "--package", "axios@1.9.0"];
const result = parsePackagesFromArguments(args);
assert.deepEqual(result, [{ name: "axios", version: "1.9.0" }]);
});
});

View file

@ -0,0 +1,17 @@
import { execSync } from "child_process";
import { ui } from "../../environment/userInteraction.js";
export function runYarnCommand(args) {
try {
const npxCommand = `yarn ${args.join(" ")}`;
execSync(npxCommand, { stdio: "inherit" });
} catch (error) {
if (error.status) {
return { status: error.status };
} else {
ui.writeError("Error executing command:", error.message);
return { status: 1 };
}
}
return { status: 0 };
}

View file

@ -0,0 +1,56 @@
import {
MALWARE_STATUS_MALWARE,
openMalwareDatabase,
} from "../malwareDatabase.js";
export async function auditChanges(changes) {
const allowedChanges = [];
const disallowedChanges = [];
var malwarePackages = await getPackagesWithMalware(
changes.filter(
(change) => change.type === "add" || change.type === "change"
)
);
for (const change of changes) {
const malwarePackage = malwarePackages.find(
(pkg) => pkg.name === change.name && pkg.version === change.version
);
if (malwarePackage) {
disallowedChanges.push({ ...change, reason: malwarePackage.status });
} else {
allowedChanges.push(change);
}
}
const auditResults = {
allowedChanges,
disallowedChanges,
isAllowed: disallowedChanges.length === 0,
};
return auditResults;
}
async function getPackagesWithMalware(changes) {
if (changes.length === 0) {
return [];
}
const malwareDb = await openMalwareDatabase();
let allVulnerablePackages = [];
for (const change of changes) {
if (malwareDb.isMalware(change.name, change.version)) {
allVulnerablePackages.push({
name: change.name,
version: change.version,
status: MALWARE_STATUS_MALWARE,
});
}
}
return allVulnerablePackages;
}

92
src/scanning/index.js Normal file
View file

@ -0,0 +1,92 @@
import { auditChanges } from "./audit/index.js";
import { getScanTimeout } from "../config/configFile.js";
import { setTimeout } from "timers/promises";
import chalk from "chalk";
import { getPackageManager } from "../packagemanager/currentPackageManager.js";
import { ui } from "../environment/userInteraction.js";
export function shouldScanCommand(args) {
if (!args || args.length === 0) {
return false;
}
return getPackageManager().isSupportedCommand(args);
}
export async function scanCommand(args) {
if (!shouldScanCommand(args)) {
return [];
}
let timedOut = false;
const spinner = ui.startProcess("Scanning for malicious packages...");
let audit;
await Promise.race([
(async () => {
try {
const packageManager = getPackageManager();
const changes = await packageManager.getDependencyUpdatesForCommand(
args
);
if (timedOut) {
return;
}
if (changes.length > 0) {
spinner.setText(`Scanning ${changes.length} package(s)...`);
}
audit = await auditChanges(changes);
} catch (error) {
spinner.fail(`Error while scanning: ${error.message}`);
throw error;
}
})(),
setTimeout(getScanTimeout()).then(() => {
timedOut = true;
}),
]);
if (timedOut) {
spinner.fail("Timeout exceeded while scanning.");
throw new Error("Timeout exceeded while scanning npm install command.");
}
if (!audit || audit.isAllowed) {
spinner.succeed("No malicious packages detected.");
} else {
printMaliciousChanges(audit.disallowedChanges, spinner);
await acceptRiskOrExit(
"Do you want to continue with the installation despite the risks?",
false
);
}
}
function printMaliciousChanges(changes, spinner) {
spinner.fail(chalk.bold("Malicious changes detected:"));
for (const change of changes) {
ui.writeInformation(` - ${change.name}@${change.version}`);
}
}
async function acceptRiskOrExit(message, defaultValue) {
ui.emptyLine();
const continueInstall = await ui.confirm({
message: message,
default: defaultValue,
});
if (continueInstall) {
ui.writeInformation("Continuing with the installation...");
return;
}
ui.writeInformation("Exiting without installing packages.");
ui.emptyLine();
process.exit(1);
}

View file

@ -0,0 +1,180 @@
import assert from "node:assert/strict";
import { describe, it, mock } from "node:test";
import { setTimeout } from "node:timers/promises";
describe("scanCommand", async () => {
const getScanTimeoutMock = mock.fn(() => 1000);
const mockGetDependencyUpdatesForCommand = mock.fn();
const mockStartProcess = mock.fn(() => ({
setText: () => {},
succeed: () => {},
fail: () => {},
}));
const mockConfirm = mock.fn(() => true);
// import { getPackageManager } from "../packagemanager/currentPackageManager.js";
mock.module("../packagemanager/currentPackageManager.js", {
namedExports: {
getPackageManager: () => {
return {
isSupportedCommand: () => true,
getDependencyUpdatesForCommand: mockGetDependencyUpdatesForCommand,
};
},
},
});
// import { getScanTimeout } from "../config/configFile.js";
mock.module("../config/configFile.js", {
namedExports: {
getScanTimeout: getScanTimeoutMock,
getBaseUrl: () => undefined,
},
});
// import { ui } from "../environment/userInteraction.js";
mock.module("../environment/userInteraction.js", {
namedExports: {
ui: {
startProcess: mockStartProcess,
writeError: () => {},
writeInformation: () => {},
writeWarning: () => {},
emptyLine: () => {},
confirm: mockConfirm,
},
},
});
// import { auditChanges, MAX_LENGTH_EXCEEDED } from "./audit/index.js";
mock.module("./audit/index.js", {
namedExports: {
auditChanges: (changes) => {
const malisciousChangeName = "malicious";
const allowedChanges = changes.filter(
(change) => change.name !== malisciousChangeName
);
const disallowedChanges = changes
.filter((change) => change.name === malisciousChangeName)
.map((change) => ({
...change,
reason: "malicious",
}));
const auditResults = {
allowedChanges,
disallowedChanges,
isAllowed: disallowedChanges.length === 0,
};
return auditResults;
},
MAX_LENGTH_EXCEEDED: "MAX_LENGTH_EXCEEDED",
},
});
const { scanCommand } = await import("./index.js");
it("should succeed when there are no changes", async () => {
let successMessageWasSet = false;
mockStartProcess.mock.mockImplementationOnce(() => ({
setText: () => {},
succeed: () => {
successMessageWasSet = true;
},
fail: () => {},
}));
mockGetDependencyUpdatesForCommand.mock.mockImplementation(() => []);
await scanCommand(["install", "lodash"]);
assert.equal(successMessageWasSet, true);
});
it("should succeed when changes are not malicious", async () => {
let successMessageWasSet = false;
mockStartProcess.mock.mockImplementationOnce(() => ({
setText: () => {},
succeed: () => {
successMessageWasSet = true;
},
fail: () => {},
}));
mockGetDependencyUpdatesForCommand.mock.mockImplementation(() => [
{ name: "lodash", version: "4.17.21" },
]);
await scanCommand(["install", "lodash"]);
assert.equal(successMessageWasSet, true);
});
it("should throw an error when timing out", async () => {
let failureMessageWasSet = false;
mockStartProcess.mock.mockImplementationOnce(() => ({
setText: () => {},
succeed: () => {},
fail: () => {
failureMessageWasSet = true;
},
}));
getScanTimeoutMock.mock.mockImplementationOnce(() => 100);
mockGetDependencyUpdatesForCommand.mock.mockImplementation(async () => {
await setTimeout(150);
return [{ name: "lodash", version: "4.17.21" }];
});
await assert.rejects(scanCommand(["install", "lodash"]));
assert.equal(failureMessageWasSet, true);
});
it("should fail and prompt the user when malicious changes are detected", async () => {
let failureMessageWasSet = false;
mockStartProcess.mock.mockImplementationOnce(() => ({
setText: () => {},
succeed: () => {},
fail: () => {
failureMessageWasSet = true;
},
}));
mockGetDependencyUpdatesForCommand.mock.mockImplementation(() => [
{ name: "malicious", version: "1.0.0" },
]);
let userWasPrompted = false;
mockConfirm.mock.mockImplementationOnce(() => {
userWasPrompted = true;
return true; // Simulate user accepting the risk, otherwise the process would exit
});
await scanCommand(["install", "malicious"]);
assert.equal(failureMessageWasSet, true);
assert.equal(userWasPrompted, true);
});
it("should not report a timeout when the user takes a long time to respond (it should not affect the timeout)", async () => {
let failureMessages = [];
mockStartProcess.mock.mockImplementationOnce(() => ({
setText: () => {},
succeed: () => {},
fail: (message) => {
failureMessages.push(message);
},
}));
getScanTimeoutMock.mock.mockImplementationOnce(() => 100);
mockGetDependencyUpdatesForCommand.mock.mockImplementation(async () => {
return [{ name: "malicious", version: "4.17.21" }];
});
mockConfirm.mock.mockImplementationOnce(async () => {
await setTimeout(200);
return true; // Simulate user accepting the risk, otherwise the process would exit
});
await scanCommand(["install", "malicious"]);
assert.equal(failureMessages.length, 1);
const failureMessage = failureMessages[0];
assert.equal(failureMessage.toLowerCase().includes("timeout"), false);
assert.equal(failureMessage.toLowerCase().includes("malicious"), true);
});
});

View file

@ -0,0 +1,47 @@
import assert from "node:assert/strict";
import { describe, it, mock } from "node:test";
describe("shouldScanCommand", async () => {
const isSupportedCommandMock = mock.fn(() => undefined);
mock.module("../packagemanager/currentPackageManager.js", {
namedExports: {
getPackageManager: () => {
return {
isSupportedCommand: isSupportedCommandMock,
getDependencyUpdatesForCommand: () => [],
};
},
},
});
const { shouldScanCommand } = await import("./index.js");
it("should return false if the argument is an empty array", () => {
const result = shouldScanCommand([]);
assert.strictEqual(result, false);
});
it("should return false if the argument is undefined", () => {
const result = shouldScanCommand(undefined);
assert.strictEqual(result, false);
});
it("should return true if the package manager supports the command", () => {
isSupportedCommandMock.mock.mockImplementation(() => true);
const result = shouldScanCommand(["install", "lodash"]);
assert.strictEqual(result, true);
});
it("should return false if the package manager does not support the command", () => {
isSupportedCommandMock.mock.mockImplementation(() => false);
const result = shouldScanCommand(["unknown", "command"]);
assert.strictEqual(result, false);
});
});

View file

@ -0,0 +1,72 @@
import {
fetchMalwareDatabase,
fetchMalwareDatabaseVersion,
} from "../api/aikido.js";
import {
readDatabaseFromLocalCache,
writeDatabaseToLocalCache,
} from "../config/configFile.js";
import { ui } from "../environment/userInteraction.js";
export async function openMalwareDatabase() {
const malwareDatabase = await getMalwareDatabase();
function getPackageStatus(name, version) {
const packageData = malwareDatabase.find(
(pkg) =>
pkg.package_name === name &&
(pkg.version === version || pkg.version === "*")
);
if (!packageData) {
return MALWARE_STATUS_OK;
}
return packageData.reason;
}
return {
getPackageStatus,
isMalware: (name, version) => {
const status = getPackageStatus(name, version);
return isMalwareStatus(status);
},
};
}
async function getMalwareDatabase() {
const { malwareDatabase: cachedDatabase, version: cachedVersion } =
readDatabaseFromLocalCache();
try {
if (cachedDatabase) {
const currentVersion = await fetchMalwareDatabaseVersion();
if (cachedVersion === currentVersion) {
return cachedDatabase;
}
}
const { malwareDatabase, version } = await fetchMalwareDatabase();
writeDatabaseToLocalCache(malwareDatabase, version);
return malwareDatabase;
} catch (error) {
if (cachedDatabase) {
ui.writeWarning(
"Failed to fetch the latest malware database. Using cached version."
);
return cachedDatabase;
}
throw error;
}
}
function isMalwareStatus(status) {
let malwareStatus = status.toUpperCase();
return malwareStatus === MALWARE_STATUS_MALWARE;
}
export const MALWARE_STATUS_OK = "OK";
export const MALWARE_STATUS_MALWARE = "MALWARE";
export const MALWARE_STATUS_TELEMETRY = "TELEMETRY";
export const MALWARE_STATUS_PROTESTWARE = "PROTESTWARE";

View file

@ -0,0 +1,44 @@
const knownAikidoTools = [
{ tool: "npm", aikidoCommand: "aikido-npm" },
{ tool: "npx", aikidoCommand: "aikido-npx" },
{ tool: "yarn", aikidoCommand: "aikido-yarn" },
// When adding a new tool here, also update the expected alias in the tests (shellIntegration.spec.js)
// and add the documentation for the new tool in the README.md
];
export function getAliases(fileName) {
const fileExtension = fileName.split(".").pop().toLowerCase();
let createAlias = pickCreateAliasFunction(fileExtension);
const aliases = knownAikidoTools.map(({ tool, aikidoCommand }) =>
createAlias(tool, aikidoCommand)
);
return aliases;
}
function pickCreateAliasFunction(fileExtension) {
let createAlias;
switch (fileExtension) {
case "ps1":
createAlias = createGeneralPowershellAlias;
break;
case "fish":
createAlias = createGeneralFishAlias;
break;
default:
createAlias = createGeneralPosixAlias;
}
return createAlias;
}
function createGeneralPosixAlias(tool, aikidoCommand) {
return `alias ${tool}='${aikidoCommand}'`;
}
function createGeneralPowershellAlias(tool, aikidoCommand) {
return `Set-Alias ${tool} ${aikidoCommand}`;
}
function createGeneralFishAlias(tool, aikidoCommand) {
return `alias ${tool} "${aikidoCommand}"`;
}

View file

@ -0,0 +1,151 @@
import chalk from "chalk";
import { ui } from "../environment/userInteraction.js";
import { detectShells } from "./shellDetection.js";
import { getAliases } from "./helpers.js";
import fs from "fs";
import { EOL } from "os";
export async function setup() {
ui.writeInformation(
chalk.bold("Setting up shell aliases.") +
" This will wrap safe-chain around npm, npx, and yarn commands."
);
ui.emptyLine();
try {
const shells = detectShells();
if (shells.length === 0) {
ui.writeError("No supported shells detected. Cannot set up aliases.");
return;
}
ui.writeInformation(
`Detected ${shells.length} supported shell(s): ${shells
.map((shell) => chalk.bold(shell.name))
.join(", ")}.`
);
let updatedCount = 0;
for (const shell of shells) {
if (setupAliasesForShell(shell)) {
updatedCount++;
}
}
if (updatedCount > 0) {
ui.emptyLine();
ui.writeInformation(`Please restart your terminal to apply the changes.`);
}
} catch (error) {
ui.writeError(
`Failed to set up shell aliases: ${error.message}. Please check your shell configuration.`
);
return;
}
}
/**
* This function sets up aliases for the given shell.
* It reads the shell's startup file (eg ~/.bashrc, ~/.zshrc, etc.),
* and then appends the aliases for npm, npx, and yarn commands.
* If the aliases already exist, it will not add them again.
* If the startup file does not exist, it will create it.
*
* The shell startup script is loaded by the respective shell when it starts.
* This means that the aliases will be available in the shell after it is restarted.
*/
function setupAliasesForShell(shell) {
if (!shell.startupFile) {
ui.writeError(
`- ${chalk.bold(
shell.name
)}: no startup file found. Cannot set up aliases.`
);
return false;
}
const aliases = getAliases(shell.startupFile);
if (aliases.length === 0) {
ui.writeError(`- ${chalk.bold(shell.name)}: could not generate aliases.`);
return false;
}
const fileContent = readOrCreateStartupFile(shell.startupFile);
const { addedCount, existingCount, failedCount } = appendAliasesToFile(
aliases,
fileContent,
shell.startupFile
);
let summary = "- " + chalk.bold(shell.name) + ": ";
if (addedCount > 0) {
summary += chalk.green(`${addedCount} aliases were added`);
}
if (existingCount > 0) {
if (addedCount > 0) {
summary += ", ";
}
summary += chalk.yellow(`${existingCount} aliases were already present`);
}
if (failedCount > 0) {
if (addedCount > 0 || existingCount > 0) {
summary += ", ";
}
summary += chalk.red(`${failedCount} aliases failed to add`);
}
// write summary in a single line
ui.writeInformation(summary);
return true;
}
/**
* This reads the content of the startup file.
* If the file does not exist, it creates an empty file and returns an empty string.
* The startup file is the shell's startup script (eg: ~/.bashrc, ~/.zshrc, etc.).
* It is used to set up the shell environment when it starts.
* Some shells may not have a startup file, in which case this function will create one.
*/
export function readOrCreateStartupFile(filePath) {
if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, "", "utf-8");
ui.writeInformation(`File ${filePath} created.`);
}
return fs.readFileSync(filePath, "utf-8");
}
/**
* This function appends the aliases to the startup file.
* eg: for bash it will append 'alias npm="aikido-npm"' for npm to ~/.bashrc
* @returns an object with the counts of added, existing, and failed aliases.
*/
export function appendAliasesToFile(aliases, fileContent, startupFilePath) {
let addedCount = 0;
let existingCount = 0;
let failedCount = 0;
for (const alias of aliases) {
try {
if (fileContent.includes(alias)) {
existingCount++;
continue;
}
fs.appendFileSync(startupFilePath, `${EOL}${alias}`, "utf-8");
addedCount++;
} catch {
failedCount++;
continue;
}
}
return {
addedCount,
existingCount,
failedCount,
};
}

View file

@ -0,0 +1,304 @@
import { describe, it } from "node:test";
import assert from "node:assert";
import { EOL, tmpdir } from "node:os";
import fs from "node:fs";
import { getAliases } from "./helpers.js";
import { readOrCreateStartupFile, appendAliasesToFile } from "./setup.js";
describe("setupShell", () => {
function runSetupTestsForEnvironment(shell, startupExtension, expectedAliases) {
describe(`${shell} shell setup`, () => {
it(`should add aliases to ${shell} file`, () => {
const lines = [`#!/usr/bin/env ${shell}`, "", "alias cls='clear'"];
const filePath = createShellStartupScript(lines, startupExtension);
const aliases = getAliases(filePath);
const fileContent = fs.readFileSync(filePath, "utf-8");
const result = appendAliasesToFile(aliases, fileContent, filePath);
assert.strictEqual(result.addedCount, 3, "Should add 3 aliases");
assert.strictEqual(result.existingCount, 0, "Should find no existing aliases");
assert.strictEqual(result.failedCount, 0, "Should have no failed aliases");
const updatedContent = readAndDeleteFile(filePath);
for (const alias of expectedAliases) {
assert.ok(updatedContent.includes(alias), `Alias "${alias}" should be added`);
}
assert.ok(updatedContent.includes("alias cls='clear'"), "Original aliases should remain");
});
it(`should not add aliases if they already exist in ${shell} file`, () => {
const lines = [`#!/usr/bin/env ${shell}`, "", ...expectedAliases];
const filePath = createShellStartupScript(lines, startupExtension);
const aliases = getAliases(filePath);
const fileContent = fs.readFileSync(filePath, "utf-8");
const result = appendAliasesToFile(aliases, fileContent, filePath);
assert.strictEqual(result.addedCount, 0, "Should add 0 aliases");
assert.strictEqual(result.existingCount, 3, "Should find 3 existing aliases");
assert.strictEqual(result.failedCount, 0, "Should have no failed aliases");
const updatedContent = readAndDeleteFile(filePath);
// Count occurrences to ensure no duplicates were added
for (const alias of expectedAliases) {
assert.strictEqual(countOccurrences(updatedContent, alias), 1, `Alias "${alias}" should appear exactly once`);
}
});
it(`should create file and add aliases if file does not exist for ${shell}`, () => {
const randomName = Math.random().toString(36).substring(2, 15);
const filePath = `${tmpdir()}/nonexistent-${randomName}${startupExtension}`;
if (fs.existsSync(filePath)) {
fs.rmSync(filePath, { force: true });
}
// Test readOrCreateStartupFile function
const fileContent = readOrCreateStartupFile(filePath);
assert.strictEqual(fileContent, "", "Should return empty string for new file");
assert.ok(fs.existsSync(filePath), "File should be created");
// Test adding aliases to the newly created file
const aliases = getAliases(filePath);
const result = appendAliasesToFile(aliases, fileContent, filePath);
assert.strictEqual(result.addedCount, 3, "Should add 3 aliases");
assert.strictEqual(result.existingCount, 0, "Should find no existing aliases");
assert.strictEqual(result.failedCount, 0, "Should have no failed aliases");
const updatedContent = readAndDeleteFile(filePath);
for (const alias of expectedAliases) {
assert.ok(updatedContent.includes(alias), `Alias "${alias}" should be added`);
}
});
it(`should add aliases only once when called multiple times for ${shell}`, () => {
const lines = [`#!/usr/bin/env ${shell}`, ""];
const filePath = createShellStartupScript(lines, startupExtension);
const aliases = getAliases(filePath);
// First call - should add aliases
let fileContent = fs.readFileSync(filePath, "utf-8");
const result1 = appendAliasesToFile(aliases, fileContent, filePath);
assert.strictEqual(result1.addedCount, 3, "First call should add 3 aliases");
// Second call - should detect existing aliases
fileContent = fs.readFileSync(filePath, "utf-8");
const result2 = appendAliasesToFile(aliases, fileContent, filePath);
assert.strictEqual(result2.addedCount, 0, "Second call should add 0 aliases");
assert.strictEqual(result2.existingCount, 3, "Second call should find 3 existing aliases");
const updatedContent = readAndDeleteFile(filePath);
for (const alias of expectedAliases) {
assert.strictEqual(countOccurrences(updatedContent, alias), 1, `Alias "${alias}" should appear exactly once`);
}
});
it(`should use real getAliases() for ${shell} file`, () => {
const filePath = `${tmpdir()}/test${startupExtension}`;
const aliases = getAliases(filePath);
// Verify we get the expected aliases for this shell type
assert.strictEqual(aliases.length, 3, "Should get 3 aliases (npm, npx, yarn)");
for (let i = 0; i < aliases.length; i++) {
assert.strictEqual(aliases[i], expectedAliases[i], `Alias ${i} should match expected format`);
}
});
it(`should handle mixed scenario - some existing, some new for ${shell}`, () => {
const lines = [`#!/usr/bin/env ${shell}`, "", expectedAliases[0], "alias other='command'"];
const filePath = createShellStartupScript(lines, startupExtension);
const aliases = getAliases(filePath);
const fileContent = fs.readFileSync(filePath, "utf-8");
const result = appendAliasesToFile(aliases, fileContent, filePath);
assert.strictEqual(result.addedCount, 2, "Should add 2 new aliases");
assert.strictEqual(result.existingCount, 1, "Should find 1 existing alias");
assert.strictEqual(result.failedCount, 0, "Should have no failed aliases");
const updatedContent = readAndDeleteFile(filePath);
for (const alias of expectedAliases) {
assert.ok(updatedContent.includes(alias), `Alias "${alias}" should be present`);
}
assert.ok(updatedContent.includes("alias other='command'"), "Other aliases should remain");
});
});
}
// Test for each shell type using real getAliases() output
runSetupTestsForEnvironment("bash", ".bashrc", [
"alias npm='aikido-npm'",
"alias npx='aikido-npx'",
"alias yarn='aikido-yarn'"
]);
runSetupTestsForEnvironment("zsh", ".zshrc", [
"alias npm='aikido-npm'",
"alias npx='aikido-npx'",
"alias yarn='aikido-yarn'"
]);
runSetupTestsForEnvironment("fish", ".fish", [
'alias npm "aikido-npm"',
'alias npx "aikido-npx"',
'alias yarn "aikido-yarn"'
]);
runSetupTestsForEnvironment("pwsh", ".ps1", [
"Set-Alias npm aikido-npm",
"Set-Alias npx aikido-npx",
"Set-Alias yarn aikido-yarn"
]);
describe("readOrCreateStartupFile", () => {
it("should read existing file content", () => {
const lines = ["#!/usr/bin/env bash", "", "alias test='echo test'"];
const filePath = createShellStartupScript(lines, ".bashrc");
const content = readOrCreateStartupFile(filePath);
assert.ok(content.includes("#!/usr/bin/env bash"), "Should contain shebang");
assert.ok(content.includes("alias test='echo test'"), "Should contain existing aliases");
// Cleanup
fs.rmSync(filePath, { force: true });
});
it("should create file if it doesn't exist", () => {
const filePath = `${tmpdir()}/test-${Math.random().toString(36).substring(2, 15)}.bashrc`;
if (fs.existsSync(filePath)) {
fs.rmSync(filePath, { force: true });
}
const content = readOrCreateStartupFile(filePath);
assert.strictEqual(content, "", "Should return empty string for new file");
assert.ok(fs.existsSync(filePath), "File should be created");
// Cleanup
fs.rmSync(filePath, { force: true });
});
it("should handle empty existing file", () => {
const filePath = `${tmpdir()}/test-${Math.random().toString(36).substring(2, 15)}.bashrc`;
fs.writeFileSync(filePath, "", "utf-8");
const content = readOrCreateStartupFile(filePath);
assert.strictEqual(content, "", "Should return empty string for empty file");
assert.ok(fs.existsSync(filePath), "File should still exist");
// Cleanup
fs.rmSync(filePath, { force: true });
});
});
describe("appendAliasesToFile edge cases", () => {
it("should handle empty aliases array", () => {
const lines = ["#!/usr/bin/env bash", "", "alias test='echo test'"];
const filePath = createShellStartupScript(lines, ".bashrc");
const fileContent = fs.readFileSync(filePath, "utf-8");
const result = appendAliasesToFile([], fileContent, filePath);
assert.strictEqual(result.addedCount, 0, "Should add 0 aliases");
assert.strictEqual(result.existingCount, 0, "Should find 0 existing aliases");
assert.strictEqual(result.failedCount, 0, "Should have 0 failed aliases");
const updatedContent = readAndDeleteFile(filePath);
assert.ok(updatedContent.includes("alias test='echo test'"), "Original content should remain");
});
it("should handle partial substring matches correctly", () => {
const lines = [
"#!/usr/bin/env bash",
"",
"alias npmx='some-other-command'", // Contains 'npm' but shouldn't match 'alias npm='
"alias test='echo test'"
];
const filePath = createShellStartupScript(lines, ".bashrc");
const fileContent = fs.readFileSync(filePath, "utf-8");
const aliases = ["alias npm='aikido-npm'"];
const result = appendAliasesToFile(aliases, fileContent, filePath);
assert.strictEqual(result.addedCount, 1, "Should add 1 alias (npm)");
assert.strictEqual(result.existingCount, 0, "Should find 0 existing aliases");
assert.strictEqual(result.failedCount, 0, "Should have 0 failed aliases");
const updatedContent = readAndDeleteFile(filePath);
assert.ok(updatedContent.includes("alias npm='aikido-npm'"), "npm alias should be added");
assert.ok(updatedContent.includes("alias npmx='some-other-command'"), "npmx alias should remain");
});
it("should handle file with only whitespace", () => {
const filePath = `${tmpdir()}/test-${Math.random().toString(36).substring(2, 15)}.bashrc`;
const fileContent = `${EOL}${EOL} ${EOL}`;
fs.writeFileSync(filePath, fileContent, "utf-8");
const aliases = ["alias npm='aikido-npm'"];
const result = appendAliasesToFile(aliases, fileContent, filePath);
assert.strictEqual(result.addedCount, 1, "Should add 1 alias");
assert.strictEqual(result.existingCount, 0, "Should find 0 existing aliases");
assert.strictEqual(result.failedCount, 0, "Should have 0 failed aliases");
const updatedContent = fs.readFileSync(filePath, "utf-8");
assert.ok(updatedContent.includes("alias npm='aikido-npm'"), "Alias should be added");
// Cleanup
fs.rmSync(filePath, { force: true });
});
});
describe("appendAliasesToFile error handling", () => {
it("should handle file permission errors gracefully", () => {
const filePath = `${tmpdir()}/test-${Math.random().toString(36).substring(2, 15)}.bashrc`;
fs.writeFileSync(filePath, "#!/usr/bin/env bash", "utf-8");
// Make file read-only to simulate permission error
fs.chmodSync(filePath, 0o444);
const aliases = ["alias npm='aikido-npm'"];
const fileContent = fs.readFileSync(filePath, "utf-8");
const result = appendAliasesToFile(aliases, fileContent, filePath);
assert.strictEqual(result.addedCount, 0, "Should add 0 aliases due to permission error");
assert.strictEqual(result.existingCount, 0, "Should find 0 existing aliases");
assert.strictEqual(result.failedCount, 1, "Should have 1 failed alias");
// Restore permissions and cleanup
fs.chmodSync(filePath, 0o644);
fs.rmSync(filePath, { force: true });
});
});
});
function createShellStartupScript(lines, fileExtension) {
const randomFileName = Math.random().toString(36).substring(2, 15);
const filePath = `${tmpdir()}/${randomFileName}${fileExtension}`;
fs.writeFileSync(filePath, lines.join(EOL), "utf-8");
return filePath;
}
function readAndDeleteFile(filePath) {
const fileContent = fs.readFileSync(filePath, "utf-8");
fs.rmSync(filePath, { force: true });
return fileContent.split(EOL);
}
function countOccurrences(lines, searchString) {
let count = 0;
for (const line of lines) {
if (line.includes(searchString)) {
count++;
}
}
return count;
}

View file

@ -0,0 +1,75 @@
import * as os from "os";
import { execSync } from "child_process";
const shellList = {
bash: {
name: "Bash",
executable: "bash",
getStartupFileCommand: "echo ~/.bashrc",
},
zsh: {
name: "Zsh",
executable: "zsh",
getStartupFileCommand: "echo ${ZDOTDIR:-$HOME}/.zshrc",
},
fish: {
name: "Fish",
executable: "fish",
getStartupFileCommand: "echo ~/.config/fish/config.fish",
},
powershell: {
name: "PowerShell Core",
executable: "pwsh",
getStartupFileCommand: "echo $PROFILE",
},
windowsPowerShell: {
name: "Windows PowerShell",
executable: "powershell",
getStartupFileCommand: "echo $PROFILE",
},
};
export function detectShells() {
let availableShells = [];
for (const shellName of Object.keys(shellList)) {
const shell = shellList[shellName];
if (isShellAvailable(shell)) {
const startupFile = getShellStartupFile(shell);
availableShells.push({
name: shell.name,
executable: shell.executable,
startupFile: startupFile || null,
});
}
}
return availableShells;
}
function isShellAvailable(shell) {
try {
if (os.platform() === "win32") {
execSync(`where ${shell.executable}`, { stdio: "ignore" });
} else {
execSync(`which ${shell.executable}`, { stdio: "ignore" });
}
return true;
} catch {
return false;
}
}
function getShellStartupFile(shell) {
try {
const command = shell.getStartupFileCommand;
const output = execSync(command, {
encoding: "utf8",
shell: shell.executable,
}).trim();
return output;
} catch {
return null;
}
}

View file

@ -0,0 +1,140 @@
import chalk from "chalk";
import { ui } from "../environment/userInteraction.js";
import { detectShells } from "./shellDetection.js";
import { getAliases } from "./helpers.js";
import fs from "fs";
import { EOL } from "os";
export async function teardown() {
ui.writeInformation(
chalk.bold("Removing shell aliases.") +
" This will remove safe-chain aliases for npm, npx, and yarn commands."
);
ui.emptyLine();
try {
const shells = detectShells();
if (shells.length === 0) {
ui.writeError("No supported shells detected. Cannot remove aliases.");
return;
}
ui.writeInformation(
`Detected ${shells.length} supported shell(s): ${shells
.map((shell) => chalk.bold(shell.name))
.join(", ")}.`
);
let updatedCount = 0;
for (const shell of shells) {
if (removeAliasesForShell(shell)) {
updatedCount++;
}
}
if (updatedCount > 0) {
ui.emptyLine();
ui.writeInformation(`Please restart your terminal to apply the changes.`);
}
} catch (error) {
ui.writeError(
`Failed to remove shell aliases: ${error.message}. Please check your shell configuration.`
);
return;
}
}
/**
* This function removes aliases for the given shell.
* It reads the shell's startup file (eg ~/.bashrc, ~/.zshrc, etc.),
* and then removes the aliases for npm, npx, and yarn commands.
* If the aliases don't exist, it will report that they were not found.
* If the startup file does not exist, it will report that no aliases need to be removed.
*
* The shell startup script is loaded by the respective shell when it starts.
* This means that the aliases will be removed from the shell after it is restarted.
*/
function removeAliasesForShell(shell) {
if (!shell.startupFile) {
ui.writeError(
`- ${chalk.bold(
shell.name
)}: no startup file found. Cannot remove aliases.`
);
return false;
}
if (!fs.existsSync(shell.startupFile)) {
ui.writeInformation(
`- ${chalk.bold(
shell.name
)}: startup file does not exist. No aliases to remove.`
);
return false;
}
const aliases = getAliases(shell.startupFile);
const fileContent = fs.readFileSync(shell.startupFile, "utf-8");
const { removedCount, notFoundCount } = removeAliasesFromFile(
aliases,
fileContent,
shell.startupFile
);
let summary = "- " + chalk.bold(shell.name) + ": ";
if (removedCount > 0) {
summary += chalk.green(`${removedCount} aliases were removed`);
}
if (notFoundCount > 0) {
if (removedCount > 0) {
summary += ", ";
}
summary += chalk.yellow(`${notFoundCount} aliases were not found`);
}
if (removedCount === 0 && notFoundCount === 0) {
summary += chalk.yellow("no aliases found to remove");
}
ui.writeInformation(summary);
return removedCount > 0;
}
/**
* This function removes the aliases from the startup file.
* It searches for exact matches of each alias line and removes them.
* eg: for bash it will remove 'alias npm="aikido-npm"' for npm from ~/.bashrc
* @returns an object with the counts of removed and not found aliases.
*/
export function removeAliasesFromFile(aliases, fileContent, startupFilePath) {
let removedCount = 0;
let notFoundCount = 0;
let updatedContent = fileContent;
for (const alias of aliases) {
const lines = updatedContent.split(EOL);
let aliasLineIndex = lines.findIndex((line) => line.trim() === alias);
if (aliasLineIndex !== -1) {
removedCount++;
// Remove all occurrences of the alias line, in case it appears multiple times
while (aliasLineIndex !== -1) {
lines.splice(aliasLineIndex, 1);
aliasLineIndex = lines.findIndex((line) => line.trim() === alias);
}
updatedContent = lines.join(EOL);
} else {
notFoundCount++;
}
}
if (removedCount > 0) {
fs.writeFileSync(startupFilePath, updatedContent, "utf-8");
}
return {
removedCount,
notFoundCount,
};
}

View file

@ -0,0 +1,177 @@
import { describe, it } from "node:test";
import assert from "node:assert";
import { EOL, tmpdir } from "node:os";
import fs from "node:fs";
import { getAliases } from "./helpers.js";
import { removeAliasesFromFile } from "./teardown.js";
describe("teardown", () => {
function runRemovalTestsForEnvironment(shell, startupExtension, expectedAliases) {
describe(`${shell} shell removal`, () => {
it(`should remove aliases from ${shell} file`, () => {
const lines = [`#!/usr/bin/env ${shell}`, "", ...expectedAliases, ""];
const filePath = createShellStartupScript(lines, startupExtension);
// Test the removeAliasesFromFile function directly
const aliases = getAliases(filePath);
const fileContent = fs.readFileSync(filePath, "utf-8");
const result = removeAliasesFromFile(aliases, fileContent, filePath);
assert.strictEqual(result.removedCount, 3, "Should remove 3 aliases");
assert.strictEqual(result.notFoundCount, 0, "Should find all aliases");
const updatedContent = readAndDeleteFile(filePath);
for (const alias of expectedAliases) {
assert.ok(!updatedContent.includes(alias), `Alias "${alias}" should be removed`);
}
});
it(`should handle file with no aliases for ${shell}`, () => {
const lines = [`#!/usr/bin/env ${shell}`, "", "alias other='command'", ""];
const filePath = createShellStartupScript(lines, startupExtension);
const aliases = getAliases(filePath);
const fileContent = fs.readFileSync(filePath, "utf-8");
const result = removeAliasesFromFile(aliases, fileContent, filePath);
assert.strictEqual(result.removedCount, 0, "Should remove 0 aliases");
assert.strictEqual(result.notFoundCount, 3, "Should report 3 aliases not found");
const updatedContent = readAndDeleteFile(filePath);
assert.ok(updatedContent.includes("alias other='command'"), "Other aliases should remain unchanged");
});
it(`should remove duplicate aliases from ${shell} file`, () => {
const lines = [
`#!/usr/bin/env ${shell}`,
"",
...expectedAliases,
"alias other='command'",
...expectedAliases, // duplicates
""
];
const filePath = createShellStartupScript(lines, startupExtension);
const aliases = getAliases(filePath);
const fileContent = fs.readFileSync(filePath, "utf-8");
const result = removeAliasesFromFile(aliases, fileContent, filePath);
assert.strictEqual(result.removedCount, 3, "Should remove 3 aliases (counting duplicates as single removal)");
assert.strictEqual(result.notFoundCount, 0, "Should find all aliases");
const updatedContent = readAndDeleteFile(filePath);
for (const alias of expectedAliases) {
assert.ok(!updatedContent.includes(alias), `Alias "${alias}" should be completely removed`);
}
assert.ok(updatedContent.includes("alias other='command'"), "Other aliases should remain");
});
it(`should use real getAliases() for ${shell} file`, () => {
const filePath = `${tmpdir()}/test${startupExtension}`;
const aliases = getAliases(filePath);
// Verify we get the expected aliases for this shell type
assert.strictEqual(aliases.length, 3, "Should get 3 aliases (npm, npx, yarn)");
for (let i = 0; i < aliases.length; i++) {
assert.strictEqual(aliases[i], expectedAliases[i], `Alias ${i} should match expected format`);
}
});
it(`should handle partial alias matches for ${shell}`, () => {
const lines = [
`#!/usr/bin/env ${shell}`,
"",
expectedAliases[0], // Only first alias
"alias other='command'",
""
];
const filePath = createShellStartupScript(lines, startupExtension);
const aliases = getAliases(filePath);
const fileContent = fs.readFileSync(filePath, "utf-8");
const result = removeAliasesFromFile(aliases, fileContent, filePath);
assert.strictEqual(result.removedCount, 1, "Should remove 1 alias");
assert.strictEqual(result.notFoundCount, 2, "Should report 2 aliases not found");
const updatedContent = readAndDeleteFile(filePath);
assert.ok(!updatedContent.includes(expectedAliases[0]), "First alias should be removed");
assert.ok(updatedContent.includes("alias other='command'"), "Other aliases should remain");
});
});
}
// Test for each shell type using real getAliases() output
runRemovalTestsForEnvironment("bash", ".bashrc", [
"alias npm='aikido-npm'",
"alias npx='aikido-npx'",
"alias yarn='aikido-yarn'"
]);
runRemovalTestsForEnvironment("zsh", ".zshrc", [
"alias npm='aikido-npm'",
"alias npx='aikido-npx'",
"alias yarn='aikido-yarn'"
]);
runRemovalTestsForEnvironment("fish", ".fish", [
'alias npm "aikido-npm"',
'alias npx "aikido-npx"',
'alias yarn "aikido-yarn"'
]);
runRemovalTestsForEnvironment("pwsh", ".ps1", [
"Set-Alias npm aikido-npm",
"Set-Alias npx aikido-npx",
"Set-Alias yarn aikido-yarn"
]);
describe("removeAliasesFromFile edge cases", () => {
it("should handle empty file", () => {
const aliases = ["alias npm='aikido-npm'"];
const fileContent = "";
const filePath = `${tmpdir()}/test-${Math.random().toString(36).substring(2, 15)}.bashrc`;
fs.writeFileSync(filePath, fileContent, "utf-8");
const result = removeAliasesFromFile(aliases, fileContent, filePath);
assert.strictEqual(result.removedCount, 0, "Should remove 0 aliases from empty file");
assert.strictEqual(result.notFoundCount, 1, "Should report 1 alias not found");
// Cleanup
fs.rmSync(filePath, { force: true });
});
it("should handle file with only whitespace", () => {
const aliases = ["alias npm='aikido-npm'"];
const fileContent = `${EOL}${EOL} ${EOL}`;
const filePath = `${tmpdir()}/test-${Math.random().toString(36).substring(2, 15)}.bashrc`;
fs.writeFileSync(filePath, fileContent, "utf-8");
const result = removeAliasesFromFile(aliases, fileContent, filePath);
assert.strictEqual(result.removedCount, 0, "Should remove 0 aliases from whitespace-only file");
assert.strictEqual(result.notFoundCount, 1, "Should report 1 alias not found");
// Cleanup
fs.rmSync(filePath, { force: true });
});
});
});
function createShellStartupScript(lines, fileExtension) {
const randomFileName = Math.random().toString(36).substring(2, 15);
const filePath = `${tmpdir()}/${randomFileName}${fileExtension}`;
fs.writeFileSync(filePath, lines.join(EOL), "utf-8");
return filePath;
}
function readAndDeleteFile(filePath) {
const fileContent = fs.readFileSync(filePath, "utf-8");
fs.rmSync(filePath, { force: true });
return fileContent.split(EOL);
}