diff --git a/.claude/DesignSpecification.MVP.md b/.claude/DesignSpecification.MVP.md index 39e6685..9938d26 100644 --- a/.claude/DesignSpecification.MVP.md +++ b/.claude/DesignSpecification.MVP.md @@ -1,5 +1,5 @@ # End-to-End MVP Specification -## .NET Agent + NATS over WebSocket + ASP.NET Core Backend + SvelteKit Web UI +## .NET Agent + NATS over WebSocket + ASP.NET Core Backend + React (MUI, Mantis Pro) Web UI **Document purpose:** Build-ready MVP specification for Claude or another coding agent. @@ -23,7 +23,7 @@ Primary technologies: - NATS JetStream - System.Management.Automation SDK for PowerShell execution - Windows CIM/WMI APIs for stable hardware identity and inventory -- SvelteKit +- React 19 + MUI 9 on the Mantis Pro template (Vite, TypeScript, SWR, React Router) - TypeScript - Monaco Editor for browser script editing - xterm.js for browser terminal rendering @@ -99,18 +99,21 @@ Use the following repository structure exactly unless a platform limitation requ │ │ └── Security/ │ ├── WebUI/ │ │ ├── package.json -│ │ ├── svelte.config.js -│ │ ├── vite.config.ts +│ │ ├── vite.config.mts +│ │ ├── server.mjs │ │ ├── src/ -│ │ │ ├── lib/ -│ │ │ │ ├── api/ -│ │ │ │ ├── auth/ -│ │ │ │ ├── components/ -│ │ │ │ ├── messaging/ -│ │ │ │ ├── stores/ -│ │ │ │ └── theme/ -│ │ │ └── routes/ -│ │ └── static/ +│ │ │ ├── api/ +│ │ │ ├── components/ +│ │ │ ├── contexts/ +│ │ │ ├── hooks/ +│ │ │ ├── layout/ +│ │ │ ├── messaging/ +│ │ │ ├── pages/ +│ │ │ ├── routes/ +│ │ │ ├── sections/ +│ │ │ ├── themes/ +│ │ │ └── utils/ +│ │ └── public/ │ ├── Shared.Contracts/ │ │ ├── Shared.Contracts.csproj │ │ ├── Api/ @@ -1174,7 +1177,7 @@ PowerShell ProgressRecord -> NATS -> Backend -> browser-authorized NATS subject - -> Svelte store + -> console NATS client (React subscription) -> live progress bar ``` @@ -1577,7 +1580,7 @@ Agent only acknowledges script command after it has durably recorded the job ID ## 32.1 General Design -SvelteKit UI should look polished rather than like an admin scaffold. +The React console (MUI 9 on the Mantis Pro shell, styled like the house consoles: slate surfaces, blue accent, page headers, side sheets, a group tree beside grids, menus as data with disabled-with-reason entries) should look polished rather than like an admin scaffold. Required visual characteristics: @@ -2029,9 +2032,9 @@ NATS_ACCOUNT_SIGNING_SEED= # 45. WebUI Docker Image -Build SvelteKit using Node during build stage. +Build the console with Vite (`npm run build`, typecheck first) in a Node 24 build stage; the output is a static SPA in `dist/`. -Use SvelteKit Node adapter or a minimal production Node runtime. +Serve `dist/` from a minimal Node runtime with the dependency-free `server.mjs` (SPA fallback, immutable asset caching). The combined server binary embeds the same `dist/`. Container listens on: @@ -2238,7 +2241,7 @@ Behavior: - build - unit tests - integration tests where feasible -- Svelte check/build +- WebUI check (typecheck + lint) and build - no image push - no release @@ -2458,7 +2461,7 @@ The MVP is not complete until this sequence works reliably. - JetStream durable script dispatch ## Browser -- SvelteKit +- React + MUI console (Mantis Pro shell) - System/Light/Dark - polished dashboard - device list live status @@ -2667,11 +2670,11 @@ Include Mermaid architecture diagrams. flowchart LR A[Windows Agent] -->|HTTPS bootstrap| P[Reverse Proxy :443] A -->|WSS NATS| P - B[Browser / SvelteKit] -->|HTTPS REST| P + B[Browser / React console] -->|HTTPS REST| P B -->|WSS NATS| P P -->|/api| API[ASP.NET Core Backend] - P -->|/| UI[SvelteKit WebUI] + P -->|/| UI[React WebUI] P -->|/messaging/agent| N[NATS WebSocket] P -->|/messaging/browser| N diff --git a/.editorconfig b/.editorconfig index 02d8557..123cfdc 100644 --- a/.editorconfig +++ b/.editorconfig @@ -28,7 +28,7 @@ csharp_style_prefer_primary_constructors = false:none [*.{json,yml,yaml}] indent_size = 2 -[*.{js,ts,svelte,css,html}] +[*.{js,mjs,ts,tsx,css,html}] indent_size = 2 [*.{ps1,psm1}] diff --git a/.env.example b/.env.example index 7ed4c0a..47cbb4c 100644 --- a/.env.example +++ b/.env.example @@ -103,14 +103,19 @@ TLS_CERT_DIR= # pruned). 0 disables pruning. JOB_HISTORY_LIMIT=200 -# ── Initial local admin (first startup only) ─────────────────────────────── +# ── Break-glass account (first startup only) ─────────────────────────────── +# The one recovery built-in account. Left empty, a one-time password is +# generated and written once to the server log. Recover with `auth-reset`. INITIAL_ADMIN_USERNAME=admin # Generate: openssl rand -base64 24 INITIAL_ADMIN_PASSWORD= -# ── OIDC (optional; also configurable from Settings → Authentication) ────── -# Register the redirect URI /api/auth/oidc/callback at your provider. -# The path is fixed by design — the Settings page shows the exact value. +# ── Sign-in ──────────────────────────────────────────────────────────────── +# Sign-in methods (Built-In, Local Windows Accounts, LDAP, OIDC) are set in +# Settings › Authentication. The OIDC_* and AUTH_LOGIN_MODE values below are +# read once, to carry an older install's settings over when no sign-in +# settings exist yet; after that the console is the only place to change them. +# The OIDC callback to register is /api/auth/oidc/callback. OIDC_ENABLED=0 OIDC_AUTHORITY= OIDC_CLIENT_ID= @@ -127,7 +132,7 @@ OIDC_DEFAULT_ROLE=Operator OIDC_REQUIRE_MAPPED_ROLE=0 # LocalOnly | Both | OidcOnly | OidcAutoRedirect AUTH_LOGIN_MODE=Both -# Break-glass: 1 bypasses OIDC entirely regardless of saved settings. +# Always offer the built-in form, whatever the saved settings say (a way back in). AUTH_FORCE_LOCAL=0 # ── NATS decentralized auth (generated — do NOT hand-edit) ───────────────── diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 252c035..83457c0 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -89,6 +89,7 @@ jobs: run: | dotnet test tests/Shared.Tests -c Release --no-build --nologo dotnet test tests/Agent.Tests -c Release --no-build --nologo + dotnet test tests/Agent.Watchdog.Tests -c Release --no-build --nologo dotnet test tests/Backend.Tests -c Release --no-build --nologo - name: Integration tests diff --git a/.gitignore b/.gitignore index 5c2eff5..fe1bae3 100644 --- a/.gitignore +++ b/.gitignore @@ -12,10 +12,9 @@ TestResults/ *.user *.suo -# Node / SvelteKit +# Node / WebUI (Vite) node_modules/ -.svelte-kit/ -src/WebUI/build/ +src/WebUI/dist/ npm-debug.log* # Local state @@ -43,4 +42,3 @@ Thumbs.db src/Infra/backend/agent-package/* !src/Infra/backend/agent-package/.gitkeep -src/WebUI/build-static/ diff --git a/Directory.Build.props b/Directory.Build.props index 375fc30..e20fce1 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -17,6 +17,7 @@ $(UnifiedVersion) false ExecuteR + Copyright (c) 2026 Grace Solutions. All rights reserved. diff --git a/Directory.Packages.props b/Directory.Packages.props index 9747d33..a6c56b9 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -6,7 +6,8 @@ - + + @@ -38,7 +39,8 @@ - + + diff --git a/ExecuteR.slnx b/ExecuteR.slnx index 2fbd3a7..a42c97b 100644 --- a/ExecuteR.slnx +++ b/ExecuteR.slnx @@ -1,12 +1,14 @@ + + diff --git a/IaC/compose/docker-compose.yml b/IaC/compose/docker-compose.yml index 04c72dc..7630104 100644 --- a/IaC/compose/docker-compose.yml +++ b/IaC/compose/docker-compose.yml @@ -1,6 +1,6 @@ #============================================================================= # ExecuteR - Windows endpoint management control plane -# Agent + NATS-over-WebSocket + ASP.NET Core backend + SvelteKit web UI +# Agent + NATS-over-WebSocket + ASP.NET Core backend + React (MUI) web console #============================================================================= # # CREDENTIALS: diff --git a/LICENSE b/LICENSE index 60d258b..854885c 100644 --- a/LICENSE +++ b/LICENSE @@ -1,235 +1,16 @@ -GNU AFFERO GENERAL PUBLIC LICENSE -Version 3, 19 November 2007 +Copyright (c) 2026 Grace Solutions. All rights reserved. -Copyright (C) 2007 Free Software Foundation, Inc. +This software and its source code, documentation and associated files (the "Software") are proprietary to Grace +Solutions and are provided under licence only. -Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. +No part of the Software may be copied, modified, distributed, sublicensed, sold or made available to any third +party, in source or binary form, except as permitted by a written licence agreement with Grace Solutions. - Preamble +The Software includes third-party components that remain under their own licences; see THIRD-PARTY-NOTICES.md. +The web console is built on a commercial user-interface template licensed to Grace Solutions for use in this product +only; its source may not be extracted or redistributed on its own. -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. - - ExecuteR - Copyright (C) 2026 gsadmin - - 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 . - -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 . +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL GRACE SOLUTIONS +BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index 1195104..26a4700 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ updates with **no SignalR, SSE, or polling**. - **Backend** — ASP.NET Core control plane: REST API, SQLite, local + OIDC auth, RBAC, NATS operator/JWT issuance, JetStream command dispatch, live event relay. -- **WebUI** — SvelteKit dashboard: live device status, Monaco PowerShell editor +- **WebUI** — React + MUI console (Mantis Pro shell): live device status, a nested group tree, run now and schedules, Monaco PowerShell editor with typed parameters and reusable Functions, live job output and progress, xterm.js remote shell. @@ -38,23 +38,27 @@ updates with **no SignalR, SSE, or polling**. 10. [Networking and TLS](#networking-and-tls) 11. [Reverse proxy routes](#reverse-proxy-routes) 12. [Agent foreground mode and service lifecycle](#agent-foreground-mode-and-service-lifecycle) -13. [MSI public properties](#msi-public-properties) -14. [Registry paths and GPO precedence](#registry-paths-and-gpo-precedence) -15. [Bootstrap and URL install](#bootstrap-and-url-install) -16. [Local login and OIDC](#local-login-and-oidc) -17. [Custom roles and permissions](#custom-roles-and-permissions) -18. [Typed script parameters and Functions](#typed-script-parameters-and-functions) -19. [Script engines](#script-engines) -20. [Secrets providers and $Secrets](#secrets-providers-and-secrets) -21. [Device groups and script triggers](#device-groups-and-script-triggers) -22. [Group runs and schedules](#group-runs-and-schedules) -23. [Database providers](#database-providers) -24. [Logging](#logging) -25. [Device lifecycle: reconnect or orphan](#device-lifecycle-reconnect-or-orphan) -26. [S3 file delivery](#s3-file-delivery) -27. [CI/CD and GITEA_* variables](#cicd-and-gitea_-variables) -28. [Versioning](#versioning) -29. [Troubleshooting](#troubleshooting) +13. [Agent upgrades and the watchdog](#agent-upgrades-and-the-watchdog) +14. [MSI public properties](#msi-public-properties) +15. [Registry paths and GPO precedence](#registry-paths-and-gpo-precedence) +16. [Bootstrap and URL install](#bootstrap-and-url-install) +17. [Windows PE](#windows-pe) +18. [Sign-in](#sign-in) +19. [Custom roles and permissions](#custom-roles-and-permissions) +20. [Typed script parameters and Functions](#typed-script-parameters-and-functions) +21. [Script engines](#script-engines) +22. [Secrets providers and $Secrets](#secrets-providers-and-secrets) +23. [Device groups and script triggers](#device-groups-and-script-triggers) +24. [Group runs and schedules](#group-runs-and-schedules) +25. [Database providers](#database-providers) +26. [Logging](#logging) +27. [Device lifecycle: reconnect or orphan](#device-lifecycle-reconnect-or-orphan) +28. [Agent upgrades from the server](#agent-upgrades-from-the-server) +29. [S3 file delivery](#s3-file-delivery) +30. [CI/CD and GITEA_* variables](#cicd-and-gitea_-variables) +31. [Versioning](#versioning) +32. [Troubleshooting](#troubleshooting) +33. [Licence](#licence) --- @@ -67,7 +71,7 @@ WebSocket to the reverse proxy, which forwards to the NATS WebSocket listener. ```mermaid flowchart LR A["Windows Agent"] - B["Browser / SvelteKit"] + B["Browser / React console"] P["Reverse Proxy :443"] A -->|"HTTPS: bootstrap, install"| P @@ -76,7 +80,7 @@ flowchart LR B <-->|"WSS: NATS session"| P subgraph Stack ["Docker stack (private network)"] - UI["SvelteKit WebUI"] + UI["React WebUI"] API["ASP.NET Core Backend"] N["NATS: WebSocket + TCP"] DB[("SQLite / Postgres / SQL Server")] @@ -127,7 +131,7 @@ How a request or event moves through the internal components. ```mermaid flowchart TB subgraph Browser - UI["SvelteKit pages"] + UI["React pages"] BN["Browser NATS client (WSS)"] end @@ -204,7 +208,7 @@ Full script-execution, enrollment, and remote-shell sequence diagrams are in ## Prerequisites - **.NET SDK 10** (`dotnet --version` gives 10.x) -- **Node.js LTS** (20+) and npm — for the WebUI +- **Node.js LTS** (22+) and npm — for the WebUI - **Docker + Docker Compose** — to run the stack - **Windows** — required to build/run the agent (CIM, ConPTY, DPAPI, Windows service). The backend and WebUI are cross-platform. @@ -224,7 +228,7 @@ Full script-execution, enrollment, and remote-shell sequence diagrams are in # Run tests ./scripts/Test.ps1 # unit -./scripts/Test.ps1 -IncludeWebUI # + svelte-check +./scripts/Test.ps1 -IncludeWebUI # + WebUI typecheck and lint ``` Run the stack: @@ -555,6 +559,149 @@ Remote shell works on every platform — ConPTY on Windows, a forkpty-backed PTY (with a real controlling terminal, so job control and Ctrl-C behave) on Linux and macOS. +On Windows devices the shell page's **Shell** picker chooses what starts: +**Automatic** (the default) takes the first of PowerShell 7 (`pwsh.exe`, +Program Files or `PATH`), Windows PowerShell, the agent's **Built-In +PowerShell** and Command Prompt (`%ComSpec%`); an explicit choice that is not +installed fails with a clear message instead of falling back. The last +choice is remembered per browser, and the shell page shows which shell +Automatic started. Built-In PowerShell is the agent's own embedded engine in +the SDK console host (the hidden `ExecuteR-Agent.exe shell-host` verb, with +the bundled modules on `PSModulePath`), so a PowerShell prompt is available +even where none is installed — Windows PE without the WinPE-PowerShell +component, for example. Linux and macOS agents ignore the choice and start +the login shell (`$SHELL`, else bash/zsh/sh). + +In the console, **Pop Out** moves a shell into its own browser window +without interrupting it: the session, scrollback and anything running carry +over, and it keeps running while you use the rest of the console. **Return +to Console** (or **Bring Back** on the shell page) docks the same terminal +back. Closing the window brings it back when the console is showing that +device's shell and ends the session otherwise; reloading or closing the +console tab ends every popped-out shell, since they run on its page. + +--- + +## Agent upgrades and the watchdog + +Every agent package (zip and MSI) carries a second, small binary beside the +agent: the **watchdog** (`ExecuteR-Watchdog.exe`, `executer-watchdog` on +Linux/macOS; self-contained, trimmed, about 12 MB). It runs as its own service, +keeps the agent running and applies the upgrades the server sends (see +[Agent upgrades from the server](#agent-upgrades-from-the-server) for starting, +pacing and rolling them back). + +| | Windows | Linux | macOS | +|---|---|---|---| +| Watchdog service | `ExecuteRWatchdog` (LocalSystem, Automatic, restart on failure) | systemd `executer-watchdog.service` | launchd `info.executer.watchdog` | +| Install folder | `%ProgramFiles%\ExecuteR\Agent` | `/opt/executer/agent` | `/opt/executer/agent` | +| Upgrade files | `%ProgramData%\ExecuteR\upgrade` | `/var/lib/executer/upgrade` | `/var/lib/executer/upgrade` | +| Watchdog log | `\Logs\ExecuteR-Watchdog.log` | `/Logs/executer-watchdog.log` | same | + +The MSI installs and starts both services. `ExecuteR-Agent.exe install` / +`initialize` also register (and start) the watchdog when its binary sits next +to the agent, and `remove` takes the watchdog out first, so it cannot start the +agent again meanwhile. The watchdog has the same service verbs itself +(`install`, `remove`, `start`, `stop`, `status`, `version`, `foreground`). An +install from before the watchdog existed gets it with its first upgrade: the +agent copies it out of the downloaded package and registers it before handing +the package over. + +### How an upgrade runs on the device + +1. The agent takes the `command.agent.upgrade` command. It answers at once, + without downloading, when it cannot or need not upgrade: **unsupported** + (not running as the installed service, or the package is for another + platform), **busy** (another hand-over, swap or unreported outcome is + pending), or **succeeded / already** (it runs that version). A redelivered + command (same upgrade ID) is ignored. +2. It waits a random start jitter (0 to the seconds the server sends), then + downloads the package (a server path resolved against the configured server + URL, or a presigned URL as is; the configured proxy and TLS trust apply) to + `upgrade/downloads/.zip`, reporting **downloading** with progress. + Size and SHA-256 must match the command (else **failed / hash**). It unpacks + to `upgrade/staging/-/` (no agent binary inside: **failed / + package**), makes sure the watchdog runs, writes `upgrade/handover.json` and + reports **installing**. A hand-over the watchdog has not taken within 10 + minutes fails as **watchdog**. +3. The watchdog checks the staging again (location, safe relative paths, every + file's size and SHA-256), stops the agent service, copies the files into + `/.next//` and checks them there, moves the files they replace + into `/.previous//` and the new ones into place, and starts the + agent. A move is retried only while another process holds the file (10 × 500 + ms). Failures before any file moved leave the agent running and are tried + again, three times in all, then end as **failed / watchdog**. +4. The new version is **kept** only when its health beacon reports the new + version, **connected** (command consumer bound and NATS open), written after + the start, within the health deadline the server sends (10 minutes by + default). Then `.next` and `.previous` go and the outcome is **succeeded**. +5. Otherwise it is **rolled back**: the new files go to `/.failed//` + (and are then deleted), `.previous` comes back, the previous agent is started + and given 5 minutes to report healthy. The reason is **health-deadline**, + **crashed** (the new version exited three times, which ends the wait early) + or **swap** (a file could not be moved), with up to 40 log lines: the new + agent's own for a health or crash failure, the watchdog's for a swap. +6. The outcome is written to `upgrade/outcome.json` and reported by whichever + agent version runs afterwards as soon as it is connected; then the file is + deleted, and old downloads and staging folders are removed (the newest is + kept). + +What a swap touches: the files the package brings, and every file inside a +top-level folder it ships (`Modules\`, so a module the new version dropped goes +too). `Logs\`, an operator's own files and the running watchdog binary are +never moved. The watchdog replaces **its own binary last**, after the new agent +is kept, and only when the package's watchdog is newer and runs (`version` +exits 0 within 30 s); it then restarts onto it through the service manager. + +### What you see on disk + +| Path | Meaning | +|---|---| +| `upgrade/health.json` | the agent's beacon (version, PID, connected, time), every 5 s; written only by the installed service | +| `upgrade/handover.json` | a package waiting for the watchdog | +| `upgrade/handover.taken.json` + `upgrade/journal.json` | a swap under way; the journal names the phase (`stopping`, `swapping`, `verifying`, `committed`, `rolling-back`, `rolled-back`) and the SHA-256 of every file on both sides | +| `upgrade/outcome.json` | how the last swap ended, until the agent has reported it | +| `upgrade/downloads/`, `upgrade/staging/` | the newest package, zipped and unpacked | +| `/.next`, `.previous`, `.failed` | exist only during a swap | + +If the watchdog itself stops part way (power loss, a kill), its next start +finishes or undoes the run from the journal: `stopping` starts over (the agent +runs meanwhile), `swapping` and `rolling-back` put the previous version back, +`verifying` goes on waiting for the new version (at least another minute when +the deadline has passed) and keeps or rolls it back. An upgrade that has a +journal or an outcome is never applied a second time. + +### When the watchdog restarts the agent + +The watchdog never fights an admin. It acts only while the agent service is set +to start **automatically**, and then only in two cases, at most once every 3 +minutes: + +- the agent runs, has run for over 3 minutes, and its beacon is older than 3 + minutes: it hangs, so it is restarted (an agent that writes no beacon at all, + an older version, is left alone); +- the agent **stopped with a failure** and is still stopped 3 minutes later + (the service manager's own restarts gave up): it is started. + +A clean stop is never undone. To stop the agent without the watchdog starting +it again: + +```powershell +ExecuteR-Agent.exe stop # stays stopped until started or the next boot +Set-Service ExecuteRAgent -StartupType Manual # also across reboots: the watchdog leaves a non-automatic service alone +ExecuteR-Watchdog.exe stop # or stop the watchdog too +``` + +On Linux `systemctl stop executer-agent` (and `systemctl disable` for reboots). +On macOS the agent's launchd `KeepAlive` restarts a killed agent by itself; use +`launchctl bootout system/info.executer.agent` to keep it stopped. + +For development, `ExecuteR-Watchdog.exe foreground --agent process +--install-dir --data-dir ` runs the same loop with console logging +against an agent it starts as a child process instead of a service (an agent +in the foreground refuses upgrade commands itself, so drive it with a +hand-made `handover.json`). + --- ## MSI public properties @@ -643,74 +790,189 @@ connects over WSS. The device appears in the UI within seconds. --- -## Local login and OIDC +## Windows PE -Local auth uses ASP.NET Core `PasswordHasher` (no compiled default password). -The initial admin is created on first boot from `INITIAL_ADMIN_USERNAME` / -`INITIAL_ADMIN_PASSWORD`. Sessions are HTTP-only cookies with double-submit CSRF -protection on state-changing calls; login is rate limited. +The agent runs in Windows PE, so a device is reachable before it is imaged — +and it stays the **same device** afterwards. Its identity is derived from the +hardware (SMBIOS UUID, BIOS/baseboard serials, make and model), never from the +OS, so the installed OS enrolls into the same device row. In WinPE the OS reads +**Windows PE** (with the real build version, shown as a **WinPE** chip) and the +hostname is WinPE's random `MINWINPC-…`; when the installed OS enrolls, both +update and the transition is kept in the device's **Device History**. -Generic OIDC (any compliant provider — Authentik, Keycloak, Entra ID, Okta) is -configurable from **Settings → Authentication** (saved values override the -environment and apply without a restart) or bootstrapped via environment: +**Boot image prerequisites** (optional components added with `Dism /Add-Package`): + +| Component | Why | +|-----------|-----| +| `WinPE-WMI` | **Required.** Hardware identity and inventory come from WMI; without it the agent logs `WMI is unavailable … add the WinPE-WMI optional component` and cannot enroll. | +| `WinPE-PowerShell` (brings `WinPE-NetFx` and `WinPE-Scripting`) | The PowerShell install one-liner, and the `powershell.exe` script engine. | +| `WinPE-NetFx` alone | Not needed — the agent is self-contained .NET. | + +Scripts from the console run in the agent's embedded PowerShell either way. In +the remote shell, **Built-In PowerShell** (the agent's own PowerShell host) +gives a PowerShell prompt without `WinPE-PowerShell`, and **Command Prompt** +(`cmd.exe`) is always there; **Automatic** picks the first of PowerShell 7, +Windows PowerShell, Built-In PowerShell and Command Prompt that the device has. +WinPE runs from a RAM drive (`X:`) whose default scratch space (32 MB) is too +small for the agent — raise it on the image, and keep the default `wpeinit` +so networking is up: ```text -OIDC_ENABLED=1 -OIDC_AUTHORITY=https://idp.example.com/application/o/executer/ -OIDC_CLIENT_ID=executer -OIDC_CLIENT_SECRET= -OIDC_SCOPES=openid profile email -OIDC_ROLE_CLAIM=groups -OIDC_ADMIN_ROLE=executer-admins -OIDC_OPERATOR_ROLE=executer-operators -OIDC_VIEWER_ROLE=executer-viewers -AUTH_LOGIN_MODE=Both # LocalOnly | Both | OidcOnly | OidcAutoRedirect +Dism /Image:C:\WinPE_amd64\mount /Set-ScratchSpace:512 ``` -Register the redirect URI `/api/auth/oidc/callback` at the -provider — the path is fixed by design and shown (copyable) in the Settings UI. -Displayed URLs and generated install commands use `PUBLIC_SERVER_URL` when -set; otherwise they derive from **trusted forwarded headers**, so they are -correct behind the reverse proxy without any configuration. +**One-liner.** The Windows command from **Add device** works as-is in WinPE +(paste it at the WinPE command prompt; it starts `powershell.exe`). The script +detects WinPE (`HKLM\SYSTEM\CurrentControlSet\Control\MiniNT`), takes the +portable ZIP instead of the MSI (Windows Installer does not run in WinPE), +unpacks to `X:\Program Files\ExecuteR\Agent` with .NET's ZipFile (no +`Expand-Archive`/CIM cmdlets needed) and registers and starts the Windows +service through `ExecuteR-Agent.exe initialize` — the Service Control Manager +APIs, not `sc.exe`. Everything lives on `X:` and is gone at the next reboot, +by design. -Role mapping: custom roles list their own IdP claim values (see -[Custom roles and permissions](#custom-roles-and-permissions)); the legacy -Admin → Operator → Viewer mapping above still resolves onto the seeded system -roles. Unmatched users get the configured default role, or are refused when -*Require mapped role* is on. +**`startnet.cmd` alternative** — no PowerShell needed: copy the portable ZIP's +contents into the mounted image (e.g. `\ExecuteR`) and run the agent in +the foreground from `Windows\System32\startnet.cmd`. Environment variables are +honored in `foreground` only (a service reads the registry): -**Lockout recovery** (an IdP outage is never terminal): +```bat +wpeinit +set AGENT_SERVER_URL=https://control.example.com +set AGENT_BOOTSTRAP_TOKEN= +start "ExecuteR Agent" X:\ExecuteR\ExecuteR-Agent.exe foreground +``` -- `/login?local=1` always reveals the local sign-in form, even in SSO-only modes. -- `docker exec EXECUTER-API-00001 dotnet Backend.dll auth-reset --admin admin --password ''` - disables OIDC in the database and restores/creates a local admin. -- `AUTH_FORCE_LOCAL=1` (environment only) bypasses stored OIDC settings at startup. +To run it as a service there instead, use +`X:\ExecuteR\ExecuteR-Agent.exe configure --url --token ` followed +by `X:\ExecuteR\ExecuteR-Agent.exe initialize`. -![Login](docs/screenshots/login.png) +**The token after imaging.** The installed OS enrolls through its own install +(the MSI or one-liner in the task sequence / `SetupComplete.cmd`). Re-enrolling +the same device with the token that enrolled it spends no further use, so one +token can cover both phases — but it must still be valid (not expired or +revoked) when the installed OS enrolls. Give it an expiry longer than imaging +takes, and use a multi-use token for a batch of devices. + +**History.** The device page's **Device History** tab lists **Enrolled** +(with the name and OS it enrolled as), **Renamed** (`MINWINPC-ABC → LAB-PC-01`) +and **OS Changed** (`Windows PE 10.0.26100 → Windows 11 10.0.26100.4351`), +newest first; the same trail is `GET /api/devices/{clientId}/history` +(`devices.view`, device scope applies). Events are written only when a value +actually changes; each enrollment's audit entry also records hostname and OS. + +**On-enrollment triggers** fire once per device per trigger — so one aimed at +all devices fires at the WinPE enrollment and not again after imaging. Aim it +at a dynamic group with **OS name** *not equals* `Windows PE` to run it in the +installed OS (enrolling a new OS drops the WinPE inventory, so the group sees +the new OS straight away), or *equals* `Windows PE` for a pre-imaging step. + +--- + +## Sign-in + +Sign-in works as it does in StifleR. There are four methods, each a tab under +**Settings › Authentication**, and several can be on at once: + +| Method | What it checks | Groups that bind to roles | +|---|---|---| +| **Built-In** | ExecuteR's own accounts (PBKDF2-SHA512, at least 12 characters, changed at first sign-in) | Built-in groups | +| **Local Windows Accounts** | This server's own Windows accounts, checked by Windows (`LogonUser`); Windows servers only, on by default on Windows Server | The account's SID and its local groups' SIDs (for example `BUILTIN\Administrators`) | +| **LDAP** | A directory or Active Directory: LDAPS, StartTLS, or Kerberos (signed and sealed); user and group filters, nested groups | Group DNs | +| **OIDC** | Any OpenID Connect provider (authorization code with PKCE); ID token validated; sign-out at the provider | `claim=value`, for example `groups=executer-admins` | + +The sign-in page offers the built-in form (one form for built-in and local +Windows accounts, with an **Account Type** toggle when the directory is on +too) and a **Sign In with {provider}** button. With **Redirect Mode** on and +OIDC the only way in, it goes straight to the provider, except after an error +or a sign-out. + +**Access comes from groups, never from the person.** A role binding names a +group (built-in group, Windows SID, directory DN or OIDC claim) and one of +ExecuteR's roles. Someone in several bound groups gets all their roles: +permissions add up, and so do device scopes (a role with no scope reaches +every device). A person whose groups are bound to nothing is refused at +sign-in. Each method's tab has its own bindings card. + +**Sessions** are database rows behind an HTTP-only `__Host-session` cookie. +They end on sign-out at once, on every node. They slide with use up to an +absolute limit (Built-In tab: idle 120 minutes, at most 12 hours by default), +and carry a CSRF token checked on every write. + +**Safety rails:** + +- **Failed sign-ins** back off per account and per address (from 30 seconds, + doubling to 15 minutes). Nothing is locked for good. +- **Turning a method on or off** asks you to confirm it is you (step-up: your + password, or your provider again). +- **The last method on** cannot be turned off. +- **Leaving only LDAP, OIDC or Windows on** needs a passed **Test** sign-in + through it in this session, with its settings as they are. +- **Secrets** (the LDAP service password, the OIDC client secret) are + write-only and encrypted at rest. +- **On a domain-joined Windows server**, LDAP sets itself up from the join + (Kerberos, the computer account) until you change its settings. A breaker + turns it off after repeated directory failures. + +**Break-glass account.** One built-in account always has full access through +no binding, and cannot be turned off or removed. On an empty database it is +created from `INITIAL_ADMIN_USERNAME` / `INITIAL_ADMIN_PASSWORD`. Without +those, it is `admin` with a one-time password written once to the server log. + +**Lockout recovery** (an identity-provider outage is never terminal): + +- `AUTH_FORCE_LOCAL=1` (environment only) always offers the built-in form. +- `dotnet Backend.dll auth-reset` turns Built-In sign-in back on, turns + redirect off, and prints a new one-time password for the break-glass + account. Add `--user ` for another built-in account. + +**Upgrading from an earlier ExecuteR** happens once, at the first start: + +- Each user's role becomes membership of a built-in group named after the + role, bound to it. +- The old OIDC settings (saved, or `OIDC_*` / `AUTH_LOGIN_MODE` in the + environment) become the OIDC tab. +- Roles' claim values and the Admin/Operator/Viewer mappings become + `claim=value` bindings. +- The old *default role* has no equivalent. Bind the claim your people carry + instead. + +Displayed URLs (the OIDC callback `/api/auth/oidc/callback`, its +post-logout `/sign-in`, install commands) use `PUBLIC_SERVER_URL` +when set, otherwise trusted forwarded headers. + +![Sign in](docs/screenshots/login.png) --- ## Custom roles and permissions -**Access** (nav) manages users and roles. A role is a named permission set — -devices, groups, scripts, functions, jobs, automation, secrets, remote shell, -file delivery, settings, access — optionally limited to a **device scope**: -pick device groups and members only see and target those devices (device -listing, job dispatch including group fan-out, shell, file delivery, inventory -refresh and tags all honor it). +**Access** (nav) manages roles and shows people. A role is a named permission +set (devices, groups, scripts, functions, jobs, automation, secrets, remote +shell, file delivery, settings, access), optionally limited to a **device +scope**. Pick device groups, and holders only see and target those devices: +device listing, job dispatch including group fan-out, shell, file delivery, +inventory refresh and tags all honor it. -Three system roles are seeded and immutable — **Admin** (`*`, includes future -permissions), **Operator** (day-to-day operations), **Viewer** (read-only) — -matching the pre-RBAC tiers, so existing users and sessions carry over -unchanged. Custom roles apply to local users (assign in the Users table) and -OIDC sign-ins alike: give a role *OIDC claim values* and anyone presenting one -of them in the configured role claim lands on it (custom matches beat the -legacy mapping; the most privileged wins on ties). +Three system roles are seeded and immutable: -Permission edits apply within seconds without re-login (roles resolve through -a short-TTL cache at request time). Safety rails: the last full-access user -cannot be deleted or demoted, system roles cannot be edited, and a role with -assigned users cannot be dropped. +- **Admin**: `*`, which includes future permissions. +- **Operator**: day-to-day operations. +- **Viewer**: read-only. + +People get roles only through role bindings on their groups (see +[Sign-in](#sign-in)). **People** lists everyone who has signed in, of every +kind, and what they hold and where each grant came from. + +Permission and binding edits apply within seconds without signing in again: +roles and bindings resolve through short caches on every request. + +Safety rails: + +- System roles cannot be edited. +- A role still bound cannot be deleted. +- Removing the last binding that manages access is refused while there is no + break-glass account to recover with. ![Access control](docs/screenshots/access.png) @@ -774,12 +1036,80 @@ An engine unavailable on a device (PowerShell 5 on Linux, bash without Git Bash on Windows) fails the job immediately with a clear message instead of running. -The editor itself pops out to fill the window (Esc restores) and offers -optional **IntelliSense** — a curated offline provider with common cmdlets, -keywords, snippets, plus the script's own parameters, `$Secrets` bindings and -`$Files` entries (typed as FileInfo or DirectoryInfo); no language server -involved. Execution flows vertically beneath the editor: target and -**Execution values**, Schedules, Triggers, then full-width output. +**Output reads the way PowerShell shows it.** Both PowerShell engines pipe +the script's output through `Out-String -Stream` at a 4096-column width, so +objects arrive as their table or list view (a hashtable's Name/Value rows, +an object's properties as columns) rather than a type name such as +`System.Collections.Hashtable`, still streamed line by line and without +`…` truncation. Strings pass through unchanged. + +**Downloads.** A job's output drawer downloads its complete stored output as +`COMPUTERNAME.JobID.yyyy.MM.dd.HHmmss.log` (optionally with timestamps), and +a run (Jobs › run, or a script's Executions tab) downloads every target's +output in one `ScriptName.RunID.yyyy.MM.dd.HHmmss.log` with a section per +device and its state and exit code. The time is when the job or run was +created, in UTC on a 24-hour clock. Non-output streams are tagged +(`[ERROR]`, `[WARNING]`, …). Endpoints: `GET /api/jobs/{jobId}/output/download` +and `GET /api/executions/{runId}/output/download` (`?timestamps=true`); +device-scoped roles only reach their own devices' output. + +**Bulk log downloads.** On a run, check devices and **Download Logs** (or +**Download All Logs** with none checked) saves `ScriptName.RunID.yyyy.MM.dd.HHmmss.zip` +holding one `COMPUTERNAME.JobID.yyyy.MM.dd.HHmmss.log` per device, the same +file its drawer downloads. Skipped targets have no log. Endpoint: +`POST /api/executions/{runId}/output/archive` with `{ "jobIds": [...], "timestamps": false }` +(no `jobIds` = every job); the zip streams as it is written. + +The code editor is meant to feel like VS Code (offline, no language server): + +- **Highlighting** after VS Code's Dark/Light Modern themes: cmdlets, + `-Parameters`, word operators, types and attributes, and variables and + `$( … )` inside double-quoted and here-strings. +- **IntelliSense** (toggle per browser) that follows the context. After `-` + it offers the command's parameters (cmdlets, functions in the script and + functions in attached modules) or operators after a value. After `$` it + offers variables the script declares, its parameters, `$Secrets` and + `$Files`. After `$Secrets.`, `$Files.`, `$env:` and `[` it offers bound + names, environment variables and types. It also includes snippets. +- **Hover cards** with syntax and synopsis for cmdlets and functions + (comment-based `.SYNOPSIS`), and where a variable is declared. +- **Navigation:** go to symbol (Ctrl+Shift+O), sticky scroll, go to + definition (F12), find references (Shift+F12), rename (F2), matching + highlights and bracket pair colours. +- **Problems:** squiggles for unbalanced brackets and for `$Secrets.X` / + `$Files.X` names not bound to the script (F8 steps through them). +- **Against the saved version:** change bars in the gutter, and **Compare + with Saved** (Ctrl+K D) as a side-by-side diff with per-change revert. +- **Status bar:** position and selection, problems, the function you're in, + indentation (spaces or tabs, convert), LF/CRLF, the command palette (F1), + and toggles for word wrap (Alt+Z), sticky scroll and the minimap + (remembered per browser). + +It also fills the window (Esc restores). The editor is organized in tabs — Code, Parameters, Functions, +Secrets, Files, Executions (runs → targets → output) and Schedules — and +**Run…** / **Schedule…** open the shared run-now and schedule dialogs. + +**Running a script** works the same way from a script and from devices. The +Run Script dialog has tabs: + +- **Script:** searchable. It's fixed when you open the dialog from a script. +- **Devices:** search, a status filter and multi-select, with **Choose + Results** to pick everything the search found. Devices you chose on the + Devices page come preselected. +- **Groups:** the group tree with checkboxes. +- **Parameters** +- **Review:** reach (online, offline, orphaned) and **Only Devices Online Now**. + +Starting a run opens its page (`/runs/{runId}`): + +- one progress bar over every target; +- counters for Targets, Online, Pending, Running, Succeeded, Failed and + Skipped, each of which filters the target list; +- every target, skipped devices included; a row opens that device's output. + +**Jobs** opens on **Runs**: recent runs across scripts, each with its +progress and source (Run Now, Schedule or Event Trigger). The **Jobs** tab +keeps the per-device job history. ![Script execution flow](docs/screenshots/script-execution.png) @@ -831,19 +1161,40 @@ way as manual runs. ## Device groups and script triggers -Groups are either **static** (an explicit member list) or **dynamic** (rules -evaluated against live device data). +Groups form a **tree**. Each group is one of three kinds: -Rules are one or more **condition groups**. Conditions inside a group combine -with AND or OR, the groups themselves combine with AND or OR, groups can nest, -and both conditions and groups have an independent **NOT**. +| Kind | Members | +|------|---------| +| **Folder** | None of its own — it organizes the groups nested under it | +| **Static** | An explicit list of devices | +| **Dynamic** | The devices matching its rules, evaluated against live device data | + +A group's membership **includes every group nested under it**, so running, +scheduling or scoping a role on `Sites` reaches `Sites › Office › Web` too. +Groups nest up to eight levels; a group can never be moved inside its own +subtree. + +In the console the tree sits beside the device grid (Devices and Groups +pages): counts per node include nested groups, the selection and filters live +in the URL, groups are dragged onto other groups to nest them (with a +confirmation), and right-click / Shift+F10 / long-press opens a group's menu — +Run Script, Schedule Script, View Devices, New Group Here, Edit, Duplicate, +Move to Top Level, Delete. Deleting a group moves its nested groups up to its +parent and disables schedules that targeted it (with the reason recorded); a +group that limits a role's device scope cannot be deleted until it is removed +from that role, because dropping it would widen the role to every device. + +Rules are one or more **condition blocks**. Conditions inside a block combine +with AND or OR, the blocks themselves combine with AND or OR, and both +conditions and blocks have an independent **NOT**. Operators: `equals`, `notEquals`, `contains`, `notContains`, `startsWith`, `endsWith`, `regex`, `in`, `notIn`, `>`, `>=`, `<`, `<=`, `exists`, `notExists`, `inCidr`, `notInCidr`. The CIDR operators evaluate IP fields against comma-separated ranges (`10.20.0.0/16, 192.168.1.0/24`) using the BCL `System.Net.IPNetwork` — IPv4 and IPv6, bare IPs mean equality, and host -bits in the base address are normalized. +bits in the base address are normalized. The rule builder offers only the +operators that fit the chosen field. Fields come from hardware inventory, tags, hostname/identity, and live status — the full catalogue is served by `GET /api/groups/fields`, so the rule builder @@ -869,14 +1220,15 @@ positive operator, and require **all** values for the negative ones. A missing field satisfies only the negative operators. Invalid or runaway regex never matches and never throws. -**Preview** evaluates candidate rules against live devices before you save. +The group editor **previews** candidate rules against live devices as you +type. Membership is evaluated once per request for every group, so the group +list, device list and fan-out stay cheap at fleet scale. ![Group rule builder](docs/screenshots/groups-rule-builder.png) -**Triggers** belong to scripts (the Triggers card on the script's page). A -trigger fires the script automatically — on a device lifecycle event, or on a -schedule — and each trigger carries **its own target**: all devices, a group -(members resolved at fire time), or a single device. +**Triggers** fire a script automatically — on a device lifecycle event, or on +a schedule — and each carries **its own target**: all devices, a group +(members, nested groups included, resolved at fire time), or a single device. | Trigger | Fires when | |---------|-----------| @@ -885,42 +1237,61 @@ schedule — and each trigger carries **its own target**: all devices, a group | `scheduled` | A cadence comes due — one-shot or recurring | Lifecycle triggers fire **once per device** (recorded durably). Triggered runs -use the normal job pipeline, so they carry the script's Functions prelude and -typed parameters and appear alongside manual runs. +use the normal job pipeline, so they carry the script's Functions prelude, +typed parameters and the trigger's captured arguments, and appear alongside +manual runs. --- -## Group runs and scheduled triggers +## Group runs and schedules -The script's target selector offers **devices and groups**. A group run -creates one job per non-orphaned member — offline members receive theirs -durably when they reconnect — and the side panel tracks every job live, with -click-to-focus output per device. Orphaned members are reported as skipped. +**Run now** works from anywhere a target is in view: a device row's **…** +menu, the bulk **Actions** of chosen devices, a group in the tree, the device +and group pages, and the script editor. One dialog picks the script, any mix +of devices and groups, and typed arguments (starting from each parameter's +default). Before you confirm it shows the reach — how many devices, how many +online, and orphaned ones that will be skipped — and **Only Devices Online +Now** skips offline devices instead of queueing for their return (by default +offline members receive their job durably when they reconnect). Every target +of one run shares one execution, which the result links to. -**Scheduled triggers carry their cadence inline.** A `scheduled` trigger stores -*when* (one-shot or recurring), its *target* (a device, a group whose members -resolve at fire time, or all devices), and the execution values to run with — -no separate schedule object to manage. +`POST /api/jobs` accepts the same mix: `clientId` (the original single-device +call, answering with the job), `clientIds`, `groupId`, `groupIds` and +`onlineOnly`, deduplicated and scope-filtered into one `runId`. + +**Schedules** (the Schedules page, plus a Schedules tab on scripts, devices +and groups) are scheduled triggers: *when* (one-shot or recurring), *target* +(a device, a group whose members resolve at fire time, or all devices), an +optional name, and the arguments to run with — no separate schedule object to +manage. Each can be edited in place, duplicated, paused, or **run now** +without disturbing its cadence. The cadence builder leads with friendly selectors — *every N minutes/hours*, -*daily/weekly/monthly at a time* with weekday chips — and compiles them to -cron internally; a raw cron field exists only under **Advanced**. Whatever is -chosen is auto-described in plain English. +*daily/weekly/monthly at a time* with weekday chips, *once* — and compiles them +to cron; a raw cron field exists only under **Advanced**, and a saved cron +reopens in its friendly form when it has one. The next runs are computed by +the server (`POST /api/triggers/preview`) in the schedule's time zone, so what +you see is what will fire. ![Scheduled trigger builder](docs/screenshots/script-schedule.png) Semantics worth knowing: -- Expressions evaluate in the trigger's **time zone** (default UTC), so - "daily at 01:00" tracks DST; storage and comparison are UTC. +- Expressions evaluate in the schedule's **time zone** (the browser's by + default), so "daily at 01:00" tracks DST; storage and comparison are UTC. +- An unknown time zone, a never-firing cron, or an enabled one-shot in the + past is refused when saving. - The worker sweeps regularly; recurrence advances from *now* after each firing, so server downtime causes **at most one late firing**, never a storm. -- One-shot triggers disable themselves after firing. -- Each trigger records its own **last result** (jobs queued, or the error — - e.g. a vault failure) without stalling, and triggered jobs are attributed to - `trigger:`. -- Deleting a script removes its triggers with it. -- Execution values captured on the trigger are used for every firing; secret +- One-shot schedules disable themselves after firing. +- Each schedule records its **last result** (jobs queued, or the error — e.g. + a vault failure) and the execution it created; scheduled jobs are attributed + to `schedule`, run-now firings to the operator. +- A device-scoped role can only aim schedules inside its scope: a device it + can see, or a group whose members it can all see — never all devices. +- Deleting a script removes its schedules with it; schedule changes are + audited under the `automation` category. +- Arguments captured on the schedule are used for every firing; secret bindings resolve fresh server-side at each fire time. --- @@ -1067,6 +1438,84 @@ For a local build without CI: --- +## Agent upgrades from the server + +How upgrades are started, paced and rolled back. What happens on the device is in +[Agent upgrades and the watchdog](#agent-upgrades-and-the-watchdog). + +### On the server + +**Versions arrive with each server release.** The agent packages that ship in +the backend image (or are dropped into `AGENT_PACKAGE_PATH`, with their +`VERSION` marker) are imported into the server's **version catalog** at +startup and every five minutes: the portable Windows zip and the Linux/macOS +builds (the MSI is for installs only — Windows upgrades swap files from the +zip). Each package is copied to `/agent-packages//`, so a +device can still be rolled back after the image moves on. A development build +(`0.0.0.0`) or a package without a version is not catalogued. + +The catalog keeps the newest **KeepVersions** versions (default 5). It never +drops the newest version, a version an open upgrade goes to, or a version some +device's last upgrade came from (its rollback target); removing a version by +hand is refused with the same reason (409). + +Agents download from `GET /api/agent-packages/{sha256}` — anonymous like the +install package, with range support, and **not** rate-limited per address (a +fleet behind one NAT upgrades through it). With S3 agent offload on, catalog +packages are uploaded too and upgrade commands carry a presigned URL instead. + +| Route | Permission | | +|---|---|---| +| `GET /api/agent-versions` | devices.view | Versions newest first: packages, devices on it, why it cannot be removed | +| `DELETE /api/agent-versions/{version}` | settings.manage | Remove a version (409 while needed) | +| `POST /api/agent-upgrades` | devices.manage | Upgrade devices and groups (nested included) to `version`, or the newest per platform | +| `POST /api/agent-upgrades/rollback` | devices.manage | Back to the version each device's last upgrade came from | +| `POST /api/agent-upgrades/{id}/cancel` | devices.manage | Cancel an upgrade not yet sent | +| `GET /api/agent-upgrades?clientId=&open=true&limit=` | devices.view | Upgrade attempts, newest first | +| `GET`/`PUT /api/settings/agent-upgrades` | devices.view / settings.manage | Settings › Agent Upgrades | + +A start or roll back returns what was queued and who was left out: `already` +(on the target), `busy` (an upgrade is open), `no-package`, `unsupported` (no +build for its platform), `orphaned`, or `no-previous` for a roll back. The +package comes from the runtime the agent reports; older agents are matched by +their inventory's OS and architecture. Offline devices are queued and start +when they come back (a request waits up to 7 days, then expires). + +**Upgrades start in paced batches** so a large fleet never downloads at once: +every 15 seconds the next batch of queued, online devices is sent, sized so +each starts within **StartWithinMinutes** (default 3) of being ready — at least +10 a batch — and each agent waits a random 0–15 seconds before downloading. +Only downloads are paced; a device installing has finished its download. A +device that goes quiet is failed `no-report` (30 minutes without an event +while downloading, or the health deadline plus 15 minutes while installing); +a late outcome still counts. When a device's presence already shows the target +version, its upgrade is closed as succeeded. + +**Automatic Upgrades** (off by default) keep online devices outside the +excluded groups on the newest version held for their platform, through the +same paced batches. They never go to an older version and never retry a +version that already failed or rolled back on that device. + +| Setting | Default | Range | +|---|---|---| +| AutomaticUpgrades | off | | +| StartWithinMinutes | 3 | 1–30 | +| HealthDeadlineMinutes | 10 | 2–60 (the watchdog keeps the new version only when it reports healthy in time) | +| ExcludedGroupIds | none | existing groups; nested members are excluded too | +| KeepVersions | 5 | 2–50 | + +**Device History** shows `agent-upgraded` (`2026.10.20.1200 → 2026.10.23.1400`), +`agent-rolled-back` (an operator's roll back, or the watchdog undoing an +upgrade, with its reason) and `agent-upgrade-failed` (with the reason). + +With several replicas, the upgrade scheduler runs where the schedules do +(`SCHEDULE_WORKER=1`), and every replica keeps its own catalog copies. Without +a shared data volume, a replica only serves versions it has itself carried, so +turn on S3 agent offload (or share `DATA_PATH`) to keep older versions +reachable. `AGENT_CATALOG_SYNC=0` turns the catalog import off. + +--- + ## S3 file delivery Configure an S3-compatible store (AWS S3, MinIO, Backblaze B2) from @@ -1190,7 +1639,7 @@ is private — set `REGISTRY_USERNAME` and `REGISTRY_TOKEN` in `.env` and Gitea Actions workflows live in `.gitea/workflows`: -- **Pull request to `main`** — restore, build, unit + integration tests, Svelte +- **Pull request to `main`** — restore, build, unit + integration tests, WebUI check. No image push, no release. - **Push to `dev`** — build + test, agent binaries for every platform (win-x64, win-arm64, linux-x64, linux-arm64, osx-x64, osx-arm64) + MSI, the @@ -1261,3 +1710,12 @@ Built to prove one idea cleanly: secure HTTPS enrollment, scoped NATS over WebSocket through one proxy edge, durable work, in-process PowerShell, and a secured terminal — with a browser that updates in real time over NATS, no SignalR or SSE. + +--- + +## Licence + +ExecuteR is proprietary software of Grace Solutions, provided under licence +only; see [LICENSE](LICENSE). It includes third-party components under their +own licences, and its web console is built on the commercially licensed Mantis +Pro template — see [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md). diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md new file mode 100644 index 0000000..fdd7c77 --- /dev/null +++ b/THIRD-PARTY-NOTICES.md @@ -0,0 +1,56 @@ +# Third-party notices + +ExecuteR includes the components below. Each remains under its own licence. + +## Commercial + +| Component | Licence | Notes | +| --- | --- | --- | +| Mantis React Material UI Pro template (CodedThemes) | Commercial licence purchased from the MUI Store | Basis of the web console's layout and theme. Licensed for this product only; the template source may not be redistributed on its own. | + +## Shipped beside the server + +| Component | Licence | Notes | +| --- | --- | --- | +| NATS server (`nats-server`, Synadia / NATS authors) | Apache-2.0 | Bundled unmodified in the standalone server packages and run as a separate process (the sidecar); the container deployments use the official `nats` image. | + +## Server and agent + +| Component | Licence | +| --- | --- | +| .NET runtime, ASP.NET Core, Entity Framework Core, Microsoft.Extensions.*, System.* | MIT | +| Microsoft.AspNetCore.Authentication.OpenIdConnect | MIT | +| Microsoft.EntityFrameworkCore.Sqlite, Microsoft.Data.Sqlite, Microsoft.EntityFrameworkCore.SqlServer | MIT | +| SQLitePCLRaw | Apache-2.0 | +| SQLite (e_sqlite3) | Public domain | +| Npgsql.EntityFrameworkCore.PostgreSQL | PostgreSQL | +| NATS.Net, NATS.Jwt, NATS.NKeys | Apache-2.0 | +| AWSSDK.S3 | Apache-2.0 | +| Cronos | MIT | +| Serilog and sinks | Apache-2.0 | +| Microsoft.PowerShell.SDK (PowerShell 7) | MIT | +| Microsoft.PowerShell.PSResourceGet, Microsoft.PowerShell.Archive, Microsoft.PowerShell.ThreadJob (bundled with the agent) | MIT | + +## Web console + +| Component | Licence | +| --- | --- | +| React, React DOM, React Router | MIT | +| MUI (Material UI) | MIT | +| Emotion | MIT | +| Ant Design colors and icons | MIT | +| SWR, notistack, lodash-es | MIT | +| Monaco Editor | MIT | +| xterm.js and its fit addon | MIT | +| NATS JavaScript client (@nats-io/nats-core, @nats-io/nkeys) | Apache-2.0 | +| Public Sans font (@fontsource/public-sans) | SIL Open Font License 1.1 | + +## Build and packaging + +| Component | Licence | +| --- | --- | +| WiX Toolset 5 and extensions | MS-RL | +| xUnit.net | Apache-2.0 | +| Vite, TypeScript, ESLint, Prettier | MIT / Apache-2.0 | + +Full licence texts ship with each package in the NuGet and npm caches and in `src/WebUI/node_modules/*/LICENSE`. diff --git a/docs/screenshots/access-role-editor.png b/docs/screenshots/access-role-editor.png index f416734..44c4e05 100644 Binary files a/docs/screenshots/access-role-editor.png and b/docs/screenshots/access-role-editor.png differ diff --git a/docs/screenshots/access.png b/docs/screenshots/access.png index d2c580b..8e26747 100644 Binary files a/docs/screenshots/access.png and b/docs/screenshots/access.png differ diff --git a/docs/screenshots/add-device.png b/docs/screenshots/add-device.png index 3199e7d..ad366b7 100644 Binary files a/docs/screenshots/add-device.png and b/docs/screenshots/add-device.png differ diff --git a/docs/screenshots/dashboard-light.png b/docs/screenshots/dashboard-light.png index 2fe55c0..d920a4c 100644 Binary files a/docs/screenshots/dashboard-light.png and b/docs/screenshots/dashboard-light.png differ diff --git a/docs/screenshots/dashboard.png b/docs/screenshots/dashboard.png index 1d1cf97..b2c976b 100644 Binary files a/docs/screenshots/dashboard.png and b/docs/screenshots/dashboard.png differ diff --git a/docs/screenshots/device-actions.png b/docs/screenshots/device-actions.png index a26fe7c..404f1b9 100644 Binary files a/docs/screenshots/device-actions.png and b/docs/screenshots/device-actions.png differ diff --git a/docs/screenshots/device-detail.png b/docs/screenshots/device-detail.png index c7cf471..24ef344 100644 Binary files a/docs/screenshots/device-detail.png and b/docs/screenshots/device-detail.png differ diff --git a/docs/screenshots/device-execution-history.png b/docs/screenshots/device-execution-history.png deleted file mode 100644 index 3c058c2..0000000 Binary files a/docs/screenshots/device-execution-history.png and /dev/null differ diff --git a/docs/screenshots/device-hardware.png b/docs/screenshots/device-hardware.png index cd6fbcc..77ce151 100644 Binary files a/docs/screenshots/device-hardware.png and b/docs/screenshots/device-hardware.png differ diff --git a/docs/screenshots/device-network.png b/docs/screenshots/device-network.png index e122b39..5906afe 100644 Binary files a/docs/screenshots/device-network.png and b/docs/screenshots/device-network.png differ diff --git a/docs/screenshots/device-public-ip.png b/docs/screenshots/device-public-ip.png deleted file mode 100644 index bc6ee5d..0000000 Binary files a/docs/screenshots/device-public-ip.png and /dev/null differ diff --git a/docs/screenshots/devices.png b/docs/screenshots/devices.png index 8bd69ba..a776b5a 100644 Binary files a/docs/screenshots/devices.png and b/docs/screenshots/devices.png differ diff --git a/docs/screenshots/functions.png b/docs/screenshots/functions.png index 6d3cee0..bf4c03b 100644 Binary files a/docs/screenshots/functions.png and b/docs/screenshots/functions.png differ diff --git a/docs/screenshots/groups-light.png b/docs/screenshots/groups-light.png deleted file mode 100644 index be68957..0000000 Binary files a/docs/screenshots/groups-light.png and /dev/null differ diff --git a/docs/screenshots/groups-rule-builder.png b/docs/screenshots/groups-rule-builder.png index 15502c7..0cb57a8 100644 Binary files a/docs/screenshots/groups-rule-builder.png and b/docs/screenshots/groups-rule-builder.png differ diff --git a/docs/screenshots/groups-static-members.png b/docs/screenshots/groups-static-members.png index 3847a24..6ff0ddd 100644 Binary files a/docs/screenshots/groups-static-members.png and b/docs/screenshots/groups-static-members.png differ diff --git a/docs/screenshots/groups.png b/docs/screenshots/groups.png index 6733f74..d4f4e42 100644 Binary files a/docs/screenshots/groups.png and b/docs/screenshots/groups.png differ diff --git a/docs/screenshots/jobs.png b/docs/screenshots/jobs.png index 38f9d96..d931971 100644 Binary files a/docs/screenshots/jobs.png and b/docs/screenshots/jobs.png differ diff --git a/docs/screenshots/login-reset.png b/docs/screenshots/login-reset.png index 157f832..6bb3f46 100644 Binary files a/docs/screenshots/login-reset.png and b/docs/screenshots/login-reset.png differ diff --git a/docs/screenshots/login.png b/docs/screenshots/login.png index 075784e..a667fb7 100644 Binary files a/docs/screenshots/login.png and b/docs/screenshots/login.png differ diff --git a/docs/screenshots/script-editor.png b/docs/screenshots/script-editor.png index e8b00fe..8c8abb2 100644 Binary files a/docs/screenshots/script-editor.png and b/docs/screenshots/script-editor.png differ diff --git a/docs/screenshots/script-execution.png b/docs/screenshots/script-execution.png index 75fade5..6c9ac1e 100644 Binary files a/docs/screenshots/script-execution.png and b/docs/screenshots/script-execution.png differ diff --git a/docs/screenshots/script-parameters.png b/docs/screenshots/script-parameters.png index d5cca90..d40b582 100644 Binary files a/docs/screenshots/script-parameters.png and b/docs/screenshots/script-parameters.png differ diff --git a/docs/screenshots/script-schedule.png b/docs/screenshots/script-schedule.png index 5c7c1a3..342ef67 100644 Binary files a/docs/screenshots/script-schedule.png and b/docs/screenshots/script-schedule.png differ diff --git a/docs/screenshots/scripts.png b/docs/screenshots/scripts.png index 8adf426..036686d 100644 Binary files a/docs/screenshots/scripts.png and b/docs/screenshots/scripts.png differ diff --git a/docs/screenshots/settings-install-command.png b/docs/screenshots/settings-install-command.png index f2ad7ab..f1a12b7 100644 Binary files a/docs/screenshots/settings-install-command.png and b/docs/screenshots/settings-install-command.png differ diff --git a/docs/screenshots/settings-secrets.png b/docs/screenshots/settings-secrets.png index 86d00da..a1f4709 100644 Binary files a/docs/screenshots/settings-secrets.png and b/docs/screenshots/settings-secrets.png differ diff --git a/docs/screenshots/settings.png b/docs/screenshots/settings.png deleted file mode 100644 index 1ca4925..0000000 Binary files a/docs/screenshots/settings.png and /dev/null differ diff --git a/scripts/Initialize-Repository.ps1 b/scripts/Initialize-Repository.ps1 index 0791f34..175014c 100644 --- a/scripts/Initialize-Repository.ps1 +++ b/scripts/Initialize-Repository.ps1 @@ -15,7 +15,10 @@ if (-not $dotnet) { throw '.NET SDK 10.x is required (https://dotnet.microsoft.c Write-Host "dotnet $(dotnet --version)" $node = Get-Command node -ErrorAction SilentlyContinue -if (-not $node) { throw 'Node.js LTS is required (https://nodejs.org).' } +if (-not $node) { throw 'Node.js 22 or later is required (https://nodejs.org).' } +# The NATS browser client (@nats-io/*) needs Node 22+; npm enforces it too (engines). +$nodeMajor = [int]((node --version).TrimStart('v').Split('.')[0]) +if ($nodeMajor -lt 22) { throw "Node.js 22 or later is required; found $(node --version)." } Write-Host "node $(node --version)" Write-Host '── Restoring .NET packages ──' diff --git a/scripts/Package-Agent.ps1 b/scripts/Package-Agent.ps1 index e8a7ee4..f69341e 100644 --- a/scripts/Package-Agent.ps1 +++ b/scripts/Package-Agent.ps1 @@ -1,7 +1,8 @@ <# .SYNOPSIS -Publishes the self-contained single-file Agent executable per platform, zips -each, and builds the MSI (win-x64) when the WiX project is present. +Publishes the self-contained single-file Agent executable and its watchdog +per platform, zips each, and builds the MSI (win-x64) when the WiX project is +present. Windows RIDs publish the net10.0-windows flavor (WMI, ConPTY, DPAPI, service); everything else publishes the portable net10.0 flavor (file config, @@ -62,7 +63,27 @@ foreach ($rid in $Runtimes) { Rename-Item (Join-Path $ridPublishDir 'ExecuteR-Agent') 'executer-agent' } + # The watchdog (keeps the agent running, applies upgrades) travels in every + # package beside the agent: one small trimmed single-file binary per RID. + $watchdogPublishDir = Join-Path $artifacts "watchdog/$Version/$rid" + if (Test-Path $watchdogPublishDir) { Remove-Item $watchdogPublishDir -Recurse -Force } + dotnet publish (Join-Path $repoRoot 'src/Agent.Watchdog/Agent.Watchdog.csproj') ` + -c Release ` + -r $rid ` + -p:DebugType=None ` + "-p:UnifiedVersion=$Version" ` + "-p:GitCommitShort=$(git -C $repoRoot rev-parse --short HEAD 2>$null)" ` + -o $watchdogPublishDir + if ($LASTEXITCODE -ne 0) { throw "Watchdog publish for $rid failed ($LASTEXITCODE)." } + if ($rid -like 'win-*') { + Copy-Item (Join-Path $watchdogPublishDir 'ExecuteR-Watchdog.exe') $ridPublishDir + } else { + Copy-Item (Join-Path $watchdogPublishDir 'ExecuteR-Watchdog') (Join-Path $ridPublishDir 'executer-watchdog') + } + Copy-Item $modulesStage (Join-Path $ridPublishDir 'Modules') -Recurse + # Licence terms and third-party notices travel with every package. + Copy-Item (Join-Path $repoRoot 'LICENSE'), (Join-Path $repoRoot 'THIRD-PARTY-NOTICES.md') $ridPublishDir $zipPath = Join-Path $artifacts "ExecuteR-Agent-$Version-$rid.zip" if (Test-Path $zipPath) { Remove-Item $zipPath -Force } diff --git a/scripts/Package-Server.ps1 b/scripts/Package-Server.ps1 index 4126f66..96dd3f5 100644 --- a/scripts/Package-Server.ps1 +++ b/scripts/Package-Server.ps1 @@ -37,16 +37,15 @@ if (-not $SkipIcon) { Push-Location (Join-Path $repoRoot 'src/WebUI') try { if (-not (Test-Path 'node_modules')) { npm ci } - $env:ADAPTER = 'static' $env:PUBLIC_BUILD_VERSION = $Version npm run build if ($LASTEXITCODE -ne 0) { throw "WebUI static build failed ($LASTEXITCODE)." } } finally { - Remove-Item Env:\ADAPTER -ErrorAction SilentlyContinue + Remove-Item Env:\PUBLIC_BUILD_VERSION -ErrorAction SilentlyContinue Pop-Location } -$staticBuild = Join-Path $repoRoot 'src/WebUI/build-static' +$staticBuild = Join-Path $repoRoot 'src/WebUI/dist' if (-not (Test-Path (Join-Path $staticBuild 'index.html'))) { throw "Static WebUI build missing at $staticBuild" } @@ -172,6 +171,9 @@ TRUSTED_NETWORKS (replace the default trust with an allow-list), TRUSTED_HOSTS, TRUST_PROXY=0 to disable. "@ + # Licence terms and third-party notices travel with every package. + Copy-Item (Join-Path $repoRoot 'LICENSE'), (Join-Path $repoRoot 'THIRD-PARTY-NOTICES.md') $publishDir + # ── Zip it ─────────────────────────────────────────────────────────────── $zipPath = Join-Path $artifacts "ExecuteR-Server-$Version-$rid.zip" if (Test-Path $zipPath) { Remove-Item $zipPath -Force } diff --git a/scripts/Test.ps1 b/scripts/Test.ps1 index 2de817f..f1f6e9b 100644 --- a/scripts/Test.ps1 +++ b/scripts/Test.ps1 @@ -1,6 +1,6 @@ <# .SYNOPSIS -Runs unit tests (and optionally the Svelte check + integration tests). +Runs unit tests (and optionally the WebUI typecheck + lint and the integration tests). .EXAMPLE ./scripts/Test.ps1 @@ -43,7 +43,7 @@ if ($IncludeWebUI) { if ($LASTEXITCODE -ne 0) { throw "npm ci failed ($LASTEXITCODE)." } } npm run check - if ($LASTEXITCODE -ne 0) { throw "svelte-check failed ($LASTEXITCODE)." } + if ($LASTEXITCODE -ne 0) { throw "WebUI check (typecheck + lint) failed ($LASTEXITCODE)." } } finally { Pop-Location diff --git a/src/Agent.Watchdog/Abstractions.cs b/src/Agent.Watchdog/Abstractions.cs new file mode 100644 index 0000000..9017a82 --- /dev/null +++ b/src/Agent.Watchdog/Abstractions.cs @@ -0,0 +1,106 @@ +using System.Diagnostics; + +namespace Agent.Watchdog; + +/// The watchdog's clock; replaced in tests so a ten-minute wait takes no time. +public interface IWatchdogClock +{ + DateTimeOffset UtcNow { get; } + + Task DelayAsync(TimeSpan delay, CancellationToken cancellationToken); +} + +public sealed class SystemClock : IWatchdogClock +{ + public static readonly SystemClock Instance = new(); + + public DateTimeOffset UtcNow => DateTimeOffset.UtcNow; + + public Task DelayAsync(TimeSpan delay, CancellationToken cancellationToken) => Task.Delay(delay, cancellationToken); +} + +public enum AgentRunState +{ + NotInstalled, + Stopped, + Starting, + Running, + Stopping, +} + +/// +/// What the service manager says about the agent. AutoStart: set to start +/// automatically (an admin's Manual or Disabled is left alone). +/// StoppedWithFailure: it stopped by exiting with an error rather than +/// by a stop request. +/// +public sealed record AgentServiceStatus(AgentRunState State, bool AutoStart, bool StoppedWithFailure) +{ + public static readonly AgentServiceStatus NotInstalled = new(AgentRunState.NotInstalled, false, false); + + public bool IsRunning => State is AgentRunState.Running or AgentRunState.Starting or AgentRunState.Stopping; +} + +/// The agent, through its service manager (or as a child process in the development mode). +public interface IAgentService +{ + Task QueryAsync(CancellationToken cancellationToken); + + /// Starts the agent; throws when the service manager refuses. + Task StartAsync(CancellationToken cancellationToken); + + /// Stops the agent and waits until it and its processes are gone, so its files can be moved. + Task StopAsync(CancellationToken cancellationToken); +} + +/// Runs a candidate watchdog binary once (<binary> version) to see that it starts. +public interface ISmokeTest +{ + /// The version it printed when it exited 0 within the time allowed; null otherwise. + string? Run(string binary); +} + +public sealed class ProcessSmokeTest : ISmokeTest +{ + public static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); + + public string? Run(string binary) + { + try + { + using var process = Process.Start(new ProcessStartInfo(binary, "version") + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + WorkingDirectory = Path.GetDirectoryName(binary)!, + }); + if (process is null) + { + return null; + } + + var output = process.StandardOutput.ReadToEndAsync(); + _ = process.StandardError.ReadToEndAsync(); + if (!process.WaitForExit(Timeout)) + { + process.Kill(entireProcessTree: true); + return null; + } + + return process.ExitCode == 0 ? output.GetAwaiter().GetResult().Trim() : null; + } + catch (Exception exception) when (exception is System.ComponentModel.Win32Exception or InvalidOperationException or IOException) + { + return null; + } + } +} + +/// Restarts the watchdog onto its new binary after it replaced itself. +public interface IWatchdogRestart +{ + /// True when a restart is under way and this process should now exit. + bool Restart(string newBinary); +} diff --git a/src/Agent.Watchdog/Agent.Watchdog.csproj b/src/Agent.Watchdog/Agent.Watchdog.csproj new file mode 100644 index 0000000..4b61635 --- /dev/null +++ b/src/Agent.Watchdog/Agent.Watchdog.csproj @@ -0,0 +1,53 @@ + + + + Exe + + net10.0 + Agent.Watchdog + ExecuteR-Watchdog + ExecuteR Watchdog + ExecuteR Watchdog + win-x64;win-arm64;linux-x64;linux-arm64;osx-x64;osx-arm64 + + true + true + en + + true + $(MSBuildThisFileDirectory)..\..\assets\icons\app.ico + + + + + true + true + true + full + true + none + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Agent.Watchdog/AgentSupervisor.cs b/src/Agent.Watchdog/AgentSupervisor.cs new file mode 100644 index 0000000..746ce87 --- /dev/null +++ b/src/Agent.Watchdog/AgentSupervisor.cs @@ -0,0 +1,103 @@ +using Shared.Contracts.Serialization; + +namespace Agent.Watchdog; + +/// +/// Keeps the agent running without fighting an admin. It acts only while the +/// agent service is installed and set to start automatically (a Manual or +/// Disabled service is the admin's choice and left alone), and then only in two +/// cases, at most once per : +/// +/// the agent runs, has run for longer than the stale period, and its +/// health beacon is older than that: it hangs, so it is restarted (no beacon at +/// all means a version that writes none, and is left alone); +/// the agent stopped with a failure and is still stopped a stale period +/// later (the service manager's own restarts gave up): it is started. +/// +/// A clean stop (ExecuteR-Agent.exe stop, systemctl stop) is never undone. +/// +public sealed class AgentSupervisor(WatchdogOptions options, IAgentService agent, IWatchdogClock clock, WatchdogLog log) +{ + private DateTimeOffset? runningSince; + private DateTimeOffset? failedSince; + private DateTimeOffset lastRestart = DateTimeOffset.MinValue; + private string? lastNote; + + public async Task CheckAsync(CancellationToken cancellationToken) + { + var status = await agent.QueryAsync(cancellationToken); + var now = clock.UtcNow; + + if (status.State == AgentRunState.NotInstalled || !status.AutoStart) + { + runningSince = null; + failedSince = null; + Note(status.State == AgentRunState.NotInstalled + ? "The agent service is not installed; nothing to watch" + : "The agent service is not set to start automatically; it is left as the admin set it"); + return; + } + + Note(null); + if (status.IsRunning) + { + failedSince = null; + runningSince ??= now; + var beacon = WatchdogFileStore.Read(options.HealthPath, WatchdogJsonContext.Default.WatchdogHealthBeacon); + if (beacon is not null + && now - beacon.AtUtc > options.StaleAfter + && now - runningSince > options.StaleAfter + && now - lastRestart > options.StaleAfter) + { + log.Warn($"The agent stopped answering (last health beacon {beacon.AtUtc:O}); restarting it"); + lastRestart = now; + runningSince = now; + try + { + await agent.StopAsync(cancellationToken); + await agent.StartAsync(cancellationToken); + } + catch (Exception exception) when (exception is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + log.Warn("Restarting the agent failed", exception); + } + } + + return; + } + + runningSince = null; + if (!status.StoppedWithFailure || status.State != AgentRunState.Stopped) + { + failedSince = null; + return; + } + + failedSince ??= now; + if (now - failedSince > options.StaleAfter && now - lastRestart > options.StaleAfter) + { + log.Warn("The agent stopped with a failure and was not started again; starting it"); + lastRestart = now; + failedSince = null; + try + { + await agent.StartAsync(cancellationToken); + } + catch (Exception exception) when (exception is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + log.Warn("Starting the agent failed", exception); + } + } + } + + /// Logs a standing condition once, not every poll. + private void Note(string? note) + { + if (note is not null && note != lastNote) + { + log.Info(note); + } + + lastNote = note; + } +} diff --git a/src/Agent.Watchdog/Platform/ProcessAgentService.cs b/src/Agent.Watchdog/Platform/ProcessAgentService.cs new file mode 100644 index 0000000..b04d4bb --- /dev/null +++ b/src/Agent.Watchdog/Platform/ProcessAgentService.cs @@ -0,0 +1,105 @@ +using System.Diagnostics; + +namespace Agent.Watchdog.Platform; + +/// +/// Development mode (--agent process): the agent runs as the watchdog's +/// child (<agent> foreground) instead of a service, so the swap and +/// rollback can be driven on a machine without installing services. An agent in +/// the foreground refuses upgrade commands itself; this mode is for driving the +/// watchdog with a stub agent and a hand-made hand-over. +/// +public sealed class ProcessAgentService(WatchdogOptions options, WatchdogLog log) : IAgentService, IDisposable +{ + private readonly Lock gate = new(); + private Process? process; + + public Task QueryAsync(CancellationToken cancellationToken) + { + lock (gate) + { + if (process is null) + { + return Task.FromResult(new AgentServiceStatus(AgentRunState.Stopped, true, false)); + } + + return Task.FromResult(process.HasExited + ? new AgentServiceStatus(AgentRunState.Stopped, true, process.ExitCode != 0) + : new AgentServiceStatus(AgentRunState.Running, true, false)); + } + } + + public Task StartAsync(CancellationToken cancellationToken) + { + lock (gate) + { + if (process is { HasExited: false }) + { + return Task.CompletedTask; + } + + var executable = Path.Combine(options.InstallDirectory, options.AgentExecutable); + var start = new ProcessStartInfo(executable, "foreground") + { + UseShellExecute = false, + CreateNoWindow = true, + WorkingDirectory = options.InstallDirectory, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + process?.Dispose(); + process = Process.Start(start) ?? throw new InvalidOperationException($"{executable} did not start"); + process.OutputDataReceived += (_, _) => { }; + process.ErrorDataReceived += (_, _) => { }; + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + log.Info($"Agent process {process.Id} started ({executable})"); + } + + return Task.CompletedTask; + } + + public async Task StopAsync(CancellationToken cancellationToken) + { + Process? running; + lock (gate) + { + running = process; + } + + if (running is null || running.HasExited) + { + return; + } + + try + { + running.Kill(entireProcessTree: true); + } + catch (InvalidOperationException) + { + } + + await running.WaitForExitAsync(cancellationToken); + log.Info($"Agent process {running.Id} stopped"); + } + + public void Dispose() + { + lock (gate) + { + if (process is { HasExited: false } running) + { + try + { + running.Kill(entireProcessTree: true); + } + catch (InvalidOperationException) + { + } + } + + process?.Dispose(); + } + } +} diff --git a/src/Agent.Watchdog/Platform/ServiceInterop.cs b/src/Agent.Watchdog/Platform/ServiceInterop.cs new file mode 100644 index 0000000..f5ae041 --- /dev/null +++ b/src/Agent.Watchdog/Platform/ServiceInterop.cs @@ -0,0 +1,158 @@ +using System.ComponentModel; +using System.Runtime.InteropServices; + +namespace Agent.Watchdog.Platform; + +/// +/// Minimal advapi32 service-control interop (never sc.exe): registration and +/// the exit code of a stopped service, which ServiceController does not show. +/// +internal static partial class ServiceInterop +{ + internal const uint SC_MANAGER_CONNECT = 0x1; + internal const uint SC_MANAGER_ALL_ACCESS = 0xF003F; + internal const uint SERVICE_QUERY_STATUS = 0x4; + internal const uint SERVICE_ALL_ACCESS = 0xF01FF; + internal const uint SERVICE_WIN32_OWN_PROCESS = 0x10; + internal const uint SERVICE_AUTO_START = 0x2; + internal const uint SERVICE_ERROR_NORMAL = 0x1; + + internal const int SERVICE_CONFIG_DESCRIPTION = 1; + internal const int SERVICE_CONFIG_FAILURE_ACTIONS = 2; + internal const int SC_ACTION_RESTART = 1; + internal const int SC_STATUS_PROCESS_INFO = 0; + + /// The service has not been started since the machine booted: not a failure. + internal const uint ERROR_SERVICE_NEVER_STARTED = 1077; + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct SERVICE_DESCRIPTION + { + public string lpDescription; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct SC_ACTION + { + public int Type; + public uint Delay; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct SERVICE_FAILURE_ACTIONS + { + public uint dwResetPeriod; + public string? lpRebootMsg; + public string? lpCommand; + public uint cActions; + public IntPtr lpsaActions; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct SERVICE_STATUS_PROCESS + { + public uint dwServiceType; + public uint dwCurrentState; + public uint dwControlsAccepted; + public uint dwWin32ExitCode; + public uint dwServiceSpecificExitCode; + public uint dwCheckPoint; + public uint dwWaitHint; + public uint dwProcessId; + public uint dwServiceFlags; + } + + [LibraryImport("advapi32.dll", EntryPoint = "OpenSCManagerW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + internal static partial IntPtr OpenSCManager(string? machineName, string? databaseName, uint access); + + [LibraryImport("advapi32.dll", EntryPoint = "OpenServiceW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + internal static partial IntPtr OpenService(IntPtr scManager, string serviceName, uint access); + + [LibraryImport("advapi32.dll", EntryPoint = "CreateServiceW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + internal static partial IntPtr CreateService( + IntPtr scManager, + string serviceName, + string displayName, + uint desiredAccess, + uint serviceType, + uint startType, + uint errorControl, + string binaryPathName, + string? loadOrderGroup, + IntPtr tagId, + string? dependencies, + string? serviceStartName, + string? password); + + [LibraryImport("advapi32.dll", EntryPoint = "ChangeServiceConfigW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool ChangeServiceConfig( + IntPtr service, + uint serviceType, + uint startType, + uint errorControl, + string? binaryPathName, + string? loadOrderGroup, + IntPtr tagId, + string? dependencies, + string? serviceStartName, + string? password, + string? displayName); + + [DllImport("advapi32.dll", EntryPoint = "ChangeServiceConfig2W", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool ChangeServiceConfig2(IntPtr service, int infoLevel, ref SERVICE_DESCRIPTION info); + + [DllImport("advapi32.dll", EntryPoint = "ChangeServiceConfig2W", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool ChangeServiceConfig2(IntPtr service, int infoLevel, ref SERVICE_FAILURE_ACTIONS info); + + [LibraryImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool QueryServiceStatusEx(IntPtr service, int infoLevel, out SERVICE_STATUS_PROCESS buffer, int bufferSize, out int bytesNeeded); + + [LibraryImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool DeleteService(IntPtr service); + + [LibraryImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool CloseServiceHandle(IntPtr handle); + + internal static Win32Exception LastError(string operation) + => new(Marshal.GetLastPInvokeError(), $"{operation} failed"); + + /// The service's status block, or null when it cannot be read. + internal static SERVICE_STATUS_PROCESS? QueryStatus(string serviceName) + { + var scm = OpenSCManager(null, null, SC_MANAGER_CONNECT); + if (scm == IntPtr.Zero) + { + return null; + } + + try + { + var service = OpenService(scm, serviceName, SERVICE_QUERY_STATUS); + if (service == IntPtr.Zero) + { + return null; + } + + try + { + return QueryServiceStatusEx(service, SC_STATUS_PROCESS_INFO, out var status, Marshal.SizeOf(), out _) + ? status + : null; + } + finally + { + CloseServiceHandle(service); + } + } + finally + { + CloseServiceHandle(scm); + } + } +} diff --git a/src/Agent.Watchdog/Platform/UnixServices.cs b/src/Agent.Watchdog/Platform/UnixServices.cs new file mode 100644 index 0000000..f240c82 --- /dev/null +++ b/src/Agent.Watchdog/Platform/UnixServices.cs @@ -0,0 +1,282 @@ +using System.Diagnostics; +using Shared.Infrastructure.Constants; + +namespace Agent.Watchdog.Platform; + +/// Runs a service-manager command (systemctl, launchctl) and captures its output. +internal static class Command +{ + public static (int ExitCode, string Output) Run(string fileName, params string[] arguments) + { + var start = new ProcessStartInfo(fileName) + { + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + foreach (var argument in arguments) + { + start.ArgumentList.Add(argument); + } + + using var process = Process.Start(start) ?? throw new InvalidOperationException($"{fileName} did not start"); + var output = process.StandardOutput.ReadToEndAsync(); + var error = process.StandardError.ReadToEndAsync(); + process.WaitForExit(); + return (process.ExitCode, output.GetAwaiter().GetResult() + error.GetAwaiter().GetResult()); + } + + public static void Require(string fileName, params string[] arguments) + { + var (code, output) = Run(fileName, arguments); + if (code != 0) + { + throw new InvalidOperationException($"{fileName} {string.Join(' ', arguments)} exited with {code}: {output.Trim()}"); + } + } +} + +/// The agent's systemd unit. +public sealed class SystemdAgentService(string unit) : IAgentService +{ + public Task QueryAsync(CancellationToken cancellationToken) + { + var (_, output) = Command.Run("systemctl", "show", unit, "--property=LoadState,ActiveState,Result,UnitFileState"); + var values = output.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Select(line => line.Split('=', 2)) + .Where(pair => pair.Length == 2) + .ToDictionary(pair => pair[0], pair => pair[1], StringComparer.Ordinal); + if (values.GetValueOrDefault("LoadState") is null or "not-found") + { + return Task.FromResult(AgentServiceStatus.NotInstalled); + } + + var active = values.GetValueOrDefault("ActiveState"); + var state = active switch + { + "active" or "reloading" => AgentRunState.Running, + "activating" => AgentRunState.Starting, + "deactivating" => AgentRunState.Stopping, + _ => AgentRunState.Stopped, + }; + var failed = state == AgentRunState.Stopped + && (active == "failed" || values.GetValueOrDefault("Result") is { } result && result != "success"); + var enabled = values.GetValueOrDefault("UnitFileState") is "enabled" or "enabled-runtime"; + return Task.FromResult(new AgentServiceStatus(state, enabled, failed)); + } + + public Task StartAsync(CancellationToken cancellationToken) => Task.Run(() => + { + // A unit systemd gave up on stays failed until reset. + Command.Run("systemctl", "reset-failed", unit); + Command.Require("systemctl", "start", unit); + }, cancellationToken); + + // systemctl stop returns once the unit's processes (its whole cgroup) are gone. + public Task StopAsync(CancellationToken cancellationToken) => Task.Run(() => Command.Require("systemctl", "stop", unit), cancellationToken); +} + +/// +/// The agent's launchd daemon. Its plist keeps it alive, so a stop unloads it +/// (bootout) and a start loads it again (bootstrap). +/// +public sealed class LaunchdAgentService(string label) : IAgentService +{ + private string Plist => $"/Library/LaunchDaemons/{label}.plist"; + + public Task QueryAsync(CancellationToken cancellationToken) + { + if (!File.Exists(Plist)) + { + return Task.FromResult(AgentServiceStatus.NotInstalled); + } + + var (code, output) = Command.Run("launchctl", "print", $"system/{label}"); + if (code != 0) + { + // Not loaded: booted out by a stop. + return Task.FromResult(new AgentServiceStatus(AgentRunState.Stopped, true, false)); + } + + var running = output.Contains("state = running", StringComparison.Ordinal); + var lastExit = output.Split('\n').Select(l => l.Trim()).FirstOrDefault(l => l.StartsWith("last exit code = ", StringComparison.Ordinal)); + var failed = !running && lastExit is not null && lastExit != "last exit code = 0"; + return Task.FromResult(new AgentServiceStatus(running ? AgentRunState.Running : AgentRunState.Stopped, true, failed)); + } + + public Task StartAsync(CancellationToken cancellationToken) => Task.Run(() => + { + if (Command.Run("launchctl", "print", $"system/{label}").ExitCode != 0) + { + Command.Require("launchctl", "bootstrap", "system", Plist); + } + else + { + Command.Require("launchctl", "kickstart", $"system/{label}"); + } + }, cancellationToken); + + public async Task StopAsync(CancellationToken cancellationToken) + { + Command.Run("launchctl", "bootout", $"system/{label}"); + var deadline = DateTime.UtcNow.AddSeconds(60); + while (Command.Run("launchctl", "print", $"system/{label}").ExitCode == 0 && DateTime.UtcNow < deadline) + { + await Task.Delay(500, cancellationToken); + } + } +} + +/// The watchdog's own systemd unit / launchd daemon: install, remove, start, stop, status, restart. +public static class UnixWatchdogRegistration +{ + private static string Unit => $"/etc/systemd/system/{Branding.WatchdogSystemdUnit}.service"; + + private static string Plist => $"/Library/LaunchDaemons/{Branding.WatchdogLaunchdLabel}.plist"; + + public static int Install(string executablePath) + { + SwapPaths.MakeExecutable(executablePath); + if (OperatingSystem.IsMacOS()) + { + File.WriteAllText(Plist, $""" + + + + + Label{Branding.WatchdogLaunchdLabel} + ProgramArguments + {executablePath}run + RunAtLoad + KeepAlive + + + """); + File.SetUnixFileMode(Plist, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.OtherRead); + Console.WriteLine($"launchd daemon {Branding.WatchdogLaunchdLabel} installed."); + return 0; + } + + File.WriteAllText(Unit, $""" + [Unit] + Description={Branding.WatchdogServiceDisplayName} + After=network-online.target + + [Service] + Type=simple + ExecStart={executablePath} run + Restart=always + RestartSec=10 + + [Install] + WantedBy=multi-user.target + """); + Command.Run("systemctl", "daemon-reload"); + Command.Require("systemctl", "enable", Branding.WatchdogSystemdUnit); + Console.WriteLine($"systemd unit {Branding.WatchdogSystemdUnit} installed."); + return 0; + } + + public static int Remove() + { + if (OperatingSystem.IsMacOS()) + { + Command.Run("launchctl", "bootout", $"system/{Branding.WatchdogLaunchdLabel}"); + if (File.Exists(Plist)) + { + File.Delete(Plist); + } + + Console.WriteLine($"launchd daemon {Branding.WatchdogLaunchdLabel} removed."); + return 0; + } + + Command.Run("systemctl", "disable", "--now", Branding.WatchdogSystemdUnit); + if (File.Exists(Unit)) + { + File.Delete(Unit); + } + + Command.Run("systemctl", "daemon-reload"); + Console.WriteLine($"systemd unit {Branding.WatchdogSystemdUnit} removed."); + return 0; + } + + public static int Start() + { + if (OperatingSystem.IsMacOS()) + { + var loaded = Command.Run("launchctl", "print", $"system/{Branding.WatchdogLaunchdLabel}").ExitCode == 0; + return loaded + ? Command.Run("launchctl", "kickstart", $"system/{Branding.WatchdogLaunchdLabel}").ExitCode + : Command.Run("launchctl", "bootstrap", "system", Plist).ExitCode; + } + + return Command.Run("systemctl", "start", Branding.WatchdogSystemdUnit).ExitCode; + } + + public static int Stop() + { + if (OperatingSystem.IsMacOS()) + { + Command.Run("launchctl", "bootout", $"system/{Branding.WatchdogLaunchdLabel}"); + return 0; + } + + Command.Run("systemctl", "stop", Branding.WatchdogSystemdUnit); + return 0; + } + + /// One machine-readable line (the agent reads it), then a human one. + public static int Status() + { + bool installed; + string state; + if (OperatingSystem.IsMacOS()) + { + installed = File.Exists(Plist); + var (code, output) = Command.Run("launchctl", "print", $"system/{Branding.WatchdogLaunchdLabel}"); + state = !installed ? "NotInstalled" : code == 0 && output.Contains("state = running", StringComparison.Ordinal) ? "Running" : "Stopped"; + } + else + { + installed = File.Exists(Unit); + var active = Command.Run("systemctl", "is-active", Branding.WatchdogSystemdUnit).Output.Trim(); + state = !installed ? "NotInstalled" : active == "active" ? "Running" : "Stopped"; + } + + Console.WriteLine($"{{\"service\":\"{(OperatingSystem.IsMacOS() ? Branding.WatchdogLaunchdLabel : Branding.WatchdogSystemdUnit)}\",\"installed\":{(installed ? "true" : "false")},\"state\":\"{state}\"}}"); + Console.WriteLine($"{Branding.WatchdogServiceDisplayName}: {state}"); + return 0; + } +} + +/// +/// Restarts the watchdog onto its new binary through the service manager: +/// systemd queues a restart job (--no-block) and stops this instance +/// itself; launchd's kickstart -k does the same. +/// +public sealed class UnixWatchdogRestart(WatchdogLog log) : IWatchdogRestart +{ + public bool Restart(string newBinary) + { + try + { + var (code, output) = OperatingSystem.IsMacOS() + ? Command.Run("launchctl", "kickstart", "-k", $"system/{Branding.WatchdogLaunchdLabel}") + : Command.Run("systemctl", "restart", "--no-block", Branding.WatchdogSystemdUnit); + if (code == 0) + { + return true; + } + + log.Warn($"The service manager would not restart the watchdog ({output.Trim()}); the new binary runs at the next start"); + return false; + } + catch (Exception exception) when (exception is InvalidOperationException or System.ComponentModel.Win32Exception) + { + log.Warn("The service manager could not restart the watchdog; the new binary runs at the next start", exception); + return false; + } + } +} diff --git a/src/Agent.Watchdog/Platform/WindowsServices.cs b/src/Agent.Watchdog/Platform/WindowsServices.cs new file mode 100644 index 0000000..46aaa8c --- /dev/null +++ b/src/Agent.Watchdog/Platform/WindowsServices.cs @@ -0,0 +1,487 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using System.ServiceProcess; +using Shared.Infrastructure.Constants; +using static Agent.Watchdog.Platform.ServiceInterop; + +namespace Agent.Watchdog.Platform; + +/// The agent's Windows service, through the Service Control Manager. +[SupportedOSPlatform("windows")] +public sealed class WindowsAgentService(string serviceName, string agentExecutablePath, WatchdogLog log) : IAgentService +{ + private static readonly TimeSpan StateChangeTimeout = TimeSpan.FromSeconds(60); + + public Task QueryAsync(CancellationToken cancellationToken) + { + using var controller = new ServiceController(serviceName); + ServiceControllerStatus status; + ServiceStartMode startMode; + try + { + status = controller.Status; + startMode = controller.StartType; + } + catch (InvalidOperationException) + { + return Task.FromResult(AgentServiceStatus.NotInstalled); + } + + var state = status switch + { + ServiceControllerStatus.Running or ServiceControllerStatus.Paused or ServiceControllerStatus.PausePending + or ServiceControllerStatus.ContinuePending => AgentRunState.Running, + ServiceControllerStatus.StartPending => AgentRunState.Starting, + ServiceControllerStatus.StopPending => AgentRunState.Stopping, + _ => AgentRunState.Stopped, + }; + + // A stop request leaves exit code 0; a crash or a failed start leaves an error. + var failed = state == AgentRunState.Stopped + && QueryStatus(serviceName) is { } block + && block.dwWin32ExitCode is not (0 or ERROR_SERVICE_NEVER_STARTED); + return Task.FromResult(new AgentServiceStatus(state, startMode == ServiceStartMode.Automatic, failed)); + } + + public Task StartAsync(CancellationToken cancellationToken) => Task.Run(() => + { + using var controller = new ServiceController(serviceName); + if (controller.Status is ServiceControllerStatus.Running) + { + return; + } + + if (controller.Status is ServiceControllerStatus.StopPending) + { + controller.WaitForStatus(ServiceControllerStatus.Stopped, StateChangeTimeout); + } + + if (controller.Status is not ServiceControllerStatus.StartPending) + { + controller.Start(); + } + + controller.WaitForStatus(ServiceControllerStatus.Running, StateChangeTimeout); + log.Info($"Agent service {serviceName} started"); + }, cancellationToken); + + public async Task StopAsync(CancellationToken cancellationToken) + { + await Task.Run(() => + { + using var controller = new ServiceController(serviceName); + if (controller.Status is ServiceControllerStatus.Stopped) + { + return; + } + + if (controller.Status is ServiceControllerStatus.StartPending) + { + controller.WaitForStatus(ServiceControllerStatus.Running, StateChangeTimeout); + } + + if (controller.Status is not ServiceControllerStatus.StopPending) + { + controller.Stop(); + } + + controller.WaitForStatus(ServiceControllerStatus.Stopped, StateChangeTimeout); + log.Info($"Agent service {serviceName} stopped"); + }, cancellationToken); + + // The service process can outlive its STOPPED report by a moment, and the + // agent's own children (its remote-shell host is the agent binary) hold + // the binary: wait for them, then end what is left. + await StopLeftoversAsync(cancellationToken); + } + + private async Task StopLeftoversAsync(CancellationToken cancellationToken) + { + var name = Path.GetFileNameWithoutExtension(agentExecutablePath); + var deadline = DateTime.UtcNow.AddSeconds(10); + while (true) + { + var leftovers = Process.GetProcessesByName(name).Where(IsAgentBinary).ToList(); + if (leftovers.Count == 0) + { + return; + } + + if (DateTime.UtcNow >= deadline) + { + foreach (var process in leftovers) + { + try + { + log.Warn($"Ending agent process {process.Id} that outlived the service"); + process.Kill(entireProcessTree: true); + } + catch (Exception exception) when (exception is InvalidOperationException or System.ComponentModel.Win32Exception) + { + } + } + + return; + } + + foreach (var process in leftovers) + { + process.Dispose(); + } + + await Task.Delay(500, cancellationToken); + } + } + + private bool IsAgentBinary(Process process) + { + try + { + return string.Equals(process.MainModule?.FileName, agentExecutablePath, StringComparison.OrdinalIgnoreCase); + } + catch (Exception exception) when (exception is InvalidOperationException or System.ComponentModel.Win32Exception) + { + return false; + } + } +} + +/// +/// The watchdog's own Windows service: LocalSystem, automatic start, restarted +/// by the Service Control Manager when it fails. Registered through the SCM +/// APIs, never sc.exe; idempotent. +/// +[SupportedOSPlatform("windows")] +public static class WindowsWatchdogRegistration +{ + private static readonly TimeSpan StateChangeTimeout = TimeSpan.FromSeconds(60); + private static readonly TimeSpan RecoveryRestartDelay = TimeSpan.FromSeconds(10); + + public static int Install(string executablePath) + { + var binaryPath = $"\"{executablePath}\" run"; + var scm = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS); + if (scm == IntPtr.Zero) + { + throw LastError("OpenSCManager (administrator rights required)"); + } + + try + { + var service = OpenService(scm, Branding.WatchdogServiceName, SERVICE_ALL_ACCESS); + if (service == IntPtr.Zero) + { + service = CreateService(scm, Branding.WatchdogServiceName, Branding.WatchdogServiceDisplayName, SERVICE_ALL_ACCESS, + SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, binaryPath, + loadOrderGroup: null, tagId: IntPtr.Zero, dependencies: null, serviceStartName: null, password: null); + if (service == IntPtr.Zero) + { + throw LastError("CreateService"); + } + + Console.WriteLine($"Service '{Branding.WatchdogServiceName}' created."); + } + else + { + if (!ChangeServiceConfig(service, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, binaryPath, + loadOrderGroup: null, tagId: IntPtr.Zero, dependencies: null, serviceStartName: null, password: null, + Branding.WatchdogServiceDisplayName)) + { + throw LastError("ChangeServiceConfig"); + } + + Console.WriteLine($"Service '{Branding.WatchdogServiceName}' updated."); + } + + try + { + ApplyMetadata(service); + } + finally + { + CloseServiceHandle(service); + } + + return 0; + } + finally + { + CloseServiceHandle(scm); + } + } + + private static void ApplyMetadata(IntPtr service) + { + var description = new SERVICE_DESCRIPTION { lpDescription = Branding.WatchdogServiceDescription }; + if (!ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, ref description)) + { + throw LastError("ChangeServiceConfig2(description)"); + } + + var size = Marshal.SizeOf(); + var actionsPtr = Marshal.AllocHGlobal(size * 3); + try + { + for (var i = 0; i < 3; i++) + { + Marshal.StructureToPtr(new SC_ACTION { Type = SC_ACTION_RESTART, Delay = (uint)RecoveryRestartDelay.TotalMilliseconds }, + actionsPtr + i * size, false); + } + + var failureActions = new SERVICE_FAILURE_ACTIONS + { + dwResetPeriod = (uint)TimeSpan.FromDays(1).TotalSeconds, + cActions = 3, + lpsaActions = actionsPtr, + }; + if (!ChangeServiceConfig2(service, SERVICE_CONFIG_FAILURE_ACTIONS, ref failureActions)) + { + throw LastError("ChangeServiceConfig2(failure actions)"); + } + } + finally + { + Marshal.FreeHGlobal(actionsPtr); + } + } + + public static int Remove() + { + if (!Exists()) + { + Console.WriteLine($"Service '{Branding.WatchdogServiceName}' is not installed."); + return 0; + } + + Stop(); + var scm = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS); + if (scm == IntPtr.Zero) + { + throw LastError("OpenSCManager (administrator rights required)"); + } + + try + { + var service = OpenService(scm, Branding.WatchdogServiceName, SERVICE_ALL_ACCESS); + if (service == IntPtr.Zero) + { + return 0; + } + + try + { + if (!DeleteService(service)) + { + throw LastError("DeleteService"); + } + } + finally + { + CloseServiceHandle(service); + } + + Console.WriteLine($"Service '{Branding.WatchdogServiceName}' removed."); + return 0; + } + finally + { + CloseServiceHandle(scm); + } + } + + public static int Start() + { + if (!Exists()) + { + Console.Error.WriteLine($"Service '{Branding.WatchdogServiceName}' is not installed."); + return 1; + } + + using var controller = new ServiceController(Branding.WatchdogServiceName); + if (controller.Status is ServiceControllerStatus.Running) + { + Console.WriteLine("Service is already running."); + return 0; + } + + if (controller.Status is not ServiceControllerStatus.StartPending) + { + controller.Start(); + } + + controller.WaitForStatus(ServiceControllerStatus.Running, StateChangeTimeout); + Console.WriteLine("Service started."); + return 0; + } + + public static int Stop() + { + if (!Exists()) + { + Console.WriteLine($"Service '{Branding.WatchdogServiceName}' is not installed."); + return 0; + } + + using var controller = new ServiceController(Branding.WatchdogServiceName); + if (controller.Status is ServiceControllerStatus.Stopped) + { + Console.WriteLine("Service is already stopped."); + return 0; + } + + if (controller.CanStop) + { + controller.Stop(); + } + + controller.WaitForStatus(ServiceControllerStatus.Stopped, StateChangeTimeout); + Console.WriteLine("Service stopped."); + return 0; + } + + /// One machine-readable line (the agent reads it), then a human one. + public static int Status() + { + var installed = Exists(); + string state; + if (installed) + { + using var controller = new ServiceController(Branding.WatchdogServiceName); + state = controller.Status.ToString(); + } + else + { + state = "NotInstalled"; + } + + Console.WriteLine($"{{\"service\":\"{Branding.WatchdogServiceName}\",\"installed\":{(installed ? "true" : "false")},\"state\":\"{state}\"}}"); + Console.WriteLine($"Service '{Branding.WatchdogServiceDisplayName}': {state}"); + return 0; + } + + /// + /// Hidden verb run by a watchdog that replaced its own binary: started from + /// the new binary, it outlives the service process (the SCM kills no + /// children), waits for it to exit and starts the service again. + /// + public static int RestartAfterExit(int processId) + { + try + { + using var previous = Process.GetProcessById(processId); + previous.WaitForExit(TimeSpan.FromMinutes(2)); + } + catch (ArgumentException) + { + // Already gone. + } + + for (var attempt = 1; ; attempt++) + { + try + { + using var controller = new ServiceController(Branding.WatchdogServiceName); + controller.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30)); + controller.Start(); + controller.WaitForStatus(ServiceControllerStatus.Running, StateChangeTimeout); + return 0; + } + catch (Exception exception) when (exception is InvalidOperationException or System.ServiceProcess.TimeoutException && attempt < 3) + { + Thread.Sleep(TimeSpan.FromSeconds(10)); + } + } + } + + private static bool Exists() + => ServiceController.GetServices().Any(s => + string.Equals(s.ServiceName, Branding.WatchdogServiceName, StringComparison.OrdinalIgnoreCase)); +} + +/// Restarts the watchdog service onto its new binary (see ). +[SupportedOSPlatform("windows")] +public sealed class WindowsWatchdogRestart(WatchdogLog log) : IWatchdogRestart +{ + public bool Restart(string newBinary) + { + try + { + var start = new ProcessStartInfo(newBinary) + { + UseShellExecute = false, + CreateNoWindow = true, + WorkingDirectory = Path.GetDirectoryName(newBinary)!, + }; + start.ArgumentList.Add(WatchdogCli.RestartVerb); + start.ArgumentList.Add(Environment.ProcessId.ToString(System.Globalization.CultureInfo.InvariantCulture)); + Process.Start(start)?.Dispose(); + return true; + } + catch (Exception exception) when (exception is System.ComponentModel.Win32Exception or InvalidOperationException) + { + log.Warn("The watchdog could not arrange its restart; the new binary runs at the next start", exception); + return false; + } + } +} + +/// The watchdog as a Windows service: the loop runs until the SCM stops it, or it replaced itself. +[SupportedOSPlatform("windows")] +public sealed class WindowsWatchdogHost : ServiceBase +{ + private readonly Func> run; + private readonly CancellationTokenSource stopping = new(); + private Task? loop; + + public WindowsWatchdogHost(Func> run) + { + this.run = run; + ServiceName = Branding.WatchdogServiceName; + CanStop = true; + CanShutdown = true; + } + + protected override void OnShutdown() => OnStop(); + + protected override void OnStart(string[] args) + { + loop = Task.Run(async () => + { + bool restart; + try + { + restart = await run(stopping.Token); + } + catch (OperationCanceledException) + { + restart = false; + } + + if (!stopping.IsCancellationRequested) + { + // Ended by itself (a restart onto the new binary): stop the + // service from another thread, since OnStop waits for this one. + _ = Task.Run(Stop); + } + + return restart; + }); + } + + protected override void OnStop() + { + stopping.Cancel(); + loop?.Wait(TimeSpan.FromSeconds(30)); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + stopping.Dispose(); + } + + base.Dispose(disposing); + } +} diff --git a/src/Agent.Watchdog/Program.cs b/src/Agent.Watchdog/Program.cs new file mode 100644 index 0000000..2eab268 --- /dev/null +++ b/src/Agent.Watchdog/Program.cs @@ -0,0 +1,3 @@ +using Agent.Watchdog; + +return await WatchdogCli.RunAsync(args); diff --git a/src/Agent.Watchdog/SwapPaths.cs b/src/Agent.Watchdog/SwapPaths.cs new file mode 100644 index 0000000..687cfd6 --- /dev/null +++ b/src/Agent.Watchdog/SwapPaths.cs @@ -0,0 +1,98 @@ +using System.Security.Cryptography; +using Shared.Contracts.Models; + +namespace Agent.Watchdog; + +/// Relative-path rules and file helpers of the swap. +public static class SwapPaths +{ + /// File names compare as the platform's file system does. + public static StringComparer Comparer { get; } = OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; + + public static StringComparison Comparison { get; } = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + + /// The swap's own folders and the agent's log folder: never part of a package, never moved. + public static readonly string[] Reserved = [WatchdogFiles.NextFolder, WatchdogFiles.PreviousFolder, WatchdogFiles.FailedFolder, "Logs"]; + + /// + /// A package path the swap accepts: relative, '/'-separated, no empty, + /// "." or ".." segment, no drive or backslash, not in a reserved folder. + /// + public static bool IsSafe(string path) + => path.Length is > 0 and < 400 + && !path.Contains('\\') + && !path.Contains(':') + && !path.StartsWith('/') + && path.Split('/').All(segment => segment.Length > 0 && segment != "." && segment != "..") + && !Reserved.Contains(FirstSegment(path), Comparer); + + public static string FirstSegment(string relative) + { + var slash = relative.IndexOf('/'); + return slash < 0 ? relative : relative[..slash]; + } + + public static string Relative(string root, string path) => Path.GetRelativePath(root, path).Replace('\\', '/'); + + public static string Combine(string root, string relative) => Path.Combine(root, relative.Replace('/', Path.DirectorySeparatorChar)); + + /// True when lies inside (not the folder itself). + public static bool IsInside(string path, string folder) + { + var full = Path.GetFullPath(path); + var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder)) + Path.DirectorySeparatorChar; + return full.StartsWith(root, Comparison) && full.Length > root.Length; + } + + public static string Sha256(string path) + { + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); + return Convert.ToHexStringLower(SHA256.HashData(stream)); + } + + /// A sharing or lock violation: another process has the file open for a moment. + public static bool IsInUse(IOException exception) => (exception.HResult & 0xFFFF) is 32 or 33; + + public static void TryDeleteDirectory(string directory) + { + try + { + if (Directory.Exists(directory)) + { + Directory.Delete(directory, recursive: true); + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // Something still holds a file (a replaced watchdog that is still + // running, say); the next start's tidy takes it. + } + } + + /// Removes the folder when nothing is left in it. + public static void TryDeleteIfEmpty(string directory) + { + try + { + if (Directory.Exists(directory) && !Directory.EnumerateFileSystemEntries(directory).Any()) + { + Directory.Delete(directory); + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + } + } + + /// rwxr-xr-x for a binary on linux/macOS (a zip made on Windows carries no modes). + public static void MakeExecutable(string path) + { + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(path, + UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute + | UnixFileMode.GroupRead | UnixFileMode.GroupExecute + | UnixFileMode.OtherRead | UnixFileMode.OtherExecute); + } + } +} diff --git a/src/Agent.Watchdog/UpgradeApplier.cs b/src/Agent.Watchdog/UpgradeApplier.cs new file mode 100644 index 0000000..39db203 --- /dev/null +++ b/src/Agent.Watchdog/UpgradeApplier.cs @@ -0,0 +1,848 @@ +using Shared.Contracts.Models; +using Shared.Contracts.Serialization; + +namespace Agent.Watchdog; + +/// What one pass of the watchdog did. +public enum PassResult +{ + /// No upgrade waiting: the agent is supervised this pass. + Idle, + + /// An upgrade was worked on (or is waiting for its next attempt). + Worked, + + /// The watchdog replaced its own binary and is restarting onto it: this process exits. + RestartRequested, +} + +/// +/// Applies an upgrade the agent handed over. The run, journalled before each +/// step so a watchdog stopped half way finishes or undoes it at its next start: +/// +/// take handover.json (it becomes handover.taken.json; the agent sees it picked up); +/// check the staging: in the data folder's staging folder, safe relative paths, the agent binary present, +/// every file there with the size and SHA-256 the hand-over names (otherwise failed: package / hash, nothing touched); +/// stopping: stop the agent, copy the files into <install>/.next/<id>/ and check them again; +/// a failure here moved nothing: the agent is started again and the run is tried again, three attempts in all, +/// then it ends failed / watchdog; +/// swapping: the current files the package replaces (its files, and everything in a top-level folder it ships) +/// move to .previous/<id>/, the new ones in; a move is retried only while the file is in use (10 × 500 ms); +/// verifying: start the agent and wait for a beacon of the new version, connected, written after the start, +/// within the hand-over's deadline; three exits of the agent end the wait early; +/// committed: the swap folders go, outcome succeeded, then the watchdog replaces its own binary if the package +/// brings a newer one; or rolling-back: the new files go to .failed/<id>/, the previous ones come back, +/// the previous agent starts, and the outcome says rolled-back with the new version's last log lines. +/// +/// The watchdog's own binary is never part of the swap. +/// +public sealed class UpgradeApplier( + WatchdogOptions options, + IAgentService agent, + IWatchdogClock clock, + WatchdogLog log, + ISmokeTest? smoke = null, + IWatchdogRestart? restart = null) +{ + public const int MaxAttempts = 3; + public const int MoveAttempts = 10; + public const int MaxExits = 3; + public const int LogLines = 40; + + public static readonly TimeSpan MoveRetryDelay = TimeSpan.FromMilliseconds(500); + + /// After a restart in verifying whose deadline has passed: how long the new version gets to be seen healthy. + public static readonly TimeSpan RecheckWindow = TimeSpan.FromMinutes(1); + + private readonly HashSet finished = []; + private DateTimeOffset notBefore = DateTimeOffset.MinValue; + + /// The running watchdog's version: a packaged watchdog replaces it only when newer. + public string OwnVersion { get; init; } = WatchdogVersion.Current; + + private string Install => options.InstallDirectory; + + /// An upgrade waits or is under way: the agent is not supervised meanwhile. + public bool Pending => File.Exists(options.HandoverPath) || File.Exists(options.JournalPath); + + /// The watchdog's own binary relative to the install folder, when it runs from there. + private string? SelfRelative => options.SelfPath is { } self && SwapPaths.IsInside(self, Install) + ? SwapPaths.Relative(Install, Path.GetFullPath(self)) + : null; + + private bool IsSelf(string relative) => SelfRelative is { } self && SwapPaths.Comparer.Equals(relative, self); + + private string RunPath(string folder, Guid upgradeId) => Path.Combine(Install, folder, upgradeId.ToString("N")); + + /// The candidate a new watchdog binary is tried as, beside the running one. + private string? Candidate + { + get + { + if (SelfRelative is not { } self) + { + return null; + } + + var current = SwapPaths.Combine(Install, self); + return Path.Combine(Path.GetDirectoryName(current)!, + Path.GetFileNameWithoutExtension(current) + ".next" + Path.GetExtension(current)); + } + } + + /// One pass: takes a hand-over, or carries a waiting run on. Idle when there is nothing to do. + public async Task PassAsync(CancellationToken cancellationToken) + { + TakeHandover(); + + var journal = ReadJournal(); + if (journal is null) + { + return PassResult.Idle; + } + + if (journal.Phase != WatchdogPhases.Stopping) + { + // Only a run cut short leaves a journal past "stopping" between passes. + return await RecoverAsync(cancellationToken); + } + + if (clock.UtcNow < notBefore) + { + return PassResult.Worked; + } + + var handover = WatchdogFileStore.Read(options.TakenHandoverPath, WatchdogJsonContext.Default.WatchdogHandover); + if (handover is null || handover.UpgradeId != journal.UpgradeId) + { + log.Error($"The upgrade to {journal.Version} lost its hand-over before any file moved; nothing was changed"); + await EnsureAgentRunningAsync(cancellationToken); + Finish(journal, AgentUpgradeStates.Failed, AgentUpgradeReasons.Watchdog, log.RunTail(LogLines)); + return PassResult.Worked; + } + + return await AttemptAsync(handover, journal, cancellationToken); + } + + /// + /// At start: a run the journal says was under way is finished or undone. + /// stopping → started over (the agent runs meanwhile); swapping or + /// rolling-back → the previous version is put back; verifying → the wait + /// goes on; committed / rolled-back → the tidy-up is finished. + /// + public async Task RecoverAsync(CancellationToken cancellationToken) + { + var journal = ReadJournal(); + if (journal is null) + { + return PassResult.Idle; + } + + log.BeginRun(); + var handover = WatchdogFileStore.Read(options.TakenHandoverPath, WatchdogJsonContext.Default.WatchdogHandover) is { } taken + && taken.UpgradeId == journal.UpgradeId + ? taken + : null; + + switch (journal.Phase) + { + case WatchdogPhases.Stopping: + await EnsureAgentRunningAsync(cancellationToken); + if (handover is null) + { + log.Error($"The upgrade to {journal.Version} was cut short before any file moved and its hand-over is gone; nothing was changed"); + Finish(journal, AgentUpgradeStates.Failed, AgentUpgradeReasons.Watchdog, log.RunTail(LogLines)); + } + else + { + log.Warn($"The upgrade to {journal.Version} was cut short before any file moved; it starts over (attempt {journal.Attempts + 1} of {MaxAttempts})"); + } + + return PassResult.Worked; + + case WatchdogPhases.Swapping or WatchdogPhases.RollingBack: + log.Warn($"The watchdog stopped part way through the {(journal.Phase == WatchdogPhases.Swapping ? "swap" : "rollback")} to {journal.Version}; {journal.FromVersion} is put back"); + await RollBackAsync(journal, AgentUpgradeReasons.Swap, journal.StartedUtc, cancellationToken); + return PassResult.Worked; + + case WatchdogPhases.Verifying: + { + var now = clock.UtcNow; + var deadline = journal.DeadlineUtc is { } at && at > now + RecheckWindow ? at : now + RecheckWindow; + log.Warn($"The watchdog restarted while waiting for {journal.Version} to report healthy; it goes on waiting until {deadline:O}"); + await EnsureAgentRunningAsync(cancellationToken); + var (healthy, exits) = await WaitHealthyAsync(journal.Version, journal.StartedUtc, deadline, 0, cancellationToken); + if (healthy) + { + return Commit(journal, handover); + } + + await RollBackAsync(journal, exits >= MaxExits ? AgentUpgradeReasons.Crashed : AgentUpgradeReasons.HealthDeadline, + journal.StartedUtc, cancellationToken); + return PassResult.Worked; + } + + case WatchdogPhases.Committed: + // Cut short after the new version was kept: the outcome is written + // unless it already was, and the tidy-up finished. + if (ReadOutcome()?.UpgradeId != journal.UpgradeId) + { + WriteOutcome(journal, AgentUpgradeStates.Succeeded, null, []); + } + + Cleanup(journal); + return PassResult.Worked; + + case WatchdogPhases.RolledBack: + if (ReadOutcome()?.UpgradeId != journal.UpgradeId) + { + WriteOutcome(journal, AgentUpgradeStates.RolledBack, AgentUpgradeReasons.Swap, []); + } + + Cleanup(journal); + await EnsureAgentRunningAsync(cancellationToken); + return PassResult.Worked; + + default: + log.Warn($"Unknown journal phase '{journal.Phase}'; the journal is dropped"); + WatchdogFileStore.TryDelete(options.JournalPath); + return PassResult.Worked; + } + } + + /// + /// Removes what runs cut short left in the install folder (.next, + /// .previous, .failed, a candidate watchdog binary) while no + /// upgrade is waiting or under way. + /// + public void Tidy() + { + if (Pending || File.Exists(options.TakenHandoverPath)) + { + return; + } + + foreach (var folder in new[] { WatchdogFiles.NextFolder, WatchdogFiles.PreviousFolder, WatchdogFiles.FailedFolder }) + { + SwapPaths.TryDeleteDirectory(Path.Combine(Install, folder)); + } + + if (Candidate is { } candidate && File.Exists(candidate)) + { + WatchdogFileStore.TryDelete(candidate); + } + } + + /// handover.json → handover.taken.json and a new journal; a duplicate or unreadable one is set aside. + private void TakeHandover() + { + if (!File.Exists(options.HandoverPath)) + { + return; + } + + var handover = WatchdogFileStore.Read(options.HandoverPath, WatchdogJsonContext.Default.WatchdogHandover); + if (handover is null) + { + var id = WatchdogFileStore.ReadUpgradeId(options.HandoverPath); + log.Error($"The upgrade hand-over does not read; it is set aside and nothing was changed (upgrade {id?.ToString() ?? "unknown"})"); + WatchdogFileStore.TryDelete(options.HandoverPath); + if (id is { } upgradeId) + { + WatchdogFileStore.Write(options.OutcomePath, + new WatchdogOutcome(upgradeId, AgentUpgradeStates.Failed, AgentUpgradeReasons.Watchdog, "", "", log.RunTail(LogLines), clock.UtcNow), + WatchdogJsonContext.Default.WatchdogOutcome); + } + + return; + } + + if (ReadJournal() is { } open) + { + // Never applied twice: a run with a journal is finished from the journal. + log.Warn(open.UpgradeId == handover.UpgradeId + ? $"Upgrade {handover.UpgradeId} is already under way ({open.Phase}); the repeated hand-over is not applied again" + : $"Upgrade {open.UpgradeId} is under way; hand-over {handover.UpgradeId} is set aside"); + WatchdogFileStore.TryDelete(options.HandoverPath); + return; + } + + if (finished.Contains(handover.UpgradeId) || ReadOutcome()?.UpgradeId == handover.UpgradeId) + { + log.Warn($"Upgrade {handover.UpgradeId} has already ended; the repeated hand-over is not applied again"); + WatchdogFileStore.TryDelete(options.HandoverPath); + return; + } + + log.BeginRun(); + log.Info($"Upgrade {handover.UpgradeId} handed over: {handover.FromVersion} -> {handover.Version}{(handover.Revert ? " (rollback)" : "")}, {handover.Files.Count} files"); + WatchdogFileStore.Write(options.TakenHandoverPath, handover, WatchdogJsonContext.Default.WatchdogHandover); + WatchdogFileStore.TryDelete(options.HandoverPath); + WriteJournal(new WatchdogJournal( + handover.UpgradeId, + handover.Version, + handover.FromVersion, + WatchdogPhases.Stopping, + new Dictionary(SwapPaths.Comparer), + handover.Files.Where(f => !IsSelf(f.Path)) + .ToDictionary(f => f.Path, f => f.Sha256.ToLowerInvariant(), SwapPaths.Comparer), + clock.UtcNow, + DeadlineUtc: null, + Attempts: 0)); + notBefore = DateTimeOffset.MinValue; + } + + private async Task AttemptAsync(WatchdogHandover handover, WatchdogJournal journal, CancellationToken cancellationToken) + { + if (Validate(handover) is { } problem) + { + log.Error($"The staged package does not check out; nothing was changed ({problem.Detail})"); + Finish(journal, AgentUpgradeStates.Failed, problem.Reason, log.RunTail(LogLines)); + return PassResult.Worked; + } + + var attempt = journal.Attempts + 1; + journal = journal with { Attempts = attempt, StartedUtc = clock.UtcNow }; + WriteJournal(journal); + log.Info($"Applying {handover.Version} (attempt {attempt} of {MaxAttempts}): stopping the agent"); + + var next = RunPath(WatchdogFiles.NextFolder, handover.UpgradeId); + try + { + await agent.StopAsync(cancellationToken); + Prepare(handover, next); + journal = journal with { Phase = WatchdogPhases.Swapping, Previous = CurrentFiles(journal.Incoming) }; + WriteJournal(journal); + } + catch (Exception exception) when (exception is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + // Nothing has moved: the agent runs again and the run is tried again. + SwapPaths.TryDeleteDirectory(next); + await EnsureAgentRunningAsync(cancellationToken); + if (attempt >= MaxAttempts) + { + log.Error($"The upgrade to {handover.Version} could not start after {attempt} attempts; nothing was changed", exception); + Finish(journal, AgentUpgradeStates.Failed, AgentUpgradeReasons.Watchdog, log.RunTail(LogLines)); + return PassResult.Worked; + } + + log.Warn($"The upgrade to {handover.Version} could not start (attempt {attempt}); nothing was moved, it is tried again", exception); + notBefore = clock.UtcNow + options.AttemptRetryDelay; + return PassResult.Worked; + } + + try + { + await SwapAsync(journal, cancellationToken); + } + catch (Exception exception) when (exception is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + log.Error($"The swap to {handover.Version} failed part way; {handover.FromVersion} is put back", exception); + await RollBackAsync(journal, AgentUpgradeReasons.Swap, journal.StartedUtc, cancellationToken); + return PassResult.Worked; + } + + var started = clock.UtcNow; + var deadline = started + (handover.HealthDeadlineSeconds > 0 + ? TimeSpan.FromSeconds(handover.HealthDeadlineSeconds) + : options.DefaultHealthDeadline); + journal = journal with { Phase = WatchdogPhases.Verifying, DeadlineUtc = deadline }; + WriteJournal(journal); + + var startFailures = 0; + try + { + await agent.StartAsync(cancellationToken); + log.Info($"Started {handover.Version}; waiting until {deadline:O} for it to report healthy"); + } + catch (Exception exception) when (exception is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + // A start the service manager refuses counts as an exit; the wait goes on. + log.Warn($"The new agent did not start", exception); + startFailures = 1; + } + + var (healthy, exits) = await WaitHealthyAsync(handover.Version, started, deadline, startFailures, cancellationToken); + if (healthy) + { + return Commit(journal, handover); + } + + await RollBackAsync(journal, exits >= MaxExits ? AgentUpgradeReasons.Crashed : AgentUpgradeReasons.HealthDeadline, started, cancellationToken); + return PassResult.Worked; + } + + /// The checks on the staging before anything is touched; null when it checks out. + private (string Reason, string Detail)? Validate(WatchdogHandover handover) + { + if (string.IsNullOrWhiteSpace(handover.StagingPath) + || !SwapPaths.IsInside(handover.StagingPath, options.StagingDirectory) + || !Directory.Exists(handover.StagingPath)) + { + return (AgentUpgradeReasons.Package, "the staged package is not in the data folder's staging folder"); + } + + if (handover.Files.Count == 0 || handover.Files.Any(f => !SwapPaths.IsSafe(f.Path))) + { + return (AgentUpgradeReasons.Package, "the hand-over lists no files, or a file with an unsafe path"); + } + + if (!handover.Files.Any(f => SwapPaths.Comparer.Equals(f.Path, options.AgentExecutable))) + { + return (AgentUpgradeReasons.Package, $"the package has no {options.AgentExecutable}"); + } + + if (handover.Files.Select(f => f.Path).Distinct(SwapPaths.Comparer).Count() != handover.Files.Count) + { + return (AgentUpgradeReasons.Package, "the hand-over lists a file twice"); + } + + foreach (var file in handover.Files) + { + var staged = SwapPaths.Combine(handover.StagingPath, file.Path); + if (!File.Exists(staged)) + { + return (AgentUpgradeReasons.Package, $"{file.Path} is not staged"); + } + + if (new FileInfo(staged).Length != file.Size + || !string.Equals(SwapPaths.Sha256(staged), file.Sha256, StringComparison.OrdinalIgnoreCase)) + { + return (AgentUpgradeReasons.Hash, $"{file.Path} does not match its size and SHA-256"); + } + } + + return null; + } + + /// Copies the staged files into .next/<id> and checks them there, where they are moved from. + private void Prepare(WatchdogHandover handover, string next) + { + SwapPaths.TryDeleteDirectory(next); + Directory.CreateDirectory(next); + foreach (var file in handover.Files) + { + var target = SwapPaths.Combine(next, file.Path); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + File.Copy(SwapPaths.Combine(handover.StagingPath, file.Path), target, overwrite: true); + if (new FileInfo(target).Length != file.Size + || !string.Equals(SwapPaths.Sha256(target), file.Sha256, StringComparison.OrdinalIgnoreCase)) + { + throw new InvalidDataException($"{file.Path} changed while it was copied into {WatchdogFiles.NextFolder}"); + } + + if (SwapPaths.Comparer.Equals(file.Path, options.AgentExecutable) || IsSelf(file.Path)) + { + SwapPaths.MakeExecutable(target); + } + } + } + + /// + /// The installed files the package replaces, with their SHA-256: every file + /// it brings that is installed, and every file in a top-level folder it ships + /// (so a module it no longer has goes too). The log folder, the swap's + /// folders and the running watchdog are never part of it; a file the package + /// knows nothing of (an operator's) stays where it is. + /// + private Dictionary CurrentFiles(IReadOnlyDictionary incoming) + { + var keys = new HashSet(incoming.Keys, SwapPaths.Comparer); + var folders = new HashSet(incoming.Keys.Where(k => k.Contains('/')).Select(SwapPaths.FirstSegment), SwapPaths.Comparer); + var candidate = Candidate is { } c ? SwapPaths.Relative(Install, c) : null; + var current = new Dictionary(SwapPaths.Comparer); + foreach (var path in Directory.EnumerateFiles(Install, "*", SearchOption.AllDirectories)) + { + var relative = SwapPaths.Relative(Install, path); + var first = SwapPaths.FirstSegment(relative); + if (SwapPaths.Reserved.Contains(first, SwapPaths.Comparer) || IsSelf(relative) || SwapPaths.Comparer.Equals(relative, candidate)) + { + continue; + } + + if (keys.Contains(relative) || (relative.Contains('/') && folders.Contains(first))) + { + current[relative] = SwapPaths.Sha256(path); + } + } + + return current; + } + + /// The current files into this run's .previous, then every new one out of its .next into place. + private async Task SwapAsync(WatchdogJournal journal, CancellationToken cancellationToken) + { + var previous = RunPath(WatchdogFiles.PreviousFolder, journal.UpgradeId); + var next = RunPath(WatchdogFiles.NextFolder, journal.UpgradeId); + Directory.CreateDirectory(previous); + foreach (var relative in journal.Previous.Keys) + { + await MoveAsync(SwapPaths.Combine(Install, relative), SwapPaths.Combine(previous, relative), relative, overwrite: false, cancellationToken); + } + + foreach (var relative in journal.Incoming.Keys) + { + await MoveAsync(SwapPaths.Combine(next, relative), SwapPaths.Combine(Install, relative), relative, overwrite: false, cancellationToken); + } + + log.Info($"Swapped {journal.Incoming.Count} files in ({journal.Previous.Count} set aside); the previous version is kept until the new one is healthy"); + } + + /// + /// The new files into this run's .failed, and what .previous + /// holds back into place; safe to repeat after a stop half way. A new file is + /// one that has left .next and is not the previous version. + /// + private async Task RollBackFilesAsync(WatchdogJournal journal, CancellationToken cancellationToken) + { + var previous = RunPath(WatchdogFiles.PreviousFolder, journal.UpgradeId); + var next = RunPath(WatchdogFiles.NextFolder, journal.UpgradeId); + var failed = RunPath(WatchdogFiles.FailedFolder, journal.UpgradeId); + var previousHashes = new Dictionary(journal.Previous, SwapPaths.Comparer); + + foreach (var relative in journal.Incoming.Keys) + { + if (File.Exists(SwapPaths.Combine(next, relative))) + { + continue; + } + + var path = SwapPaths.Combine(Install, relative); + if (File.Exists(path) && IsNewVersion(journal.Incoming[relative], previousHashes.GetValueOrDefault(relative), path)) + { + await MoveAsync(path, SwapPaths.Combine(failed, relative), relative, overwrite: true, cancellationToken); + } + } + + var kept = Directory.Exists(previous) + ? Directory.EnumerateFiles(previous, "*", SearchOption.AllDirectories).Select(f => SwapPaths.Relative(previous, f)).ToList() + : []; + foreach (var relative in kept) + { + var path = SwapPaths.Combine(Install, relative); + if (File.Exists(path)) + { + await MoveAsync(path, SwapPaths.Combine(failed, relative), relative, overwrite: true, cancellationToken); + } + + await MoveAsync(SwapPaths.Combine(previous, relative), path, relative, overwrite: false, cancellationToken); + } + + log.Info($"The previous version is back in place ({kept.Count} files)"); + } + + private static bool IsNewVersion(string incoming, string? previous, string path) + { + if (previous is null) + { + return true; + } + + // A file both versions share is right either way and stays. + return !string.Equals(incoming, previous, StringComparison.OrdinalIgnoreCase) + && !string.Equals(SwapPaths.Sha256(path), previous, StringComparison.OrdinalIgnoreCase); + } + + /// One move of the swap, retried only while another process has the file open. + private async Task MoveAsync(string from, string to, string relative, bool overwrite, CancellationToken cancellationToken) + { + for (var attempt = 1; ; attempt++) + { + try + { + Directory.CreateDirectory(Path.GetDirectoryName(to)!); + File.Move(from, to, overwrite); + return; + } + catch (IOException exception) when (SwapPaths.IsInUse(exception) && attempt < MoveAttempts) + { + log.Info($"{relative} is in use; it is tried again shortly (attempt {attempt})"); + await clock.DelayAsync(MoveRetryDelay, cancellationToken); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + throw new IOException($"{relative} could not be moved: {exception.Message}", exception); + } + } + } + + /// + /// Healthy: a beacon of , connected, written after + /// , before . Each time the + /// agent is found not running counts as an exit (and it is started again); + /// the third ends the wait. + /// + private async Task<(bool Healthy, int Exits)> WaitHealthyAsync( + string version, DateTimeOffset since, DateTimeOffset deadline, int exits, CancellationToken cancellationToken) + { + var reported = clock.UtcNow; + while (clock.UtcNow < deadline && exits < MaxExits) + { + var beacon = WatchdogFileStore.Read(options.HealthPath, WatchdogJsonContext.Default.WatchdogHealthBeacon); + if (beacon is { Connected: true } + && string.Equals(beacon.Version, version, StringComparison.OrdinalIgnoreCase) + && beacon.AtUtc > since) + { + return (true, exits); + } + + if (clock.UtcNow - reported >= TimeSpan.FromMinutes(1)) + { + reported = clock.UtcNow; + log.Info($"Waiting for {version} to report healthy; beacon: {Describe(beacon)}"); + } + + if (!(await agent.QueryAsync(cancellationToken)).IsRunning) + { + exits++; + if (exits >= MaxExits) + { + log.Warn($"{version} exited {exits} times; the wait ends"); + break; + } + + log.Warn($"{version} is not running (exit {exits}); starting it again"); + try + { + await agent.StartAsync(cancellationToken); + } + catch (Exception exception) when (exception is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + log.Warn("The agent did not start", exception); + exits++; + } + } + + await clock.DelayAsync(options.PollInterval, cancellationToken); + } + + return (false, exits); + } + + private static string Describe(WatchdogHealthBeacon? beacon) => beacon is null + ? "none" + : $"version {beacon.Version}, pid {beacon.ProcessId}, connected={beacon.Connected}, at {beacon.AtUtc:O}"; + + private PassResult Commit(WatchdogJournal journal, WatchdogHandover? handover) + { + journal = journal with { Phase = WatchdogPhases.Committed }; + WriteJournal(journal); + log.Info($"{journal.Version} is healthy; the upgrade is kept"); + + // Last of all, and never part of the swap: the watchdog's own binary. + var replacedSelf = handover is not null ? ReplaceSelf(handover) : null; + Finish(journal, AgentUpgradeStates.Succeeded, null, []); + + if (replacedSelf is not null && restart is not null && restart.Restart(replacedSelf)) + { + log.Info("The watchdog restarts onto its new binary"); + return PassResult.RestartRequested; + } + + return PassResult.Worked; + } + + private async Task RollBackAsync(WatchdogJournal journal, string reason, DateTimeOffset since, CancellationToken cancellationToken) + { + journal = journal with { Phase = WatchdogPhases.RollingBack }; + WriteJournal(journal); + log.Warn($"Rolling back {journal.Version} ({reason}); {journal.FromVersion} is put back. Beacon: " + + Describe(WatchdogFileStore.Read(options.HealthPath, WatchdogJsonContext.Default.WatchdogHealthBeacon))); + + // A version that did not come up healthy is told by its own last log + // lines (taken before it is stopped); a swap that broke, by the watchdog's. + var lastLog = reason is AgentUpgradeReasons.HealthDeadline or AgentUpgradeReasons.Crashed ? TailAgentLog(since) : []; + try + { + await agent.StopAsync(cancellationToken); + } + catch (Exception exception) when (exception is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + log.Warn("The new agent could not be stopped", exception); + } + + var result = AgentUpgradeStates.RolledBack; + try + { + await RollBackFilesAsync(journal, cancellationToken); + } + catch (Exception exception) when (exception is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + log.Error($"The previous version could not be put back whole", exception); + result = AgentUpgradeStates.Failed; + reason = AgentUpgradeReasons.Swap; + } + + // An earlier version may write no beacon; the new one's must not outlive it. + WatchdogFileStore.TryDelete(options.HealthPath); + var restarted = clock.UtcNow; + await EnsureAgentRunningAsync(cancellationToken); + var (back, _) = await WaitHealthyAsync(journal.FromVersion, restarted, restarted + options.RollbackHealthDeadline, 0, cancellationToken); + log.Info(back + ? $"{journal.FromVersion} is back and healthy" + : $"{journal.FromVersion} is back; it has not reported healthy within {options.RollbackHealthDeadline.TotalMinutes:0} minutes"); + + WriteOutcome(journal, result, reason, lastLog.Count > 0 ? lastLog : log.RunTail(LogLines)); + WriteJournal(journal with { Phase = WatchdogPhases.RolledBack }); + Cleanup(journal); + } + + /// + /// The candidate binary, checked, tried once (version) and swapped in + /// by renaming the running one aside; only when the package's watchdog is + /// newer than this one. The path to restart onto, or null. + /// + private string? ReplaceSelf(WatchdogHandover handover) + { + if (SelfRelative is not { } self || Candidate is not { } candidate + || handover.Files.FirstOrDefault(f => SwapPaths.Comparer.Equals(f.Path, self)) is not { } file) + { + return null; + } + + var current = SwapPaths.Combine(Install, self); + var incoming = SwapPaths.Combine(RunPath(WatchdogFiles.NextFolder, handover.UpgradeId), self); + try + { + if (!File.Exists(incoming) || string.Equals(SwapPaths.Sha256(current), file.Sha256, StringComparison.OrdinalIgnoreCase)) + { + return null; + } + + File.Copy(incoming, candidate, overwrite: true); + SwapPaths.MakeExecutable(candidate); + if (!string.Equals(SwapPaths.Sha256(candidate), file.Sha256, StringComparison.OrdinalIgnoreCase)) + { + log.Warn("The new watchdog binary changed while it was copied; this one keeps running"); + WatchdogFileStore.TryDelete(candidate); + return null; + } + + var version = (smoke ?? new ProcessSmokeTest()).Run(candidate); + if (version is null) + { + log.Warn("The new watchdog binary did not run; this one keeps running"); + WatchdogFileStore.TryDelete(candidate); + return null; + } + + if (!AgentVersions.IsNewer(version, OwnVersion)) + { + log.Info($"The package's watchdog ({version}) is not newer than this one ({OwnVersion}); it is kept"); + WatchdogFileStore.TryDelete(candidate); + return null; + } + + var aside = SwapPaths.Combine(RunPath(WatchdogFiles.PreviousFolder, handover.UpgradeId), self); + Directory.CreateDirectory(Path.GetDirectoryName(aside)!); + File.Move(current, aside, overwrite: true); + File.Move(candidate, current); + log.Info($"The watchdog replaced itself: {OwnVersion} -> {version}"); + return current; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + log.Warn("The watchdog could not replace itself; it keeps its version", exception); + WatchdogFileStore.TryDelete(candidate); + return null; + } + } + + private async Task EnsureAgentRunningAsync(CancellationToken cancellationToken) + { + try + { + if (!(await agent.QueryAsync(cancellationToken)).IsRunning) + { + await agent.StartAsync(cancellationToken); + } + } + catch (Exception exception) when (exception is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + log.Warn("The agent could not be started", exception); + } + } + + /// Writes the outcome, then the run's files and folders go. + private void Finish(WatchdogJournal journal, string result, string? reason, IReadOnlyList lastLog) + { + WriteOutcome(journal, result, reason, lastLog); + Cleanup(journal); + } + + private void WriteOutcome(WatchdogJournal journal, string result, string? reason, IReadOnlyList lastLog) + { + WatchdogFileStore.Write(options.OutcomePath, + new WatchdogOutcome(journal.UpgradeId, result, reason, journal.Version, journal.FromVersion, + [.. lastLog.Skip(Math.Max(0, lastLog.Count - LogLines))], clock.UtcNow), + WatchdogJsonContext.Default.WatchdogOutcome); + log.Info($"Upgrade {journal.UpgradeId} to {journal.Version} ended: {result}{(reason is null ? "" : $" ({reason})")}"); + } + + private void Cleanup(WatchdogJournal journal) + { + finished.Add(journal.UpgradeId); + notBefore = DateTimeOffset.MinValue; + foreach (var folder in new[] { WatchdogFiles.NextFolder, WatchdogFiles.PreviousFolder, WatchdogFiles.FailedFolder }) + { + SwapPaths.TryDeleteDirectory(RunPath(folder, journal.UpgradeId)); + SwapPaths.TryDeleteIfEmpty(Path.Combine(Install, folder)); + } + + WatchdogFileStore.TryDelete(options.TakenHandoverPath); + WatchdogFileStore.TryDelete(options.JournalPath); + } + + /// The agent's last log lines, from its newest log file written since . + private List TailAgentLog(DateTimeOffset since) + { + try + { + var prefix = Path.GetFileNameWithoutExtension(options.AgentExecutable); + var file = Directory.Exists(options.LogDirectory) + ? new DirectoryInfo(options.LogDirectory).GetFiles("*.log") + .Where(f => f.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) + && f.LastWriteTimeUtc >= since.UtcDateTime.AddSeconds(-5)) + .OrderByDescending(f => f.LastWriteTimeUtc) + .FirstOrDefault() + : null; + if (file is null) + { + return []; + } + + using var stream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + using var reader = new StreamReader(stream); + var lines = new Queue(); + while (reader.ReadLine() is { } line) + { + lines.Enqueue(line.Length <= 2000 ? line : line[..2000]); + if (lines.Count > LogLines) + { + lines.Dequeue(); + } + } + + return [.. lines]; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return []; + } + } + + private WatchdogJournal? ReadJournal() + => WatchdogFileStore.Read(options.JournalPath, WatchdogJsonContext.Default.WatchdogJournal) is { } journal + ? journal with + { + Previous = new Dictionary(journal.Previous ?? new Dictionary(), SwapPaths.Comparer), + Incoming = new Dictionary(journal.Incoming ?? new Dictionary(), SwapPaths.Comparer), + } + : null; + + private void WriteJournal(WatchdogJournal journal) + => WatchdogFileStore.Write(options.JournalPath, journal, WatchdogJsonContext.Default.WatchdogJournal); + + private WatchdogOutcome? ReadOutcome() + => WatchdogFileStore.Read(options.OutcomePath, WatchdogJsonContext.Default.WatchdogOutcome); +} diff --git a/src/Agent.Watchdog/WatchdogCli.cs b/src/Agent.Watchdog/WatchdogCli.cs new file mode 100644 index 0000000..79b0da0 --- /dev/null +++ b/src/Agent.Watchdog/WatchdogCli.cs @@ -0,0 +1,192 @@ +using System.Globalization; +using System.Runtime.InteropServices; +using System.ServiceProcess; +using Agent.Watchdog.Platform; +using Shared.Infrastructure.Constants; + +namespace Agent.Watchdog; + +/// +/// The watchdog's verbs. run is what the service manager starts; +/// foreground runs the same loop with console logging. install, +/// remove, start, stop and status manage its own +/// service (the agent's install verbs call them). +/// +public static class WatchdogCli +{ + /// Hidden: run by a watchdog that replaced itself (Windows), see . + public const string RestartVerb = "restart-after-exit"; + + public static async Task RunAsync(string[] args) + { + var command = args.Length > 0 ? args[0].Trim().ToLowerInvariant() : null; + try + { + switch (command) + { + case "run": + return await RunLoopAsync(args[1..], asService: true); + + case "foreground": + return await RunLoopAsync(args[1..], asService: false); + + case "version": + Console.WriteLine(WatchdogVersion.Current); + return 0; + + case "install": + return OperatingSystem.IsWindows() ? WindowsWatchdogRegistration.Install(SelfPath) : UnixWatchdogRegistration.Install(SelfPath); + + case "remove": + return OperatingSystem.IsWindows() ? WindowsWatchdogRegistration.Remove() : UnixWatchdogRegistration.Remove(); + + case "start": + return OperatingSystem.IsWindows() ? WindowsWatchdogRegistration.Start() : UnixWatchdogRegistration.Start(); + + case "stop": + return OperatingSystem.IsWindows() ? WindowsWatchdogRegistration.Stop() : UnixWatchdogRegistration.Stop(); + + case "status": + return OperatingSystem.IsWindows() ? WindowsWatchdogRegistration.Status() : UnixWatchdogRegistration.Status(); + + case RestartVerb when OperatingSystem.IsWindows() && args.Length > 1 + && int.TryParse(args[1], NumberStyles.None, CultureInfo.InvariantCulture, out var processId): + return WindowsWatchdogRegistration.RestartAfterExit(processId); + + case null or "help" or "-h" or "--help" or "/?": + PrintUsage(); + return command is null ? 1 : 0; + + default: + Console.Error.WriteLine($"Unknown command '{command}'."); + PrintUsage(); + return 1; + } + } + catch (Exception exception) + { + Console.Error.WriteLine($"error: {exception.Message}"); + return 2; + } + } + + private static string SelfPath => Environment.ProcessPath ?? throw new InvalidOperationException("Cannot determine the executable path."); + + /// + /// --install-dir <path> (default: the watchdog's own folder), + /// --data-dir <path> (default: the agent's data folder), + /// --agent service|process (default: service). + /// + internal static (WatchdogOptions Options, bool ProcessMode) ParseOptions(string[] args) + { + string? Value(string name) + { + for (var i = 0; i < args.Length - 1; i++) + { + if (string.Equals(args[i], name, StringComparison.OrdinalIgnoreCase)) + { + return args[i + 1]; + } + } + + return null; + } + + var options = new WatchdogOptions + { + InstallDirectory = Path.GetFullPath(Value("--install-dir") ?? AppContext.BaseDirectory), + DataDirectory = Path.GetFullPath(Value("--data-dir") ?? Branding.AgentProgramDataDirectory), + }; + return (options, string.Equals(Value("--agent"), "process", StringComparison.OrdinalIgnoreCase)); + } + + private static async Task RunLoopAsync(string[] args, bool asService) + { + var (options, processMode) = ParseOptions(args); + var log = new WatchdogLog(options.LogDirectory, console: !asService); + + IAgentService agent; + if (processMode) + { + agent = new ProcessAgentService(options, log); + } + else if (OperatingSystem.IsWindows()) + { + agent = new WindowsAgentService(Branding.AgentServiceName, Path.Combine(options.InstallDirectory, options.AgentExecutable), log); + } + else if (OperatingSystem.IsMacOS()) + { + agent = new LaunchdAgentService(Branding.AgentLaunchdLabel); + } + else + { + agent = new SystemdAgentService(Branding.AgentSystemdUnit); + } + + // In the foreground the replaced binary simply takes over at the next start. + IWatchdogRestart? restart = !asService ? null + : OperatingSystem.IsWindows() ? new WindowsWatchdogRestart(log) + : new UnixWatchdogRestart(log); + + var clock = SystemClock.Instance; + var applier = new UpgradeApplier(options, agent, clock, log, new ProcessSmokeTest(), restart); + var supervisor = new AgentSupervisor(options, agent, clock, log); + var service = new WatchdogService(options, applier, supervisor, clock, log); + + if (processMode) + { + await agent.StartAsync(CancellationToken.None); + } + + try + { + if (asService && OperatingSystem.IsWindows()) + { + using var host = new WindowsWatchdogHost(service.RunAsync); + ServiceBase.Run(host); + return 0; + } + + using var stopping = new CancellationTokenSource(); + Console.CancelKeyPress += (_, e) => + { + e.Cancel = true; + stopping.Cancel(); + }; + using var sigterm = PosixSignalRegistration.Create(PosixSignal.SIGTERM, context => + { + context.Cancel = true; + stopping.Cancel(); + }); + + await service.RunAsync(stopping.Token); + return 0; + } + finally + { + (agent as IDisposable)?.Dispose(); + } + } + + private static void PrintUsage() + { + Console.WriteLine($"{Branding.WatchdogServiceDisplayName} {WatchdogVersion.Current}"); + Console.WriteLine(); + Console.WriteLine($"Usage: {Branding.WatchdogBinaryName} "); + Console.WriteLine(); + Console.WriteLine("Commands:"); + Console.WriteLine(" run Run as the service (started by the service manager)"); + Console.WriteLine(" foreground Run interactively with console logging"); + Console.WriteLine(" install Create/update the watchdog service registration"); + Console.WriteLine(" remove Stop and remove the watchdog service"); + Console.WriteLine(" start Start the watchdog service"); + Console.WriteLine(" stop Stop the watchdog service"); + Console.WriteLine(" status Show the watchdog service state"); + Console.WriteLine(" version Print the build version"); + Console.WriteLine(); + Console.WriteLine("Options (run/foreground):"); + Console.WriteLine(" --install-dir The agent's install folder (default: this binary's folder)"); + Console.WriteLine(" --data-dir The agent's data folder (default: the installed one)"); + Console.WriteLine(" --agent process Development: run the agent as a child process, not a service"); + } +} diff --git a/src/Agent.Watchdog/WatchdogLog.cs b/src/Agent.Watchdog/WatchdogLog.cs new file mode 100644 index 0000000..b90f9df --- /dev/null +++ b/src/Agent.Watchdog/WatchdogLog.cs @@ -0,0 +1,120 @@ +using System.Globalization; + +namespace Agent.Watchdog; + +/// +/// The watchdog's own log: one small rolling file in the agent's log folder +/// (ExecuteR-Watchdog.log, rolled at 1 MB, three files kept), the +/// console in the foreground, and the lines of the current upgrade run kept in +/// memory so a failure's outcome can carry them. +/// +public sealed class WatchdogLog +{ + public const long RollBytes = 1024 * 1024; + public const int KeptFiles = 3; + + private readonly Lock gate = new(); + private readonly string? path; + private readonly bool console; + private readonly List run = []; + private bool fileBroken; + + public WatchdogLog(string? directory, bool console, string? name = null) + { + this.console = console; + if (!string.IsNullOrWhiteSpace(directory)) + { + name ??= Path.GetFileNameWithoutExtension(Environment.ProcessPath) is { Length: > 0 } exe + && !exe.Equals("dotnet", StringComparison.OrdinalIgnoreCase) + ? exe + : "ExecuteR-Watchdog"; + path = Path.Combine(directory, name + ".log"); + } + } + + /// Every line written, for tests and the foreground. + public event Action? Written; + + public void Info(string message) => Write("INF", message); + + public void Warn(string message, Exception? exception = null) => Write("WRN", With(message, exception)); + + public void Error(string message, Exception? exception = null) => Write("ERR", With(message, exception)); + + /// Starts collecting the lines of an upgrade run. + public void BeginRun() + { + lock (gate) + { + run.Clear(); + } + } + + /// The last lines of the current run. + public IReadOnlyList RunTail(int count) + { + lock (gate) + { + return [.. run.Skip(Math.Max(0, run.Count - count))]; + } + } + + private static string With(string message, Exception? exception) + => exception is null ? message : $"{message}: {exception.GetBaseException().Message}"; + + private void Write(string level, string message) + { + var line = $"{DateTimeOffset.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture)} [{level}] {message}"; + lock (gate) + { + run.Add(line); + if (run.Count > 400) + { + run.RemoveRange(0, run.Count - 400); + } + + if (console) + { + Console.WriteLine(line); + } + + if (path is not null && !fileBroken) + { + try + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + Roll(); + File.AppendAllText(path, line + Environment.NewLine); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // A log that cannot be written must never stop the watchdog. + fileBroken = true; + Console.Error.WriteLine($"warning: watchdog file logging disabled ({exception.Message})"); + } + } + } + + Written?.Invoke(line); + } + + private void Roll() + { + var current = new FileInfo(path!); + if (!current.Exists || current.Length < RollBytes) + { + return; + } + + var stem = Path.Combine(current.DirectoryName!, Path.GetFileNameWithoutExtension(current.Name)); + for (var i = KeptFiles - 1; i >= 1; i--) + { + var from = i == 1 ? path! : $"{stem}.{i - 1}.log"; + var to = $"{stem}.{i}.log"; + if (File.Exists(from)) + { + File.Move(from, to, overwrite: true); + } + } + } +} diff --git a/src/Agent.Watchdog/WatchdogOptions.cs b/src/Agent.Watchdog/WatchdogOptions.cs new file mode 100644 index 0000000..e1a0057 --- /dev/null +++ b/src/Agent.Watchdog/WatchdogOptions.cs @@ -0,0 +1,55 @@ +using Shared.Contracts.Models; +using Shared.Infrastructure.Constants; + +namespace Agent.Watchdog; + +/// What the watchdog watches and where; defaults are the installed layout. +public sealed record WatchdogOptions +{ + /// The agent's install folder: the watchdog's own folder unless --install-dir says otherwise. + public required string InstallDirectory { get; init; } + + /// The data folder the agent and the watchdog share (%ProgramData%\ExecuteR, /var/lib/executer). + public required string DataDirectory { get; init; } + + /// The agent binary's name inside the install folder. + public string AgentExecutable { get; init; } = Branding.AgentBinaryName; + + /// The running watchdog's own binary: excluded from the agent swap and replaced last. + public string? SelfPath { get; init; } = Environment.ProcessPath; + + public TimeSpan PollInterval { get; init; } = TimeSpan.FromSeconds(2); + + /// A beacon this old while the agent should run gets it restarted (at most once per period). + public TimeSpan StaleAfter { get; init; } = WatchdogFiles.BeaconStaleAfter; + + /// Used when a hand-over names no health deadline. + public TimeSpan DefaultHealthDeadline { get; init; } = TimeSpan.FromMinutes(10); + + public TimeSpan RollbackHealthDeadline { get; init; } = WatchdogFiles.RollbackHealthDeadline; + + /// How long a failed attempt (nothing moved yet) waits before the next one. + public TimeSpan AttemptRetryDelay { get; init; } = TimeSpan.FromSeconds(10); + + /// Where the watchdog writes its own rolling log: the agent's log folder. + public string LogDirectory => Path.Combine(InstallDirectory, "Logs"); + + public string UpgradeDirectory => Path.Combine(DataDirectory, WatchdogFiles.Folder); + + public string StagingDirectory => Path.Combine(UpgradeDirectory, WatchdogFiles.Staging); + + public string HandoverPath => Path.Combine(UpgradeDirectory, WatchdogFiles.Handover); + + /// + /// The hand-over once taken: handover.json is moved here as the run starts, + /// so the agent sees it picked up while a retry or a restarted watchdog can + /// still start over from it. Private to the watchdog; goes with the journal. + /// + public string TakenHandoverPath => Path.Combine(UpgradeDirectory, "handover.taken.json"); + + public string HealthPath => Path.Combine(UpgradeDirectory, WatchdogFiles.Health); + + public string JournalPath => Path.Combine(UpgradeDirectory, WatchdogFiles.Journal); + + public string OutcomePath => Path.Combine(UpgradeDirectory, WatchdogFiles.Outcome); +} diff --git a/src/Agent.Watchdog/WatchdogService.cs b/src/Agent.Watchdog/WatchdogService.cs new file mode 100644 index 0000000..051d5ad --- /dev/null +++ b/src/Agent.Watchdog/WatchdogService.cs @@ -0,0 +1,63 @@ +namespace Agent.Watchdog; + +/// +/// The watchdog's loop: at start it finishes or undoes a swap a previous run +/// left half done and tidies the install folder; then, every poll, it carries an +/// upgrade on when one is waiting and otherwise supervises the agent. +/// +public sealed class WatchdogService(WatchdogOptions options, UpgradeApplier applier, AgentSupervisor supervisor, IWatchdogClock clock, WatchdogLog log) +{ + /// Runs until cancelled, or until the watchdog replaced itself (true: exit so the new binary takes over). + public async Task RunAsync(CancellationToken cancellationToken) + { + log.Info($"Watchdog {WatchdogVersion.Current} watching {Path.Combine(options.InstallDirectory, options.AgentExecutable)} (data {options.DataDirectory})"); + try + { + if (await applier.RecoverAsync(cancellationToken) == PassResult.RestartRequested) + { + return true; + } + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + log.Error("Recovering an interrupted upgrade failed", exception); + } + + applier.Tidy(); + + while (!cancellationToken.IsCancellationRequested) + { + try + { + switch (await applier.PassAsync(cancellationToken)) + { + case PassResult.RestartRequested: + return true; + case PassResult.Idle: + await supervisor.CheckAsync(cancellationToken); + break; + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + break; + } + catch (Exception exception) + { + log.Warn("A watchdog pass failed; the next one tries again", exception); + } + + try + { + await clock.DelayAsync(options.PollInterval, cancellationToken); + } + catch (OperationCanceledException) + { + break; + } + } + + log.Info("Watchdog stopping"); + return false; + } +} diff --git a/src/Agent.Watchdog/WatchdogVersion.cs b/src/Agent.Watchdog/WatchdogVersion.cs new file mode 100644 index 0000000..fb089f1 --- /dev/null +++ b/src/Agent.Watchdog/WatchdogVersion.cs @@ -0,0 +1,27 @@ +using System.Reflection; + +namespace Agent.Watchdog; + +/// +/// The watchdog's unified version (yyyy.MM.dd.HHmm), read the way the +/// agent's BuildVersion reads its own: the informational version without the +/// short-commit suffix or build metadata. +/// +public static class WatchdogVersion +{ + public static string Current { get; } = Resolve(typeof(WatchdogVersion).Assembly); + + public static string Resolve(Assembly assembly) + { + var informational = assembly.GetCustomAttribute()?.InformationalVersion; + if (string.IsNullOrWhiteSpace(informational)) + { + return "0.0.0.0"; + } + + var plus = informational.IndexOf('+'); + var trimmed = plus >= 0 ? informational[..plus] : informational; + var dash = trimmed.IndexOf('-'); + return dash >= 0 ? trimmed[..dash] : trimmed; + } +} diff --git a/src/Agent/Commands/AgentCli.cs b/src/Agent/Commands/AgentCli.cs index 528a7c4..25ee5d1 100644 --- a/src/Agent/Commands/AgentCli.cs +++ b/src/Agent/Commands/AgentCli.cs @@ -46,11 +46,21 @@ public static class AgentCli Console.WriteLine(BuildVersion.Resolve(typeof(AgentCli).Assembly)); return 0; + // install/initialize also register (and start) the watchdog when + // its binary sits next to the agent; remove takes it out first, + // so it cannot start the agent again meanwhile. case "install": - return Lifecycle.Install(); + { + var installResult = Lifecycle.Install(); + return installResult != 0 ? installResult : Watchdog("install"); + } case "remove": - return Lifecycle.Remove(); + { + var watchdogResult = Watchdog("remove"); + var removeResult = Lifecycle.Remove(); + return removeResult != 0 ? removeResult : watchdogResult; + } case "start": return Lifecycle.Start(); @@ -59,8 +69,21 @@ public static class AgentCli return Lifecycle.Stop(); case "initialize": + { var installResult = Lifecycle.Install(); - return installResult != 0 ? installResult : Lifecycle.Start(); + if (installResult == 0) + { + installResult = Watchdog("install"); + } + + if (installResult != 0) + { + return installResult; + } + + var startResult = Lifecycle.Start(); + return startResult != 0 ? startResult : Watchdog("start"); + } case "status": return Lifecycle.Status(); @@ -77,6 +100,11 @@ public static class AgentCli CancellationToken.None); return 0; + // Hidden: the remote shell's built-in PowerShell console, started + // by the agent under a PTY. Touches no agent config or state. + case Agent.Shell.WindowsShellResolver.HostVerb: + return Agent.Shell.BuiltInShellHost.Run(args[1..]); + // Hidden: invoked by the MSI during explicit full uninstall // (never during upgrade) to remove credentials and runtime state. case "purge-credentials": @@ -113,6 +141,32 @@ public static class AgentCli #endif } + /// + /// Runs one of the watchdog's own service verbs when its binary sits next to + /// the agent (a build without it, or a development run, has none: nothing to do). + /// + private static int Watchdog(string verb) + { + var binary = Path.Combine(AppContext.BaseDirectory, Branding.WatchdogBinaryName); + if (!File.Exists(binary)) + { + return 0; + } + + var (exitCode, output) = Agent.Upgrade.WatchdogInstaller.RunVerb(binary, verb); + if (!string.IsNullOrWhiteSpace(output)) + { + Console.WriteLine(output.TrimEnd()); + } + + if (exitCode != 0) + { + Console.Error.WriteLine($"{Branding.WatchdogBinaryName} {verb} exited with {exitCode}"); + } + + return exitCode; + } + private static int Configure(string[] args) { string? url = null; @@ -195,11 +249,11 @@ public static class AgentCli Console.WriteLine(); Console.WriteLine("Commands:"); Console.WriteLine(" foreground Run interactively with console logging"); - Console.WriteLine(" install Create/update the Windows service registration"); - Console.WriteLine(" remove Stop and remove the Windows service"); + Console.WriteLine(" install Create/update the agent and watchdog service registrations"); + Console.WriteLine(" remove Stop and remove the watchdog and agent services"); Console.WriteLine(" start Start the installed service"); - Console.WriteLine(" stop Stop the service"); - Console.WriteLine(" initialize install + start"); + Console.WriteLine(" stop Stop the service (the watchdog never undoes a stop)"); + Console.WriteLine(" initialize install + start (agent and watchdog)"); Console.WriteLine(" status Show service and enrollment state"); Console.WriteLine(" version Print the build version"); } diff --git a/src/Agent/Commands/CommandProcessor.cs b/src/Agent/Commands/CommandProcessor.cs index 5b76bd8..3a1a117 100644 --- a/src/Agent/Commands/CommandProcessor.cs +++ b/src/Agent/Commands/CommandProcessor.cs @@ -4,6 +4,7 @@ using Agent.Inventory; using Agent.Messaging; using Agent.PowerShell; using Agent.Storage; +using Agent.Upgrade; using Microsoft.Extensions.Logging; using NATS.Client.Core; using NATS.Client.JetStream; @@ -26,6 +27,8 @@ public sealed class CommandProcessor( FileDownloadHandler fileHandler, JobHistoryStore jobHistory, AgentConfiguration configuration, + AgentUpgradeHandler upgrades, + AgentHealthState health, ILogger logger) { public async Task RunAsync(CancellationToken cancellationToken) @@ -52,17 +55,25 @@ public sealed class CommandProcessor( publisher.ClientId, AgentEventKinds.Ready, "command consumer bound", DateTimeOffset.UtcNow), cancellationToken: cancellationToken); + // Healthy for the watchdog from here: an upgrade is kept only once + // the new version gets this far. + health.CommandsBound = true; + await foreach (var message in consumer.ConsumeAsync(cancellationToken: cancellationToken)) { await HandleMessageAsync(message, cancellationToken); } + + health.CommandsBound = false; } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { + health.CommandsBound = false; break; } catch (Exception ex) { + health.CommandsBound = false; logger.LogWarning(ex, "Command consumer unavailable ({Message}); retrying in 15s", ex.Message); try @@ -110,6 +121,10 @@ public sealed class CommandProcessor( await HandleFileCommandAsync(envelope, message, cancellationToken); break; + case MessageTypes.CommandAgentUpgrade: + await HandleUpgradeCommandAsync(envelope, message, cancellationToken); + break; + default: logger.LogWarning("Unknown command type {MessageType}; terminating delivery", envelope.MessageType); await message.AckTerminateAsync(cancellationToken: cancellationToken); @@ -161,6 +176,39 @@ public sealed class CommandProcessor( cancellationToken); } + private async Task HandleUpgradeCommandAsync( + MessageEnvelope envelope, INatsJSMsg message, CancellationToken cancellationToken) + { + var command = envelope.GetPayload(); + if (command is null || command.UpgradeId == Guid.Empty || string.IsNullOrWhiteSpace(command.Version)) + { + await message.AckTerminateAsync(cancellationToken: cancellationToken); + return; + } + + // Idempotent per upgrade: recorded durably before the ack, so a + // redelivery (also to the version that runs after the swap) is skipped. + if (!jobHistory.TryRecordAccepted(command.UpgradeId)) + { + logger.LogInformation("Duplicate delivery of upgrade {UpgradeId}; acknowledged without running it again", command.UpgradeId); + await message.AckAsync(cancellationToken: cancellationToken); + return; + } + + await message.AckAsync(cancellationToken: cancellationToken); + _ = Task.Run(async () => + { + try + { + await upgrades.RunAsync(command, cancellationToken); + } + finally + { + jobHistory.MarkCompleted(command.UpgradeId, "AgentUpgrade"); + } + }, cancellationToken); + } + private async Task HandleFileCommandAsync( MessageEnvelope envelope, INatsJSMsg message, CancellationToken cancellationToken) { diff --git a/src/Agent/Enrollment/CredentialStore.cs b/src/Agent/Enrollment/CredentialStore.cs index 3dcdd61..4384cef 100644 --- a/src/Agent/Enrollment/CredentialStore.cs +++ b/src/Agent/Enrollment/CredentialStore.cs @@ -21,6 +21,16 @@ public sealed record AgentCredentials( public const int CurrentVersion = 1; } +/// Where the agent keeps its enrolled credentials (a seam for tests). +public interface ICredentialStore +{ + AgentCredentials? Load(); + + void Save(AgentCredentials credentials); + + void Delete(); +} + /// /// Credential persistence in the agent data directory. Windows: a /// DPAPI(LocalMachine)-encrypted blob, file + directory ACL'd to SYSTEM and @@ -28,7 +38,7 @@ public sealed record AgentCredentials( /// a mode-700 directory (the platform's standard secret-at-rest posture). /// Content is a versioned JSON payload either way. /// -public sealed class CredentialStore(ILogger logger) +public sealed class CredentialStore(ILogger logger) : ICredentialStore { private static readonly JsonSerializerOptions SerializerOptions = new(JsonSerializerDefaults.Web); diff --git a/src/Agent/Enrollment/EnrollmentService.cs b/src/Agent/Enrollment/EnrollmentService.cs index 56377c6..4a3c6b0 100644 --- a/src/Agent/Enrollment/EnrollmentService.cs +++ b/src/Agent/Enrollment/EnrollmentService.cs @@ -3,6 +3,7 @@ using System.Net.Security; using System.Security.Cryptography.X509Certificates; using Agent.Configuration; using Agent.Identity; +using Agent.Inventory; using Agent.Storage; using Microsoft.Extensions.Logging; using NATS.NKeys; @@ -19,9 +20,10 @@ namespace Agent.Enrollment; /// the bootstrap token from the registry. /// public sealed class EnrollmentService( - CredentialStore credentialStore, + ICredentialStore credentialStore, RuntimeStateStore runtimeState, IHardwareIdentitySource hardwareIdentity, + IInventoryCollector inventory, ILogger logger) { /// @@ -34,43 +36,91 @@ public sealed class EnrollmentService( var clientId = ResolveClientId(); var stored = credentialStore.Load(); - if (stored is not null) + if (stored is not null && stored.ClientId != clientId) { - if (stored.ClientId != clientId) - { - // Hardware materially changed: treat as a new device (MVP rule). - logger.LogWarning( - "Stored credentials belong to client {StoredClientId} but recomputed identity is {ClientId}; re-enrolling as new device", - stored.ClientId, clientId); - credentialStore.Delete(); - } - else if (configuration.HasBootstrapToken) - { - // A token is only present because an administrator just placed - // one (it is erased after every successful enrollment), so it - // is an explicit instruction to re-enroll — this is how an - // orphaned device is brought back. - logger.LogInformation( - "Bootstrap token present for already-enrolled client {ClientId}; re-enrolling", clientId); - credentialStore.Delete(); - } - else - { - return stored; - } + // Hardware materially changed: treat as a new device (MVP rule). + logger.LogWarning( + "Stored credentials belong to client {StoredClientId} but recomputed identity is {ClientId}; re-enrolling as new device", + stored.ClientId, clientId); + credentialStore.Delete(); + stored = null; } if (!configuration.HasBootstrapToken) { - logger.LogError("Agent is not enrolled and no bootstrap token is configured"); - return null; + if (stored is null) + { + logger.LogError("Agent is not enrolled and no bootstrap token is configured"); + } + + return stored; } + if (stored is not null) + { + // A token is only present because an administrator just placed one + // (it is erased after every successful enrollment): a reinstall or + // redeploy, or bringing an orphaned device back. Re-enroll, but keep + // the current enrollment until the new one has succeeded. + logger.LogInformation( + "Bootstrap token present for already-enrolled client {ClientId}; re-enrolling", clientId); + } + + BootstrapOutcome outcome; + try + { + outcome = await BootstrapAsync(configuration, clientId, cancellationToken); + } + catch (Exception ex) when (stored is not null + && ex is HttpRequestException or TaskCanceledException + && !cancellationToken.IsCancellationRequested) + { + // Server unreachable mid-redeploy: an enrolled agent keeps working. + logger.LogWarning(ex, "Re-enrollment could not reach the server"); + outcome = BootstrapOutcome.Failed; + } + + if (outcome.Credentials is not null || stored is null) + { + return outcome.Credentials; + } + + if (outcome.Rejected) + { + // A spent, expired or revoked token must not strand a working agent: + // drop the token (retrying it can only fail) and carry on as before. + logger.LogWarning( + "Bootstrap token rejected; keeping the current enrollment of client {ClientId}", clientId); + runtimeState.ClearBootstrapToken(); + } + else + { + logger.LogWarning( + "Re-enrollment did not complete; keeping the current enrollment of client {ClientId} and retrying at the next start", + clientId); + } + + return stored; + } + + /// What a bootstrap attempt produced; Rejected = the server refused the token. + private sealed record BootstrapOutcome(AgentCredentials? Credentials, bool Rejected) + { + public static readonly BootstrapOutcome Failed = new(null, false); + } + + /// + /// One bootstrap against the server with a fresh NKey pair; on success the + /// new credentials replace the stored ones and the token is cleared. + /// + private async Task BootstrapAsync( + AgentConfiguration configuration, string clientId, CancellationToken cancellationToken) + { var serverUrl = configuration.ServerUrl; if (serverUrl is null) { logger.LogError("Agent cannot enroll: ServerURL is missing or invalid"); - return null; + return BootstrapOutcome.Failed; } using var userKey = KeyPair.CreatePair(PrefixByte.User); @@ -114,7 +164,7 @@ public sealed class EnrollmentService( { logger.LogError( "Server certificate is not trusted and the bootstrap token carries no CA fingerprint; refusing to enroll"); - return null; + return BootstrapOutcome.Failed; } var (status, pinnedChain) = await ServerTrust.FetchAndInstallCaAsync( @@ -122,7 +172,7 @@ public sealed class EnrollmentService( if (status != ServerCaStatus.Installed) { logger.LogError("Could not anchor server trust ({Status}); refusing to enroll", status); - return null; + return BootstrapOutcome.Failed; } // Retry, validating the leaf against the CA we just verified so it @@ -141,7 +191,9 @@ public sealed class EnrollmentService( if (!response.IsSuccessStatusCode) { logger.LogError("Bootstrap rejected with HTTP {StatusCode}", (int)response.StatusCode); - return null; + // 401/403: the token itself was refused (spent, expired, revoked). + var refused = response.StatusCode is System.Net.HttpStatusCode.Unauthorized or System.Net.HttpStatusCode.Forbidden; + return new BootstrapOutcome(null, refused); } result = await response.Content.ReadFromJsonAsync(JsonDefaults.Options, cancellationToken); @@ -150,7 +202,7 @@ public sealed class EnrollmentService( if (result is null || string.IsNullOrWhiteSpace(result.UserJwt)) { logger.LogError("Bootstrap response was empty or invalid"); - return null; + return BootstrapOutcome.Failed; } var credentials = new AgentCredentials( @@ -169,7 +221,7 @@ public sealed class EnrollmentService( runtimeState.ClearBootstrapToken(); logger.LogInformation("Enrollment {EnrollmentId} complete; bootstrap token cleared", result.EnrollmentId); - return credentials; + return new BootstrapOutcome(credentials, false); } private static async Task PostBootstrapAsync( @@ -231,16 +283,32 @@ public sealed class EnrollmentService( private EnrollDeviceInfo ReadDeviceInfo() { var identity = hardwareIdentity.Read(); + + // The same OS reading inventory reports ("Windows 11", or "Windows PE" + // before imaging), so the device row does not flip between two + // spellings of one OS at every enrollment. string? osCaption = null; string? osVersion = null; try { - osCaption = Environment.OSVersion.VersionString; - osVersion = Environment.OSVersion.Version.ToString(); + var os = inventory.CollectOs(); + osCaption = os.Caption; + osVersion = os.Version; } - catch (InvalidOperationException) + catch (Exception ex) { // Non-fatal; inventory supplies full OS details later. + logger.LogDebug(ex, "OS details unavailable for enrollment"); + } + + if (string.IsNullOrWhiteSpace(osCaption)) + { + osCaption = Environment.OSVersion.VersionString; + } + + if (string.IsNullOrWhiteSpace(osVersion)) + { + osVersion = Environment.OSVersion.Version.ToString(); } return new EnrollDeviceInfo( diff --git a/src/Agent/Identity/CimHardwareIdentitySource.cs b/src/Agent/Identity/CimHardwareIdentitySource.cs index 169b2aa..6f11ac7 100644 --- a/src/Agent/Identity/CimHardwareIdentitySource.cs +++ b/src/Agent/Identity/CimHardwareIdentitySource.cs @@ -1,11 +1,15 @@ #if WINDOWS_AGENT using System.Management; +using System.Runtime.InteropServices; +using Microsoft.Extensions.Logging; namespace Agent.Identity; /// Reads stable hardware identifiers from CIM/WMI via managed APIs. -public sealed class CimHardwareIdentitySource : IHardwareIdentitySource +public sealed class CimHardwareIdentitySource(ILogger? logger = null) : IHardwareIdentitySource { + private int wmiUnavailableLogged; + public HardwareIdentity Read() { string? uuid = null; @@ -33,7 +37,7 @@ public sealed class CimHardwareIdentitySource : IHardwareIdentitySource return new HardwareIdentity(uuid, biosSerial, boardSerial, identifyingNumber, manufacturer, model); } - private static void Query(string wql, Action onFirst) + private void Query(string wql, Action onFirst) { try { @@ -52,6 +56,18 @@ public sealed class CimHardwareIdentitySource : IHardwareIdentitySource { // Missing WMI class/values — treated as absent identifiers. } + catch (Exception ex) when (ex is COMException or PlatformNotSupportedException or TypeInitializationException) + { + // No WMI service at all — typically Windows PE built without the + // WinPE-WMI optional component. Identity cannot be computed, so + // say why once instead of failing with a bare COM error. + if (Interlocked.Exchange(ref wmiUnavailableLogged, 1) == 0) + { + logger?.LogError( + "WMI is unavailable ({Error}); hardware identity cannot be read. In Windows PE, add the WinPE-WMI optional component", + ex.Message); + } + } } } #endif diff --git a/src/Agent/Inventory/IInventoryCollector.cs b/src/Agent/Inventory/IInventoryCollector.cs index aa8706a..7709130 100644 --- a/src/Agent/Inventory/IInventoryCollector.cs +++ b/src/Agent/Inventory/IInventoryCollector.cs @@ -6,4 +6,10 @@ namespace Agent.Inventory; public interface IInventoryCollector { InventoryReport Collect(string clientId); + + /// + /// The operating system section alone — also sent at enrollment, so the + /// device reads the same before and after its first inventory. + /// + InventoryOs CollectOs(); } diff --git a/src/Agent/Inventory/InventoryCollector.cs b/src/Agent/Inventory/InventoryCollector.cs index cb7d637..f737a6a 100644 --- a/src/Agent/Inventory/InventoryCollector.cs +++ b/src/Agent/Inventory/InventoryCollector.cs @@ -1,13 +1,17 @@ #if WINDOWS_AGENT using System.Management; +using System.Runtime.InteropServices; using Agent.Identity; +using Agent.Platform; using Shared.Contracts.Models; namespace Agent.Inventory; /// Collects the MVP inventory snapshot from CIM/WMI and managed APIs. -public sealed class InventoryCollector(IHardwareIdentitySource identitySource) : IInventoryCollector +public sealed class InventoryCollector(IHardwareIdentitySource identitySource, WindowsPhase? phase = null) : IInventoryCollector { + private readonly WindowsPhase phase = phase ?? WindowsPhase.Current; + public InventoryReport Collect(string clientId) { var hardware = identitySource.Read(); @@ -72,7 +76,7 @@ public sealed class InventoryCollector(IHardwareIdentitySource identitySource) : CollectedUtc: DateTimeOffset.UtcNow); } - private static InventoryOs CollectOs() + public InventoryOs CollectOs() { string? rawCaption = null; string? version = null; @@ -104,8 +108,10 @@ public sealed class InventoryCollector(IHardwareIdentitySource identitySource) : version = $"{version}.{ubr}"; } - // "Microsoft Windows 11 Pro" -> caption "Windows 11", edition "Pro". - var (caption, edition) = ParseWindowsCaption(rawCaption); + // "Microsoft Windows 11 Pro" -> caption "Windows 11", edition "Pro"; + // Windows PE reads "Windows PE" with its real build version. + var parsed = ParseWindowsCaption(rawCaption); + var (caption, edition) = phase.Describe(parsed.Caption, parsed.Edition); var productType = productTypeCode switch { 1 => "Workstation", @@ -335,9 +341,10 @@ public sealed class InventoryCollector(IHardwareIdentitySource identitySource) : } } } - catch (ManagementException) + catch (Exception ex) when (ex is ManagementException or COMException or PlatformNotSupportedException) { - // Missing class/namespace — section stays empty. + // Missing class/namespace, or no WMI at all (Windows PE without + // WinPE-WMI) — section stays empty. } } diff --git a/src/Agent/Inventory/UnixInventoryCollector.cs b/src/Agent/Inventory/UnixInventoryCollector.cs index e233389..b740fe5 100644 --- a/src/Agent/Inventory/UnixInventoryCollector.cs +++ b/src/Agent/Inventory/UnixInventoryCollector.cs @@ -15,7 +15,6 @@ public sealed class UnixInventoryCollector(IHardwareIdentitySource identitySourc public InventoryReport Collect(string clientId) { var hardware = identitySource.Read(); - var (osName, osVersion) = ReadOsRelease(); var identity = new InventoryIdentity( ClientId: clientId, @@ -32,8 +31,23 @@ public sealed class UnixInventoryCollector(IHardwareIdentitySource identitySourc BaseboardManufacturer: ReadTrimmed("/sys/class/dmi/id/board_vendor"), BaseboardProduct: ReadTrimmed("/sys/class/dmi/id/board_name")); + return new InventoryReport( + Identity: identity, + Os: CollectOs(), + Cpu: new InventoryCpu(ReadCpuName(), Environment.ProcessorCount, Environment.ProcessorCount), + Memory: [], + TotalPhysicalMemoryBytes: ReadTotalMemoryBytes(), + Disks: CollectDisks(), + Volumes: CollectVolumes(), + Network: CollectNetwork(), + CollectedUtc: DateTimeOffset.UtcNow); + } + + public InventoryOs CollectOs() + { + var (osName, osVersion) = ReadOsRelease(); var role = DetectEdition(); // Server / Workstation - var os = new InventoryOs( + return new InventoryOs( Caption: osName, Version: osVersion, Build: Environment.OSVersion.Version.ToString(), @@ -42,17 +56,6 @@ public sealed class UnixInventoryCollector(IHardwareIdentitySource identitySourc LastBootUtc: ReadLastBoot(), Edition: role, ProductType: role); - - return new InventoryReport( - Identity: identity, - Os: os, - Cpu: new InventoryCpu(ReadCpuName(), Environment.ProcessorCount, Environment.ProcessorCount), - Memory: [], - TotalPhysicalMemoryBytes: ReadTotalMemoryBytes(), - Disks: CollectDisks(), - Volumes: CollectVolumes(), - Network: CollectNetwork(), - CollectedUtc: DateTimeOffset.UtcNow); } /// diff --git a/src/Agent/Platform/PlatformServices.cs b/src/Agent/Platform/PlatformServices.cs index 4968f74..2ee56ca 100644 --- a/src/Agent/Platform/PlatformServices.cs +++ b/src/Agent/Platform/PlatformServices.cs @@ -1,6 +1,7 @@ using Agent.Configuration; using Agent.Identity; using Agent.Inventory; +using Microsoft.Extensions.Logging; namespace Agent.Platform; @@ -18,16 +19,16 @@ public static class PlatformServices => new FileRegistryStore(); #endif - public static IHardwareIdentitySource CreateIdentitySource() + public static IHardwareIdentitySource CreateIdentitySource(ILogger? logger = null) #if WINDOWS_AGENT - => new CimHardwareIdentitySource(); + => new CimHardwareIdentitySource(logger); #else => new UnixHardwareIdentitySource(); #endif public static IInventoryCollector CreateInventoryCollector(IHardwareIdentitySource identitySource) #if WINDOWS_AGENT - => new InventoryCollector(identitySource); + => new InventoryCollector(identitySource, WindowsPhase.Current); #else => new UnixInventoryCollector(identitySource); #endif diff --git a/src/Agent/Platform/WindowsPhase.cs b/src/Agent/Platform/WindowsPhase.cs new file mode 100644 index 0000000..b3f892d --- /dev/null +++ b/src/Agent/Platform/WindowsPhase.cs @@ -0,0 +1,47 @@ +namespace Agent.Platform; + +/// +/// Which Windows phase the agent runs in. Windows PE (the pre-imaging +/// environment) marks itself with the HKLM\SYSTEM\CurrentControlSet\Control\MiniNT +/// key; there the OS is reported as "Windows PE" with the real build version, +/// so the same device later reports its installed OS normally after imaging. +/// The probe is injectable for tests; linux/macOS are never Windows PE. +/// +public sealed class WindowsPhase(Func miniNtPresent) +{ + public const string MiniNtKeyPath = @"SYSTEM\CurrentControlSet\Control\MiniNT"; + + public const string WinPeCaption = "Windows PE"; + + private readonly Lazy isWinPe = new(miniNtPresent); + + /// The phase of the running system (probed once). + public static WindowsPhase Current { get; } = new(ProbeMiniNt); + + public bool IsWinPe => isWinPe.Value; + + /// + /// The reported OS caption and edition: "Windows PE" (no edition) in + /// Windows PE — whatever WMI calls it there — otherwise unchanged. + /// + public (string? Caption, string? Edition) Describe(string? caption, string? edition) + => IsWinPe ? (WinPeCaption, null) : (caption, edition); + + private static bool ProbeMiniNt() + { +#if WINDOWS_AGENT + try + { + using var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(MiniNtKeyPath); + return key is not null; + } + catch (Exception) + { + // Unreadable registry: assume a full OS (the normal case). + return false; + } +#else + return false; +#endif + } +} diff --git a/src/Agent/PowerShell/ExternalScriptRunner.cs b/src/Agent/PowerShell/ExternalScriptRunner.cs index 227767b..797b42b 100644 --- a/src/Agent/PowerShell/ExternalScriptRunner.cs +++ b/src/Agent/PowerShell/ExternalScriptRunner.cs @@ -114,7 +114,9 @@ public static class ExternalScriptRunner wrapper.AppendLine($"$__splat[{PsLiteral(name)}] = {PsLiteral(value)}"); } - wrapper.AppendLine($"& '{payloadPath}' @__splat"); + // Same rendering as the in-process engine: objects as PowerShell shows + // them, at a width that does not truncate tables. + wrapper.AppendLine($"& '{payloadPath}' @__splat | Out-String -Stream -Width {PowerShellExecutionService.OutputWidth}"); wrapper.AppendLine("exit $LASTEXITCODE"); var wrapperPath = Path.Combine(workDir, "wrapper.ps1"); @@ -207,6 +209,11 @@ public static class ExternalScriptRunner { foreach (var (key, value) in environment) { + // Windows environment names are case-insensitive: assigning + // "ApiKey" over an inherited "APIKEY" keeps the old spelling, + // and bash (case-sensitive) then sees $ApiKey as empty. Drop + // the inherited entry so the script's exact name is used. + process.StartInfo.Environment.Remove(key); process.StartInfo.Environment[key] = value; } } @@ -215,7 +222,8 @@ public static class ExternalScriptRunner { if (e.Data is not null) { - onRecord(new NormalizedOutputRecord(OutputStreamKind.Output, e.Data)); + // Formatted table/list lines are padded to the column width. + onRecord(new NormalizedOutputRecord(OutputStreamKind.Output, e.Data.TrimEnd())); } }; process.ErrorDataReceived += (_, e) => diff --git a/src/Agent/PowerShell/PowerShellExecutionService.cs b/src/Agent/PowerShell/PowerShellExecutionService.cs index 3af8add..1cff545 100644 --- a/src/Agent/PowerShell/PowerShellExecutionService.cs +++ b/src/Agent/PowerShell/PowerShellExecutionService.cs @@ -60,6 +60,7 @@ public sealed class PowerShellExecutionService if (!string.IsNullOrWhiteSpace(prelude)) { powerShell.AddScript(prelude); + AddFormatter(powerShell); powerShell.AddStatement(); } @@ -72,6 +73,8 @@ public sealed class PowerShellExecutionService } } + AddFormatter(powerShell); + var output = new PSDataCollection(); output.DataAdded += (_, e) => onRecord(PowerShellOutputNormalizer.FromOutput(output[e.Index])); @@ -123,4 +126,20 @@ public sealed class PowerShellExecutionService WasCancelled: wasCancelled, FailureMessage: failureMessage); } + + /// + /// Width handed to the formatter: wide enough that tables and lists are not + /// cut short with "…" the way an 80/120-column console would. + /// + internal const int OutputWidth = 4096; + + /// + /// Pipes the statement's output through Out-String -Stream, so pipeline + /// objects arrive as PowerShell would display them (their table or list view, + /// a hashtable's keys and values) instead of a bare ToString() such as + /// "System.Collections.Hashtable". Strings pass through unchanged, one record + /// per line, still streamed as they are produced. + /// + private static void AddFormatter(System.Management.Automation.PowerShell powerShell) + => powerShell.AddCommand("Out-String").AddParameter("Stream").AddParameter("Width", OutputWidth); } diff --git a/src/Agent/PowerShell/PowerShellOutputNormalizer.cs b/src/Agent/PowerShell/PowerShellOutputNormalizer.cs index cfd1b6a..bbbf981 100644 --- a/src/Agent/PowerShell/PowerShellOutputNormalizer.cs +++ b/src/Agent/PowerShell/PowerShellOutputNormalizer.cs @@ -49,6 +49,11 @@ public static class PowerShellOutputNormalizer PercentComplete: record.PercentComplete >= 0 ? record.PercentComplete : null, SecondsRemaining: record.SecondsRemaining >= 0 ? record.SecondsRemaining : null); + /// + /// Output arrives as formatted lines (see PowerShellExecutionService); + /// table/list lines carry padding out to the column width, so trailing + /// spaces are dropped. + /// private static string ToText(PSObject? value) { if (value?.BaseObject is null) @@ -56,6 +61,6 @@ public static class PowerShellOutputNormalizer return string.Empty; } - return value.ToString() ?? string.Empty; + return (value.ToString() ?? string.Empty).TrimEnd(); } } diff --git a/src/Agent/Progress/PresencePublisher.cs b/src/Agent/Progress/PresencePublisher.cs index 6dea4f7..45688c1 100644 --- a/src/Agent/Progress/PresencePublisher.cs +++ b/src/Agent/Progress/PresencePublisher.cs @@ -1,3 +1,4 @@ +using System.Runtime.InteropServices; using Agent.Messaging; using Microsoft.Extensions.Logging; using Shared.Contracts.Messages; @@ -30,7 +31,9 @@ public sealed class PresencePublisher( Status: "online", TimestampUtc: DateTimeOffset.UtcNow, UptimeSeconds: Environment.TickCount64 / 1000, - ActiveJobs: activeJobCounter()); + ActiveJobs: activeJobCounter(), + // The build's RID ("win-x64"): the server picks the upgrade package by it. + Runtime: RuntimeInformation.RuntimeIdentifier); await publisher.PublishAsync(subject, MessageTypes.AgentPresence, payload, cancellationToken: cancellationToken); } diff --git a/src/Agent/Service/AgentHost.cs b/src/Agent/Service/AgentHost.cs index 973950a..e57faec 100644 --- a/src/Agent/Service/AgentHost.cs +++ b/src/Agent/Service/AgentHost.cs @@ -58,11 +58,17 @@ public static class AgentHost builder.Services.AddSingleton(registry); builder.Services.AddSingleton(); - builder.Services.AddSingleton(); - builder.Services.AddSingleton(Platform.PlatformServices.CreateIdentitySource()); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(sp => Platform.PlatformServices.CreateIdentitySource( + sp.GetRequiredService().CreateLogger("Agent.Identity"))); + builder.Services.AddSingleton(sp => Platform.PlatformServices.CreateInventoryCollector( + sp.GetRequiredService())); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); + builder.Services.AddSingleton(new Upgrade.AgentRuntimeInfo(runAsService)); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(Upgrade.UpgradeFolders.Installed); // Environment variables are development-only and never apply in // service mode (and never override GPO in any mode). @@ -73,6 +79,13 @@ public static class AgentHost // renewals (no-op for a real/edge certificate). builder.Services.AddHostedService(); + // The watchdog's health beacon, on its own timer; only the installed + // service writes it (a foreground run must not speak for the service). + if (runAsService) + { + builder.Services.AddHostedService(); + } + return builder.Build(); } } diff --git a/src/Agent/Service/AgentSession.cs b/src/Agent/Service/AgentSession.cs index b610898..a476237 100644 --- a/src/Agent/Service/AgentSession.cs +++ b/src/Agent/Service/AgentSession.cs @@ -9,6 +9,7 @@ using Agent.PowerShell; using Agent.Progress; using Agent.Shell; using Agent.Storage; +using Agent.Upgrade; using Microsoft.Extensions.Logging; using NATS.Client.Core; @@ -29,15 +30,18 @@ public interface IAgentSession public sealed class AgentSessionFactory( IHardwareIdentitySource hardwareIdentity, JobHistoryStore jobHistory, + AgentRuntimeInfo runtime, + AgentHealthState health, ILoggerFactory loggerFactory) : IAgentSessionFactory { public IAgentSession Create(NatsConnection connection, AgentCredentials credentials, AgentConfiguration configuration) - => new AgentSession(connection, credentials, configuration, hardwareIdentity, jobHistory, loggerFactory); + => new AgentSession(connection, credentials, configuration, hardwareIdentity, jobHistory, runtime, health, loggerFactory); } /// /// Runs the concurrent per-connection components: presence heartbeat, -/// inventory publishing and durable command processing. +/// inventory publishing, durable command processing and the report of an +/// upgrade's outcome. /// public sealed class AgentSession : IAgentSession { @@ -45,6 +49,9 @@ public sealed class AgentSession : IAgentSession private readonly InventoryPublisher inventory; private readonly CommandProcessor commands; private readonly ShellCommandListener shell; + private readonly UpgradeOutcomeReporter upgradeOutcomes; + private readonly NatsConnection connection; + private readonly AgentHealthState health; private readonly ILogger logger; private readonly AgentCredentials credentials; private readonly AgentConfiguration configuration; @@ -55,8 +62,12 @@ public sealed class AgentSession : IAgentSession AgentConfiguration configuration, IHardwareIdentitySource hardwareIdentity, JobHistoryStore jobHistory, + AgentRuntimeInfo runtime, + AgentHealthState health, ILoggerFactory loggerFactory) { + this.connection = connection; + this.health = health; this.credentials = credentials; this.configuration = configuration; logger = loggerFactory.CreateLogger(); @@ -68,12 +79,29 @@ public sealed class AgentSession : IAgentSession executionService, publisher, jobHistory, loggerFactory.CreateLogger()); var fileHandler = new FileDownloadHandler(publisher, jobHistory, loggerFactory.CreateLogger()); + var folders = UpgradeFolders.Installed; + var upgradeEvents = new NatsUpgradeEvents(publisher); + var upgrades = new AgentUpgradeHandler( + new AgentUpgradeContext + { + Folders = folders, + ClientId = credentials.ClientId, + CanSelfUpgrade = runtime.CanSelfUpgrade, + ServerUrl = configuration.ServerUrl, + TlsSkipVerify = configuration.TlsSkipVerify.Value, + }, + upgradeEvents, + new WatchdogInstaller(folders.InstallDirectory, loggerFactory.CreateLogger()), + loggerFactory.CreateLogger()); + upgradeOutcomes = new UpgradeOutcomeReporter( + folders, upgradeEvents, () => health.Connected, credentials.ClientId, loggerFactory.CreateLogger()); + presence = new PresencePublisher( publisher, () => jobHandler.ActiveJobs, loggerFactory.CreateLogger()); inventory = new InventoryPublisher( collector, publisher, configuration.InventoryInterval.Value, loggerFactory.CreateLogger()); commands = new CommandProcessor( - connection, publisher, inventory, jobHandler, fileHandler, jobHistory, configuration, + connection, publisher, inventory, jobHandler, fileHandler, jobHistory, configuration, upgrades, health, loggerFactory.CreateLogger()); shell = new ShellCommandListener( connection, publisher, configuration, loggerFactory.CreateLogger()); @@ -87,6 +115,8 @@ public sealed class AgentSession : IAgentSession configuration.AllowRemoteShell.Value ? "enabled" : "disabled", configuration.AllowScriptExecution.Value ? "enabled" : "disabled"); + health.Attach(connection); + // Inventory publishes immediately (enrollment/reconnect), then on interval. try { @@ -94,10 +124,12 @@ public sealed class AgentSession : IAgentSession presence.RunAsync(cancellationToken), inventory.RunAsync(cancellationToken), commands.RunAsync(cancellationToken), - shell.RunAsync(cancellationToken)); + shell.RunAsync(cancellationToken), + upgradeOutcomes.RunAsync(cancellationToken)); } finally { + health.Detach(connection); shell.Dispose(); } } diff --git a/src/Agent/Shell/BuiltInShellHost.cs b/src/Agent/Shell/BuiltInShellHost.cs new file mode 100644 index 0000000..42d16a1 --- /dev/null +++ b/src/Agent/Shell/BuiltInShellHost.cs @@ -0,0 +1,36 @@ +using System.Management.Automation.Runspaces; +using Agent.PowerShell; +using Microsoft.PowerShell; +using Shared.Infrastructure.Versioning; + +namespace Agent.Shell; + +/// +/// The hidden shell-host verb: an interactive PowerShell console on +/// the agent's embedded engine (the SDK's own console host), so a remote shell +/// is available where no PowerShell is installed — Windows PE without the +/// WinPE-PowerShell component, a stripped Server Core. Runs in its own process +/// under the session's PTY; it never starts the agent's workers or reads its +/// configuration and credentials, and exits with the console. +/// +public static class BuiltInShellHost +{ + public static int Run(string[] args) + { + PowerShellRunspaceFactory.EnsureBundledModulesOnPath(); + + var initialSessionState = InitialSessionState.CreateDefault2(); + initialSessionState.ExecutionPolicy = ExecutionPolicy.Bypass; + + var banner = $"ExecuteR built-in PowerShell {System.Management.Automation.PSVersionInfo.PSVersion} (agent {BuildVersion.Resolve(typeof(BuiltInShellHost).Assembly)})"; + + // -NoLogo drops the stock PowerShell banner (and update notice); ours + // greets interactive sessions only, so `shell-host -Command ...` stays clean. + if (args.Length == 0) + { + Console.WriteLine(banner); + } + + return ConsoleShell.Start(initialSessionState, banner, helpText: string.Empty, ["-NoLogo", .. args]); + } +} diff --git a/src/Agent/Shell/ShellManager.cs b/src/Agent/Shell/ShellManager.cs index 76ede54..9f23543 100644 --- a/src/Agent/Shell/ShellManager.cs +++ b/src/Agent/Shell/ShellManager.cs @@ -32,9 +32,20 @@ public sealed class ShellManager(AgentPublisher publisher, ILogger logger) : IDi { CloseCurrent("superseded by new session"); - var (fileName, args) = ResolveShellCommand(); - var pty = CreatePty(); Guid sessionId = command.SessionId; + ShellLaunch launch; + try + { + launch = ResolveShell(command.Shell); + } + catch (ShellUnavailableException ex) + { + logger.LogWarning("Shell session {SessionId} not opened: {Reason}", sessionId, ex.Message); + PublishState(sessionId, ShellSessionState.Failed, ex.Message); + return; + } + + var pty = CreatePty(); var active = new ActiveShell { @@ -54,9 +65,10 @@ public sealed class ShellManager(AgentPublisher publisher, ILogger logger) : IDi try { - pty.Start(fileName, args, Math.Max(command.Cols, 1), Math.Max(command.Rows, 1)); - PublishState(sessionId, ShellSessionState.Open, null); - logger.LogInformation("Shell session {SessionId} opened ({Shell})", sessionId, fileName); + pty.Start(launch.FileName, launch.Args, Math.Max(command.Cols, 1), Math.Max(command.Rows, 1)); + PublishState(sessionId, ShellSessionState.Open, null, launch.Kind); + logger.LogInformation("Shell session {SessionId} opened: {Kind} ({Shell}, requested {Requested})", + sessionId, launch.Kind ?? "login shell", launch.FileName, command.Shell ?? ShellKinds.Auto); } catch (Exception ex) { @@ -152,12 +164,12 @@ public sealed class ShellManager(AgentPublisher publisher, ILogger logger) : IDi payload); } - private void PublishState(Guid sessionId, ShellSessionState state, string? message) + private void PublishState(Guid sessionId, ShellSessionState state, string? message, string? shell = null) { _ = publisher.PublishAsync( NatsSubjects.AgentShellState(publisher.ClientId, sessionId), MessageTypes.ShellState, - new ShellStatePayload(sessionId, state, message)); + new ShellStatePayload(sessionId, state, message, shell)); } private static void DisposeShell(ActiveShell? active, string reason) @@ -181,24 +193,19 @@ public sealed class ShellManager(AgentPublisher publisher, ILogger logger) : IDi #endif #if WINDOWS_AGENT - /// Prefers PowerShell 7 (pwsh) when present, else Windows PowerShell. - private static (string FileName, string[] Args) ResolveShellCommand() - { - var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); - var pwsh = Path.Combine(programFiles, "PowerShell", "7", "pwsh.exe"); - if (File.Exists(pwsh)) - { - return (pwsh, ["-NoLogo"]); - } - - var windowsPowerShell = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.System), - "WindowsPowerShell", "v1.0", "powershell.exe"); - return (windowsPowerShell, ["-NoLogo"]); - } + /// The requested shell (see ). + private static ShellLaunch ResolveShell(string? requested) => + WindowsShellResolver.Resolve(requested, WindowsShellLocations.FromEnvironment(), File.Exists); #else - /// Honors $SHELL, then falls back to bash/zsh/sh. - private static (string FileName, string[] Args) ResolveShellCommand() + /// Honors $SHELL, then falls back to bash/zsh/sh; the Windows shell choice does not apply. + private static ShellLaunch ResolveShell(string? requested) + { + _ = requested; + var (fileName, args) = ResolveLoginShell(); + return new ShellLaunch(null, fileName, args); + } + + private static (string FileName, string[] Args) ResolveLoginShell() { var candidates = new[] { diff --git a/src/Agent/Shell/WindowsShellResolver.cs b/src/Agent/Shell/WindowsShellResolver.cs new file mode 100644 index 0000000..d8b38ef --- /dev/null +++ b/src/Agent/Shell/WindowsShellResolver.cs @@ -0,0 +1,120 @@ +using Shared.Contracts.Models; + +namespace Agent.Shell; + +/// A resolved shell: the program the PTY starts, and which value it is (null on unix). +internal sealed record ShellLaunch(string? Kind, string FileName, string[] Args); + +/// An explicitly requested shell is not on this device; the message goes to the operator. +internal sealed class ShellUnavailableException(string message) : Exception(message); + +/// Where a Windows device keeps its shells (injectable for tests). +internal sealed record WindowsShellLocations( + string? ProgramFiles, + string? SystemDirectory, + string? ComSpec, + string? SearchPath, + string? AgentExecutable) +{ + public static WindowsShellLocations FromEnvironment() => new( + Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), + Environment.GetFolderPath(Environment.SpecialFolder.System), + Environment.GetEnvironmentVariable("ComSpec"), + Environment.GetEnvironmentVariable("PATH"), + Environment.ProcessPath); +} + +/// +/// Picks the shell a Windows session starts. Automatic takes the first of +/// PowerShell 7, Windows PowerShell, the agent's built-in PowerShell host and +/// cmd.exe that exists; an explicit choice that is missing fails the open. +/// +internal static class WindowsShellResolver +{ + /// Hidden agent verb that runs the built-in PowerShell console (see ). + public const string HostVerb = "shell-host"; + + public static ShellLaunch Resolve(string? requested, WindowsShellLocations locations, Func fileExists) + { + // Unknown values (a newer backend) fall back to automatic. + switch (ShellKinds.Normalize(requested) ?? ShellKinds.Auto) + { + case ShellKinds.Pwsh: + return FindPwsh(locations, fileExists) + ?? throw new ShellUnavailableException("PowerShell 7 (pwsh.exe) is not installed on this device."); + + case ShellKinds.WindowsPowerShell: + return FindWindowsPowerShell(locations, fileExists) + ?? throw new ShellUnavailableException("Windows PowerShell (powershell.exe) is not installed on this device."); + + case ShellKinds.Cmd: + return FindCmd(locations, fileExists) + ?? throw new ShellUnavailableException("Command Prompt (cmd.exe) was not found on this device."); + + case ShellKinds.BuiltIn: + return FindBuiltIn(locations, fileExists) + ?? throw new ShellUnavailableException("The agent's built-in PowerShell is unavailable (agent executable not found)."); + + default: + return FindPwsh(locations, fileExists) + ?? FindWindowsPowerShell(locations, fileExists) + ?? FindBuiltIn(locations, fileExists) + ?? FindCmd(locations, fileExists) + ?? throw new ShellUnavailableException("No shell was found on this device."); + } + } + + private static ShellLaunch? FindPwsh(WindowsShellLocations locations, Func fileExists) + { + var candidates = new List(); + if (!string.IsNullOrEmpty(locations.ProgramFiles)) + { + candidates.Add(Path.Combine(locations.ProgramFiles, "PowerShell", "7", "pwsh.exe")); + } + + foreach (var directory in (locations.SearchPath ?? string.Empty).Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + candidates.Add(Path.Combine(directory.Trim('"'), "pwsh.exe")); + } + + var found = candidates.FirstOrDefault(fileExists); + return found is null ? null : new ShellLaunch(ShellKinds.Pwsh, found, ["-NoLogo"]); + } + + private static ShellLaunch? FindWindowsPowerShell(WindowsShellLocations locations, Func fileExists) + { + if (string.IsNullOrEmpty(locations.SystemDirectory)) + { + return null; + } + + var path = Path.Combine(locations.SystemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe"); + return fileExists(path) ? new ShellLaunch(ShellKinds.WindowsPowerShell, path, ["-NoLogo"]) : null; + } + + private static ShellLaunch? FindCmd(WindowsShellLocations locations, Func fileExists) + { + string?[] candidates = + [ + locations.ComSpec, + string.IsNullOrEmpty(locations.SystemDirectory) ? null : Path.Combine(locations.SystemDirectory, "cmd.exe"), + ]; + + var found = candidates.FirstOrDefault(path => !string.IsNullOrEmpty(path) && fileExists(path)); + return found is null ? null : new ShellLaunch(ShellKinds.Cmd, found, []); + } + + private static ShellLaunch? FindBuiltIn(WindowsShellLocations locations, Func fileExists) + { + var agent = locations.AgentExecutable; + // Only the agent's own apphost knows the verb (not dotnet.exe hosting a dll). + if (string.IsNullOrEmpty(agent) + || string.Equals(Path.GetFileNameWithoutExtension(agent), "dotnet", StringComparison.OrdinalIgnoreCase) + || !fileExists(agent)) + { + return null; + } + + return new ShellLaunch(ShellKinds.BuiltIn, agent, [HostVerb]); + } +} diff --git a/src/Agent/Upgrade/AgentHealth.cs b/src/Agent/Upgrade/AgentHealth.cs new file mode 100644 index 0000000..e2f54b0 --- /dev/null +++ b/src/Agent/Upgrade/AgentHealth.cs @@ -0,0 +1,96 @@ +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using NATS.Client.Core; +using Shared.Contracts.Models; +using Shared.Contracts.Serialization; +using Shared.Infrastructure.Versioning; + +namespace Agent.Upgrade; + +/// How the agent runs: the installed service, or a foreground/development host. +public sealed record AgentRuntimeInfo(bool RunningAsService) +{ + /// + /// Only the installed service upgrades itself: run by its service manager + /// from its own binary (not foreground, not dotnet run). + /// + public bool CanSelfUpgrade => RunningAsService + && string.Equals(Path.GetFileName(Environment.ProcessPath), Shared.Infrastructure.Constants.Branding.AgentBinaryName, + OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); +} + +/// +/// Whether the agent is healthy for the watchdog: its command consumer is bound +/// (the moment it publishes "ready") and its NATS connection is open. +/// +public sealed class AgentHealthState +{ + private volatile NatsConnection? connection; + private volatile bool commandsBound; + + public void Attach(NatsConnection current) => connection = current; + + public void Detach(NatsConnection current) + { + if (ReferenceEquals(connection, current)) + { + connection = null; + commandsBound = false; + } + } + + public bool CommandsBound + { + get => commandsBound; + set => commandsBound = value; + } + + public bool Connected => commandsBound && connection?.ConnectionState == NatsConnectionState.Open; +} + +/// +/// Writes health.json every on +/// its own timer, so long work (a download, a script) never holds it back. Only +/// the installed service writes it: a foreground run must not speak for it. +/// +public sealed class HealthBeaconService(UpgradeFolders folders, AgentHealthState health, ILogger logger) : BackgroundService +{ + private static readonly string Version = BuildVersion.Resolve(typeof(HealthBeaconService).Assembly); + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + using var timer = new PeriodicTimer(WatchdogFiles.BeaconInterval); + var failing = false; + do + { + try + { + WatchdogFileStore.Write(folders.Health, + new WatchdogHealthBeacon(Version, Environment.ProcessId, health.Connected, DateTimeOffset.UtcNow), + WatchdogJsonContext.Default.WatchdogHealthBeacon); + failing = false; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + if (!failing) + { + logger.LogWarning(exception, "Health beacon could not be written to {Path}", folders.Health); + failing = true; + } + } + } + while (await WaitAsync(timer, stoppingToken)); + } + + private static async Task WaitAsync(PeriodicTimer timer, CancellationToken cancellationToken) + { + try + { + return await timer.WaitForNextTickAsync(cancellationToken); + } + catch (OperationCanceledException) + { + return false; + } + } +} diff --git a/src/Agent/Upgrade/AgentUpgradeHandler.cs b/src/Agent/Upgrade/AgentUpgradeHandler.cs new file mode 100644 index 0000000..4d00b0d --- /dev/null +++ b/src/Agent/Upgrade/AgentUpgradeHandler.cs @@ -0,0 +1,424 @@ +using System.IO.Compression; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using Agent.Messaging; +using Microsoft.Extensions.Logging; +using Shared.Contracts.Messages; +using Shared.Contracts.Models; +using Shared.Contracts.Serialization; +using Shared.Infrastructure.Constants; +using Shared.Infrastructure.Nats; +using Shared.Infrastructure.Routing; +using Shared.Infrastructure.Versioning; + +namespace Agent.Upgrade; + +/// Where upgrade progress and outcomes go: the agent event subject in production, a list in tests. +public interface IUpgradeEvents +{ + Task PublishAsync(AgentUpgradeEventPayload payload, CancellationToken cancellationToken); +} + +public sealed class NatsUpgradeEvents(AgentPublisher publisher) : IUpgradeEvents +{ + public async Task PublishAsync(AgentUpgradeEventPayload payload, CancellationToken cancellationToken) + => await publisher.PublishAsync( + NatsSubjects.AgentEvent(publisher.ClientId), MessageTypes.AgentUpgrade, payload, cancellationToken: cancellationToken); +} + +/// At most one upgrade per process at a time, across reconnects (a session is per connection). +public sealed class UpgradeGate +{ + public static UpgradeGate Process { get; } = new(); + + private int busy; + + public bool TryEnter() => Interlocked.CompareExchange(ref busy, 1, 0) == 0; + + public void Exit() => Volatile.Write(ref busy, 0); +} + +/// What the upgrade handler works with; every seam a test needs is here. +public sealed class AgentUpgradeContext +{ + public required UpgradeFolders Folders { get; init; } + public required string ClientId { get; init; } + public string CurrentVersion { get; init; } = BuildVersion.Resolve(typeof(AgentUpgradeContext).Assembly); + public string? RuntimeIdentifier { get; init; } = RuntimeInformation.RuntimeIdentifier; + public bool CanSelfUpgrade { get; init; } + public ServerUrl? ServerUrl { get; init; } + public bool TlsSkipVerify { get; init; } + + /// The download's HTTP handler: OS trust (the managed CA was installed there at enrollment), or accept-any when configured. + public Func? CreateHttpHandler { get; init; } + + public Func Delay { get; init; } = Task.Delay; + + /// A random whole number of milliseconds in [0, max]. + public Func RandomMilliseconds { get; init; } = max => Random.Shared.Next(max + 1); + + public Func UtcNow { get; init; } = () => DateTimeOffset.UtcNow; + + public TimeSpan PickupPollInterval { get; init; } = TimeSpan.FromSeconds(2); + + public TimeSpan PickupDeadline { get; init; } = WatchdogFiles.HandoverPickupDeadline; + + public UpgradeGate Gate { get; init; } = UpgradeGate.Process; +} + +/// +/// Handles : refuses what this +/// agent cannot do (not the installed service, another platform's package, an +/// upgrade already pending), reports an upgrade to the running version as done, +/// and otherwise waits its start jitter, downloads the package (size and SHA-256 +/// checked), unpacks it into the staging folder, makes sure the watchdog runs, +/// and hands the package over to it. The swap's outcome is reported by whichever +/// version runs afterwards (). +/// +public sealed class AgentUpgradeHandler(AgentUpgradeContext context, IUpgradeEvents events, IWatchdogInstaller watchdog, ILogger logger) +{ + private static readonly TimeSpan DownloadTimeout = TimeSpan.FromMinutes(30); + + private UpgradeFolders Folders => context.Folders; + + /// The URL to download from: a server path against the configured server URL, an absolute http(s) URL as is. + public static Uri? ResolveDownloadUrl(string downloadUrl, ServerUrl? serverUrl) + { + if (string.IsNullOrWhiteSpace(downloadUrl)) + { + return null; + } + + if (downloadUrl.StartsWith('/') && !downloadUrl.StartsWith("//", StringComparison.Ordinal)) + { + return serverUrl?.ApiEndpoint(downloadUrl); + } + + return Uri.TryCreate(downloadUrl, UriKind.Absolute, out var absolute) + && (absolute.Scheme == Uri.UriSchemeHttps || absolute.Scheme == Uri.UriSchemeHttp) + ? absolute + : null; + } + + public async Task RunAsync(AgentUpgradeCommandPayload command, CancellationToken cancellationToken) + { + try + { + await RunCoreAsync(command, cancellationToken); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + logger.LogInformation("Upgrade {UpgradeId} cancelled by the agent stopping", command.UpgradeId); + } + catch (Exception exception) + { + logger.LogError(exception, "Upgrade {UpgradeId} failed", command.UpgradeId); + await PublishAsync(command, AgentUpgradeStates.Failed, AgentUpgradeReasons.Download, exception.Message, CancellationToken.None); + } + } + + private async Task RunCoreAsync(AgentUpgradeCommandPayload command, CancellationToken cancellationToken) + { + logger.LogInformation("Upgrade {UpgradeId} requested: {From} -> {To} ({PackageType})", + command.UpgradeId, context.CurrentVersion, command.Version, command.PackageType); + + if (!context.CanSelfUpgrade) + { + await FailAsync(command, AgentUpgradeReasons.Unsupported, + "The agent runs in the foreground or a development host; only the installed service upgrades itself.", cancellationToken); + return; + } + + var expected = AgentPackageTypes.ForRuntime(context.RuntimeIdentifier); + if (expected is null || !string.Equals(expected, command.PackageType, StringComparison.OrdinalIgnoreCase)) + { + await FailAsync(command, AgentUpgradeReasons.Unsupported, + expected is null + ? $"No upgrade package is built for this platform ({context.RuntimeIdentifier})." + : $"This agent ({context.RuntimeIdentifier}) upgrades from the {expected} package, not {command.PackageType}.", + cancellationToken); + return; + } + + if (AgentVersions.Compare(context.CurrentVersion, command.Version) == 0) + { + await PublishAsync(command, AgentUpgradeStates.Succeeded, AgentUpgradeReasons.Already, + $"Already running {command.Version}.", cancellationToken); + return; + } + + if (Folders.UpgradePending || !context.Gate.TryEnter()) + { + await FailAsync(command, AgentUpgradeReasons.Busy, "Another upgrade is under way on this device.", cancellationToken); + return; + } + + try + { + await UpgradeAsync(command, cancellationToken); + } + finally + { + context.Gate.Exit(); + } + } + + private async Task UpgradeAsync(AgentUpgradeCommandPayload command, CancellationToken cancellationToken) + { + // A batch of devices must not start downloading in the same instant: + // wait the jitter before any other work. + if (command.StartJitterSeconds > 0) + { + var jitter = TimeSpan.FromMilliseconds(context.RandomMilliseconds(command.StartJitterSeconds * 1000)); + logger.LogInformation("Upgrade {UpgradeId} starts in {Seconds:0.0} s", command.UpgradeId, jitter.TotalSeconds); + await context.Delay(jitter, cancellationToken); + } + + var url = ResolveDownloadUrl(command.DownloadUrl, context.ServerUrl); + if (url is null) + { + await FailAsync(command, AgentUpgradeReasons.Download, $"The download URL '{command.DownloadUrl}' cannot be used.", cancellationToken); + return; + } + + var package = await DownloadAsync(command, url, cancellationToken); + if (package is null) + { + return; + } + + var staging = Path.Combine(Folders.Staging, $"{command.Version}-{command.UpgradeId:N}"); + IReadOnlyList files; + try + { + files = Unpack(package, staging); + } + catch (Exception exception) when (exception is IOException or InvalidDataException or UnauthorizedAccessException) + { + TryDeleteDirectory(staging); + await FailAsync(command, AgentUpgradeReasons.Package, $"The package could not be unpacked ({exception.Message}).", cancellationToken); + return; + } + + if (!files.Any(f => string.Equals(f.Path, Branding.AgentBinaryName, StringComparison.OrdinalIgnoreCase))) + { + TryDeleteDirectory(staging); + await FailAsync(command, AgentUpgradeReasons.Package, $"The package has no {Branding.AgentBinaryName}.", cancellationToken); + return; + } + + if (await watchdog.EnsureRunningAsync(staging, cancellationToken) is { } problem) + { + TryDeleteDirectory(staging); + await FailAsync(command, AgentUpgradeReasons.Watchdog, problem, cancellationToken); + return; + } + + var handover = new WatchdogHandover(command.UpgradeId, command.Version, context.CurrentVersion, staging, files, + command.HealthDeadlineSeconds, command.Revert, context.UtcNow()); + WatchdogFileStore.Write(Folders.Handover, handover, WatchdogJsonContext.Default.WatchdogHandover); + logger.LogInformation("Upgrade {UpgradeId} handed to the watchdog ({Files} files)", command.UpgradeId, files.Count); + await PublishAsync(command, AgentUpgradeStates.Installing, null, $"Handed to the watchdog ({files.Count} files).", cancellationToken); + + await WaitForPickupAsync(command, cancellationToken); + } + + /// The verified package in the downloads folder (reused when already there), or null after a failure was reported. + private async Task DownloadAsync(AgentUpgradeCommandPayload command, Uri url, CancellationToken cancellationToken) + { + var sha = command.Sha256.Trim().ToLowerInvariant(); + if (sha.Length != 64 || !sha.All(Uri.IsHexDigit)) + { + await FailAsync(command, AgentUpgradeReasons.Hash, "The command carries no valid SHA-256.", cancellationToken); + return null; + } + + Directory.CreateDirectory(Folders.Downloads); + var path = Path.Combine(Folders.Downloads, sha + ".zip"); + if (File.Exists(path) && new FileInfo(path).Length == command.SizeBytes && await HashAsync(path, cancellationToken) == sha) + { + logger.LogInformation("Upgrade {UpgradeId}: package already downloaded", command.UpgradeId); + File.SetLastWriteTimeUtc(path, DateTime.UtcNow); + await PublishAsync(command, AgentUpgradeStates.Downloading, null, "Package already downloaded.", cancellationToken); + return path; + } + + await PublishAsync(command, AgentUpgradeStates.Downloading, null, $"Downloading 0% of {Megabytes(command.SizeBytes)}.", cancellationToken); + var partial = path + ".partial"; + try + { + using var http = new HttpClient(CreateHandler(), disposeHandler: true) { Timeout = DownloadTimeout }; + using var response = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken); + response.EnsureSuccessStatusCode(); + await using (var source = await response.Content.ReadAsStreamAsync(cancellationToken)) + await using (var target = new FileStream(partial, FileMode.Create, FileAccess.Write, FileShare.None)) + { + var buffer = new byte[81920]; + long done = 0; + var reported = 0; + int read; + while ((read = await source.ReadAsync(buffer, cancellationToken)) > 0) + { + await target.WriteAsync(buffer.AsMemory(0, read), cancellationToken); + done += read; + if (done > command.SizeBytes) + { + break; + } + + var percent = command.SizeBytes > 0 ? (int)(done * 100 / command.SizeBytes) : 0; + if (percent >= reported + 10 && percent < 100) + { + reported = percent / 10 * 10; + await PublishAsync(command, AgentUpgradeStates.Downloading, null, + $"Downloading {reported}% of {Megabytes(command.SizeBytes)}.", cancellationToken); + } + } + } + } + catch (Exception exception) when (exception is HttpRequestException or IOException + || (exception is TaskCanceledException && !cancellationToken.IsCancellationRequested)) + { + TryDelete(partial); + await FailAsync(command, AgentUpgradeReasons.Download, $"The package could not be downloaded ({exception.Message}).", cancellationToken); + return null; + } + + var size = new FileInfo(partial).Length; + var actual = await HashAsync(partial, cancellationToken); + if (size != command.SizeBytes || actual != sha) + { + TryDelete(partial); + await FailAsync(command, AgentUpgradeReasons.Hash, + $"The package does not match: {size} bytes with SHA-256 {actual}, expected {command.SizeBytes} bytes with {sha}.", cancellationToken); + return null; + } + + File.Move(partial, path, overwrite: true); + logger.LogInformation("Upgrade {UpgradeId}: package downloaded and verified", command.UpgradeId); + return path; + } + + private HttpMessageHandler CreateHandler() + { + if (context.CreateHttpHandler is { } create) + { + return create(); + } + + // Same trust as enrollment: OS validation (a self-signed server's CA was + // installed into the OS store when the agent enrolled), or accept-any + // when TlsSkipVerify is configured. The system/override proxy applies. + var handler = new HttpClientHandler(); + if (context.TlsSkipVerify) + { + handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; + } + + return handler; + } + + /// Unpacks the package and lists its files ('/'-separated, with size and SHA-256). + private static List Unpack(string package, string staging) + { + TryDeleteDirectory(staging); + Directory.CreateDirectory(staging); + + // ExtractToDirectory refuses an entry that would land outside the folder. + ZipFile.ExtractToDirectory(package, staging, overwriteFiles: true); + WatchdogInstaller.MakeExecutable(Path.Combine(staging, Branding.AgentBinaryName)); + WatchdogInstaller.MakeExecutable(Path.Combine(staging, Branding.WatchdogBinaryName)); + + var files = new List(); + foreach (var path in Directory.EnumerateFiles(staging, "*", SearchOption.AllDirectories)) + { + using var stream = File.OpenRead(path); + files.Add(new WatchdogFile( + Path.GetRelativePath(staging, path).Replace('\\', '/'), + stream.Length, + Convert.ToHexStringLower(SHA256.HashData(stream)))); + } + + return files; + } + + /// Picked up once handover.json is gone; one the watchdog has not taken by the deadline fails the run. + private async Task WaitForPickupAsync(AgentUpgradeCommandPayload command, CancellationToken cancellationToken) + { + var deadline = context.UtcNow() + context.PickupDeadline; + while (File.Exists(Folders.Handover)) + { + if (context.UtcNow() >= deadline) + { + if (WatchdogFileStore.Read(Folders.Journal, WatchdogJsonContext.Default.WatchdogJournal)?.UpgradeId == command.UpgradeId) + { + return; + } + + WatchdogFileStore.TryDelete(Folders.Handover); + await FailAsync(command, AgentUpgradeReasons.Watchdog, + $"The watchdog did not pick the upgrade up within {context.PickupDeadline.TotalMinutes:0} minutes.", cancellationToken); + return; + } + + await context.Delay(context.PickupPollInterval, cancellationToken); + } + + logger.LogInformation("Upgrade {UpgradeId} picked up by the watchdog", command.UpgradeId); + } + + private Task FailAsync(AgentUpgradeCommandPayload command, string reason, string detail, CancellationToken cancellationToken) + { + logger.LogWarning("Upgrade {UpgradeId} failed ({Reason}): {Detail}", command.UpgradeId, reason, detail); + return PublishAsync(command, AgentUpgradeStates.Failed, reason, detail, cancellationToken); + } + + private async Task PublishAsync(AgentUpgradeCommandPayload command, string state, string? reason, string? detail, CancellationToken cancellationToken) + { + try + { + await events.PublishAsync(new AgentUpgradeEventPayload( + command.UpgradeId, context.ClientId, state, reason, detail, context.CurrentVersion, command.Version, null, context.UtcNow()), + cancellationToken); + } + catch (Exception exception) when (exception is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + // A dropped connection must not end the upgrade; the outcome is + // reported again by the version that runs afterwards. + logger.LogWarning(exception, "Upgrade {UpgradeId} event {State} could not be published", command.UpgradeId, state); + } + } + + private static async Task HashAsync(string path, CancellationToken cancellationToken) + { + await using var stream = File.OpenRead(path); + return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, cancellationToken)); + } + + private static string Megabytes(long bytes) => $"{bytes / 1024d / 1024d:0.0} MB"; + + private static void TryDelete(string path) + { + try + { + File.Delete(path); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + } + } + + private static void TryDeleteDirectory(string path) + { + try + { + if (Directory.Exists(path)) + { + Directory.Delete(path, recursive: true); + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + } + } +} diff --git a/src/Agent/Upgrade/UpgradeFolders.cs b/src/Agent/Upgrade/UpgradeFolders.cs new file mode 100644 index 0000000..5d1f937 --- /dev/null +++ b/src/Agent/Upgrade/UpgradeFolders.cs @@ -0,0 +1,70 @@ +using Shared.Contracts.Models; +using Shared.Infrastructure.Constants; + +namespace Agent.Upgrade; + +/// Where the agent and the watchdog meet (<data>/upgrade/) and where the agent is installed. +public sealed class UpgradeFolders(string dataDirectory, string installDirectory) +{ + /// The installed layout: the data folder and the running binary's own folder. + public static UpgradeFolders Installed { get; } = new(Branding.AgentProgramDataDirectory, AppContext.BaseDirectory); + + public string InstallDirectory { get; } = installDirectory; + + public string Root { get; } = Path.Combine(dataDirectory, WatchdogFiles.Folder); + + public string Downloads => Path.Combine(Root, WatchdogFiles.Downloads); + + public string Staging => Path.Combine(Root, WatchdogFiles.Staging); + + public string Handover => Path.Combine(Root, WatchdogFiles.Handover); + + public string Health => Path.Combine(Root, WatchdogFiles.Health); + + public string Journal => Path.Combine(Root, WatchdogFiles.Journal); + + public string Outcome => Path.Combine(Root, WatchdogFiles.Outcome); + + /// A hand-over, a swap or an outcome not yet reported: another upgrade must wait. + public bool UpgradePending => File.Exists(Handover) || File.Exists(Journal) || File.Exists(Outcome); + + /// + /// Keeps the newest download and the newest staged package, removes the rest. + /// Never while a hand-over or a swap is under way (the watchdog reads the staging then). + /// + public void Tidy() + { + if (File.Exists(Handover) || File.Exists(Journal)) + { + return; + } + + if (Directory.Exists(Downloads)) + { + foreach (var file in new DirectoryInfo(Downloads).GetFiles().OrderByDescending(f => f.LastWriteTimeUtc).Skip(1)) + { + TryDelete(() => file.Delete()); + } + } + + if (Directory.Exists(Staging)) + { + foreach (var folder in new DirectoryInfo(Staging).GetDirectories().OrderByDescending(d => d.LastWriteTimeUtc).Skip(1)) + { + TryDelete(() => folder.Delete(recursive: true)); + } + } + } + + private static void TryDelete(Action delete) + { + try + { + delete(); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // In use; the next tidy tries again. + } + } +} diff --git a/src/Agent/Upgrade/UpgradeOutcomeReporter.cs b/src/Agent/Upgrade/UpgradeOutcomeReporter.cs new file mode 100644 index 0000000..c07ac7b --- /dev/null +++ b/src/Agent/Upgrade/UpgradeOutcomeReporter.cs @@ -0,0 +1,108 @@ +using Microsoft.Extensions.Logging; +using Shared.Contracts.Messages; +using Shared.Contracts.Models; +using Shared.Contracts.Serialization; + +namespace Agent.Upgrade; + +/// +/// Reports the outcome the watchdog left (outcome.json) once the agent is +/// connected, then deletes it and tidies old downloads and staging. Whichever +/// version runs after a swap reports it: the new one after a commit (the outcome +/// appears after it connected, so this checks every few seconds), the previous +/// one after a rollback. +/// +public sealed class UpgradeOutcomeReporter( + UpgradeFolders folders, IUpgradeEvents events, Func connected, string clientId, ILogger logger) +{ + public static readonly TimeSpan CheckInterval = TimeSpan.FromSeconds(5); + + private bool tidied; + + public async Task RunAsync(CancellationToken cancellationToken) + { + while (!cancellationToken.IsCancellationRequested) + { + if (connected()) + { + await ReportPendingAsync(cancellationToken); + } + + try + { + await Task.Delay(CheckInterval, cancellationToken); + } + catch (OperationCanceledException) + { + break; + } + } + } + + /// Publishes and deletes a waiting outcome; true when one was reported. + public async Task ReportPendingAsync(CancellationToken cancellationToken) + { + var reported = false; + var outcome = WatchdogFileStore.Read(folders.Outcome, WatchdogJsonContext.Default.WatchdogOutcome); + if (outcome is not null) + { + try + { + await events.PublishAsync(ToEvent(outcome, clientId), cancellationToken); + } + catch (Exception exception) when (exception is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + // Kept for the next check. + logger.LogWarning(exception, "Upgrade outcome {UpgradeId} could not be published; retrying", outcome.UpgradeId); + return false; + } + + logger.LogInformation("Upgrade {UpgradeId} to {Version} reported: {Result} {Reason}", + outcome.UpgradeId, outcome.Version, outcome.Result, outcome.Reason); + WatchdogFileStore.TryDelete(folders.Outcome); + reported = true; + tidied = false; + } + else if (File.Exists(folders.Outcome) && !File.Exists(folders.Journal)) + { + // Unreadable, and no run that could still rewrite it: drop it. + logger.LogWarning("Upgrade outcome at {Path} does not read; it is removed", folders.Outcome); + WatchdogFileStore.TryDelete(folders.Outcome); + } + + if (!tidied) + { + folders.Tidy(); + tidied = true; + } + + return reported; + } + + public static AgentUpgradeEventPayload ToEvent(WatchdogOutcome outcome, string clientId) + { + var detail = outcome.Result switch + { + AgentUpgradeStates.Succeeded => $"Upgraded from {outcome.FromVersion} to {outcome.Version}.", + AgentUpgradeStates.RolledBack => outcome.Reason switch + { + AgentUpgradeReasons.HealthDeadline => $"{outcome.Version} did not report healthy in time; {outcome.FromVersion} was put back.", + AgentUpgradeReasons.Crashed => $"{outcome.Version} kept exiting; {outcome.FromVersion} was put back.", + AgentUpgradeReasons.Swap => $"The files of {outcome.Version} could not be swapped in; {outcome.FromVersion} was put back.", + _ => $"{outcome.FromVersion} was put back.", + }, + _ => outcome.Reason switch + { + AgentUpgradeReasons.Hash => "The staged package did not match its SHA-256; nothing was changed.", + AgentUpgradeReasons.Package => "The staged package was not usable; nothing was changed.", + AgentUpgradeReasons.Swap => "The previous version could not be put back whole.", + _ => "The watchdog could not apply the package; nothing was changed.", + }, + }; + + return new AgentUpgradeEventPayload(outcome.UpgradeId, clientId, outcome.Result, outcome.Reason, detail, + string.IsNullOrEmpty(outcome.FromVersion) ? null : outcome.FromVersion, + string.IsNullOrEmpty(outcome.Version) ? null : outcome.Version, + outcome.LastLog, outcome.FinishedUtc); + } +} diff --git a/src/Agent/Upgrade/WatchdogInstaller.cs b/src/Agent/Upgrade/WatchdogInstaller.cs new file mode 100644 index 0000000..207b680 --- /dev/null +++ b/src/Agent/Upgrade/WatchdogInstaller.cs @@ -0,0 +1,140 @@ +using System.Diagnostics; +using System.Text.Json; +using Microsoft.Extensions.Logging; +using Shared.Infrastructure.Constants; + +namespace Agent.Upgrade; + +/// Makes sure the watchdog is installed and running before an upgrade is handed to it. +public interface IWatchdogInstaller +{ + /// Null when the watchdog runs; otherwise why it could not be made to. + Task EnsureRunningAsync(string stagingDirectory, CancellationToken cancellationToken); +} + +/// +/// The watchdog binary beside the agent, driven through its own verbs +/// (status, install, start, remove): an install from +/// before the watchdog existed gets it from the staged package, so the first +/// upgrade it takes brings the watchdog along. +/// +public sealed class WatchdogInstaller(string installDirectory, ILogger logger) : IWatchdogInstaller +{ + private static readonly TimeSpan VerbTimeout = TimeSpan.FromSeconds(90); + + public string BinaryPath => Path.Combine(installDirectory, Branding.WatchdogBinaryName); + + public Task EnsureRunningAsync(string stagingDirectory, CancellationToken cancellationToken) => Task.Run(() => + { + try + { + if (!File.Exists(BinaryPath)) + { + var staged = Path.Combine(stagingDirectory, Branding.WatchdogBinaryName); + if (!File.Exists(staged)) + { + return "No watchdog is installed and the package brings none."; + } + + File.Copy(staged, BinaryPath, overwrite: false); + MakeExecutable(BinaryPath); + logger.LogInformation("Watchdog installed from the staged package to {Path}", BinaryPath); + } + + var (installed, state) = Status(BinaryPath); + if (!installed) + { + var (code, output) = RunVerb(BinaryPath, "install"); + if (code != 0) + { + return $"The watchdog service could not be registered ({Trim(output)})."; + } + + logger.LogInformation("Watchdog service registered"); + } + + if (!string.Equals(state, "Running", StringComparison.OrdinalIgnoreCase)) + { + var (code, output) = RunVerb(BinaryPath, "start"); + if (code != 0) + { + return $"The watchdog service could not be started ({Trim(output)})."; + } + } + + (_, state) = Status(BinaryPath); + return string.Equals(state, "Running", StringComparison.OrdinalIgnoreCase) + ? null + : $"The watchdog service is {state}, not running."; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException + or System.ComponentModel.Win32Exception or InvalidOperationException) + { + return $"The watchdog could not be set up ({exception.Message})."; + } + }, cancellationToken); + + /// The watchdog's status line: whether its service is registered, and its state. + public static (bool Installed, string State) Status(string binaryPath) + { + var (_, output) = RunVerb(binaryPath, "status"); + var line = output.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).FirstOrDefault(l => l.StartsWith('{')); + if (line is null) + { + return (false, "Unknown"); + } + + try + { + using var document = JsonDocument.Parse(line); + var root = document.RootElement; + return (root.TryGetProperty("installed", out var installed) && installed.ValueKind == JsonValueKind.True, + root.TryGetProperty("state", out var state) ? state.GetString() ?? "Unknown" : "Unknown"); + } + catch (JsonException) + { + return (false, "Unknown"); + } + } + + /// Runs one of the watchdog's verbs and returns its exit code and output. + public static (int ExitCode, string Output) RunVerb(string binaryPath, string verb) + { + MakeExecutable(binaryPath); + using var process = Process.Start(new ProcessStartInfo(binaryPath, verb) + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + WorkingDirectory = Path.GetDirectoryName(binaryPath)!, + }) ?? throw new InvalidOperationException($"{binaryPath} did not start"); + var output = process.StandardOutput.ReadToEndAsync(); + var error = process.StandardError.ReadToEndAsync(); + if (!process.WaitForExit(VerbTimeout)) + { + process.Kill(entireProcessTree: true); + return (-1, $"{verb} timed out"); + } + + return (process.ExitCode, output.GetAwaiter().GetResult() + error.GetAwaiter().GetResult()); + } + + /// rwxr-xr-x on linux/macOS: a zip made on Windows carries no file modes. + public static void MakeExecutable(string path) + { + if (!OperatingSystem.IsWindows() && File.Exists(path)) + { + File.SetUnixFileMode(path, + UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute + | UnixFileMode.GroupRead | UnixFileMode.GroupExecute + | UnixFileMode.OtherRead | UnixFileMode.OtherExecute); + } + } + + private static string Trim(string output) + { + var text = output.ReplaceLineEndings(" ").Trim(); + return text.Length <= 300 ? text : text[..300]; + } +} diff --git a/src/Backend/Api/DeviceEndpoints.cs b/src/Backend/Api/DeviceEndpoints.cs index 2027cce..80e4703 100644 --- a/src/Backend/Api/DeviceEndpoints.cs +++ b/src/Backend/Api/DeviceEndpoints.cs @@ -17,11 +17,13 @@ public static class DeviceEndpoints { app.MapGet(ApiRoutes.Devices, ListAsync).RequirePermission(Permissions.DevicesView); app.MapGet(ApiRoutes.Device, GetAsync).RequirePermission(Permissions.DevicesView); + app.MapGet(ApiRoutes.DeviceHistory, GetHistoryAsync).RequirePermission(Permissions.DevicesView); app.MapPost(ApiRoutes.DeviceInventory, RefreshInventoryAsync).RequirePermission(Permissions.DevicesManage); } private static async Task ListAsync( - AppDbContext db, DeviceScopeService scope, HttpContext context, CancellationToken cancellationToken) + AppDbContext db, Groups.DeviceGroupService groups, DeviceScopeService scope, HttpContext context, + CancellationToken cancellationToken) { var devices = await db.Devices.AsNoTracking() .OrderBy(d => d.Hostname) @@ -34,8 +36,31 @@ public static class DeviceEndpoints devices = devices.Where(d => allowed.Contains(d.ClientId)).ToList(); } + // Direct group memberships ride along so the console can draw the + // group tree's counts and filter by node without a call per group. + Dictionary>? groupIds = null; + if (await db.DeviceGroups.AnyAsync(cancellationToken)) + { + var membership = await groups.GetMembershipAsync(cancellationToken); + groupIds = new Dictionary>(StringComparer.Ordinal); + foreach (var group in membership.Groups) + { + foreach (var clientId in membership.Direct(group.Id)) + { + if (!groupIds.TryGetValue(clientId, out var list)) + { + groupIds[clientId] = list = []; + } + + list.Add(group.Id); + } + } + } + var now = DateTimeOffset.UtcNow; - return Results.Ok(devices.Select(d => ToDto(d, now)).ToList()); + return Results.Ok(devices + .Select(d => ToDto(d, now, groupIds is null ? null : groupIds.GetValueOrDefault(d.ClientId) ?? [])) + .ToList()); } private static async Task GetAsync( @@ -73,6 +98,33 @@ public static class DeviceEndpoints await groups.GetGroupsForDeviceAsync(clientId, cancellationToken))); } + /// The device's phase trail (enrolled, renamed, OS changed), newest first. + private static async Task GetHistoryAsync( + string clientId, int? limit, AppDbContext db, DeviceScopeService scope, + HttpContext context, CancellationToken cancellationToken) + { + if (!SubjectIdentifier.IsValid(clientId)) + { + return Results.BadRequest(); + } + + if (!await scope.IsAllowedAsync(context.User, clientId, cancellationToken) + || !await db.Devices.AnyAsync(d => d.ClientId == clientId, cancellationToken)) + { + return Results.NotFound(); + } + + var take = Math.Clamp(limit ?? 100, 1, 500); + var events = await db.AuditEvents.AsNoTracking() + .Where(e => e.ClientId == clientId && e.Category == Security.AuditCategories.Device) + .OrderByDescending(e => e.Id) + .Take(take) + .Select(e => new DeviceHistoryEventDto(e.Id, e.TimestampUtc, e.Action, e.Detail)) + .ToListAsync(cancellationToken); + + return Results.Ok(events); + } + private static async Task RefreshInventoryAsync( string clientId, AppDbContext db, @@ -103,7 +155,7 @@ public static class DeviceEndpoints : Results.Problem(statusCode: StatusCodes.Status503ServiceUnavailable, title: "Messaging unavailable."); } - internal static DeviceDto ToDto(DeviceEntity device, DateTimeOffset now) + internal static DeviceDto ToDto(DeviceEntity device, DateTimeOffset now, IReadOnlyList? groupIds = null) { IReadOnlyList addresses = []; if (!string.IsNullOrEmpty(device.IpAddressesJson)) @@ -125,6 +177,7 @@ public static class DeviceEndpoints EnrolledUtc: device.EnrolledUtc, Tags: Groups.DeviceGroupService.ParseTags(device.TagsJson), IsOrphaned: device.IsOrphaned, - PublicIp: device.PublicIp); + PublicIp: device.PublicIp, + GroupIds: groupIds); } } diff --git a/src/Backend/Api/DeviceHistory.cs b/src/Backend/Api/DeviceHistory.cs new file mode 100644 index 0000000..7add844 --- /dev/null +++ b/src/Backend/Api/DeviceHistory.cs @@ -0,0 +1,106 @@ +using Backend.Data; +using Backend.Security; + +namespace Backend.Api; + +/// +/// A device's phase trail. One device (same hardware client id) passes +/// through phases — Windows PE before imaging, then its installed OS, often +/// renamed on the way — and each transition is kept as a "device" audit event +/// on that client id, written only when a reported value actually changes. +/// The rows are added to the caller's context; the caller saves. +/// +public static class DeviceHistory +{ + public const string Enrolled = "device-enrolled"; + public const string Renamed = "device-renamed"; + public const string OsChanged = "device-os-changed"; + + /// The agent moved to a newer version ("2026.10.20.1200 → 2026.10.23.1400"). + public const string AgentUpgraded = "agent-upgraded"; + /// The agent went back to an earlier version: an operator's roll back, or the watchdog undoing an upgrade. + public const string AgentRolledBack = "agent-rolled-back"; + /// An upgrade failed and the agent stayed where it was (detail carries the reason). + public const string AgentUpgradeFailed = "agent-upgrade-failed"; + + /// + /// Applies a reported hostname and (when ) OS + /// to the device, recording a rename / OS change against the previous + /// values. A first sighting (nothing known before) records nothing. + /// True when the OS changed (a new phase). + /// + public static bool Apply( + AppDbContext db, + DeviceEntity device, + string hostname, + bool reportsOs = false, + string? osCaption = null, + string? osVersion = null) + { + var now = DateTimeOffset.UtcNow; + + // A case-only difference is the same name, not a rename. + if (!string.IsNullOrWhiteSpace(device.Hostname) + && !string.IsNullOrWhiteSpace(hostname) + && !string.Equals(device.Hostname, hostname, StringComparison.OrdinalIgnoreCase)) + { + Record(db, device.ClientId, Renamed, $"{device.Hostname} → {hostname}", now); + } + + device.Hostname = hostname; + + if (!reportsOs) + { + return false; + } + + var osChanged = IsSpecific(device.OsCaption) + && IsSpecific(osCaption) + && !string.Equals(device.OsCaption, osCaption, StringComparison.OrdinalIgnoreCase); + if (osChanged) + { + Record(db, device.ClientId, OsChanged, + $"{Describe(device.OsCaption, device.OsVersion)} → {Describe(osCaption, osVersion)}", now); + } + + device.OsCaption = osCaption; + device.OsVersion = osVersion; + return osChanged; + } + + /// Records an enrollment (first or repeat) with the name and OS it enrolled as. + public static void RecordEnrolled(AppDbContext db, DeviceEntity device) + => Record(db, device.ClientId, Enrolled, + $"{device.Hostname} · {Describe(device.OsCaption, device.OsVersion)}", DateTimeOffset.UtcNow); + + /// Records an agent upgrade outcome (one of the Agent* actions). + public static void RecordAgentUpgrade(AppDbContext db, string clientId, string action, string detail) + => Record(db, clientId, action, detail, DateTimeOffset.UtcNow); + + /// "Windows PE 10.0.26100"; just the caption when the version is unknown. + public static string Describe(string? caption, string? version) + { + var text = $"{caption?.Trim()} {version?.Trim()}".Trim(); + return text.Length > 0 ? text : "unknown OS"; + } + + /// + /// A real OS name rather than nothing, or the generic runtime string older + /// agents sent at enrollment ("Microsoft Windows NT 10.0…", "Unix 6.…") — + /// a transition to or from that is a change of spelling, not of OS. + /// + private static bool IsSpecific(string? caption) + => !string.IsNullOrWhiteSpace(caption) + && !caption.StartsWith("Microsoft Windows NT", StringComparison.OrdinalIgnoreCase) + && !caption.StartsWith("Unix ", StringComparison.OrdinalIgnoreCase); + + private static void Record(AppDbContext db, string clientId, string action, string detail, DateTimeOffset now) + => db.AuditEvents.Add(new AuditEventEntity + { + TimestampUtc = now, + Category = AuditCategories.Device, + Action = action, + ClientId = clientId, + Detail = detail, + }); +} diff --git a/src/Backend/Auth/AccessControlEndpoints.cs b/src/Backend/Auth/AccessControlEndpoints.cs index 5afff6c..53e3b38 100644 --- a/src/Backend/Auth/AccessControlEndpoints.cs +++ b/src/Backend/Auth/AccessControlEndpoints.cs @@ -8,9 +8,8 @@ using Shared.Contracts.Models; namespace Backend.Auth; /// -/// Users and roles administration. System roles are immutable; the last user -/// holding the wildcard permission can never be deleted or demoted, so an -/// admin always exists. +/// Roles administration. System roles are immutable. People get roles through +/// role bindings (AccessEndpoints); a role still bound cannot be deleted. /// public static class AccessControlEndpoints { @@ -23,18 +22,12 @@ public static class AccessControlEndpoints app.MapPost(ApiRoutes.AdminRoles, CreateRoleAsync).RequirePermission(Permissions.AccessManage); app.MapPut(ApiRoutes.AdminRole, UpdateRoleAsync).RequirePermission(Permissions.AccessManage); app.MapDelete(ApiRoutes.AdminRole, DeleteRoleAsync).RequirePermission(Permissions.AccessManage); - - app.MapGet(ApiRoutes.AdminUsers, ListUsersAsync).RequirePermission(Permissions.AccessManage); - app.MapPost(ApiRoutes.AdminUsers, CreateUserAsync).RequirePermission(Permissions.AccessManage); - app.MapPut(ApiRoutes.AdminUser, UpdateUserAsync).RequirePermission(Permissions.AccessManage); - app.MapDelete(ApiRoutes.AdminUser, DeleteUserAsync).RequirePermission(Permissions.AccessManage); } private static async Task ListRolesAsync(AppDbContext db, CancellationToken cancellationToken) { - var counts = await db.Users.AsNoTracking() - .Where(u => u.RoleId != null) - .GroupBy(u => u.RoleId!.Value) + var counts = await db.RoleBindings.AsNoTracking() + .GroupBy(b => b.RoleId) .Select(g => new { RoleId = g.Key, Count = g.Count() }) .ToDictionaryAsync(g => g.RoleId, g => g.Count, cancellationToken); @@ -102,21 +95,14 @@ public static class AccessControlEndpoints role.Name = request.Name.Trim(); Apply(role, request, context.User.Identity?.Name, DateTimeOffset.UtcNow); - // Users on this role keep a coherent coarse tier for display. - var tier = Permissions.Tier(request.Permissions.ToHashSet(StringComparer.OrdinalIgnoreCase)); - foreach (var user in await db.Users.Where(u => u.RoleId == id).ToListAsync(cancellationToken)) - { - user.Role = tier; - } - await db.SaveChangesAsync(cancellationToken); cache.Invalidate(); await audit.LogAsync(AuditCategories.Admin, "role-updated", context.User.Identity?.Name, detail: $"role={role.Name}", cancellationToken: cancellationToken); - var userCount = await db.Users.CountAsync(u => u.RoleId == id, cancellationToken); - return Results.Ok(ToDto(role, userCount)); + var bindingCount = await db.RoleBindings.CountAsync(b => b.RoleId == id, cancellationToken); + return Results.Ok(ToDto(role, bindingCount)); } private static async Task DeleteRoleAsync( @@ -134,9 +120,9 @@ public static class AccessControlEndpoints return Results.Conflict(new { error = "System roles cannot be deleted." }); } - if (await db.Users.AnyAsync(u => u.RoleId == id, cancellationToken)) + if (await db.RoleBindings.AnyAsync(b => b.RoleId == id, cancellationToken)) { - return Results.Conflict(new { error = "Reassign the users holding this role first." }); + return Results.Conflict(new { error = "Remove the role bindings that grant this role first." }); } db.Roles.Remove(role); @@ -149,164 +135,6 @@ public static class AccessControlEndpoints return Results.NoContent(); } - private static async Task ListUsersAsync(AppDbContext db, CancellationToken cancellationToken) - { - var roleNames = await db.Roles.AsNoTracking() - .ToDictionaryAsync(r => r.Id, r => r.Name, cancellationToken); - var users = await db.Users.AsNoTracking().OrderBy(u => u.Username).ToListAsync(cancellationToken); - - return Results.Ok(users.Select(u => new UserAccountDto( - u.Id, u.Username, u.DisplayName, u.AuthProvider, u.RoleId, - u.RoleId is { } rid ? roleNames.GetValueOrDefault(rid, u.Role.ToString()) : u.Role.ToString(), - u.CreatedUtc, u.LastLoginUtc)).ToList()); - } - - private static async Task CreateUserAsync( - CreateUserRequest request, AppDbContext db, UserService users, AuditService audit, - HttpContext context, CancellationToken cancellationToken) - { - var username = request.Username.Trim(); - if (username.Length is < 1 or > 64) - { - return Results.BadRequest(new { error = "Username must be 1-64 characters." }); - } - - if (request.Password.Length < 8) - { - return Results.BadRequest(new { error = "Password must be at least 8 characters." }); - } - - if (await db.Users.AnyAsync(u => u.Username == username, cancellationToken)) - { - return Results.Conflict(new { error = "A user with that name already exists." }); - } - - var role = await db.Roles.AsNoTracking() - .SingleOrDefaultAsync(r => r.Id == request.RoleId, cancellationToken); - if (role is null) - { - return Results.BadRequest(new { error = "Role not found." }); - } - - var user = new UserEntity - { - Id = Guid.NewGuid(), - Username = username, - DisplayName = string.IsNullOrWhiteSpace(request.DisplayName) ? username : request.DisplayName.Trim(), - Role = Permissions.Tier( - RoleCache.ParseStrings(role.PermissionsJson).ToHashSet(StringComparer.OrdinalIgnoreCase)), - RoleId = role.Id, - AuthProvider = AuthConstants.ProviderLocal, - CreatedUtc = DateTimeOffset.UtcNow, - }; - user.PasswordHash = users.HashPassword(user, request.Password); - db.Users.Add(user); - await db.SaveChangesAsync(cancellationToken); - - await audit.LogAsync(AuditCategories.Admin, "user-created", context.User.Identity?.Name, - detail: $"user={user.Username} role={role.Name}", cancellationToken: cancellationToken); - - return Results.Created(ApiRoutes.For.AdminUser(user.Id), new UserAccountDto( - user.Id, user.Username, user.DisplayName, user.AuthProvider, user.RoleId, role.Name, - user.CreatedUtc, user.LastLoginUtc)); - } - - private static async Task UpdateUserAsync( - Guid id, UpdateUserRequest request, AppDbContext db, UserService users, AuditService audit, - HttpContext context, CancellationToken cancellationToken) - { - var user = await db.Users.SingleOrDefaultAsync(u => u.Id == id, cancellationToken); - if (user is null) - { - return Results.NotFound(); - } - - RoleEntity? role = null; - if (request.RoleId is { } roleId && roleId != user.RoleId) - { - role = await db.Roles.AsNoTracking().SingleOrDefaultAsync(r => r.Id == roleId, cancellationToken); - if (role is null) - { - return Results.BadRequest(new { error = "Role not found." }); - } - - var demotingFromAdmin = await HoldsWildcardAsync(db, user, cancellationToken) - && !RoleCache.ParseStrings(role.PermissionsJson).Contains(Permissions.All); - if (demotingFromAdmin && await WildcardHolderCountAsync(db, cancellationToken) <= 1) - { - return Results.Conflict(new { error = "At least one user must keep a full-access role." }); - } - - user.RoleId = role.Id; - user.Role = Permissions.Tier( - RoleCache.ParseStrings(role.PermissionsJson).ToHashSet(StringComparer.OrdinalIgnoreCase)); - } - - if (request.DisplayName is not null) - { - user.DisplayName = string.IsNullOrWhiteSpace(request.DisplayName) - ? user.Username - : request.DisplayName.Trim(); - } - - if (!string.IsNullOrEmpty(request.Password)) - { - if (user.AuthProvider != AuthConstants.ProviderLocal) - { - return Results.BadRequest(new { error = "Passwords apply to local accounts only." }); - } - - if (request.Password.Length < 8) - { - return Results.BadRequest(new { error = "Password must be at least 8 characters." }); - } - - user.PasswordHash = users.HashPassword(user, request.Password); - } - - await db.SaveChangesAsync(cancellationToken); - - await audit.LogAsync(AuditCategories.Admin, "user-updated", context.User.Identity?.Name, - detail: $"user={user.Username}" + (role is not null ? $" role={role.Name}" : ""), - cancellationToken: cancellationToken); - - var roleName = user.RoleId is { } rid - ? await db.Roles.Where(r => r.Id == rid).Select(r => r.Name).SingleOrDefaultAsync(cancellationToken) - : null; - return Results.Ok(new UserAccountDto( - user.Id, user.Username, user.DisplayName, user.AuthProvider, user.RoleId, - roleName ?? user.Role.ToString(), user.CreatedUtc, user.LastLoginUtc)); - } - - private static async Task DeleteUserAsync( - Guid id, AppDbContext db, AuditService audit, HttpContext context, CancellationToken cancellationToken) - { - var user = await db.Users.SingleOrDefaultAsync(u => u.Id == id, cancellationToken); - if (user is null) - { - return Results.NotFound(); - } - - if (string.Equals(user.Username, context.User.Identity?.Name, StringComparison.OrdinalIgnoreCase)) - { - return Results.Conflict(new { error = "You cannot delete your own account." }); - } - - if (await HoldsWildcardAsync(db, user, cancellationToken) - && await WildcardHolderCountAsync(db, cancellationToken) <= 1) - { - return Results.Conflict(new { error = "At least one user must keep a full-access role." }); - } - - db.Users.Remove(user); - await db.SaveChangesAsync(cancellationToken); - - await audit.LogAsync(AuditCategories.Admin, "user-deleted", context.User.Identity?.Name, - detail: $"user={user.Username}", cancellationToken: cancellationToken); - - return Results.NoContent(); - } - private static IResult? Validate(SaveRoleRequest request) { if (string.IsNullOrWhiteSpace(request.Name) || request.Name.Trim().Length > 64) @@ -330,45 +158,15 @@ public static class AccessControlEndpoints role.Description = string.IsNullOrWhiteSpace(request.Description) ? null : request.Description.Trim(); role.PermissionsJson = JsonSerializer.Serialize( request.Permissions.Distinct(StringComparer.OrdinalIgnoreCase).ToList()); - role.OidcClaimValuesJson = JsonSerializer.Serialize( - (request.OidcClaimValues ?? []) - .Select(v => v.Trim()) - .Where(v => v.Length > 0) - .Distinct(StringComparer.OrdinalIgnoreCase) - .ToList()); role.DeviceScopeGroupIdsJson = JsonSerializer.Serialize( (request.DeviceScopeGroupIds ?? []).Distinct().ToList()); role.UpdatedUtc = now; role.UpdatedBy = actor; } - private static RoleDto ToDto(RoleEntity role, int userCount) => new( + private static RoleDto ToDto(RoleEntity role, int bindingCount) => new( role.Id, role.Name, role.Description, role.IsSystem, RoleCache.ParseStrings(role.PermissionsJson), - RoleCache.ParseStrings(role.OidcClaimValuesJson), RoleCache.ParseGuids(role.DeviceScopeGroupIdsJson), - userCount); - - private static async Task HoldsWildcardAsync( - AppDbContext db, UserEntity user, CancellationToken cancellationToken) - { - if (user.RoleId is not { } roleId) - { - return user.Role == UserRole.Admin; - } - - var role = await db.Roles.AsNoTracking().SingleOrDefaultAsync(r => r.Id == roleId, cancellationToken); - return role is not null && RoleCache.ParseStrings(role.PermissionsJson).Contains(Permissions.All); - } - - /// Users whose role grants everything (the pool of "last admins"). - private static async Task WildcardHolderCountAsync(AppDbContext db, CancellationToken cancellationToken) - { - var wildcardRoleIds = (await db.Roles.AsNoTracking().ToListAsync(cancellationToken)) - .Where(r => RoleCache.ParseStrings(r.PermissionsJson).Contains(Permissions.All)) - .Select(r => r.Id) - .ToList(); - return await db.Users.CountAsync( - u => u.RoleId != null && wildcardRoleIds.Contains(u.RoleId.Value), cancellationToken); - } + bindingCount); } diff --git a/src/Backend/Auth/AuthBootstrap.cs b/src/Backend/Auth/AuthBootstrap.cs deleted file mode 100644 index ebed666..0000000 --- a/src/Backend/Auth/AuthBootstrap.cs +++ /dev/null @@ -1,40 +0,0 @@ -using Shared.Contracts.Models; - -namespace Backend.Auth; - -/// -/// Reads the environment bootstrap defaults for authentication. Anything saved -/// from the Settings UI layers on top of these. -/// -public static class AuthBootstrap -{ - public static AuthSettings FromConfiguration(IConfiguration configuration) - { - var mode = configuration["AUTH_LOGIN_MODE"]; - - return new AuthSettings - { - OidcEnabled = configuration["OIDC_ENABLED"] == "1", - Authority = configuration["OIDC_AUTHORITY"], - ClientId = configuration["OIDC_CLIENT_ID"], - ClientSecret = configuration["OIDC_CLIENT_SECRET"], - ProviderName = configuration["OIDC_PROVIDER_NAME"], - Scopes = string.IsNullOrWhiteSpace(configuration["OIDC_SCOPES"]) - ? "openid profile email" - : configuration["OIDC_SCOPES"]!, - NameClaim = configuration["OIDC_NAME_CLAIM"], - RoleClaim = configuration["OIDC_ROLE_CLAIM"], - AdminRole = configuration["OIDC_ADMIN_ROLE"], - OperatorRole = configuration["OIDC_OPERATOR_ROLE"], - ViewerRole = configuration["OIDC_VIEWER_ROLE"], - DefaultRole = Enum.TryParse(configuration["OIDC_DEFAULT_ROLE"], true, out var role) - ? role - : UserRole.Operator, - RequireMappedRole = configuration["OIDC_REQUIRE_MAPPED_ROLE"] == "1", - LoginMode = Enum.TryParse(mode, true, out var parsed) ? parsed : LoginMode.Both, - - // Break-glass: ignores stored OIDC settings entirely. - ForceLocal = configuration["AUTH_FORCE_LOCAL"] == "1", - }; - } -} diff --git a/src/Backend/Auth/AuthConstants.cs b/src/Backend/Auth/AuthConstants.cs index 827070d..8e1ec80 100644 --- a/src/Backend/Auth/AuthConstants.cs +++ b/src/Backend/Auth/AuthConstants.cs @@ -1,20 +1,15 @@ -using Shared.Contracts.Models; - namespace Backend.Auth; -/// Auth scheme names, claim types and authorization policy names. +/// The session scheme and the claim types a signed-in request carries. public static class AuthConstants { - public const string CookieScheme = "ExecuteRCookie"; - public const string OidcScheme = "oidc"; + public const string SessionScheme = "ExecuteRSession"; - public const string RoleClaim = "role"; - /// Claim carrying the assigned RoleEntity id; the name claim is display/fallback. + /// One per role the caller's groups are bound to. public const string RoleIdClaim = "role_id"; public const string ProviderClaim = "auth_provider"; - - public const string ProviderLocal = "local"; - public const string ProviderOidc = "oidc"; - - public static string RoleName(UserRole role) => role.ToString(); + public const string DisplayNameClaim = "display_name"; + public const string SessionClaim = "session_id"; + public const string BreakGlassClaim = "break_glass"; + public const string PasswordChangeClaim = "password_change_required"; } diff --git a/src/Backend/Auth/AuthEndpoints.cs b/src/Backend/Auth/AuthEndpoints.cs deleted file mode 100644 index 37268d3..0000000 --- a/src/Backend/Auth/AuthEndpoints.cs +++ /dev/null @@ -1,183 +0,0 @@ -using System.Security.Claims; -using Backend.Proxy; -using Backend.Security; -using Microsoft.AspNetCore.Authentication; -using Microsoft.EntityFrameworkCore; -using Shared.Contracts.Api; -using Shared.Contracts.Models; - -namespace Backend.Auth; - -public static class AuthEndpoints -{ - public static void Map(WebApplication app) - { - app.MapPost(ApiRoutes.AuthLogin, LoginAsync) - .RequireRateLimiting(RateLimitPolicies.Auth) - .AllowAnonymous(); - - app.MapPost(ApiRoutes.AuthChangePassword, ChangePasswordAsync) - .RequireRateLimiting(RateLimitPolicies.Auth) - .AllowAnonymous(); - - app.MapPost(ApiRoutes.AuthLogout, (Delegate)LogoutAsync); - - app.MapGet(ApiRoutes.AuthSession, GetSessionAsync).AllowAnonymous(); - - // Challenge only when OIDC is actually usable, so a half-configured or - // disabled provider returns a clear error instead of a broken redirect. - app.MapGet(ApiRoutes.AuthOidcLogin, async ( - HttpContext context, AuthSettingsService settings, CancellationToken cancellationToken) => - { - var effective = await settings.GetEffectiveAsync(cancellationToken); - return effective.IsOidcUsable - ? Results.Challenge(new AuthenticationProperties { RedirectUri = "/" }, [AuthConstants.OidcScheme]) - : Results.NotFound(new { error = "Single sign-on is not configured." }); - }) - .AllowAnonymous(); - - // OIDC completes at CallbackPath (handler-owned); this route lets the - // SPA finalize the app cookie mapping if needed. - app.MapGet(ApiRoutes.AuthOidcCallback, () => Results.Redirect("/")).AllowAnonymous(); - } - - /// The built-in default; signing in with it forces a reset. - private const string DefaultAdminPassword = "admin"; - - private static async Task LoginAsync( - LoginRequest request, - UserService users, - RoleCache roles, - AuditService audit, - Backend.Data.AppDbContext db, - HttpContext context, - CancellationToken cancellationToken) - { - var remoteIp = ClientIp.EffectiveText(context); - - var user = await users.ValidateCredentialsAsync(request.Username, request.Password, cancellationToken); - if (user is null) - { - await audit.LogAsync(AuditCategories.Auth, "login-failed", - actor: request.Username, remoteIp: remoteIp, cancellationToken: cancellationToken); - return Results.Unauthorized(); - } - - // The reset presents only while the password is still the built-in - // default — a custom password chosen at install signs straight in, - // whatever the flag says (POST /api/auth/change-password completes - // the sign-in when the reset does apply). - if (user.MustChangePassword && request.Password == DefaultAdminPassword) - { - await audit.LogAsync(AuditCategories.Auth, "login-password-change-required", - actor: user.Username, remoteIp: remoteIp, cancellationToken: cancellationToken); - return Results.Ok(new SessionResponse( - false, user.Username, user.DisplayName, null, AuthConstants.ProviderLocal, - MustChangePassword: true)); - } - - if (user.MustChangePassword) - { - // Stale flag with a non-default password: clear it. - var tracked = await db.Users.SingleAsync(u => u.Id == user.Id, cancellationToken); - tracked.MustChangePassword = false; - await db.SaveChangesAsync(cancellationToken); - } - - var session = await IssueSessionAsync(user, roles, context, cancellationToken); - await audit.LogAsync(AuditCategories.Auth, "login-succeeded", - actor: user.Username, remoteIp: remoteIp, cancellationToken: cancellationToken); - return Results.Ok(session); - } - - private static async Task ChangePasswordAsync( - ChangePasswordRequest request, - Backend.Data.AppDbContext db, - UserService users, - RoleCache roles, - AuditService audit, - HttpContext context, - CancellationToken cancellationToken) - { - var remoteIp = ClientIp.EffectiveText(context); - - if (request.NewPassword.Length < 8) - { - return Results.BadRequest(new { error = "The new password must be at least 8 characters." }); - } - - var user = await users.ValidateCredentialsAsync( - request.Username, request.CurrentPassword, cancellationToken); - if (user is null) - { - await audit.LogAsync(AuditCategories.Auth, "password-change-failed", - actor: request.Username, remoteIp: remoteIp, cancellationToken: cancellationToken); - return Results.Unauthorized(); - } - - var tracked = await db.Users.SingleAsync(u => u.Id == user.Id, cancellationToken); - tracked.PasswordHash = users.HashPassword(tracked, request.NewPassword); - tracked.MustChangePassword = false; - await db.SaveChangesAsync(cancellationToken); - - var session = await IssueSessionAsync(tracked, roles, context, cancellationToken); - await audit.LogAsync(AuditCategories.Auth, "password-changed", - actor: tracked.Username, remoteIp: remoteIp, cancellationToken: cancellationToken); - return Results.Ok(session); - } - - /// Issues the cookie session + CSRF token and builds the response body. - private static async Task IssueSessionAsync( - Backend.Data.UserEntity user, RoleCache roles, HttpContext context, CancellationToken cancellationToken) - { - var role = user.RoleId is { } roleId ? await roles.FindByIdAsync(roleId, cancellationToken) : null; - role ??= await roles.FindByNameAsync(user.Role.ToString(), cancellationToken); - - var principal = AuthExtensions.BuildPrincipal( - user.Username, user.DisplayName, role?.Name ?? user.Role.ToString(), role?.Id, - AuthConstants.ProviderLocal); - await context.SignInAsync(AuthConstants.CookieScheme, principal); - CsrfProtection.IssueToken(context); - - var permissions = role?.Permissions.Order(StringComparer.Ordinal).ToList() ?? []; - return new SessionResponse( - true, user.Username, user.DisplayName, - role is null ? user.Role : Permissions.Tier(role.Permissions), - AuthConstants.ProviderLocal, role?.Name, permissions); - } - - private static async Task LogoutAsync(HttpContext context) - { - await context.SignOutAsync(AuthConstants.CookieScheme); - context.Response.Cookies.Delete(CsrfProtection.CookieName); - return Results.Ok(); - } - - private static async Task GetSessionAsync( - HttpContext context, PermissionHandler permissions, CancellationToken cancellationToken) - { - var user = context.User; - if (user.Identity?.IsAuthenticated != true) - { - return Results.Ok(new SessionResponse(false, null, null, null, null)); - } - - // Ensure a CSRF token exists for this authenticated session. - if (!context.Request.Cookies.ContainsKey(CsrfProtection.CookieName)) - { - CsrfProtection.IssueToken(context); - } - - var role = await permissions.ResolveRoleAsync(user, cancellationToken); - _ = Enum.TryParse(user.FindFirstValue(ClaimTypes.Role), out var claimTier); - - return Results.Ok(new SessionResponse( - true, - user.Identity.Name, - user.FindFirstValue("display_name") ?? user.Identity.Name, - role is null ? claimTier : Permissions.Tier(role.Permissions), - user.FindFirstValue(AuthConstants.ProviderClaim) ?? AuthConstants.ProviderLocal, - role?.Name ?? user.FindFirstValue(ClaimTypes.Role), - role?.Permissions.Order(StringComparer.Ordinal).ToList() ?? [])); - } -} diff --git a/src/Backend/Auth/AuthExtensions.cs b/src/Backend/Auth/AuthExtensions.cs deleted file mode 100644 index a61dd2b..0000000 --- a/src/Backend/Auth/AuthExtensions.cs +++ /dev/null @@ -1,220 +0,0 @@ -using System.Security.Claims; -using Microsoft.AspNetCore.Authentication.Cookies; -using Microsoft.AspNetCore.Authentication.OpenIdConnect; -using Microsoft.Extensions.Options; -using Microsoft.Extensions.Primitives; -using Microsoft.IdentityModel.Protocols.OpenIdConnect; -using Shared.Contracts.Models; - -namespace Backend.Auth; - -/// Wires cookie + OIDC authentication and role-based authorization. -public static class AuthExtensions -{ - public static void AddControlPlaneAuth(this WebApplicationBuilder builder, AuthSettings bootstrap) - { - builder.Services.AddSingleton(bootstrap); - builder.Services.AddSingleton(new AuthSettingsCache(bootstrap)); - builder.Services.AddScoped(); - - // OpenIdConnectOptions are rebuilt from the settings cache whenever the - // UI saves, so enabling or repointing OIDC needs no restart. - builder.Services.AddSingleton, ConfigureOidc>(); - builder.Services.AddSingleton, OidcChangeTokenSource>(); - - builder.Services - .AddAuthentication(options => - { - options.DefaultScheme = AuthConstants.CookieScheme; - // Challenges are issued explicitly by the login endpoints, so the - // default stays local; that keeps API 401s from bouncing to an IdP. - options.DefaultChallengeScheme = AuthConstants.CookieScheme; - }) - .AddCookie(AuthConstants.CookieScheme, options => - { - options.Cookie.Name = "executer_session"; - options.Cookie.HttpOnly = true; - options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; - options.Cookie.SameSite = SameSiteMode.Lax; - options.SlidingExpiration = true; - options.ExpireTimeSpan = TimeSpan.FromHours(12); - - options.Events.OnRedirectToLogin = context => - { - context.Response.StatusCode = StatusCodes.Status401Unauthorized; - return Task.CompletedTask; - }; - options.Events.OnRedirectToAccessDenied = context => - { - context.Response.StatusCode = StatusCodes.Status403Forbidden; - return Task.CompletedTask; - }; - }) - // Registered unconditionally; ConfigureOidc fills it from current - // settings and the login endpoint refuses to challenge when unusable. - .AddOpenIdConnect(AuthConstants.OidcScheme, _ => { }); - - // Permission-based authorization: endpoints demand "perm:{key}" and the - // handler resolves the caller's role (custom or system) from the cache. - builder.Services.AddAuthorization(); - builder.Services.AddSingleton(); - builder.Services.AddSingleton(); - builder.Services.AddSingleton(); - builder.Services.AddSingleton(sp => - sp.GetRequiredService()); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - } - - public static ClaimsPrincipal BuildPrincipal( - string username, string? displayName, string roleName, Guid? roleId, string provider) - { - var identity = new ClaimsIdentity(AuthConstants.CookieScheme, ClaimTypes.Name, ClaimTypes.Role); - identity.AddClaim(new Claim(ClaimTypes.Name, username)); - identity.AddClaim(new Claim(ClaimTypes.Role, roleName)); - if (roleId is { } id) - { - identity.AddClaim(new Claim(AuthConstants.RoleIdClaim, id.ToString("D"))); - } - - identity.AddClaim(new Claim(AuthConstants.ProviderClaim, provider)); - if (!string.IsNullOrWhiteSpace(displayName)) - { - identity.AddClaim(new Claim("display_name", displayName)); - } - - return new ClaimsPrincipal(identity); - } -} - -/// Builds OpenIdConnectOptions from the live settings cache. -internal sealed class ConfigureOidc(AuthSettingsCache cache, IServiceScopeFactory scopeFactory) - : IConfigureNamedOptions -{ - public void Configure(OpenIdConnectOptions options) => Configure(Options.DefaultName, options); - - public void Configure(string? name, OpenIdConnectOptions options) - { - if (name != AuthConstants.OidcScheme) - { - return; - } - - var settings = cache.Current; - - // The OIDC handler is an IAuthenticationRequestHandler, so the - // authentication middleware initializes it on every request — and - // RemoteAuthenticationOptions.Validate() throws on a null Authority or - // ClientId. Placeholders keep validation happy while OIDC is off; the - // login endpoint refuses to challenge unless the real settings are - // usable, so these are never contacted. - options.Authority = string.IsNullOrWhiteSpace(settings.Authority) - ? "https://oidc.invalid/not-configured" - : settings.Authority; - options.ClientId = string.IsNullOrWhiteSpace(settings.ClientId) - ? "oidc-not-configured" - : settings.ClientId; - options.ClientSecret = settings.ClientSecret; - options.ResponseType = OpenIdConnectResponseType.Code; - // Fixed by design — must match the IdP registration exactly. - options.CallbackPath = AuthSettingsService.CallbackPath; - options.SaveTokens = false; - options.GetClaimsFromUserInfoEndpoint = true; - options.SignInScheme = AuthConstants.CookieScheme; - options.UsePkce = true; - - options.Scope.Clear(); - foreach (var scope in settings.Scopes.Split(' ', StringSplitOptions.RemoveEmptyEntries)) - { - options.Scope.Add(scope); - } - - if (!string.IsNullOrWhiteSpace(settings.NameClaim)) - { - options.TokenValidationParameters.NameClaimType = settings.NameClaim; - } - - if (!string.IsNullOrWhiteSpace(settings.RoleClaim)) - { - options.TokenValidationParameters.RoleClaimType = settings.RoleClaim; - } - - options.Events.OnTokenValidated = async context => - { - var current = cache.Current; - if (context.Principal?.Identity is not ClaimsIdentity identity) - { - return; - } - - var principal = context.Principal; - var subject = principal.FindFirstValue(ClaimTypes.NameIdentifier) ?? principal.FindFirstValue("sub"); - if (string.IsNullOrEmpty(subject)) - { - context.Fail("OIDC token has no subject claim."); - return; - } - - var username = (current.NameClaim is not null ? principal.FindFirstValue(current.NameClaim) : null) - ?? principal.FindFirstValue(ClaimTypes.Name) - ?? principal.FindFirstValue("preferred_username") - ?? principal.FindFirstValue(ClaimTypes.Email) - ?? subject; - var displayName = principal.FindFirstValue("name") ?? username; - - // Map identity-provider groups/roles onto an application role: - // custom roles' claim values first, legacy tier mapping second. - var claimValues = string.IsNullOrWhiteSpace(current.RoleClaim) - ? [] - : principal.FindAll(current.RoleClaim).Select(c => c.Value).ToList(); - - using var scope = scopeFactory.CreateScope(); - var roleService = scope.ServiceProvider.GetRequiredService(); - var role = await roleService.MapOidcRoleAsync( - claimValues, current, context.HttpContext.RequestAborted); - if (role is null) - { - context.Fail( - "Your account is not a member of any group mapped to an ExecuteR role."); - return; - } - - var users = scope.ServiceProvider.GetRequiredService(); - await users.UpsertOidcUserAsync( - subject, username, displayName, role, context.HttpContext.RequestAborted); - - identity.AddClaim(new Claim(ClaimTypes.Role, role.Name)); - identity.AddClaim(new Claim(AuthConstants.RoleIdClaim, role.Id.ToString("D"))); - identity.AddClaim(new Claim(AuthConstants.ProviderClaim, AuthConstants.ProviderOidc)); - identity.AddClaim(new Claim("display_name", displayName)); - if (identity.FindFirst(ClaimTypes.Name) is null) - { - identity.AddClaim(new Claim(ClaimTypes.Name, username)); - } - }; - - // Never strand the operator on an IdP error page. - options.Events.OnRemoteFailure = context => - { - context.Response.Redirect( - "/login?error=" + Uri.EscapeDataString(context.Failure?.Message ?? "Single sign-on failed.")); - context.HandleResponse(); - return Task.CompletedTask; - }; - - options.Events.OnAccessDenied = context => - { - context.Response.Redirect("/login?error=" + Uri.EscapeDataString("Access denied by the identity provider.")); - context.HandleResponse(); - return Task.CompletedTask; - }; - } -} - -internal sealed class OidcChangeTokenSource(AuthSettingsCache cache) : IOptionsChangeTokenSource -{ - public string Name => AuthConstants.OidcScheme; - - public IChangeToken GetChangeToken() => cache.GetChangeToken(); -} diff --git a/src/Backend/Auth/AuthResetCli.cs b/src/Backend/Auth/AuthResetCli.cs index 4bfd894..48fceda 100644 --- a/src/Backend/Auth/AuthResetCli.cs +++ b/src/Backend/Auth/AuthResetCli.cs @@ -1,111 +1,79 @@ using Backend.Data; +using Backend.Security; using Microsoft.AspNetCore.DataProtection; -using Microsoft.AspNetCore.Identity; -using Microsoft.EntityFrameworkCore; -using Shared.Contracts.Models; namespace Backend.Auth; /// -/// Lockout recovery, runnable inside the container: +/// Lockout recovery, run on the server (or inside the container): /// -/// docker exec EXECUTER-API-00001 dotnet Backend.dll auth-reset -/// docker exec EXECUTER-API-00001 dotnet Backend.dll auth-reset --admin admin --password '<new>' +/// dotnet Backend.dll auth-reset Built-In sign-in on, OIDC redirect off, and a new one-time +/// password for the break-glass account (created if missing) +/// dotnet Backend.dll auth-reset --user jdoe a new one-time password for that built-in account instead +/// dotnet Backend.dll auth-reset --password 'secret' that password rather than a generated one (still changed at sign-in) /// -/// Disables OIDC and restores local sign-in, so an identity provider that is -/// down, misconfigured or has revoked the client can never permanently lock an -/// operator out. Optionally resets (or creates) a local admin. -/// -/// Setting AUTH_FORCE_LOCAL=1 achieves the same at startup without a database -/// write, which is the faster option if the container will not stay up. +/// So an identity provider that is down, misconfigured or has revoked the +/// client never locks anyone out for good. AUTH_FORCE_LOCAL=1 offers the +/// built-in form at startup without a database write. Exit codes: 0 done, +/// 1 failed, 2 no such account. /// public static class AuthResetCli { public static async Task RunAsync(string[] args, IConfiguration configuration) { - var username = ArgValue(args, "--admin"); + var userName = ArgValue(args, "--user") ?? ArgValue(args, "--admin"); var password = ArgValue(args, "--password"); - var databaseOptions = DatabaseOptions.FromConfiguration(configuration); - var services = new ServiceCollection(); services.AddLogging(b => b.AddSimpleConsole()); - services.AddDataProtection().PersistKeysToFileSystem( - new DirectoryInfo(DataProtectionPath(configuration))); - services.AddApplicationDatabase(databaseOptions); - services.AddScoped(); + services.AddSingleton(configuration); + services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(DataProtectionPath(configuration))); + services.AddApplicationDatabase(DatabaseOptions.FromConfiguration(configuration)); + services.AddScoped(); + services.AddSingleton(); await using var provider = services.BuildServiceProvider(); - using var scope = provider.CreateScope(); - var db = scope.ServiceProvider.GetRequiredService(); - - // Clear the OIDC flags directly: this must work even when the rest of - // the application cannot start. - foreach (var (key, value) in new[] - { - (AuthSettingsService.Keys.OidcEnabled, "0"), - (AuthSettingsService.Keys.LoginMode, nameof(LoginMode.LocalOnly)), - }) + try { - var row = await db.AppSettings.SingleOrDefaultAsync(s => s.Key == key); - if (row is null) + using (var scope = provider.CreateScope()) { - db.AppSettings.Add(new AppSettingEntity - { - Key = key, - Value = value, - IsSecret = false, - UpdatedUtc = DateTimeOffset.UtcNow, - UpdatedBy = "auth-reset", - }); + var db = scope.ServiceProvider.GetRequiredService(); + var row = await SettingsDocuments.LoadAsync(db, AuthenticationMethods.Key, CancellationToken.None); + var before = SettingsDocuments.Parse(row?.Value, AuthenticationMethods.Defaults); + SettingsDocuments.Stage(db, row, AuthenticationMethods.Key, row is null ? null : before, before with { BuiltIn = true, OidcRedirect = false }, + "auth-reset", always: true); + await db.SaveChangesAsync(); + Console.WriteLine("Built-In sign-in is on and OIDC redirect is off."); + } + + var (user, generated) = await provider.GetRequiredService().ResetAsync(userName, "auth-reset", CancellationToken.None); + if (!string.IsNullOrEmpty(password)) + { + using var scope = provider.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var tracked = await db.Users.FindAsync(user.Id); + tracked!.PasswordHash = PasswordHashing.Hash(password); + await db.SaveChangesAsync(); + Console.WriteLine($"{user.UserName}: password set; it must be changed at the next sign-in."); } else { - row.Value = value; - row.UpdatedUtc = DateTimeOffset.UtcNow; - row.UpdatedBy = "auth-reset"; + Console.WriteLine($"{user.UserName}: one-time password {generated} (change it at the next sign-in)."); } + + Console.WriteLine("No restart needed; sign in at /sign-in."); + return 0; } - - await db.SaveChangesAsync(); - Console.WriteLine("OIDC disabled; local sign-in restored."); - - if (!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password)) + catch (InvalidOperationException exception) { - var hasher = new PasswordHasher(); - var user = await db.Users.SingleOrDefaultAsync( - u => u.Username == username && u.AuthProvider == AuthConstants.ProviderLocal); - - if (user is null) - { - user = new UserEntity - { - Id = Guid.NewGuid(), - Username = username!, - DisplayName = username, - Role = UserRole.Admin, - AuthProvider = AuthConstants.ProviderLocal, - CreatedUtc = DateTimeOffset.UtcNow, - }; - db.Users.Add(user); - Console.WriteLine($"Local admin '{username}' created."); - } - else - { - user.Role = UserRole.Admin; - Console.WriteLine($"Local admin '{username}' password reset and role set to Admin."); - } - - user.PasswordHash = hasher.HashPassword(user, password!); - await db.SaveChangesAsync(); + Console.Error.WriteLine(exception.Message); + return 2; } - else + catch (Exception exception) { - Console.WriteLine("Tip: pass --admin --password to also reset a local admin."); + Console.Error.WriteLine($"auth-reset failed: {exception.Message}"); + return 1; } - - Console.WriteLine("Restart is not required; sign in at /login."); - return 0; } private static string DataProtectionPath(IConfiguration configuration) diff --git a/src/Backend/Auth/AuthSettings.cs b/src/Backend/Auth/AuthSettings.cs deleted file mode 100644 index 20e6f14..0000000 --- a/src/Backend/Auth/AuthSettings.cs +++ /dev/null @@ -1,95 +0,0 @@ -using Shared.Contracts.Models; - -namespace Backend.Auth; - -/// How the sign-in page behaves. -public enum LoginMode -{ - /// Local username/password only. - LocalOnly, - - /// Both local fields and an SSO button. - Both, - - /// SSO button only — local fields hidden (still reachable, see below). - OidcOnly, - - /// Redirect straight to the identity provider, no sign-in page. - OidcAutoRedirect, -} - -/// -/// Effective authentication configuration: values saved from the UI layered -/// over the environment bootstrap defaults. -/// -/// The OIDC redirect path is deliberately NOT operator-tunable at runtime — see -/// . -/// -public sealed record AuthSettings -{ - public bool OidcEnabled { get; init; } - public string? Authority { get; init; } - public string? ClientId { get; init; } - public string? ClientSecret { get; init; } - /// Friendly IdP name shown on the sign-in button (e.g. "Authentik", "Entra ID"). - public string? ProviderName { get; init; } - public string Scopes { get; init; } = "openid profile email"; - public string? NameClaim { get; init; } - public string? RoleClaim { get; init; } - - /// Claim values mapped to each application role. - public string? AdminRole { get; init; } - public string? OperatorRole { get; init; } - public string? ViewerRole { get; init; } - - /// Role granted to an authenticated user matching no mapping. - public UserRole DefaultRole { get; init; } = UserRole.Operator; - - /// Refuse sign-in entirely when no mapping matches. - public bool RequireMappedRole { get; init; } - - public LoginMode LoginMode { get; init; } = LoginMode.LocalOnly; - - /// - /// Emergency switch (env only, never settable from the UI): forces local - /// sign-in regardless of what is stored. See the auth-reset CLI. - /// - public bool ForceLocal { get; init; } - - public bool IsOidcUsable => OidcEnabled - && !ForceLocal - && !string.IsNullOrWhiteSpace(Authority) - && !string.IsNullOrWhiteSpace(ClientId); - - /// Local sign-in is never truly switched off — see the lockout note. - public bool ShowLocalFields => !IsOidcUsable || LoginMode is LoginMode.LocalOnly or LoginMode.Both; - - public bool AutoRedirect => IsOidcUsable && LoginMode == LoginMode.OidcAutoRedirect; - - /// Maps identity-provider claim values to an application role. - public UserRole? MapRole(IEnumerable claimValues) - { - var values = claimValues.ToList(); - - bool Matches(string? configured) => - !string.IsNullOrWhiteSpace(configured) - && values.Any(v => string.Equals(v, configured, StringComparison.OrdinalIgnoreCase)); - - if (Matches(AdminRole)) - { - return UserRole.Admin; - } - - if (Matches(OperatorRole)) - { - return UserRole.Operator; - } - - if (Matches(ViewerRole)) - { - return UserRole.Viewer; - } - - return RequireMappedRole ? null : DefaultRole; - } -} diff --git a/src/Backend/Auth/AuthSettingsEndpoints.cs b/src/Backend/Auth/AuthSettingsEndpoints.cs deleted file mode 100644 index 4f8df0b..0000000 --- a/src/Backend/Auth/AuthSettingsEndpoints.cs +++ /dev/null @@ -1,188 +0,0 @@ -using Backend.Security; -using Shared.Contracts.Api; - -using Backend.Auth; - -namespace Backend.Auth; - -/// -/// Identity-provider configuration from the UI, plus the anonymous config the -/// sign-in page needs to decide what to render. -/// -public static class AuthSettingsEndpoints -{ - public static void Map(WebApplication app) - { - app.MapGet(ApiRoutes.AuthConfig, GetPublicConfigAsync).AllowAnonymous(); - app.MapGet(ApiRoutes.AuthSettings, GetAsync).RequirePermission(Permissions.SettingsManage); - app.MapPut(ApiRoutes.AuthSettings, SaveAsync).RequirePermission(Permissions.SettingsManage); - app.MapPost(ApiRoutes.AuthSettingsTest, TestAsync).RequirePermission(Permissions.SettingsManage); - } - - /// Anonymous: only what the sign-in page needs to render itself. - private static async Task GetPublicConfigAsync( - AuthSettingsService settings, CancellationToken cancellationToken) - { - var effective = await settings.GetEffectiveAsync(cancellationToken); - return Results.Ok(new AuthConfigDto( - OidcAvailable: effective.IsOidcUsable, - ShowLocalFields: effective.ShowLocalFields, - AutoRedirect: effective.AutoRedirect, - // Friendly name (Authentik, Entra ID, …) when set; authority host - // is only the fallback. - ProviderName: effective.IsOidcUsable - ? (string.IsNullOrWhiteSpace(effective.ProviderName) - ? DescribeAuthority(effective.Authority) - : effective.ProviderName) - : null)); - } - - private static string? DescribeAuthority(string? authority) - => Uri.TryCreate(authority, UriKind.Absolute, out var uri) ? uri.Host : authority; - - private static async Task GetAsync( - AuthSettingsService settings, - HttpContext context, - IConfiguration configuration, - CancellationToken cancellationToken) - { - var effective = await settings.GetEffectiveAsync(cancellationToken); - return Results.Ok(ToDto(effective, context, configuration)); - } - - private static async Task SaveAsync( - AuthSettingsDto request, - AuthSettingsService settings, - AuditService audit, - HttpContext context, - IConfiguration configuration, - CancellationToken cancellationToken) - { - var current = await settings.GetEffectiveAsync(cancellationToken); - - if (!Enum.TryParse(request.LoginMode, true, out var mode)) - { - mode = LoginMode.LocalOnly; - } - - // Refuse to hide local sign-in behind an IdP that is not usable — - // that is exactly how an instance locks itself out. - var wouldBeUsable = request.OidcEnabled - && !string.IsNullOrWhiteSpace(request.Authority) - && !string.IsNullOrWhiteSpace(request.ClientId); - - if (!wouldBeUsable && mode is LoginMode.OidcOnly or LoginMode.OidcAutoRedirect) - { - return Results.BadRequest(new - { - error = "Configure and enable OIDC before choosing an SSO-only sign-in mode.", - }); - } - - var updated = current with - { - OidcEnabled = request.OidcEnabled, - Authority = request.Authority, - ClientId = request.ClientId, - ClientSecret = request.ClientSecret, - ProviderName = request.ProviderName, - Scopes = string.IsNullOrWhiteSpace(request.Scopes) ? "openid profile email" : request.Scopes, - NameClaim = request.NameClaim, - RoleClaim = request.RoleClaim, - AdminRole = request.AdminRole, - OperatorRole = request.OperatorRole, - ViewerRole = request.ViewerRole, - DefaultRole = request.DefaultRole, - RequireMappedRole = request.RequireMappedRole, - LoginMode = mode, - }; - - await settings.SaveAsync(updated, context.User.Identity?.Name, cancellationToken); - - await audit.LogAsync(AuditCategories.Auth, "oidc-settings-updated", context.User.Identity?.Name, - detail: $"enabled={request.OidcEnabled} mode={mode} authority={request.Authority}", - cancellationToken: cancellationToken); - - return Results.Ok(ToDto(await settings.GetEffectiveAsync(cancellationToken), context, configuration)); - } - - /// Fetches the discovery document so a bad authority is caught before saving. - private static async Task TestAsync( - AuthSettingsDto request, AuthSettingsService settings, CancellationToken cancellationToken) - { - var steps = new List(); - var authority = string.IsNullOrWhiteSpace(request.Authority) - ? (await settings.GetEffectiveAsync(cancellationToken)).Authority - : request.Authority; - - if (string.IsNullOrWhiteSpace(authority)) - { - steps.Add(new S3TestStepDto("authority", false, "Authority is required.")); - return Results.Ok(new AuthTestResultDto(false, steps)); - } - - var discovery = $"{authority.TrimEnd('/')}/.well-known/openid-configuration"; - try - { - using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(15) }; - using var response = await http.GetAsync(discovery, cancellationToken); - - if (!response.IsSuccessStatusCode) - { - steps.Add(new S3TestStepDto("discovery", false, - $"HTTP {(int)response.StatusCode} from {discovery}")); - return Results.Ok(new AuthTestResultDto(false, steps)); - } - - steps.Add(new S3TestStepDto("discovery", true, $"{discovery} reachable")); - - using var document = System.Text.Json.JsonDocument.Parse( - await response.Content.ReadAsStringAsync(cancellationToken)); - var root = document.RootElement; - - foreach (var required in new[] { "authorization_endpoint", "token_endpoint", "jwks_uri" }) - { - var present = root.TryGetProperty(required, out _); - steps.Add(new S3TestStepDto(required, present, present ? "present" : "missing from discovery")); - } - - var pkce = root.TryGetProperty("code_challenge_methods_supported", out var methods) - && methods.EnumerateArray().Any(m => m.GetString() == "S256"); - steps.Add(new S3TestStepDto("PKCE (S256)", pkce, - pkce ? "supported" : "not advertised — sign-in may fail")); - } - catch (Exception ex) - { - steps.Add(new S3TestStepDto("discovery", false, ex.Message)); - } - - return Results.Ok(new AuthTestResultDto(steps.All(s => s.Ok), steps)); - } - - private static AuthSettingsDto ToDto(AuthSettings s, HttpContext context, IConfiguration configuration) - { - // PUBLIC_SERVER_URL wins so the IdP registration matches what agents - // and browsers actually use, even when an admin browses via an - // internal hostname; trusted forwarded headers are the fallback. - var origin = Backend.Proxy.PublicUrl.Resolve(context, configuration); - return new AuthSettingsDto( - OidcEnabled: s.OidcEnabled, - Authority: s.Authority, - ClientId: s.ClientId, - ClientSecret: null, - ProviderName: s.ProviderName, - Scopes: s.Scopes, - NameClaim: s.NameClaim, - RoleClaim: s.RoleClaim, - AdminRole: s.AdminRole, - OperatorRole: s.OperatorRole, - ViewerRole: s.ViewerRole, - DefaultRole: s.DefaultRole, - RequireMappedRole: s.RequireMappedRole, - LoginMode: s.LoginMode.ToString(), - ClientSecretIsSet: !string.IsNullOrWhiteSpace(s.ClientSecret), - ForcedLocalByEnvironment: s.ForceLocal, - CallbackPath: AuthSettingsService.CallbackPath, - RedirectUri: origin + AuthSettingsService.CallbackPath); - } -} diff --git a/src/Backend/Auth/AuthSettingsService.cs b/src/Backend/Auth/AuthSettingsService.cs deleted file mode 100644 index fee2204..0000000 --- a/src/Backend/Auth/AuthSettingsService.cs +++ /dev/null @@ -1,144 +0,0 @@ -using Backend.Settings; -using Microsoft.Extensions.Primitives; -using Shared.Contracts.Models; - -namespace Backend.Auth; - -/// -/// Resolves effective auth settings (database over environment) and caches -/// them for the OIDC handler, which cannot take a scoped dependency. -/// -/// Saving triggers a change token so the handler is rebuilt without a restart. -/// -public sealed class AuthSettingsService(SettingsStore store, AuthSettings environmentDefaults, AuthSettingsCache cache) -{ - public const string Prefix = "auth."; - - /// - /// The OIDC redirect path is fixed. It must match what is registered at the - /// identity provider exactly, and letting it drift at runtime is a reliable - /// way to break sign-in with no obvious cause. It lives under /api/ so the - /// reverse proxy's existing API location covers it, and it is shown in the - /// UI so it can be copied into the IdP verbatim. - /// - public const string CallbackPath = Shared.Contracts.Api.ApiRoutes.AuthOidcCallback; - - public static class Keys - { - public const string OidcEnabled = Prefix + "oidcEnabled"; - public const string Authority = Prefix + "authority"; - public const string ClientId = Prefix + "clientId"; - public const string ClientSecret = Prefix + "clientSecret"; - public const string ProviderName = Prefix + "providerName"; - public const string Scopes = Prefix + "scopes"; - public const string NameClaim = Prefix + "nameClaim"; - public const string RoleClaim = Prefix + "roleClaim"; - public const string AdminRole = Prefix + "adminRole"; - public const string OperatorRole = Prefix + "operatorRole"; - public const string ViewerRole = Prefix + "viewerRole"; - public const string DefaultRole = Prefix + "defaultRole"; - public const string RequireMappedRole = Prefix + "requireMappedRole"; - public const string LoginMode = Prefix + "loginMode"; - } - - public async Task GetEffectiveAsync(CancellationToken cancellationToken) - { - var saved = await store.GetAllAsync(Prefix, cancellationToken); - var effective = Merge(saved, environmentDefaults); - cache.Set(effective); - return effective; - } - - internal static AuthSettings Merge(IReadOnlyDictionary saved, AuthSettings defaults) => new() - { - OidcEnabled = Bool(saved, Keys.OidcEnabled, defaults.OidcEnabled), - Authority = Str(saved, Keys.Authority, defaults.Authority), - ClientId = Str(saved, Keys.ClientId, defaults.ClientId), - ClientSecret = Str(saved, Keys.ClientSecret, defaults.ClientSecret), - ProviderName = Str(saved, Keys.ProviderName, defaults.ProviderName), - Scopes = Str(saved, Keys.Scopes, defaults.Scopes) ?? "openid profile email", - NameClaim = Str(saved, Keys.NameClaim, defaults.NameClaim), - RoleClaim = Str(saved, Keys.RoleClaim, defaults.RoleClaim), - AdminRole = Str(saved, Keys.AdminRole, defaults.AdminRole), - OperatorRole = Str(saved, Keys.OperatorRole, defaults.OperatorRole), - ViewerRole = Str(saved, Keys.ViewerRole, defaults.ViewerRole), - DefaultRole = Enum.TryParse(Str(saved, Keys.DefaultRole, null), true, out var role) - ? role - : defaults.DefaultRole, - RequireMappedRole = Bool(saved, Keys.RequireMappedRole, defaults.RequireMappedRole), - LoginMode = Enum.TryParse(Str(saved, Keys.LoginMode, null), true, out var mode) - ? mode - : defaults.LoginMode, - // Never persisted: environment-only escape hatch. - ForceLocal = defaults.ForceLocal, - }; - - public async Task SaveAsync(AuthSettings settings, string? actor, CancellationToken cancellationToken) - { - await store.SetAsync(Keys.OidcEnabled, settings.OidcEnabled ? "1" : "0", false, actor, cancellationToken); - await store.SetAsync(Keys.Authority, settings.Authority, false, actor, cancellationToken); - await store.SetAsync(Keys.ClientId, settings.ClientId, false, actor, cancellationToken); - await store.SetAsync(Keys.ProviderName, settings.ProviderName, false, actor, cancellationToken); - await store.SetAsync(Keys.Scopes, settings.Scopes, false, actor, cancellationToken); - await store.SetAsync(Keys.NameClaim, settings.NameClaim, false, actor, cancellationToken); - await store.SetAsync(Keys.RoleClaim, settings.RoleClaim, false, actor, cancellationToken); - await store.SetAsync(Keys.AdminRole, settings.AdminRole, false, actor, cancellationToken); - await store.SetAsync(Keys.OperatorRole, settings.OperatorRole, false, actor, cancellationToken); - await store.SetAsync(Keys.ViewerRole, settings.ViewerRole, false, actor, cancellationToken); - await store.SetAsync(Keys.DefaultRole, settings.DefaultRole.ToString(), false, actor, cancellationToken); - await store.SetAsync( - Keys.RequireMappedRole, settings.RequireMappedRole ? "1" : "0", false, actor, cancellationToken); - await store.SetAsync(Keys.LoginMode, settings.LoginMode.ToString(), false, actor, cancellationToken); - - // Null secret means "keep the stored one". - if (!string.IsNullOrWhiteSpace(settings.ClientSecret)) - { - await store.SetAsync(Keys.ClientSecret, settings.ClientSecret, true, actor, cancellationToken); - } - - // Rebuild the OIDC handler with the new values. - cache.Set(await GetEffectiveAsync(cancellationToken)); - cache.Reload(); - } - - /// Disables OIDC and restores local sign-in. Used by the auth-reset CLI. - public async Task ResetToLocalAsync(string? actor, CancellationToken cancellationToken) - { - await store.SetAsync(Keys.OidcEnabled, "0", false, actor, cancellationToken); - await store.SetAsync(Keys.LoginMode, nameof(LoginMode.LocalOnly), false, actor, cancellationToken); - cache.Set(await GetEffectiveAsync(cancellationToken)); - cache.Reload(); - } - - public AuthSettings EnvironmentDefaults => environmentDefaults; - - private static string? Str(IReadOnlyDictionary saved, string key, string? fallback) - => saved.TryGetValue(key, out var value) && !string.IsNullOrWhiteSpace(value) ? value : fallback; - - private static bool Bool(IReadOnlyDictionary saved, string key, bool fallback) - => saved.TryGetValue(key, out var value) ? value is "1" or "true" or "True" : fallback; -} - -/// -/// Holds the current effective auth settings for the OIDC handler (a singleton -/// that cannot resolve scoped services), and signals options reload on change. -/// -public sealed class AuthSettingsCache(AuthSettings initial) -{ - private AuthSettings current = initial; - private CancellationTokenSource changeSource = new(); - - public AuthSettings Current => Volatile.Read(ref current); - - public void Set(AuthSettings settings) => Volatile.Write(ref current, settings); - - public IChangeToken GetChangeToken() => new CancellationChangeToken(changeSource.Token); - - /// Invalidates cached OpenIdConnectOptions so they are rebuilt. - public void Reload() - { - var previous = Interlocked.Exchange(ref changeSource, new CancellationTokenSource()); - previous.Cancel(); - previous.Dispose(); - } -} diff --git a/src/Backend/Auth/CsrfProtection.cs b/src/Backend/Auth/CsrfProtection.cs deleted file mode 100644 index 2507a53..0000000 --- a/src/Backend/Auth/CsrfProtection.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System.Security.Cryptography; - -namespace Backend.Auth; - -/// -/// Double-submit-cookie CSRF protection for cookie-authenticated, -/// state-changing REST calls. The browser reads the non-HttpOnly -/// csrf_token cookie and echoes it in the X-CSRF-Token header; -/// the middleware requires the two to match. Bearer/enrollment endpoints and -/// safe methods are exempt. -/// -public static class CsrfProtection -{ - public const string CookieName = "csrf_token"; - public const string HeaderName = "X-CSRF-Token"; - - public static string IssueToken(HttpContext context) - { - var token = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); - context.Response.Cookies.Append(CookieName, token, new CookieOptions - { - HttpOnly = false, // Must be readable by the SPA. - SameSite = SameSiteMode.Lax, - Secure = context.Request.IsHttps, - Path = "/", - }); - return token; - } - - public static RequestDelegate Middleware(RequestDelegate next) => async context => - { - if (RequiresValidation(context)) - { - var cookie = context.Request.Cookies[CookieName]; - var header = context.Request.Headers[HeaderName].ToString(); - - if (string.IsNullOrEmpty(cookie) - || string.IsNullOrEmpty(header) - || !CryptographicOperations.FixedTimeEquals( - System.Text.Encoding.UTF8.GetBytes(cookie), - System.Text.Encoding.UTF8.GetBytes(header))) - { - context.Response.StatusCode = StatusCodes.Status403Forbidden; - await context.Response.WriteAsJsonAsync(new { error = "CSRF validation failed." }); - return; - } - } - - await next(context); - }; - - private static bool RequiresValidation(HttpContext context) - { - var method = context.Request.Method; - if (HttpMethods.IsGet(method) || HttpMethods.IsHead(method) || HttpMethods.IsOptions(method)) - { - return false; - } - - var path = context.Request.Path; - - // Enrollment endpoints are agent-to-server (no cookie); exempt. - if (path.StartsWithSegments("/api/enrollment")) - { - return false; - } - - // Login and the pre-session password change establish the session; - // both are protected by rate limiting + credentials. - if (path.StartsWithSegments("/api/auth/login") - || path.StartsWithSegments("/api/auth/change-password")) - { - return false; - } - - // Only guard cookie-authenticated API calls. - return path.StartsWithSegments("/api") - && context.Request.Cookies.ContainsKey("executer_session"); - } -} diff --git a/src/Backend/Auth/DeviceScopeService.cs b/src/Backend/Auth/DeviceScopeService.cs index 1eeb637..45618ac 100644 --- a/src/Backend/Auth/DeviceScopeService.cs +++ b/src/Backend/Auth/DeviceScopeService.cs @@ -6,9 +6,10 @@ using Microsoft.EntityFrameworkCore; namespace Backend.Auth; /// -/// Resolves the device scope of the caller's role: the set of client ids a -/// scoped role may see and target. Null means unrestricted. Resolved once per -/// request (this service is scoped). +/// Resolves the device scope of the caller's roles: the set of client ids +/// they may see and target. Null means unrestricted (a role, or the +/// break-glass account, reaches every device). Resolved once per request +/// (this service is scoped). /// public sealed class DeviceScopeService( AppDbContext db, PermissionHandler permissions, DeviceGroupService groups) @@ -24,15 +25,15 @@ public sealed class DeviceScopeService( return allowed; } - var role = await permissions.ResolveRoleAsync(user, cancellationToken); - if (role is null || role.ScopeGroupIds.Count == 0) + var access = await permissions.ResolveAccessAsync(user, cancellationToken); + if (access.ScopeGroupIds is not { } scopeIds) { resolved = true; return allowed = null; } var scopeGroups = await db.DeviceGroups.AsNoTracking() - .Where(g => role.ScopeGroupIds.Contains(g.Id)) + .Where(g => scopeIds.Contains(g.Id)) .ToListAsync(cancellationToken); var clientIds = new HashSet(StringComparer.Ordinal); diff --git a/src/Backend/Auth/PermissionAuthorization.cs b/src/Backend/Auth/PermissionAuthorization.cs index 32bb905..6b926bf 100644 --- a/src/Backend/Auth/PermissionAuthorization.cs +++ b/src/Backend/Auth/PermissionAuthorization.cs @@ -4,7 +4,7 @@ using Microsoft.Extensions.Options; namespace Backend.Auth; -/// Demands one permission key from the caller's effective role. +/// Demands one permission key from the roles the caller's groups are bound to. public sealed class PermissionRequirement(string permission) : IAuthorizationRequirement { public string Permission { get; } = permission; @@ -20,41 +20,29 @@ public sealed class PermissionHandler(RoleCache roles) : AuthorizationHandler - /// Prefers the role-id claim; falls back to the role-name claim, which also - /// resolves pre-upgrade cookies carrying the legacy Admin/Operator/Viewer - /// names onto the seeded system roles. + /// The caller's access from their claims: the bound roles (role-id claims, + /// re-read from the role cache so a role edit applies at once) and the + /// break-glass flag. /// - public async ValueTask ResolveRoleAsync( - ClaimsPrincipal user, CancellationToken cancellationToken) + public async ValueTask ResolveAccessAsync(ClaimsPrincipal user, CancellationToken cancellationToken) { - if (Guid.TryParse(user.FindFirstValue(AuthConstants.RoleIdClaim), out var roleId) - && await roles.FindByIdAsync(roleId, cancellationToken) is { } byId) + var bound = new List(); + foreach (var claim in user.FindAll(AuthConstants.RoleIdClaim)) { - return byId; - } - - foreach (var claim in user.FindAll(ClaimTypes.Role)) - { - if (await roles.FindByNameAsync(claim.Value, cancellationToken) is { } byName) + if (Guid.TryParse(claim.Value, out var id) && await roles.FindByIdAsync(id, cancellationToken) is { } role) { - return byName; + bound.Add(role); } } - return null; + return EffectiveAccess.Of(bound, user.HasClaim(AuthConstants.BreakGlassClaim, "true")); } } @@ -79,7 +67,7 @@ public sealed class PermissionPolicyProvider(IOptions opti return fallback.GetPolicyAsync(policyName); } - var policy = new AuthorizationPolicyBuilder(AuthConstants.CookieScheme) + var policy = new AuthorizationPolicyBuilder(AuthConstants.SessionScheme) .RequireAuthenticatedUser() .AddRequirements(new PermissionRequirement(policyName[Prefix.Length..])) .Build(); @@ -89,8 +77,13 @@ public sealed class PermissionPolicyProvider(IOptions opti public static class PermissionEndpointExtensions { - /// Requires an authenticated session whose role grants . + /// Requires a signed-in session whose roles grant . public static TBuilder RequirePermission(this TBuilder builder, string permission) where TBuilder : IEndpointConventionBuilder => builder.RequireAuthorization(PermissionPolicyProvider.Prefix + permission); + + /// Requires any signed-in session. + public static TBuilder RequireSignedIn(this TBuilder builder) + where TBuilder : IEndpointConventionBuilder + => builder.RequireAuthorization(new AuthorizationPolicyBuilder(AuthConstants.SessionScheme).RequireAuthenticatedUser().Build()); } diff --git a/src/Backend/Auth/RoleService.cs b/src/Backend/Auth/RoleService.cs index 45083a0..371de74 100644 --- a/src/Backend/Auth/RoleService.cs +++ b/src/Backend/Auth/RoleService.cs @@ -6,13 +6,12 @@ using Shared.Contracts.Models; namespace Backend.Auth; /// -/// Role lifecycle: seeds the immutable system roles, backfills pre-RBAC users -/// onto them, and maps OIDC sign-ins to a role (custom-role claim values first, -/// then the legacy Admin/Operator/Viewer mapping from auth settings). +/// Seeds the immutable system roles (Admin, Operator, Viewer). People reach +/// roles through role bindings on their groups. /// public sealed class RoleService(AppDbContext db, RoleCache cache) { - /// Idempotent: creates missing system roles and assigns roleless users. + /// Idempotent: creates the missing system roles. public async Task EnsureSystemRolesAsync(CancellationToken cancellationToken) { var existing = await db.Roles @@ -45,62 +44,10 @@ public sealed class RoleService(AppDbContext db, RoleCache cache) if (changed) { await db.SaveChangesAsync(cancellationToken); - } - - // Users created before custom roles carry only the legacy tier enum. - var roleless = await db.Users.Where(u => u.RoleId == null).ToListAsync(cancellationToken); - if (roleless.Count > 0) - { - var byName = await db.Roles - .Where(r => r.IsSystem) - .ToDictionaryAsync(r => r.Name, StringComparer.OrdinalIgnoreCase, cancellationToken); - foreach (var user in roleless) - { - user.RoleId = byName[user.Role.ToString()].Id; - } - - await db.SaveChangesAsync(cancellationToken); - } - - if (changed || roleless.Count > 0) - { cache.Invalidate(); } } - public Task FindSystemRoleAsync(UserRole tier, CancellationToken cancellationToken) - { - var name = tier.ToString(); - return db.Roles.SingleOrDefaultAsync(r => r.IsSystem && r.Name == name, cancellationToken); - } - - /// - /// Maps identity-provider claim values to a role. Custom roles whose - /// configured claim values match win (ties broken toward the most - /// privileged); otherwise the legacy settings mapping picks a system role. - /// Null means sign-in must be refused (RequireMappedRole with no match). - /// - public async Task MapOidcRoleAsync( - IReadOnlyCollection claimValues, AuthSettings settings, CancellationToken cancellationToken) - { - var values = claimValues.ToHashSet(StringComparer.OrdinalIgnoreCase); - - var candidates = (await db.Roles.AsNoTracking().ToListAsync(cancellationToken)) - .Where(r => RoleCache.ParseStrings(r.OidcClaimValuesJson).Any(values.Contains)) - .ToList(); - if (candidates.Count > 0) - { - return candidates - .OrderByDescending(r => RoleCache.ParseStrings(r.PermissionsJson).Contains(Permissions.All)) - .ThenByDescending(r => RoleCache.ParseStrings(r.PermissionsJson).Count) - .ThenBy(r => r.Name, StringComparer.OrdinalIgnoreCase) - .First(); - } - - var tier = settings.MapRole(claimValues); - return tier is null ? null : await FindSystemRoleAsync(tier.Value, cancellationToken); - } - private static IEnumerable<(string Name, string Description, IReadOnlyList Permissions)> SystemRoles() { yield return (nameof(UserRole.Admin), "Full access to everything, including future permissions.", diff --git a/src/Backend/Auth/SignIn/Access.cs b/src/Backend/Auth/SignIn/Access.cs new file mode 100644 index 0000000..986d3cf --- /dev/null +++ b/src/Backend/Auth/SignIn/Access.cs @@ -0,0 +1,182 @@ +using System.Text.Json.Serialization; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Serialization; + +namespace Backend.Auth; + +/// +/// The kinds of principal a role binding can name: groups from each sign-in +/// method. A binding is by SID, so it may also name +/// one local Windows account by its own SID. +/// +public static class PrincipalKinds +{ + public const string LocalGroup = "local-group"; + public const string WindowsGroup = "windows-group"; + public const string LdapGroup = "ldap-group"; + public const string OidcGroup = "oidc-group"; + + public static IReadOnlyList All { get; } = [LocalGroup, WindowsGroup, LdapGroup, OidcGroup]; + + /// + /// The form two ids of the same principal compare equal in: SIDs upper case, + /// distinguished names lower case without spaces around the separators, + /// GUIDs canonical. OIDC values are compared as the provider sends them. + /// + public static string Normalize(string kind, string id) + { + var value = id.Trim(); + return kind switch + { + WindowsGroup => value.ToUpperInvariant(), + LdapGroup => string.Join(',', value.Split(',').Select(part => string.Join('=', part.Split('=').Select(p => p.Trim())))).ToLowerInvariant(), + LocalGroup => Guid.TryParse(value, out var guid) ? guid.ToString("D") : value.ToLowerInvariant(), + _ => value, + }; + } +} + +/// A group a person is in, as resolved at sign-in; stored with the session. +public sealed record GroupRef(string Kind, string Id, string? Name) +{ + [JsonIgnore] + public string Key => $"{Kind}:{PrincipalKinds.Normalize(Kind, Id)}"; +} + +public static class GroupRefs +{ + public static string Serialize(IReadOnlyList groups) => JsonDefaults.Serialize(groups); + + public static IReadOnlyList Parse(string? json) + { + if (string.IsNullOrEmpty(json)) + { + return []; + } + + try + { + return JsonDefaults.Deserialize>(json) ?? []; + } + catch (System.Text.Json.JsonException) + { + return []; + } + } + + /// A built-in account's own groups, read from this server. + public static async Task> LocalAsync(AppDbContext db, Guid userId, CancellationToken cancellationToken) + { + var groups = await db.LocalGroupMembers.Where(m => m.UserId == userId) + .Join(db.LocalGroups, m => m.GroupId, g => g.Id, (_, g) => new { g.Id, g.Name }) + .ToListAsync(cancellationToken); + return groups.ConvertAll(g => new GroupRef(PrincipalKinds.LocalGroup, g.Id.ToString("D"), g.Name)); + } +} + +/// One role and the binding that gave it. +public sealed record Grant(Guid RoleId, string RoleName, Guid BindingId, string PrincipalKind, string PrincipalId, string? PrincipalName); + +/// +/// What a caller may do: the roles their groups are bound to, the union of +/// those roles' permissions, and the union of their device scopes (null: some +/// role reaches every device). The break-glass account holds everything. +/// +public sealed class EffectiveAccess +{ + public static EffectiveAccess None { get; } = new([], [], new HashSet(), []); + + public EffectiveAccess(IReadOnlyList roles, IReadOnlyList grants, IReadOnlySet permissions, + IReadOnlyList? scopeGroupIds, bool breakGlass = false) + { + Roles = roles; + Grants = grants; + Permissions = permissions; + ScopeGroupIds = scopeGroupIds; + BreakGlass = breakGlass; + } + + public IReadOnlyList Roles { get; } + public IReadOnlyList Grants { get; } + public IReadOnlySet Permissions { get; } + + /// Device groups the caller is limited to; null reaches every device. + public IReadOnlyList? ScopeGroupIds { get; } + + public bool BreakGlass { get; } + + public bool Any => BreakGlass || Permissions.Count > 0; + + public bool Has(string permission) => BreakGlass || Permissions.Contains(Auth.Permissions.All) || Permissions.Contains(permission); + + public static EffectiveAccess FullAccess(IReadOnlyList roles) => + new(roles, [], new HashSet([Auth.Permissions.All], StringComparer.OrdinalIgnoreCase), null, breakGlass: true); + + /// Access from roles alone (claims on a request), without the bindings that gave them. + public static EffectiveAccess Of(IReadOnlyList roles, bool breakGlass) + { + if (breakGlass) + { + return FullAccess(roles); + } + + var permissions = roles.SelectMany(r => r.Permissions).ToHashSet(StringComparer.OrdinalIgnoreCase); + // One role that reaches every device lifts the limit; otherwise the scopes add up. + var scoped = roles.Count > 0 && roles.All(r => r.ScopeGroupIds.Count > 0); + return new EffectiveAccess(roles, [], permissions, scoped ? [.. roles.SelectMany(r => r.ScopeGroupIds).Distinct()] : null); + } +} + +/// +/// Turns a caller's groups into roles through the role bindings. Bindings are a +/// small table read through a short cache, so an edit on any node applies +/// everywhere within , and at once on the node that +/// made it. +/// +public sealed class AccessResolver(IServiceScopeFactory scopes, RoleCache roles) +{ + public static readonly TimeSpan CacheLifetime = TimeSpan.FromSeconds(5); + + private volatile CachedBindings? cached; + + public async ValueTask ResolveAsync(IEnumerable principals, bool breakGlass, CancellationToken cancellationToken) + { + var keys = principals.Select(p => p.Key).ToHashSet(StringComparer.Ordinal); + var grants = new List(); + var bound = new Dictionary(); + foreach (var binding in await BindingsAsync(cancellationToken)) + { + if (!keys.Contains($"{binding.PrincipalKind}:{PrincipalKinds.Normalize(binding.PrincipalKind, binding.PrincipalId)}") + || await roles.FindByIdAsync(binding.RoleId, cancellationToken) is not { } role) + { + continue; + } + + bound[role.Id] = role; + grants.Add(new Grant(role.Id, role.Name, binding.Id, binding.PrincipalKind, binding.PrincipalId, binding.PrincipalName)); + } + + var access = EffectiveAccess.Of([.. bound.Values], breakGlass); + return new EffectiveAccess(access.Roles, grants, access.Permissions, access.ScopeGroupIds, access.BreakGlass); + } + + public async ValueTask> BindingsAsync(CancellationToken cancellationToken) + { + var now = DateTimeOffset.UtcNow; + if (cached is { } current && now < current.Expires) + { + return current.Bindings; + } + + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var bindings = await db.RoleBindings.AsNoTracking().ToListAsync(cancellationToken); + cached = new CachedBindings(bindings, now + CacheLifetime); + return bindings; + } + + public void Invalidate() => cached = null; + + private sealed record CachedBindings(IReadOnlyList Bindings, DateTimeOffset Expires); +} diff --git a/src/Backend/Auth/SignIn/AccessEndpoints.cs b/src/Backend/Auth/SignIn/AccessEndpoints.cs new file mode 100644 index 0000000..7e509d4 --- /dev/null +++ b/src/Backend/Auth/SignIn/AccessEndpoints.cs @@ -0,0 +1,591 @@ +using Backend.Data; +using Backend.Security; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Api; + +namespace Backend.Auth; + +/// +/// A person or built-in account. are a built-in +/// account's own groups; , and +/// are a Windows account's, read at its latest sign-in. +/// +public sealed record UserView(string Id, string Kind, string UserName, string? DisplayName, string? Email, bool Enabled, bool BreakGlass, + bool PasswordChangeRequired, DateTimeOffset CreatedUtc, DateTimeOffset? LastSignInUtc, IReadOnlyList LocalGroups, string? Description, + string? Sid, IReadOnlyList WindowsGroups); + +public sealed record UserCreate(string? UserName, string? DisplayName, string? Email, string? Password, bool? GeneratePassword, IReadOnlyList? LocalGroupIds); + +/// The created account, and its generated password when one was asked for: shown in this answer only. +public sealed record UserCreated(UserView User, string? Password); + +public sealed record UserUpdate(string? DisplayName, string? Email, bool? Enabled, IReadOnlyList? LocalGroupIds); + +public sealed record PasswordReset(string? Password, bool? Generate); + +public sealed record PasswordResetResult(string? Password, int SessionsEnded); + +public sealed record GrantView(string RoleId, string RoleName, string BindingId, string PrincipalKind, string PrincipalId, string? PrincipalName); + +/// Effective access with its provenance. For a directory person, the groups are those of their latest session. +public sealed record AccessView(bool BreakGlass, IReadOnlyList Groups, IReadOnlyList Grants, IReadOnlyList Permissions, + IReadOnlyList? DeviceScopeGroupIds); + +public sealed record LocalGroupView(string Id, string Name, string? Description, int MemberCount, IReadOnlyList Members, + DateTimeOffset CreatedUtc, IReadOnlyList Roles); + +public sealed record GroupMemberView(string Id, string UserName, string? DisplayName); + +public sealed record LocalGroupInput(string? Name, string? Description, IReadOnlyList? MemberIds); + +public sealed record RoleBindingView(string Id, string RoleId, string RoleName, string PrincipalKind, string PrincipalId, string? PrincipalName, + DateTimeOffset CreatedUtc, string? CreatedBy); + +public sealed record RoleBindingInput(string? RoleId, string? PrincipalKind, string? PrincipalId, string? PrincipalName); + +/// Users, built-in groups and role bindings (Access, and each sign-in method's bindings card). +public static class AccessEndpoints +{ + public static void Map(WebApplication app) + { + var manage = Permissions.AccessManage; + app.MapGet(ApiRoutes.AdminUsers, ListUsersAsync).RequirePermission(manage); + app.MapPost(ApiRoutes.AdminUsers, CreateUserAsync).RequirePermission(manage); + app.MapGet(ApiRoutes.AdminUser, async (string id, AppDbContext db, HttpContext context) => + { + var user = await FindUserAsync(db, id, context.RequestAborted); + return Results.Ok(View(user, await GroupsOfAsync(db, [user.Id], context.RequestAborted))); + }).RequirePermission(manage); + app.MapPut(ApiRoutes.AdminUser, UpdateUserAsync).RequirePermission(manage); + app.MapDelete(ApiRoutes.AdminUser, DeleteUserAsync).RequirePermission(manage); + app.MapPost(ApiRoutes.AdminUserPassword, ResetPasswordAsync).RequirePermission(manage); + app.MapGet(ApiRoutes.AdminUserAccess, UserAccessAsync).RequirePermission(manage); + + app.MapGet(ApiRoutes.AdminLocalGroups, ListGroupsAsync).RequirePermission(manage); + app.MapPost(ApiRoutes.AdminLocalGroups, (LocalGroupInput input, AppDbContext db, AccessResolver access, AuditService audit, HttpContext context) => + SaveGroupAsync(null, input, db, access, audit, context)).RequirePermission(manage); + app.MapPut(ApiRoutes.AdminLocalGroup, (string id, LocalGroupInput input, AppDbContext db, AccessResolver access, AuditService audit, HttpContext context) => + SaveGroupAsync(id, input, db, access, audit, context)).RequirePermission(manage); + app.MapDelete(ApiRoutes.AdminLocalGroup, DeleteGroupAsync).RequirePermission(manage); + + app.MapGet(ApiRoutes.AdminRoleBindings, ListBindingsAsync).RequirePermission(manage); + app.MapPost(ApiRoutes.AdminRoleBindings, CreateBindingAsync).RequirePermission(manage); + app.MapDelete(ApiRoutes.AdminRoleBinding, DeleteBindingAsync).RequirePermission(manage); + } + + // ── Users ───────────────────────────────────────────────────────────── + + private static async Task ListUsersAsync(AppDbContext db, string? kind, CancellationToken cancellationToken) + { + var source = db.Users.AsNoTracking(); + if (!string.IsNullOrWhiteSpace(kind)) + { + source = source.Where(u => u.Kind == kind); + } + + var users = await source.OrderBy(u => u.UserName).ToListAsync(cancellationToken); + var groups = await GroupsOfAsync(db, [.. users.Select(u => u.Id)], cancellationToken); + return Results.Ok(users.Select(u => View(u, groups)).ToList()); + } + + private static async Task CreateUserAsync(UserCreate input, AppDbContext db, AuditService audit, HttpContext context, CancellationToken cancellationToken) + { + var errors = new Dictionary(); + var userName = input.UserName?.Trim() ?? string.Empty; + if (userName.Length is 0 or > 128 || userName.Any(c => char.IsWhiteSpace(c) || char.IsControl(c) || c is '\\' or '/')) + { + errors["userName"] = ["Enter a user name of up to 128 characters, without spaces or slashes."]; + } + + var generate = input.GeneratePassword == true || string.IsNullOrEmpty(input.Password); + var password = generate ? PasswordHashing.Generate() : input.Password!; + if (!generate) + { + foreach (var (field, messages) in SignInService.PasswordProblems(password, userName, "password")) + { + errors[field] = messages; + } + } + + var groups = await ResolveGroupsAsync(db, input.LocalGroupIds, "localGroupIds", errors, cancellationToken); + if (errors.Count > 0) + { + throw AuthProblemException.InvalidFields(errors); + } + + var lowered = userName.ToLowerInvariant(); + if (await db.Users.AnyAsync(u => u.Kind == SignInProviders.Local && u.UserName.ToLower() == lowered, cancellationToken)) + { + throw new AuthProblemException(AuthProblems.Conflict, $"There is already a built-in account named {userName}."); + } + + var now = DateTimeOffset.UtcNow; + var user = new UserEntity + { + Id = Guid.NewGuid(), + Kind = SignInProviders.Local, + UserName = userName, + DisplayName = Clean(input.DisplayName), + Email = Clean(input.Email), + PasswordHash = PasswordHashing.Hash(password), + Enabled = true, + MustChangePassword = true, + CreatedUtc = now, + UpdatedUtc = now, + }; + db.Users.Add(user); + db.LocalGroupMembers.AddRange(groups.Select(g => new LocalGroupMemberEntity { GroupId = g.Id, UserId = user.Id })); + await db.SaveChangesAsync(cancellationToken); + await audit.LogAsync(AuditCategories.Admin, "auth.user.create", context.User.Identity?.Name, + detail: $"user={user.UserName} groups={string.Join(",", groups.Select(g => g.Name))}", cancellationToken: cancellationToken); + + var view = View(user, [.. groups.Select(g => new GroupView(PrincipalKinds.LocalGroup, g.Id.ToString("D"), g.Name))]); + return Results.Created(ApiRoutes.AdminUser.Replace("{id}", user.Id.ToString("D"), StringComparison.Ordinal), new UserCreated(view, generate ? password : null)); + } + + private static async Task UpdateUserAsync(string id, UserUpdate input, AppDbContext db, SessionStore sessions, AuditService audit, + HttpContext context, CancellationToken cancellationToken) + { + var user = await FindUserAsync(db, id, cancellationToken, tracking: true); + var errors = new Dictionary(); + var groups = input.LocalGroupIds is null ? null : await ResolveGroupsAsync(db, input.LocalGroupIds, "localGroupIds", errors, cancellationToken); + if (groups is not null && user.Kind != SignInProviders.Local) + { + errors["localGroupIds"] = ["Only built-in accounts join built-in groups; directory people are in their directory's groups."]; + } + + if (input.Enabled == false && user.IsBreakGlass) + { + errors["enabled"] = ["The break-glass account cannot be turned off."]; + } + + if (input.Enabled == false && context.Caller()?.UserId == user.Id) + { + errors["enabled"] = ["You cannot turn off the account you are signed in with."]; + } + + if (errors.Count > 0) + { + throw AuthProblemException.InvalidFields(errors); + } + + user.DisplayName = input.DisplayName is null ? user.DisplayName : Clean(input.DisplayName); + user.Email = input.Email is null ? user.Email : Clean(input.Email); + user.Enabled = input.Enabled ?? user.Enabled; + user.UpdatedUtc = DateTimeOffset.UtcNow; + if (groups is not null) + { + await db.LocalGroupMembers.Where(m => m.UserId == user.Id).ExecuteDeleteAsync(cancellationToken); + db.LocalGroupMembers.AddRange(groups.Select(g => new LocalGroupMemberEntity { GroupId = g.Id, UserId = user.Id })); + } + + await db.SaveChangesAsync(cancellationToken); + if (!user.Enabled) + { + await sessions.RevokeAllAsync(user.Id, null, cancellationToken); + } + + await audit.LogAsync(AuditCategories.Admin, "auth.user.update", context.User.Identity?.Name, + detail: $"user={user.UserName} enabled={user.Enabled}{(groups is null ? string.Empty : $" groups={string.Join(",", groups.Select(g => g.Name))}")}", + cancellationToken: cancellationToken); + return Results.Ok(View(user, await GroupsOfAsync(db, [user.Id], cancellationToken))); + } + + private static async Task ResetPasswordAsync(string id, PasswordReset input, AppDbContext db, SessionStore sessions, AuditService audit, + HttpContext context, CancellationToken cancellationToken) + { + var user = await FindUserAsync(db, id, cancellationToken, tracking: true); + if (user.Kind != SignInProviders.Local) + { + throw new AuthProblemException(AuthProblems.Conflict, "Only a built-in account has a password here."); + } + + var generate = input.Generate == true || string.IsNullOrEmpty(input.Password); + var password = generate ? PasswordHashing.Generate() : input.Password!; + if (!generate && SignInService.PasswordProblems(password, user.UserName, "password") is { Count: > 0 } errors) + { + throw AuthProblemException.InvalidFields(errors); + } + + var now = DateTimeOffset.UtcNow; + user.PasswordHash = PasswordHashing.Hash(password); + user.MustChangePassword = true; + user.PasswordChangedUtc = now; + user.UpdatedUtc = now; + await db.SaveChangesAsync(cancellationToken); + var ended = await sessions.RevokeAllAsync(user.Id, context.Caller()?.SessionId, cancellationToken); + await audit.LogAsync(AuditCategories.Admin, "auth.user.password.reset", context.User.Identity?.Name, detail: $"user={user.UserName}", + cancellationToken: cancellationToken); + return Results.Ok(new PasswordResetResult(generate ? password : null, ended)); + } + + private static async Task DeleteUserAsync(string id, AppDbContext db, AuditService audit, HttpContext context, CancellationToken cancellationToken) + { + var user = await FindUserAsync(db, id, cancellationToken, tracking: true); + if (user.IsBreakGlass) + { + throw new AuthProblemException(AuthProblems.Conflict, "The break-glass account is kept for recovery and cannot be removed."); + } + + if (context.Caller()?.UserId == user.Id) + { + throw new AuthProblemException(AuthProblems.Conflict, "You cannot remove the account you are signed in with."); + } + + db.Users.Remove(user); + await db.SaveChangesAsync(cancellationToken); + await audit.LogAsync(AuditCategories.Admin, "auth.user.delete", context.User.Identity?.Name, detail: $"user={user.UserName} kind={user.Kind}", + cancellationToken: cancellationToken); + return Results.NoContent(); + } + + private static async Task UserAccessAsync(string id, AppDbContext db, AccessResolver access, CancellationToken cancellationToken) + { + var user = await FindUserAsync(db, id, cancellationToken); + IReadOnlyList groups = user.Kind == SignInProviders.Local + ? await GroupRefs.LocalAsync(db, user.Id, cancellationToken) + : GroupRefs.Parse(await db.Sessions.AsNoTracking().Where(s => s.UserId == user.Id).OrderByDescending(s => s.CreatedUtc) + .Select(s => s.GroupsJson).FirstOrDefaultAsync(cancellationToken)); + var granted = await access.ResolveAsync(groups, user.IsBreakGlass, cancellationToken); + return Results.Ok(new AccessView( + user.IsBreakGlass, + [.. groups.Select(g => new GroupView(g.Kind, g.Id, g.Name))], + [.. granted.Grants.Select(g => new GrantView(g.RoleId.ToString("D"), g.RoleName, g.BindingId.ToString("D"), g.PrincipalKind, g.PrincipalId, g.PrincipalName))], + granted.BreakGlass || granted.Permissions.Contains(Permissions.All) + ? [.. Permissions.KnownKeys.Order(StringComparer.Ordinal)] + : [.. granted.Permissions.Order(StringComparer.Ordinal)], + granted.ScopeGroupIds)); + } + + // ── Built-in groups ─────────────────────────────────────────────────── + + private static async Task ListGroupsAsync(AppDbContext db, RoleCache roles, CancellationToken cancellationToken) + { + var groups = await db.LocalGroups.AsNoTracking().OrderBy(g => g.Name).ToListAsync(cancellationToken); + var members = await MembersAsync(db, [.. groups.Select(g => g.Id)], cancellationToken); + var bound = await BoundRolesAsync(db, roles, cancellationToken); + return Results.Ok(groups.Select(g => GroupView(g, members, bound)).ToList()); + } + + private static async Task SaveGroupAsync(string? id, LocalGroupInput input, AppDbContext db, AccessResolver access, AuditService audit, + HttpContext context) + { + var ct = context.RequestAborted; + var group = id is null ? null : await FindGroupAsync(db, id, ct, tracking: true); + var errors = new Dictionary(); + var name = input.Name?.Trim() ?? group?.Name ?? string.Empty; + if (name.Length is 0 or > 128) + { + errors["name"] = ["Enter a name of up to 128 characters."]; + } + else if (await db.LocalGroups.AnyAsync(g => g.Name.ToLower() == name.ToLower() && (group == null || g.Id != group.Id), ct)) + { + errors["name"] = [$"There is already a built-in group named {name}."]; + } + + List? members = null; + if (input.MemberIds is not null) + { + var wanted = input.MemberIds.Select(i => Guid.TryParse(i, out var g) ? g : Guid.Empty).ToList(); + members = await db.Users.Where(u => wanted.Contains(u.Id)).ToListAsync(ct); + if (members.Count != wanted.Distinct().Count()) + { + errors["memberIds"] = ["Some of those users no longer exist."]; + } + else if (members.Any(m => m.Kind != SignInProviders.Local)) + { + errors["memberIds"] = ["Only built-in accounts join built-in groups."]; + } + } + + if (errors.Count > 0) + { + throw AuthProblemException.InvalidFields(errors); + } + + var now = DateTimeOffset.UtcNow; + var created = group is null; + if (group is null) + { + group = new LocalGroupEntity { Id = Guid.NewGuid(), Name = name, CreatedUtc = now }; + db.LocalGroups.Add(group); + } + + group.Name = name; + group.Description = input.Description is null ? group.Description : Clean(input.Description); + group.UpdatedUtc = now; + if (members is not null) + { + await db.LocalGroupMembers.Where(m => m.GroupId == group.Id).ExecuteDeleteAsync(ct); + db.LocalGroupMembers.AddRange(members.Select(m => new LocalGroupMemberEntity { GroupId = group.Id, UserId = m.Id })); + } + + // A renamed group keeps its bindings; their display name follows. + var principal = group.Id.ToString("D"); + await db.RoleBindings.Where(b => b.PrincipalKind == PrincipalKinds.LocalGroup && b.PrincipalId == principal) + .ExecuteUpdateAsync(set => set.SetProperty(b => b.PrincipalName, name), ct); + await db.SaveChangesAsync(ct); + access.Invalidate(); + await audit.LogAsync(AuditCategories.Admin, created ? "auth.local-group.create" : "auth.local-group.update", context.User.Identity?.Name, + detail: $"group={group.Name}{(members is null ? string.Empty : $" members={string.Join(",", members.Select(m => m.UserName))}")}", cancellationToken: ct); + + var view = GroupView(group, await MembersAsync(db, [group.Id], ct), await BoundRolesAsync(db, context.RequestServices.GetRequiredService(), ct)); + return created ? Results.Created(ApiRoutes.AdminLocalGroup.Replace("{id}", principal, StringComparison.Ordinal), view) : Results.Ok(view); + } + + private static async Task DeleteGroupAsync(string id, AppDbContext db, AccessResolver access, RoleCache roles, AuditService audit, + HttpContext context, CancellationToken cancellationToken) + { + var group = await FindGroupAsync(db, id, cancellationToken, tracking: true); + var key = group.Id.ToString("D"); + var bindings = await db.RoleBindings.Where(b => b.PrincipalKind == PrincipalKinds.LocalGroup && b.PrincipalId == key).ToListAsync(cancellationToken); + await RequireFullAccessRemainsAsync(db, roles, [.. bindings.Select(b => b.Id)], cancellationToken); + db.RoleBindings.RemoveRange(bindings); + db.LocalGroups.Remove(group); + await db.SaveChangesAsync(cancellationToken); + access.Invalidate(); + await audit.LogAsync(AuditCategories.Admin, "auth.local-group.delete", context.User.Identity?.Name, detail: $"group={group.Name}", + cancellationToken: cancellationToken); + return Results.NoContent(); + } + + // ── Role bindings ───────────────────────────────────────────────────── + + private static async Task ListBindingsAsync(AppDbContext db, RoleCache roles, string? principalKind, string? roleId, + CancellationToken cancellationToken) + { + var source = db.RoleBindings.AsNoTracking(); + if (!string.IsNullOrWhiteSpace(principalKind)) + { + source = source.Where(b => b.PrincipalKind == principalKind); + } + + if (Guid.TryParse(roleId, out var role)) + { + source = source.Where(b => b.RoleId == role); + } + + var bindings = await source.OrderBy(b => b.PrincipalName).ToListAsync(cancellationToken); + var views = new List(); + foreach (var binding in bindings) + { + views.Add(await BindingViewAsync(binding, roles, cancellationToken)); + } + + return Results.Ok(views); + } + + private static async Task CreateBindingAsync(RoleBindingInput input, AppDbContext db, AccessResolver access, RoleCache roles, AuditService audit, + HttpContext context, CancellationToken cancellationToken) + { + var errors = new Dictionary(); + var role = Guid.TryParse(input.RoleId, out var roleId) ? await roles.FindByIdAsync(roleId, cancellationToken) : null; + if (role is null) + { + errors["roleId"] = ["Choose a role."]; + } + + var kind = input.PrincipalKind ?? string.Empty; + var (principalId, principalName) = await ResolvePrincipalAsync(db, kind, input.PrincipalId, input.PrincipalName, errors, cancellationToken); + if (errors.Count > 0) + { + throw AuthProblemException.InvalidFields(errors); + } + + var normalized = PrincipalKinds.Normalize(kind, principalId!); + if (await db.RoleBindings.AnyAsync(b => b.PrincipalKind == kind && b.PrincipalId == normalized && b.RoleId == role!.Id, cancellationToken)) + { + throw new AuthProblemException(AuthProblems.Conflict, $"{principalName ?? principalId} already has the {role!.Name} role."); + } + + var binding = new RoleBindingEntity + { + Id = Guid.NewGuid(), + RoleId = role!.Id, + PrincipalKind = kind, + PrincipalId = normalized, + PrincipalName = principalName, + CreatedUtc = DateTimeOffset.UtcNow, + CreatedBy = context.User.Identity?.Name, + }; + db.RoleBindings.Add(binding); + await db.SaveChangesAsync(cancellationToken); + access.Invalidate(); + await audit.LogAsync(AuditCategories.Admin, "auth.role-binding.create", context.User.Identity?.Name, + detail: $"role={role.Name} principal={kind}:{principalName ?? normalized}", cancellationToken: cancellationToken); + return Results.Created(ApiRoutes.AdminRoleBinding.Replace("{id}", binding.Id.ToString("D"), StringComparison.Ordinal), + await BindingViewAsync(binding, roles, cancellationToken)); + } + + private static async Task DeleteBindingAsync(string id, AppDbContext db, AccessResolver access, RoleCache roles, AuditService audit, + HttpContext context, CancellationToken cancellationToken) + { + var binding = Guid.TryParse(id, out var guid) ? await db.RoleBindings.SingleOrDefaultAsync(b => b.Id == guid, cancellationToken) : null; + if (binding is null) + { + throw new AuthProblemException(AuthProblems.NotFound, "There is no such role binding."); + } + + await RequireFullAccessRemainsAsync(db, roles, [binding.Id], cancellationToken); + db.RoleBindings.Remove(binding); + await db.SaveChangesAsync(cancellationToken); + access.Invalidate(); + await audit.LogAsync(AuditCategories.Admin, "auth.role-binding.delete", context.User.Identity?.Name, + detail: $"role={(await roles.FindByIdAsync(binding.RoleId, cancellationToken))?.Name} principal={binding.PrincipalKind}:{binding.PrincipalName ?? binding.PrincipalId}", + cancellationToken: cancellationToken); + return Results.NoContent(); + } + + /// Refuses a change that would leave nobody able to manage access: no break-glass account and no other full-access binding. + private static async Task RequireFullAccessRemainsAsync(AppDbContext db, RoleCache roles, IReadOnlyList removing, CancellationToken cancellationToken) + { + if (removing.Count == 0 || await db.Users.AnyAsync(u => u.IsBreakGlass && u.Enabled, cancellationToken)) + { + return; + } + + foreach (var binding in await db.RoleBindings.AsNoTracking().Where(b => !removing.Contains(b.Id)).ToListAsync(cancellationToken)) + { + if (await roles.FindByIdAsync(binding.RoleId, cancellationToken) is { } role + && (role.Permissions.Contains(Permissions.All) || role.Permissions.Contains(Permissions.AccessManage))) + { + return; + } + } + + throw new AuthProblemException(AuthProblems.Conflict, "This would remove the last way to manage access, and there is no break-glass account to recover with."); + } + + private static async Task<(string? Id, string? Name)> ResolvePrincipalAsync(AppDbContext db, string kind, string? id, string? name, + Dictionary errors, CancellationToken cancellationToken) + { + var value = id?.Trim() ?? string.Empty; + switch (kind) + { + case PrincipalKinds.LocalGroup: + { + var group = Guid.TryParse(value, out var guid) ? await db.LocalGroups.AsNoTracking().SingleOrDefaultAsync(g => g.Id == guid, cancellationToken) : null; + if (group is null) + { + errors["principalId"] = ["Choose a built-in group."]; + } + + return (group?.Id.ToString("D"), group?.Name); + } + + case PrincipalKinds.WindowsGroup: + { + var sid = value.Length == 0 ? null : WindowsSignIn.SidOf(value); + if (sid is null) + { + errors["principalId"] = ["Enter a Windows account or group this server can resolve (MACHINE\\Name or DOMAIN\\Group), or its SID (S-1-5-…)."]; + } + + return (sid, Clean(name) ?? (sid is null ? null : WindowsSignIn.NameOf(sid) ?? (value.StartsWith("S-1-", StringComparison.OrdinalIgnoreCase) ? null : value))); + } + + case PrincipalKinds.LdapGroup: + if (value.Length is 0 or > 450 || !value.Contains('=', StringComparison.Ordinal)) + { + errors["principalId"] = ["Enter the group's distinguished name, for example cn=helpdesk,ou=groups,dc=example,dc=com."]; + } + + return (value, Clean(name) ?? SignInService.FirstRdn(value)); + + case PrincipalKinds.OidcGroup: + if (value.Length is 0 or > 450 || !value.Contains('=', StringComparison.Ordinal)) + { + errors["principalId"] = ["Enter the claim and its value as claim=value, for example groups=executer-admins."]; + } + + return (value, Clean(name) ?? value); + + default: + errors["principalKind"] = [$"Choose one of: {string.Join(", ", PrincipalKinds.All)}."]; + return (null, null); + } + } + + private static async Task> ResolveGroupsAsync(AppDbContext db, IReadOnlyList? ids, string field, + Dictionary errors, CancellationToken cancellationToken) + { + if (ids is null || ids.Count == 0) + { + return []; + } + + var wanted = ids.Select(i => Guid.TryParse(i, out var g) ? g : Guid.Empty).Distinct().ToList(); + var found = await db.LocalGroups.Where(g => wanted.Contains(g.Id)).ToListAsync(cancellationToken); + if (found.Count != wanted.Count) + { + errors[field] = ["Some of those built-in groups no longer exist."]; + } + + return found; + } + + private static async Task>> GroupsOfAsync(AppDbContext db, IReadOnlyList userIds, CancellationToken cancellationToken) + { + var rows = await db.LocalGroupMembers.AsNoTracking().Where(m => userIds.Contains(m.UserId)) + .Join(db.LocalGroups, m => m.GroupId, g => g.Id, (m, g) => new { m.UserId, g.Id, g.Name }).ToListAsync(cancellationToken); + return rows.GroupBy(r => r.UserId).ToDictionary(g => g.Key, g => g.Select(r => new GroupView(PrincipalKinds.LocalGroup, r.Id.ToString("D"), r.Name)) + .OrderBy(v => v.Name, StringComparer.OrdinalIgnoreCase).ToList()); + } + + private static async Task>> MembersAsync(AppDbContext db, IReadOnlyList groupIds, CancellationToken cancellationToken) + { + var rows = await db.LocalGroupMembers.AsNoTracking().Where(m => groupIds.Contains(m.GroupId)) + .Join(db.Users, m => m.UserId, u => u.Id, (m, u) => new { m.GroupId, u.Id, u.UserName, u.DisplayName }).ToListAsync(cancellationToken); + return rows.GroupBy(r => r.GroupId).ToDictionary(g => g.Key, g => g.Select(r => new GroupMemberView(r.Id.ToString("D"), r.UserName, r.DisplayName)) + .OrderBy(v => v.UserName, StringComparer.OrdinalIgnoreCase).ToList()); + } + + /// Role names bound to each built-in group, by group id. + private static async Task>> BoundRolesAsync(AppDbContext db, RoleCache roles, CancellationToken cancellationToken) + { + var bindings = await db.RoleBindings.AsNoTracking().Where(b => b.PrincipalKind == PrincipalKinds.LocalGroup).ToListAsync(cancellationToken); + var result = new Dictionary>(StringComparer.OrdinalIgnoreCase); + foreach (var binding in bindings) + { + if (await roles.FindByIdAsync(binding.RoleId, cancellationToken) is { } role) + { + (result.TryGetValue(binding.PrincipalId, out var list) ? list : result[binding.PrincipalId] = []).Add(role.Name); + } + } + + return result; + } + + private static async Task FindUserAsync(AppDbContext db, string id, CancellationToken cancellationToken, bool tracking = false) + { + var source = tracking ? db.Users : db.Users.AsNoTracking(); + return (Guid.TryParse(id, out var guid) ? await source.SingleOrDefaultAsync(u => u.Id == guid, cancellationToken) : null) + ?? throw new AuthProblemException(AuthProblems.NotFound, "There is no such user."); + } + + private static async Task FindGroupAsync(AppDbContext db, string id, CancellationToken cancellationToken, bool tracking = false) + { + var source = tracking ? db.LocalGroups : db.LocalGroups.AsNoTracking(); + return (Guid.TryParse(id, out var guid) ? await source.SingleOrDefaultAsync(g => g.Id == guid, cancellationToken) : null) + ?? throw new AuthProblemException(AuthProblems.NotFound, "There is no such built-in group."); + } + + private static UserView View(UserEntity user, Dictionary> groups) => View(user, groups.GetValueOrDefault(user.Id, [])); + + private static UserView View(UserEntity user, IReadOnlyList groups) => new(user.Id.ToString("D"), user.Kind, user.UserName, user.DisplayName, + user.Email, user.Enabled, user.IsBreakGlass, user.MustChangePassword && user.Kind == SignInProviders.Local, user.CreatedUtc, user.LastSignInUtc, groups, + user.Description, SignInService.SidOf(user), WindowsGroups.Parse(user.WindowsGroupsJson)); + + private static LocalGroupView GroupView(LocalGroupEntity group, Dictionary> members, Dictionary> roles) + { + var list = members.GetValueOrDefault(group.Id, []); + return new LocalGroupView(group.Id.ToString("D"), group.Name, group.Description, list.Count, list, group.CreatedUtc, + [.. roles.GetValueOrDefault(group.Id.ToString("D"), []).Order(StringComparer.OrdinalIgnoreCase)]); + } + + private static async Task BindingViewAsync(RoleBindingEntity b, RoleCache roles, CancellationToken cancellationToken) => + new(b.Id.ToString("D"), b.RoleId.ToString("D"), (await roles.FindByIdAsync(b.RoleId, cancellationToken))?.Name ?? "(deleted role)", b.PrincipalKind, + b.PrincipalId, b.PrincipalName, b.CreatedUtc, b.CreatedBy); + + private static string? Clean(string? value) => value?.Trim() is { Length: > 0 } text ? text : null; +} diff --git a/src/Backend/Auth/SignIn/AuthProblems.cs b/src/Backend/Auth/SignIn/AuthProblems.cs new file mode 100644 index 0000000..66f8aef --- /dev/null +++ b/src/Backend/Auth/SignIn/AuthProblems.cs @@ -0,0 +1,79 @@ +namespace Backend.Auth; + +/// A kind of refusal, answered as problem+json with type: urn:problem:{Id} so the console can react (step up, change password, wait). +public sealed record AuthProblem(string Id, int Status, string Title); + +public static class AuthProblems +{ + public static readonly AuthProblem SignInFailed = new("sign-in-failed", StatusCodes.Status401Unauthorized, "The user name or password is not correct."); + public static readonly AuthProblem NoAccess = new("no-access", StatusCodes.Status403Forbidden, + "You signed in, but none of your groups is bound to a role here. Ask an administrator for access."); + public static readonly AuthProblem PasswordChangeRequired = new("password-change-required", StatusCodes.Status403Forbidden, + "Change your password before continuing."); + public static readonly AuthProblem Csrf = new("csrf", StatusCodes.Status403Forbidden, "The request is missing its CSRF token; reload the page."); + public static readonly AuthProblem TooManyAttempts = new("too-many-attempts", StatusCodes.Status429TooManyRequests, + "Too many failed sign-ins; wait a little and try again."); + public static readonly AuthProblem StepUpRequired = new("step-up-required", StatusCodes.Status403Forbidden, + "Confirm it is you again (your password, or your identity provider), then repeat the action."); + public static readonly AuthProblem StepUpUnavailable = new("step-up-unavailable", StatusCodes.Status403Forbidden, + "This session cannot confirm its person here. Sign in again to do this."); + public static readonly AuthProblem NotReady = new("not-ready", StatusCodes.Status503ServiceUnavailable, "Not available just now; try again."); + public static readonly AuthProblem Forbidden = new("forbidden", StatusCodes.Status403Forbidden, "Not allowed."); + public static readonly AuthProblem Conflict = new("conflict", StatusCodes.Status409Conflict, "That conflicts with the current state."); + public static readonly AuthProblem NotFound = new("not-found", StatusCodes.Status404NotFound, "Not found."); + public static readonly AuthProblem Invalid = new("invalid", StatusCodes.Status400BadRequest, "Some fields need attention."); + public static readonly AuthProblem PreconditionRequired = new("precondition-required", StatusCodes.Status428PreconditionRequired, + "Save with the version you loaded (If-Match)."); + public static readonly AuthProblem PreconditionFailed = new("precondition-failed", StatusCodes.Status412PreconditionFailed, + "Someone changed these settings since you opened them; reload and try again."); +} + +/// Thrown by sign-in and access code; turns it into the problem response. +public sealed class AuthProblemException(AuthProblem problem, string? detail = null) : Exception(detail ?? problem.Title) +{ + public AuthProblem Problem { get; } = problem; + public string? Detail { get; } = detail; + public IReadOnlyDictionary? Errors { get; init; } + public int? RetryAfterSeconds { get; init; } + + public static AuthProblemException InvalidFields(IReadOnlyDictionary errors) => + new(AuthProblems.Invalid, errors.Values.SelectMany(v => v).FirstOrDefault()) { Errors = errors }; +} + +public static class AuthProblemHandling +{ + /// Answers an from any endpoint as problem+json. + public static async Task Middleware(HttpContext context, RequestDelegate next) + { + try + { + await next(context); + } + catch (AuthProblemException problem) when (!context.Response.HasStarted) + { + await WriteAsync(context, problem); + } + } + + public static Task WriteAsync(HttpContext context, AuthProblemException problem) + { + context.Response.Clear(); + context.Response.StatusCode = problem.Problem.Status; + if (problem.RetryAfterSeconds is { } wait) + { + context.Response.Headers.RetryAfter = wait.ToString(System.Globalization.CultureInfo.InvariantCulture); + } + + return context.Response.WriteAsJsonAsync(new + { + type = $"urn:problem:{problem.Problem.Id}", + title = problem.Problem.Title, + status = problem.Problem.Status, + detail = problem.Detail ?? problem.Problem.Title, + // The console's error text reads `error` first. + error = problem.Detail ?? problem.Problem.Title, + errors = problem.Errors, + retryAfterSeconds = problem.RetryAfterSeconds, + }, Shared.Contracts.Serialization.JsonDefaults.Options, "application/problem+json"); + } +} diff --git a/src/Backend/Auth/SignIn/AuthenticationSettingsEndpoints.cs b/src/Backend/Auth/SignIn/AuthenticationSettingsEndpoints.cs new file mode 100644 index 0000000..5042393 --- /dev/null +++ b/src/Backend/Auth/SignIn/AuthenticationSettingsEndpoints.cs @@ -0,0 +1,553 @@ +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Api; +using Shared.Contracts.Serialization; + +namespace Backend.Auth; + +public sealed record SignInTestStart(string Url); + +public sealed record SignInTestView(string Provider, string Status, string? Detail, DateTimeOffset? CompletedUtc, bool CurrentSettings); + +/// +/// Settings › Authentication: each tab saves its method's switch (in the +/// one authentication document) and its own settings together, under +/// one If-Match naming both versions. A change to which methods are on needs +/// step-up, and is refused when it would leave no way in: no method on, or +/// only providers on and none of them passed a test sign-in in this session +/// with its settings as they are. +/// +public sealed class AuthenticationStore(IServiceScopeFactory scopes, SettingsDocuments documents, SignInSettings settings, SignInEnvironment environment) +{ + /// The version of a tab: the methods document's etag, and its own document's when it has one. + public static string Etag(string methods, string? own) => own is null ? methods : $"{methods}.{own}"; + + public async Task<(AuthenticationView View, string Etag)> SummaryAsync(CancellationToken cancellationToken) + { + var (methods, etag) = await settings.MethodsAsync(cancellationToken); + var views = new List(); + foreach (var method in SignInProviders.Methods) + { + views.Add(new AuthenticationMethodView(method, await settings.LabelAsync(method, cancellationToken), methods.IsOn(method), + method != SignInProviders.Windows || WindowsPlatform.Supported, await settings.IsConfiguredAsync(method, cancellationToken))); + } + + return (new AuthenticationView(views, methods.OidcRedirect, await RedirectAsync(cancellationToken) is not null, environment.ForceBuiltIn, + SignInEnvironment.ForceBuiltInVariable), etag); + } + + /// + /// The provider sign-in goes straight to: OIDC, when redirect mode is on and + /// it is the only way in (Built-In off and not forced, no other method on). + /// Null otherwise, so the sign-in page shows its options. + /// + public async Task RedirectAsync(CancellationToken cancellationToken) + { + var (methods, _) = await settings.MethodsAsync(cancellationToken); + if (!methods.OidcRedirect || methods.BuiltIn || environment.ForceBuiltIn || !await settings.IsUsableAsync(SignInProviders.Oidc, cancellationToken)) + { + return null; + } + + foreach (var other in SignInProviders.Methods.Where(p => p is not (SignInProviders.Oidc or SignInProviders.Local))) + { + if (await settings.IsUsableAsync(other, cancellationToken)) + { + return null; + } + } + + return SignInProviders.Oidc; + } + + /// + /// Saves a tab: changes the methods document, + /// (when the method has settings of its own) its + /// document, in one transaction. Returns both as stored and the tab's new version. + /// + public async Task<(AuthenticationMethods Methods, T? Own, string Etag)> SaveAsync(HttpContext context, string method, string? ifMatch, + Func switches, string? ownKey, T? ownDefaults, Func? change, + Func>? validate, StepUpService stepUp, CancellationToken cancellationToken) + where T : class + { + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var methodsRow = await SettingsDocuments.LoadAsync(db, AuthenticationMethods.Key, cancellationToken); + var ownRow = ownKey is null ? null : await SettingsDocuments.LoadAsync(db, ownKey, cancellationToken); + ETags.RequireMatch(ifMatch, Etag(methodsRow?.Etag ?? SettingsDocuments.InitialEtag, ownKey is null ? null : ownRow?.Etag ?? SettingsDocuments.InitialEtag)); + + var actor = context.User.Identity?.Name; + var methodsBefore = SettingsDocuments.Parse(methodsRow?.Value, AuthenticationMethods.Defaults); + var methodsAfter = switches(methodsBefore); + T? ownAfter = null; + var ownChanged = false; + if (ownKey is not null && change is not null && ownDefaults is not null) + { + var ownBefore = SettingsDocuments.Parse(ownRow?.Value, ownDefaults); + ownAfter = change(ownBefore); + + // A method that is on must be able to sign people in; one that is off may keep settings half done. + if (methodsAfter.IsOn(method) && validate?.Invoke(ownAfter) is { Count: > 0 } errors) + { + throw AuthProblemException.InvalidFields(errors); + } + + ownChanged = SettingsDocuments.Stage(db, ownRow, ownKey, ownRow is null ? null : ownBefore, ownAfter, actor); + } + + var switched = JsonDefaults.Serialize(methodsBefore) != JsonDefaults.Serialize(methodsAfter); + if (switched) + { + await GuardAsync(db, context, methodsBefore, methodsAfter, ownKey is null ? null : (method, ownChanged ? (ownRow?.Etag ?? db.AppSettings.Local.First(s => s.Key == ownKey).Etag!) : ownRow?.Etag ?? SettingsDocuments.InitialEtag), cancellationToken); + await stepUp.RequireAsync(context, cancellationToken); + SettingsDocuments.Stage(db, methodsRow, AuthenticationMethods.Key, methodsBefore, methodsAfter, actor, always: true); + } + + await db.SaveChangesAsync(cancellationToken); + documents.Invalidate(ownKey is null ? [AuthenticationMethods.Key] : [AuthenticationMethods.Key, ownKey]); + + var audit = scope.ServiceProvider.GetRequiredService(); + if (switched) + { + await audit.LogAsync(Backend.Security.AuditCategories.Settings, "settings.authentication.update", actor, + detail: $"on={string.Join(",", methodsAfter.On())} redirect={methodsAfter.OidcRedirect}", cancellationToken: cancellationToken); + } + + if (ownChanged) + { + await audit.LogAsync(Backend.Security.AuditCategories.Settings, $"settings.authentication.{method}.update", actor, cancellationToken: cancellationToken); + } + + var methodsEtag = (await SettingsDocuments.LoadAsync(db, AuthenticationMethods.Key, cancellationToken))?.Etag ?? SettingsDocuments.InitialEtag; + var ownEtag = ownKey is null ? null : (await SettingsDocuments.LoadAsync(db, ownKey, cancellationToken))?.Etag ?? SettingsDocuments.InitialEtag; + return (methodsAfter, ownAfter, Etag(methodsEtag, ownEtag)); + } + + /// + /// Keeps a way in: at least one method stays on, and a change that leaves + /// only providers on (Built-In off) needs one of them to have passed a test + /// sign-in in this session, with its settings as they are. The + /// environment's forced built-in form does not count: it is a way back, + /// not a way in. + /// + private async Task GuardAsync(AppDbContext db, HttpContext context, AuthenticationMethods before, AuthenticationMethods after, + (string Method, string Etag)? saved, CancellationToken cancellationToken) + { + var on = after.On(); + if (on.Count == 0) + { + throw new AuthProblemException(AuthProblems.Conflict, "Keep at least one sign-in method on."); + } + + var turnedOff = before.On().Except(on).ToList(); + if (after.BuiltIn || turnedOff.Count == 0) + { + return; + } + + var caller = context.RequireCaller(); + var etags = new Dictionary(StringComparer.Ordinal); + foreach (var provider in on) + { + etags[provider] = saved is { } s && s.Method == provider ? s.Etag : await settings.EtagAsync(provider, cancellationToken); + } + + var now = DateTimeOffset.UtcNow; + var passed = caller.SessionId is null ? [] : await db.SignInRequests.AsNoTracking() + .Where(r => r.TestSessionId == caller.SessionId && on.Contains(r.Provider) && r.Status == SignInRequestStatus.Passed && r.ExpiresUtc > now) + .Select(r => new { r.Provider, r.SettingsEtag }).ToListAsync(cancellationToken); + if (passed.Any(p => etags.TryGetValue(p.Provider, out var etag) && etag == p.SettingsEtag)) + { + return; + } + + var names = on.Select(p => p == SignInProviders.Windows ? "local Windows accounts" : p == SignInProviders.Ldap ? "LDAP" : "OIDC"); + throw new AuthProblemException(AuthProblems.Conflict, $"This leaves only {string.Join(" and ", names)}: run a test sign-in through it in this session first."); + } +} + +/// The routes of Settings › Authentication, and the test sign-ins each provider's tab runs. +public static class AuthenticationSettingsEndpoints +{ + public static readonly TimeSpan TestValidity = TimeSpan.FromMinutes(30); + public const string SignInTestNone = "none"; + + /// The console page of each method's tab; a test sign-in that left the console comes back to it. + public static string TabPath(string provider) => provider switch + { + SignInProviders.Local => "/settings/authentication/built-in", + SignInProviders.Windows => "/settings/authentication/local", + _ => $"/settings/authentication/{provider}", + }; + + private static string Route(string method) => ApiRoutes.SettingsAuthenticationMethod.Replace("{method}", method, StringComparison.Ordinal); + + private static string TestRoute(string method) => ApiRoutes.SettingsAuthenticationTest.Replace("{method}", method, StringComparison.Ordinal); + + public static void Map(WebApplication app) + { + var manage = Permissions.AccessManage; + + app.MapGet(ApiRoutes.SettingsAuthentication, async (AuthenticationStore store, HttpContext context) => + { + var (view, etag) = await store.SummaryAsync(context.RequestAborted); + return Document(context, view, etag); + }).RequirePermission(manage); + + app.MapGet(Route("built-in"), async (SignInSettings settings, SettingsDocuments documents, SignInEnvironment environment, AppDbContext db, + HttpContext context) => + { + var ct = context.RequestAborted; + var (methods, methodsEtag) = await settings.MethodsAsync(ct); + var (lifetimes, etag) = await documents.GetAsync(SignInLifetimes.Key, SignInLifetimes.Defaults, ct); + return Document(context, await BuiltInViewAsync(methods, lifetimes, environment, db, ct), AuthenticationStore.Etag(methodsEtag, etag)); + }).RequirePermission(manage); + + app.MapPut(Route("built-in"), async (BuiltInSignInUpdate update, AuthenticationStore store, StepUpService stepUp, SignInEnvironment environment, + AppDbContext db, HttpContext context) => + { + var lifetimes = ValidateLifetimes(update); + var (methods, saved, etag) = await store.SaveAsync(context, SignInProviders.Local, context.Request.Headers.IfMatch, + m => update.Enabled is { } on ? m with { BuiltIn = on } : m, SignInLifetimes.Key, SignInLifetimes.Defaults, _ => lifetimes, null, stepUp, + context.RequestAborted); + return Document(context, await BuiltInViewAsync(methods, saved!, environment, db, context.RequestAborted), etag); + }).RequirePermission(manage); + + app.MapGet(Route("windows"), async (SignInSettings settings, HttpContext context) => + { + var (methods, etag) = await settings.MethodsAsync(context.RequestAborted); + return Document(context, WindowsView(methods), etag); + }).RequirePermission(manage); + + app.MapPut(Route("windows"), async (WindowsSignInUpdate update, AuthenticationStore store, StepUpService stepUp, HttpContext context) => + { + if (update.Enabled is not { } on) + { + throw AuthProblemException.InvalidFields(new Dictionary { ["enabled"] = ["Say whether local Windows accounts are on."] }); + } + + if (on && !WindowsPlatform.Supported) + { + throw new AuthProblemException(AuthProblems.Conflict, "Local Windows accounts need a Windows server."); + } + + var (methods, _, etag) = await store.SaveAsync(context, SignInProviders.Windows, context.Request.Headers.IfMatch, + m => m.WindowsOn == on ? m : m with { Windows = on }, null, null, null, null, stepUp, context.RequestAborted); + return Document(context, WindowsView(methods), etag); + }).RequirePermission(manage); + + app.MapGet(Route("ldap"), async (SignInSettings settings, HttpContext context) => + { + var (methods, methodsEtag) = await settings.MethodsAsync(context.RequestAborted); + var (value, etag) = await settings.LdapAsync(context.RequestAborted); + return Document(context, LdapView(methods.Ldap, value), AuthenticationStore.Etag(methodsEtag, etag)); + }).RequirePermission(manage); + + app.MapPut(Route("ldap"), async (LdapSignInUpdate update, AuthenticationStore store, StepUpService stepUp, SignInSecrets secrets, + SignInSettings settings, HttpContext context) => + { + // Any change an administrator makes, the switch included, makes the settings theirs: automatic LDAP no longer follows the join. + var (current, _) = await settings.MethodsAsync(context.RequestAborted); + var switched = update.Enabled is { } enabled && enabled != current.Ldap; + var (methods, saved, etag) = await store.SaveAsync(context, SignInProviders.Ldap, context.Request.Headers.IfMatch, + m => update.Enabled is { } on ? m with { Ldap = on } : m, LdapSignInSettings.Key, LdapSignInSettings.Defaults, + before => ChangeLdap(update, before, secrets, switched), LdapDirectory.Validate, stepUp, context.RequestAborted); + return Document(context, LdapView(methods.Ldap, saved!), etag); + }).RequirePermission(manage); + + app.MapPost(ApiRoutes.SettingsLdapBreakerReset, async (AuthenticationStore store, StepUpService stepUp, AutomaticDirectory automatic, + HttpContext context) => + { + var (methods, saved, etag) = await store.SaveAsync(context, SignInProviders.Ldap, context.Request.Headers.IfMatch, m => m with { Ldap = true }, + LdapSignInSettings.Key, LdapSignInSettings.Defaults, before => before with { BreakerTrippedUtc = null }, LdapDirectory.Validate, stepUp, + context.RequestAborted); + await automatic.ResetCountAsync(context.RequestAborted); + return Document(context, LdapView(methods.Ldap, saved!), etag); + }).RequirePermission(manage); + + app.MapPost(TestRoute("ldap"), TestLdapAsync).RequirePermission(manage); + + app.MapGet(Route("oidc"), async (SignInSettings settings, OidcSignIn oidc, HttpContext context) => + { + var (methods, methodsEtag) = await settings.MethodsAsync(context.RequestAborted); + var (value, etag) = await settings.OidcAsync(context.RequestAborted); + return Document(context, OidcView(context, oidc, methods, value), AuthenticationStore.Etag(methodsEtag, etag)); + }).RequirePermission(manage); + + app.MapPut(Route("oidc"), async (OidcSignInUpdate update, AuthenticationStore store, StepUpService stepUp, SignInSecrets secrets, OidcSignIn oidc, + HttpContext context) => + { + var (methods, saved, etag) = await store.SaveAsync(context, SignInProviders.Oidc, context.Request.Headers.IfMatch, + m => m with { Oidc = update.Enabled ?? m.Oidc, OidcRedirect = update.Redirect ?? m.OidcRedirect }, OidcSignInSettings.Key, + OidcSignInSettings.Defaults, before => ChangeOidc(update, before, secrets), OidcSignIn.Validate, stepUp, context.RequestAborted); + return Document(context, OidcView(context, oidc, methods, saved!), etag); + }).RequirePermission(manage); + + app.MapPost(TestRoute("oidc"), async (OidcSignIn oidc, SignInSettings settings, HttpContext context) => + { + var caller = context.RequireCaller(); + if (caller.SessionId is null) + { + throw new AuthProblemException(AuthProblems.Conflict, "A test sign-in belongs to a browser session; sign in to the console to run one."); + } + + if (!await settings.IsConfiguredAsync(SignInProviders.Oidc, context.RequestAborted)) + { + throw new AuthProblemException(AuthProblems.Conflict, "Save the issuer and client ID first."); + } + + try + { + return Results.Ok(new SignInTestStart(await oidc.BeginAsync(context, null, caller.SessionId, context.RequestAborted))); + } + catch (OidcException exception) + { + throw new AuthProblemException(AuthProblems.Conflict, exception.Message); + } + }).RequirePermission(manage); + + app.MapPost(TestRoute("windows"), TestWindowsAsync).RequirePermission(manage); + + app.MapGet(ApiRoutes.SettingsAuthenticationTestResult, async (string method, AppDbContext db, SignInSettings settings, HttpContext context) => + { + var caller = context.RequireCaller(); + var latest = caller.SessionId is null ? null : await db.SignInRequests.AsNoTracking() + .Where(r => r.TestSessionId == caller.SessionId && r.Provider == method) + .OrderByDescending(r => r.CreatedUtc).FirstOrDefaultAsync(context.RequestAborted); + context.Response.Headers.CacheControl = "no-store"; + if (latest is null) + { + return Results.Ok(new SignInTestView(method, SignInTestNone, null, null, false)); + } + + var current = latest.SettingsEtag == await settings.EtagAsync(method, context.RequestAborted); + return Results.Ok(new SignInTestView(method, latest.Status, latest.Detail, latest.CompletedUtc, current)); + }).RequirePermission(manage); + } + + private static async Task TestLdapAsync(SignInBody body, SignInSettings settings, ILdapDirectory ldap, AccessResolver access, AppDbContext db, + SignInService signIn, HttpContext context) + { + var ct = context.RequestAborted; + var caller = context.RequireCaller(); + var (value, etag) = await settings.LdapAsync(ct); + if (LdapDirectory.Validate(value).Count > 0) + { + throw new AuthProblemException(AuthProblems.Conflict, "Save the directory's servers and base DN first."); + } + + SignInTestResult result; + try + { + ldap.Probe(value); + var account = ldap.Authenticate(value, body.UserName ?? string.Empty, body.Password ?? string.Empty); + if (account is null) + { + result = new SignInTestResult(false, SignInProviders.Ldap, body.UserName, [], [], [], "The directory did not accept that user name and password."); + } + else + { + var groups = account.Groups.Select(dn => new GroupRef(PrincipalKinds.LdapGroup, dn, SignInService.FirstRdn(dn))).ToList(); + var granted = await access.ResolveAsync(groups, breakGlass: false, ct); + result = Result(SignInProviders.Ldap, account.UserName, groups, granted, "Signed in, but no group of theirs is bound to a role."); + } + } + catch (DirectoryException exception) + { + result = new SignInTestResult(false, SignInProviders.Ldap, body.UserName, [], [], [], exception.Message); + } + + await RecordTestAsync(db, caller, SignInProviders.Ldap, etag, result.Passed, result.Detail ?? "Signed in.", ct); + await signIn.AuditAsync(context, "settings.authentication.ldap.test", SignInProviders.Ldap, body.UserName ?? string.Empty, + result.Passed ? "succeeded" : "failed", result.Detail, ct); + return Results.Ok(result); + } + + /// + /// Checks a local Windows account the way sign-in would, without signing + /// anyone in or keeping a row. Throttled like a sign-in, since it checks a + /// password. + /// + private static async Task TestWindowsAsync(SignInBody body, SignInSettings settings, ILocalLogon logon, ILocalAccounts accounts, + AccessResolver access, SignInThrottling throttling, AppDbContext db, SignInService signIn, HttpContext context) + { + var ct = context.RequestAborted; + var caller = context.RequireCaller(); + if (!WindowsPlatform.Supported) + { + throw new AuthProblemException(AuthProblems.Conflict, "Local Windows accounts need a Windows server."); + } + + var typed = body.UserName?.Trim() ?? string.Empty; + var name = WindowsSignIn.ParseName(typed, Environment.MachineName); + if (name is null || string.IsNullOrEmpty(body.Password) || body.Password.Length > PasswordHashing.MaxLength) + { + throw AuthProblemException.InvalidFields(new Dictionary { ["userName"] = ["Enter one of this server's account names and its password."] }); + } + + var accountKey = SignInThrottling.AccountKey(SignInProviders.Local, name.Name); + var addressKey = SignInThrottling.AddressKey(Backend.Proxy.ClientIp.EffectiveText(context)); + if (await throttling.BlockedUntilAsync([accountKey, addressKey], ct) is { } until) + { + throw new AuthProblemException(AuthProblems.TooManyAttempts) { RetryAfterSeconds = SignInThrottling.SecondsUntil(until) }; + } + + SignInTestResult result; + var logonResult = logon.Validate(name.Name, body.Password); + if (logonResult is not { Outcome: LocalLogonOutcome.Accepted, Sid: { } sid, AccountName: { } accountName }) + { + await throttling.FailedAsync(accountKey, addressKey, ct); + result = new SignInTestResult(false, SignInProviders.Windows, typed, [], [], [], "Windows did not accept that user name and password."); + } + else + { + var details = accounts.Read(accountName, sid); + var groups = WindowsSignIn.Principals(sid, accountName, [.. (details?.Groups ?? []).Select(g => new WindowsGroupView(g.Name, g.Sid))]); + var granted = await access.ResolveAsync(groups, breakGlass: false, ct); + result = Result(SignInProviders.Windows, accountName, groups, granted, "Signed in, but neither the account nor its local groups is bound to a role."); + } + + await RecordTestAsync(db, caller, SignInProviders.Windows, await settings.EtagAsync(SignInProviders.Windows, ct), result.Passed, + result.Detail ?? $"Signed in as {result.UserName}: {string.Join(", ", result.Roles)}.", ct); + await signIn.AuditAsync(context, "settings.authentication.windows.test", SignInProviders.Windows, typed, result.Passed ? "succeeded" : "failed", + result.Detail, ct); + return Results.Ok(result); + } + + private static SignInTestResult Result(string provider, string userName, IReadOnlyList groups, EffectiveAccess granted, string noAccess) => new( + granted.Any, + provider, + userName, + [.. groups.Select(g => new GroupView(g.Kind, g.Id, g.Name))], + [.. granted.Roles.Select(r => r.Name).Order(StringComparer.OrdinalIgnoreCase)], + [.. granted.Permissions.Order(StringComparer.Ordinal)], + granted.Any ? null : noAccess); + + private static async Task RecordTestAsync(AppDbContext db, Caller caller, string provider, string etag, bool passed, string detail, + CancellationToken cancellationToken) + { + if (caller.SessionId is null) + { + return; + } + + var now = DateTimeOffset.UtcNow; + db.SignInRequests.Add(new SignInRequestEntity + { + Id = RandomText.UrlSafe(32), + Provider = provider, + Status = passed ? SignInRequestStatus.Passed : SignInRequestStatus.Failed, + TestSessionId = caller.SessionId, + SettingsEtag = etag, + Detail = detail.Length > 2000 ? detail[..2000] : detail, + CreatedUtc = now, + ExpiresUtc = now + TestValidity, + CompletedUtc = now, + }); + await db.SaveChangesAsync(cancellationToken); + } + + private static IResult Document(HttpContext context, T value, string etag) + { + context.Response.Headers.ETag = ETags.Quote(etag); + context.Response.Headers.CacheControl = "no-cache"; + return Results.Ok(value); + } + + private static async Task BuiltInViewAsync(AuthenticationMethods methods, SignInLifetimes value, SignInEnvironment environment, + AppDbContext db, CancellationToken cancellationToken) + { + var breakGlass = await db.Users.AsNoTracking().Where(u => u.IsBreakGlass).Select(u => u.UserName).FirstOrDefaultAsync(cancellationToken); + return new BuiltInSignInView(methods.BuiltIn, value.SessionIdleMinutes, value.SessionMaxHours, environment.ForceBuiltIn, + SignInEnvironment.ForceBuiltInVariable, breakGlass); + } + + private static SignInLifetimes ValidateLifetimes(BuiltInSignInUpdate update) + { + var errors = new Dictionary(); + if (update.SessionIdleMinutes is not (>= 5 and <= 24 * 60)) + { + errors["sessionIdleMinutes"] = ["Enter 5 to 1440 minutes."]; + } + + if (update.SessionMaxHours is not (>= 1 and <= 24 * 30)) + { + errors["sessionMaxHours"] = ["Enter 1 to 720 hours."]; + } + + if (errors.Count > 0) + { + throw AuthProblemException.InvalidFields(errors); + } + + return new SignInLifetimes(update.SessionIdleMinutes!.Value, update.SessionMaxHours!.Value); + } + + private static WindowsSignInView WindowsView(AuthenticationMethods methods) => new(methods.WindowsOn, WindowsPlatform.IsWindowsServer, WindowsPlatform.Supported); + + private static LdapSignInView LdapView(bool enabled, LdapSignInSettings v) => new(enabled, v.Label, v.Servers, v.Port, v.Security, v.BaseDn, v.BindDn, + !string.IsNullOrEmpty(v.BindPassword), v.UserFilter, v.GroupBaseDn, v.GroupFilter, v.NestedGroups, v.TimeoutSeconds, v.Automatic, v.BreakerFailures, + v.BreakerWindowMinutes, v.BreakerTrippedUtc, OperatingSystem.IsWindows()); + + /// An administrator's save: the values sent, and no longer automatic once anything changed (: the method's switch). + private static LdapSignInSettings ChangeLdap(LdapSignInUpdate update, LdapSignInSettings before, SignInSecrets secrets, bool switched) + { + var after = ChangeLdapValues(update, before, secrets); + var same = !switched && JsonDefaults.Serialize(after) == JsonDefaults.Serialize(before); + return same ? after : after with { Automatic = false }; + } + + private static LdapSignInSettings ChangeLdapValues(LdapSignInUpdate update, LdapSignInSettings before, SignInSecrets secrets) + { + var servers = (update.Servers ?? before.Servers).Select(s => s.Trim()).Where(s => s.Length > 0).Distinct(StringComparer.OrdinalIgnoreCase).ToList(); + var password = update.BindPassword switch + { + null => before.BindPassword, + "" => null, + var text => secrets.Seal(text, LdapSignInSettings.BindPasswordPurpose), + }; + return new LdapSignInSettings( + string.IsNullOrWhiteSpace(update.Label) ? before.Label : update.Label.Trim(), + servers, + update.Port ?? before.Port, + update.Security ?? before.Security, + Trimmed(update.BaseDn, before.BaseDn), + Trimmed(update.BindDn, before.BindDn), + password, + string.IsNullOrWhiteSpace(update.UserFilter) ? before.UserFilter : update.UserFilter.Trim(), + Trimmed(update.GroupBaseDn, before.GroupBaseDn), + Trimmed(update.GroupFilter, before.GroupFilter), + update.NestedGroups ?? before.NestedGroups, + update.TimeoutSeconds ?? before.TimeoutSeconds, + before.Automatic, + update.BreakerFailures ?? before.BreakerFailures, + update.BreakerWindowMinutes ?? before.BreakerWindowMinutes, + before.BreakerTrippedUtc); + } + + private static OidcSignInView OidcView(HttpContext context, OidcSignIn oidc, AuthenticationMethods methods, OidcSignInSettings v) => + new(methods.Oidc, methods.OidcRedirect, v.Label, v.Authority, v.ClientId, !string.IsNullOrEmpty(v.ClientSecret), v.Scopes, v.UserNameClaim, v.GroupClaims, + oidc.RedirectUri(context), oidc.PostLogoutRedirectUri(context)); + + private static OidcSignInSettings ChangeOidc(OidcSignInUpdate update, OidcSignInSettings before, SignInSecrets secrets) + { + var secret = update.ClientSecret switch + { + null => before.ClientSecret, + "" => null, + var text => secrets.Seal(text, OidcSignInSettings.ClientSecretPurpose), + }; + static List Clean(IEnumerable values) => [.. values.Select(v => v.Trim()).Where(v => v.Length > 0).Distinct(StringComparer.Ordinal)]; + return new OidcSignInSettings( + string.IsNullOrWhiteSpace(update.Label) ? before.Label : update.Label.Trim(), + Trimmed(update.Authority, before.Authority), + Trimmed(update.ClientId, before.ClientId), + secret, + Clean(update.Scopes ?? before.Scopes), + string.IsNullOrWhiteSpace(update.UserNameClaim) ? before.UserNameClaim : update.UserNameClaim.Trim(), + Clean(update.GroupClaims ?? before.GroupClaims)); + } + + /// A field left out keeps its value; sent empty, it is cleared. + private static string? Trimmed(string? update, string? before) => update is null ? before : update.Trim() is { Length: > 0 } text ? text : null; +} diff --git a/src/Backend/Auth/SignIn/AutomaticDirectory.cs b/src/Backend/Auth/SignIn/AutomaticDirectory.cs new file mode 100644 index 0000000..44adef3 --- /dev/null +++ b/src/Backend/Auth/SignIn/AutomaticDirectory.cs @@ -0,0 +1,228 @@ +using Backend.Data; +using Backend.Security; +using Microsoft.EntityFrameworkCore; + +namespace Backend.Auth; + +/// What one pass of did. +public enum AutomaticDirectoryChange +{ + None, + TurnedOn, + Updated, + TurnedOff, +} + +/// +/// Automatic LDAP: on a domain-joined Windows server whose LDAP settings no +/// administrator has changed, LDAP is on with settings taken from the join: +/// the domain the controller locator finds, Kerberos with signing and sealing, +/// lookups bound as the computer account. It follows the join until an +/// administrator saves the LDAP tab, which makes it theirs. A breaker turns +/// it off after repeated directory failures, so sign-in falls back to the +/// other methods, until someone turns it on again. +/// +public sealed class AutomaticDirectory(IServiceScopeFactory scopes, IDomainMembership membership, SettingsDocuments documents, + ILogger logger) +{ + public const string BreakerKey = "breaker:ldap"; + + /// The settings automatic LDAP uses for , keeping the breaker's numbers and state from . + public static LdapSignInSettings For(string dnsDomain, LdapSignInSettings keep) => new( + dnsDomain, + [dnsDomain], + 389, + LdapSecurity.Kerberos, + BaseDnOf(dnsDomain), + null, + null, + LdapSignInSettings.DefaultUserFilter, + null, + null, + true, + 10, + Automatic: true, + keep.BreakerFailures, + keep.BreakerWindowMinutes, + keep.BreakerTrippedUtc); + + /// corp.example.com is searched under DC=corp,DC=example,DC=com. + public static string BaseDnOf(string dnsDomain) => string.Join(',', dnsDomain.Trim().TrimEnd('.').Split('.').Select(label => $"DC={label}")); + + /// Brings automatic LDAP in line with the join; settings an administrator saved are left alone. + public async Task ApplyAsync(CancellationToken cancellationToken) + { + var join = membership.Read(); + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var ldapRow = await SettingsDocuments.LoadAsync(db, LdapSignInSettings.Key, cancellationToken); + var ldapBefore = SettingsDocuments.ParseOrNull(ldapRow?.Value); + if (ldapBefore is { Automatic: false }) + { + return AutomaticDirectoryChange.None; + } + + var methodsRow = await SettingsDocuments.LoadAsync(db, AuthenticationMethods.Key, cancellationToken); + var methods = SettingsDocuments.Parse(methodsRow?.Value, AuthenticationMethods.Defaults); + var current = ldapBefore ?? LdapSignInSettings.Defaults; + LdapSignInSettings ldapAfter; + AuthenticationMethods methodsAfter; + AutomaticDirectoryChange change; + if (join?.DnsName is { } domain) + { + ldapAfter = For(domain, current); + methodsAfter = methods with { Ldap = ldapAfter.BreakerTrippedUtc is null }; + change = ldapBefore is null || !methods.Ldap ? AutomaticDirectoryChange.TurnedOn : AutomaticDirectoryChange.Updated; + } + else if (join is null && ldapBefore is not null) + { + // Out of the domain: off, and still automatic, so a new join turns it on again. + ldapAfter = current; + methodsAfter = methods with { Ldap = false }; + change = AutomaticDirectoryChange.TurnedOff; + } + else + { + // A workgroup server that never had it, or a joined one whose controller does not answer yet: nothing to do now. + return AutomaticDirectoryChange.None; + } + + var ldapChanged = SettingsDocuments.Stage(db, ldapRow, LdapSignInSettings.Key, ldapBefore, ldapAfter, "system"); + var methodsChanged = SettingsDocuments.Stage(db, methodsRow, AuthenticationMethods.Key, methodsRow is null ? null : methods, methodsAfter, "system", + always: methods.Ldap != methodsAfter.Ldap); + if (!ldapChanged && !methodsChanged) + { + return AutomaticDirectoryChange.None; + } + + try + { + await db.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateException) + { + // Another node applied the join at the same moment; the next pass finds its result. + return AutomaticDirectoryChange.None; + } + + documents.Invalidate(LdapSignInSettings.Key, AuthenticationMethods.Key); + await scope.ServiceProvider.GetRequiredService().LogAsync(AuditCategories.Settings, "settings.authentication.ldap.automatic", "system", + detail: $"change={change} domain={join?.DnsName ?? "(none)"} ldap={methodsAfter.Ldap}", cancellationToken: cancellationToken); + if (change == AutomaticDirectoryChange.TurnedOn && methodsAfter.Ldap) + { + logger.LogInformation("LDAP sign-in is on for the domain {Domain}, set up from this server's domain join.", join!.DnsName); + } + else if (change == AutomaticDirectoryChange.TurnedOff) + { + logger.LogInformation("This server left its domain, so automatic LDAP sign-in is off."); + } + + return change; + } + + /// + /// Counts a directory failure (a bind or search that did not complete, + /// never a wrong password) against automatic LDAP's breaker: past its number + /// within its window, LDAP turns off and one warning is logged. Settings an + /// administrator saved are never switched by it, and nor is LDAP when it is + /// the only method on, since that would leave no way in. + /// + public async Task FailedAsync(CancellationToken cancellationToken) + { + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var ldapRow = await SettingsDocuments.LoadAsync(db, LdapSignInSettings.Key, cancellationToken); + var ldap = SettingsDocuments.ParseOrNull(ldapRow?.Value); + var methodsRow = await SettingsDocuments.LoadAsync(db, AuthenticationMethods.Key, cancellationToken); + var methods = SettingsDocuments.Parse(methodsRow?.Value, AuthenticationMethods.Defaults); + if (ldap is not { Automatic: true, BreakerTrippedUtc: null } || !methods.Ldap) + { + return; + } + + var now = DateTimeOffset.UtcNow; + var row = await db.SignInThrottles.SingleOrDefaultAsync(t => t.Key == BreakerKey, cancellationToken); + if (row is null) + { + row = new SignInThrottleEntity { Key = BreakerKey, FirstFailureUtc = now }; + db.SignInThrottles.Add(row); + } + else if (now - row.FirstFailureUtc > TimeSpan.FromMinutes(ldap.BreakerWindowMinutes)) + { + row.Failures = 0; + row.FirstFailureUtc = now; + } + + row.Failures++; + row.LastFailureUtc = now; + var trip = row.Failures >= ldap.BreakerFailures && methods.On().Count > 1; + if (trip) + { + SettingsDocuments.Stage(db, ldapRow, LdapSignInSettings.Key, ldap, ldap with { BreakerTrippedUtc = now }, "system"); + SettingsDocuments.Stage(db, methodsRow, AuthenticationMethods.Key, methods, methods with { Ldap = false }, "system", always: true); + db.SignInThrottles.Remove(row); + } + + try + { + await db.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateException) + { + // Another node counted or tripped at the same moment; its count stands. + return; + } + + if (trip) + { + documents.Invalidate(LdapSignInSettings.Key, AuthenticationMethods.Key); + await scope.ServiceProvider.GetRequiredService().LogAsync(AuditCategories.Settings, "settings.authentication.ldap.breaker", "system", + detail: $"failures={row.Failures} windowMinutes={ldap.BreakerWindowMinutes} ldap=off", cancellationToken: cancellationToken); + logger.LogWarning( + "LDAP sign-in is off for safety after {Failures} directory failures within {Minutes} minutes; sign-in uses the other methods until it is turned on again in Settings › Authentication.", + row.Failures, ldap.BreakerWindowMinutes); + } + } + + /// Clears the breaker's count, for Turn On Again. + public async Task ResetCountAsync(CancellationToken cancellationToken) + { + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await db.SignInThrottles.Where(t => t.Key == BreakerKey).ExecuteDeleteAsync(cancellationToken); + } +} + +/// Applies automatic LDAP at start, then every , so a join or a departure is followed. +public sealed class AutomaticDirectoryWatch(AutomaticDirectory directory, ILogger logger) : BackgroundService +{ + public static readonly TimeSpan Interval = TimeSpan.FromMinutes(5); + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + if (!OperatingSystem.IsWindows()) + { + return; + } + + try + { + using var timer = new PeriodicTimer(Interval); + do + { + try + { + await directory.ApplyAsync(stoppingToken); + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + logger.LogWarning(exception, "Automatic LDAP could not follow the domain join; it tries again in a few minutes."); + } + } + while (await timer.WaitForNextTickAsync(stoppingToken)); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + } + } +} diff --git a/src/Backend/Auth/SignIn/BreakGlass.cs b/src/Backend/Auth/SignIn/BreakGlass.cs new file mode 100644 index 0000000..dd6fcca --- /dev/null +++ b/src/Backend/Auth/SignIn/BreakGlass.cs @@ -0,0 +1,326 @@ +using Backend.Data; +using Backend.Security; +using Backend.Settings; +using Microsoft.EntityFrameworkCore; + +namespace Backend.Auth; + +/// +/// The one break-glass built-in account: full access through no binding, kept +/// for recovery, audited on every use. Created on the first start of an empty +/// database: with INITIAL_ADMIN_USERNAME/INITIAL_ADMIN_PASSWORD when the +/// deployment set them, otherwise as admin with a generated password +/// written once to the log. The auth-reset verb gives it a new one-time +/// password. +/// +public sealed class BreakGlass(IServiceScopeFactory scopes) +{ + public const string DefaultUserName = "admin"; + public const string DisplayName = "Break-glass administrator"; + public const string AdministratorsSid = "S-1-5-32-544"; + + /// + /// Creates the account when no user exists yet. Returns the generated + /// password when this call created one, so the caller can show it once. + /// + public async Task EnsureAsync(string? userName, string? password, bool mustChange, CancellationToken cancellationToken) + { + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + if (await db.Users.AnyAsync(cancellationToken)) + { + return null; + } + + var generated = string.IsNullOrEmpty(password); + var secret = generated ? PasswordHashing.Generate() : password!; + var now = DateTimeOffset.UtcNow; + var user = new UserEntity + { + Id = Guid.NewGuid(), + Kind = SignInProviders.Local, + UserName = string.IsNullOrWhiteSpace(userName) ? DefaultUserName : userName.Trim(), + DisplayName = DisplayName, + PasswordHash = PasswordHashing.Hash(secret), + IsBreakGlass = true, + Enabled = true, + MustChangePassword = generated || mustChange, + CreatedUtc = now, + UpdatedUtc = now, + }; + db.Users.Add(user); + + // On Windows the machine's Administrators can sign in with their local Windows account from the start. It grants nothing new: + // a local administrator can already run auth-reset here. Listed and removable like any binding. + if (OperatingSystem.IsWindows() + && await db.Roles.AsNoTracking().SingleOrDefaultAsync(r => r.IsSystem && r.Name == "Admin", cancellationToken) is { } admin + && !await db.RoleBindings.AnyAsync(b => b.PrincipalKind == PrincipalKinds.WindowsGroup && b.PrincipalId == AdministratorsSid, cancellationToken)) + { + db.RoleBindings.Add(new RoleBindingEntity + { + Id = Guid.NewGuid(), + RoleId = admin.Id, + PrincipalKind = PrincipalKinds.WindowsGroup, + PrincipalId = AdministratorsSid, + PrincipalName = @"BUILTIN\Administrators", + CreatedUtc = now, + CreatedBy = "system", + }); + } + + try + { + await db.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateException) + { + return null; + } + + await scope.ServiceProvider.GetRequiredService().LogAsync(AuditCategories.Auth, "identity.break-glass.create", "system", + detail: $"user={user.UserName}", cancellationToken: cancellationToken); + return generated ? secret : null; + } + + /// + /// Gives a built-in account (the break-glass account when + /// is null, creating it if missing) a new generated password that must be + /// changed at the next sign-in, clears its back-off and ends its sessions. + /// + public async Task<(UserEntity User, string Password)> ResetAsync(string? userName, string actor, CancellationToken cancellationToken) + { + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var user = userName is null + ? await db.Users.FirstOrDefaultAsync(u => u.IsBreakGlass, cancellationToken) + : await db.Users.SingleOrDefaultAsync(u => u.Kind == SignInProviders.Local && u.UserName.ToLower() == userName.ToLower(), cancellationToken); + if (user is null && userName is not null) + { + throw new InvalidOperationException($"There is no built-in account named {userName}."); + } + + var now = DateTimeOffset.UtcNow; + var password = PasswordHashing.Generate(); + if (user is null) + { + var taken = await db.Users.AnyAsync(u => u.Kind == SignInProviders.Local && u.UserName == DefaultUserName, cancellationToken); + user = new UserEntity + { + Id = Guid.NewGuid(), + Kind = SignInProviders.Local, + UserName = taken ? $"{DefaultUserName}-recovery" : DefaultUserName, + DisplayName = DisplayName, + IsBreakGlass = true, + CreatedUtc = now, + }; + db.Users.Add(user); + } + + user.PasswordHash = PasswordHashing.Hash(password); + user.MustChangePassword = true; + user.Enabled = true; + user.PasswordChangedUtc = now; + user.UpdatedUtc = now; + var throttleKey = SignInThrottling.AccountKey(SignInProviders.Local, user.UserName); + await db.SignInThrottles.Where(t => t.Key == throttleKey).ExecuteDeleteAsync(cancellationToken); + await db.Sessions.Where(s => s.UserId == user.Id && s.RevokedUtc == null).ExecuteUpdateAsync(set => set.SetProperty(s => s.RevokedUtc, now), cancellationToken); + await db.SaveChangesAsync(cancellationToken); + await scope.ServiceProvider.GetRequiredService().LogAsync(AuditCategories.Auth, + user.IsBreakGlass ? "identity.break-glass.reset" : "auth.user.password.reset", actor, detail: $"user={user.UserName}", cancellationToken: cancellationToken); + return (user, password); + } +} + +/// +/// Runs once at start, after the database is migrated: seeds the system roles, +/// creates the break-glass account on an empty database, and brings an older +/// installation onto role bindings (once each, idempotently): +/// +/// each built-in user's own role becomes membership of a built-in group named after the role, bound to it; +/// the INITIAL_ADMIN_USERNAME account (or admin) becomes the break-glass account; +/// the old OIDC settings (database or OIDC_* environment) and AUTH_LOGIN_MODE become the sign-in documents; +/// roles' OIDC claim values and the old Admin/Operator/Viewer mappings become claim=value bindings. +/// +/// +public sealed class IdentityStartup(IServiceScopeFactory scopes, BreakGlass breakGlass, SettingsDocuments documents, SignInSecrets secrets, + RoleCache roleCache, AccessResolver access, IConfiguration configuration, ILogger logger) +{ + private const string LegacyPrefix = "auth."; + + public async Task RunAsync(CancellationToken cancellationToken) + { + using (var scope = scopes.CreateScope()) + { + await scope.ServiceProvider.GetRequiredService().EnsureSystemRolesAsync(cancellationToken); + } + + var userName = configuration["INITIAL_ADMIN_USERNAME"]; + var generated = await breakGlass.EnsureAsync(userName, configuration["INITIAL_ADMIN_PASSWORD"], + configuration["INITIAL_ADMIN_MUST_CHANGE"] is "1" or "true", cancellationToken); + if (generated is not null) + { + logger.LogWarning( + "First start: sign in as {User} with the one-time password {Password} and choose a new one. This is the only place it is shown; if it is lost, run the auth-reset verb on this server.", + string.IsNullOrWhiteSpace(userName) ? BreakGlass.DefaultUserName : userName.Trim(), generated); + } + + await UpgradeUsersAsync(userName, cancellationToken); + await UpgradeSettingsAsync(cancellationToken); + roleCache.Invalidate(); + access.Invalidate(); + } + + private async Task UpgradeUsersAsync(string? initialAdmin, CancellationToken cancellationToken) + { + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var legacy = await db.Users.Where(u => u.LegacyRoleId != null || u.LegacyRole != null).ToListAsync(cancellationToken); + if (legacy.Count > 0) + { + var roles = await db.Roles.AsNoTracking().ToListAsync(cancellationToken); + var now = DateTimeOffset.UtcNow; + foreach (var user in legacy) + { + var role = roles.FirstOrDefault(r => r.Id == user.LegacyRoleId) + ?? roles.FirstOrDefault(r => r.IsSystem && string.Equals(r.Name, user.LegacyRole, StringComparison.OrdinalIgnoreCase)); + if (role is not null && user.Kind == SignInProviders.Local) + { + var group = await db.LocalGroups.FirstOrDefaultAsync(g => g.Name == role.Name, cancellationToken) + ?? db.LocalGroups.Local.FirstOrDefault(g => g.Name == role.Name); + if (group is null) + { + group = new LocalGroupEntity { Id = Guid.NewGuid(), Name = role.Name, Description = $"{role.Name} role", CreatedUtc = now, UpdatedUtc = now }; + db.LocalGroups.Add(group); + } + + var principal = group.Id.ToString("D"); + if (!await db.RoleBindings.AnyAsync(b => b.PrincipalKind == PrincipalKinds.LocalGroup && b.PrincipalId == principal && b.RoleId == role.Id, cancellationToken) + && !db.RoleBindings.Local.Any(b => b.PrincipalId == principal && b.RoleId == role.Id)) + { + db.RoleBindings.Add(new RoleBindingEntity + { + Id = Guid.NewGuid(), RoleId = role.Id, PrincipalKind = PrincipalKinds.LocalGroup, PrincipalId = principal, + PrincipalName = group.Name, CreatedUtc = now, CreatedBy = "upgrade", + }); + } + + if (!await db.LocalGroupMembers.AnyAsync(m => m.GroupId == group.Id && m.UserId == user.Id, cancellationToken)) + { + db.LocalGroupMembers.Add(new LocalGroupMemberEntity { GroupId = group.Id, UserId = user.Id }); + } + } + + // Directory and identity-provider people get their access from their groups at each sign-in. + user.LegacyRoleId = null; + user.LegacyRole = null; + } + + await db.SaveChangesAsync(cancellationToken); + logger.LogInformation("Moved {Count} users' roles onto built-in groups and role bindings.", legacy.Count); + } + + if (!await db.Users.AnyAsync(u => u.IsBreakGlass, cancellationToken)) + { + var name = string.IsNullOrWhiteSpace(initialAdmin) ? BreakGlass.DefaultUserName : initialAdmin.Trim(); + var admin = await db.Users.FirstOrDefaultAsync(u => u.Kind == SignInProviders.Local && u.UserName == name, cancellationToken); + if (admin is not null) + { + admin.IsBreakGlass = true; + admin.Enabled = true; + await db.SaveChangesAsync(cancellationToken); + logger.LogInformation("{User} is the break-glass account.", admin.UserName); + } + } + } + + private async Task UpgradeSettingsAsync(CancellationToken cancellationToken) + { + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + if (await db.AppSettings.AnyAsync(s => s.Key == AuthenticationMethods.Key, cancellationToken)) + { + return; + } + + var saved = await scope.ServiceProvider.GetRequiredService().GetAllAsync(LegacyPrefix, cancellationToken); + string? Value(string key, string env) => saved.TryGetValue(LegacyPrefix + key, out var v) && v.Length > 0 ? v : configuration[env] is { Length: > 0 } e ? e : null; + + var mode = Value("loginMode", "AUTH_LOGIN_MODE") ?? "Both"; + var oidcOn = (Value("oidcEnabled", "OIDC_ENABLED") is "1" or "true" or "True") && Value("authority", "OIDC_AUTHORITY") is not null; + var methods = AuthenticationMethods.Defaults with + { + BuiltIn = !oidcOn || !mode.StartsWith("Oidc", StringComparison.OrdinalIgnoreCase), + Oidc = oidcOn && !mode.Equals("LocalOnly", StringComparison.OrdinalIgnoreCase), + OidcRedirect = oidcOn && mode.Equals("OidcAutoRedirect", StringComparison.OrdinalIgnoreCase), + }; + + var roleClaim = Value("roleClaim", "OIDC_ROLE_CLAIM") ?? "groups"; + if (Value("authority", "OIDC_AUTHORITY") is { } authority) + { + var secret = Value("clientSecret", "OIDC_CLIENT_SECRET"); + var scopesText = Value("scopes", "OIDC_SCOPES") ?? "openid profile email"; + var oidc = new OidcSignInSettings( + Value("providerName", "OIDC_PROVIDER_NAME") ?? OidcSignInSettings.Defaults.Label, + authority, + Value("clientId", "OIDC_CLIENT_ID"), + secret is null ? null : secrets.Seal(secret, OidcSignInSettings.ClientSecretPurpose), + [.. scopesText.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)], + Value("nameClaim", "OIDC_NAME_CLAIM") ?? OidcSignInSettings.Defaults.UserNameClaim, + [roleClaim]); + SettingsDocuments.Stage(db, null, OidcSignInSettings.Key, null, oidc, "upgrade"); + + // What used to map sign-ins to roles becomes claim=value bindings. + var roles = await db.Roles.ToListAsync(cancellationToken); + var now = DateTimeOffset.UtcNow; + void Bind(RoleEntity role, string value) + { + var id = $"{roleClaim}={value.Trim()}"; + if (!db.RoleBindings.Local.Any(b => b.PrincipalId == id && b.RoleId == role.Id)) + { + db.RoleBindings.Add(new RoleBindingEntity + { + Id = Guid.NewGuid(), RoleId = role.Id, PrincipalKind = PrincipalKinds.OidcGroup, PrincipalId = id, PrincipalName = value.Trim(), + CreatedUtc = now, CreatedBy = "upgrade", + }); + } + } + + foreach (var role in roles) + { + foreach (var value in RoleCache.ParseStrings(role.OidcClaimValuesJson).Where(v => v.Trim().Length > 0)) + { + Bind(role, value); + } + + role.OidcClaimValuesJson = null; + } + + foreach (var (key, env, roleName) in new[] { ("adminRole", "OIDC_ADMIN_ROLE", "Admin"), ("operatorRole", "OIDC_OPERATOR_ROLE", "Operator"), ("viewerRole", "OIDC_VIEWER_ROLE", "Viewer") }) + { + if (Value(key, env) is { } value && roles.FirstOrDefault(r => r.IsSystem && r.Name == roleName) is { } role) + { + Bind(role, value); + } + } + + if (Value("defaultRole", "OIDC_DEFAULT_ROLE") is { } defaultRole && Value("requireMappedRole", "OIDC_REQUIRE_MAPPED_ROLE") is not ("1" or "true")) + { + logger.LogWarning( + "The old OIDC default role ({Role}) has no equivalent: people now need a group claim bound to a role. Bind one in Settings › Authentication › OIDC.", + defaultRole); + } + } + + SettingsDocuments.Stage(db, null, AuthenticationMethods.Key, null, methods, "upgrade"); + try + { + await db.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateException) + { + // Another node wrote the documents first. + } + + documents.Invalidate(AuthenticationMethods.Key, OidcSignInSettings.Key); + } +} diff --git a/src/Backend/Auth/SignIn/LdapDirectory.cs b/src/Backend/Auth/SignIn/LdapDirectory.cs new file mode 100644 index 0000000..e9a7045 --- /dev/null +++ b/src/Backend/Auth/SignIn/LdapDirectory.cs @@ -0,0 +1,396 @@ +using System.DirectoryServices.Protocols; +using System.Net; +using System.Text; + +namespace Backend.Auth; + +/// A person the directory knows: a stable subject, the entry's DN, names, and the DNs of every group they are in. +public sealed record DirectoryAccount(string Subject, string DistinguishedName, string UserName, string? DisplayName, string? Email, IReadOnlyList Groups); + +/// A directory problem worth showing to whoever is configuring the provider: unreachable, refused bind, bad base DN. +public class DirectoryException(string message, Exception? inner = null) : Exception(message, inner); + +/// The name typed matches more than one entry (two accounts sharing an email address, say): refused rather than guessed. +public sealed class AmbiguousAccountException() + : DirectoryException("That name matches more than one directory account. Sign in with your account name instead."); + +/// The directory as sign-in, step-up and the settings page's test use it; a test double stands in for it without a directory. +public interface ILdapDirectory +{ + /// Connects and binds as the service account, and confirms the base DN exists. + void Probe(LdapSignInSettings settings); + + /// + /// The account when the password is right; null when the user is unknown or the password is wrong. Throws + /// when the name matches more than one entry. + /// + DirectoryAccount? Authenticate(LdapSignInSettings settings, string login, string password); +} + +/// +/// LDAP sign-in: a service account searches for the person, then the person binds as themselves. The user filter says which attributes a +/// typed name is matched against (by default the account name, user principal name and email address); a name matching two entries is refused. +/// Groups come from memberOf or the group filter; nested groups are followed (or left to Active Directory's matching rule in chain when +/// the filter uses it). TLS is LDAPS or StartTLS with the platform's certificate validation, which is never switched off; Kerberos (Active +/// Directory, on Windows) signs and seals instead, with lookups bound as the computer account; plain LDAP is accepted only on loopback. +/// +public sealed class LdapDirectory(SignInSecrets secrets) : ILdapDirectory +{ + public const string InChainRule = "1.2.840.113556.1.4.1941"; + private const int InvalidCredentials = 49; + private const int MaxGroups = 1000; + + private static readonly string[] UserAttributes = + ["objectGUID", "entryUUID", "sAMAccountName", "uid", "userPrincipalName", "displayName", "cn", "mail", "memberOf"]; + + /// Why these settings cannot be used, field by field; empty when they can. + public static Dictionary Validate(LdapSignInSettings settings) + { + var errors = new Dictionary(); + if (settings.Servers.Count == 0) + { + errors["servers"] = ["Add at least one directory server."]; + } + + if (settings.Port is < 1 or > 65535) + { + errors["port"] = ["The port is a number from 1 to 65535."]; + } + + if (!LdapSecurity.All.Contains(settings.Security)) + { + errors["security"] = [$"Choose one of: {string.Join(", ", LdapSecurity.All)}."]; + } + else if (settings.Security == LdapSecurity.None && !settings.Servers.All(IsLoopback)) + { + errors["security"] = ["Without TLS the bind passwords would cross the network in the clear; use LDAPS or StartTLS. Plain LDAP is only for a directory on this machine."]; + } + else if (settings.Security == LdapSecurity.Kerberos && !OperatingSystem.IsWindows()) + { + errors["security"] = ["Kerberos needs a Windows server in the domain; use LDAPS or StartTLS here."]; + } + + if (settings.BreakerFailures is < 3 or > 1000) + { + errors["breakerFailures"] = ["Enter 3 to 1000 failures."]; + } + + if (settings.BreakerWindowMinutes is < 1 or > 120) + { + errors["breakerWindowMinutes"] = ["Enter 1 to 120 minutes."]; + } + + if (string.IsNullOrWhiteSpace(settings.BaseDn)) + { + errors["baseDn"] = ["Enter the base DN people are searched under, for example dc=example,dc=com."]; + } + + if (!settings.UserFilter.Contains("{0}", StringComparison.Ordinal)) + { + errors["userFilter"] = ["The user filter must contain {0}, where the user name goes."]; + } + + if (settings.TimeoutSeconds is < 1 or > 120) + { + errors["timeoutSeconds"] = ["The timeout is 1 to 120 seconds."]; + } + + return errors; + } + + /// Connects and binds as the service account, and confirms the base DN exists. + public void Probe(LdapSignInSettings settings) + { + using var connection = Connect(settings); + BindService(connection, settings); + Send(connection, new SearchRequest(settings.BaseDn, "(objectClass=*)", SearchScope.Base, "objectClass")); + } + + /// The one entry the typed name finds; null when none does. Two or more are refused (). + public DirectoryAccount? Lookup(LdapSignInSettings settings, string login) + { + if (UserFilter(settings, login) is not { } filter) + { + return null; + } + + using var connection = Connect(settings); + BindService(connection, settings); + SearchResponse response; + try + { + response = (SearchResponse)connection.SendRequest(new SearchRequest(settings.BaseDn, filter, SearchScope.Subtree, UserAttributes) { SizeLimit = 2 }); + } + catch (DirectoryOperationException exception) when (exception.Response?.ResultCode == ResultCode.SizeLimitExceeded) + { + throw new AmbiguousAccountException(); + } + catch (Exception exception) when (exception is DirectoryOperationException or LdapException) + { + throw new DirectoryException($"The directory refused the search for the user: {exception.Message}", exception); + } + + if (!IsSingle(response.Entries.Count)) + { + return null; + } + + var entry = response.Entries[0]; + var userName = First(entry, "sAMAccountName") ?? First(entry, "uid") ?? First(entry, "userPrincipalName") ?? LoginName(login); + return new DirectoryAccount( + Subject(entry), + entry.DistinguishedName, + userName, + First(entry, "displayName") ?? First(entry, "cn"), + First(entry, "mail"), + Groups(connection, settings, entry, userName)); + } + + /// + /// The search for a typed name: the user filter with every {0} replaced by the name, escaped (RFC 4515); null when nothing was typed. + /// The name is only ever an assertion value, so it cannot add a clause, a wildcard or a second filter. + /// + public static string? UserFilter(LdapSignInSettings settings, string login) + { + var name = LoginName(login); + return name.Length == 0 ? null : settings.UserFilter.Replace("{0}", Escape(name), StringComparison.Ordinal); + } + + /// Whether a search found the one entry to sign in: none is false, and more than one is refused, never guessed. + public static bool IsSingle(int matches) => matches switch + { + 0 => false, + 1 => true, + _ => throw new AmbiguousAccountException(), + }; + + public DirectoryAccount? Authenticate(LdapSignInSettings settings, string login, string password) + { + if (string.IsNullOrEmpty(password)) + { + return null; + } + + var account = Lookup(settings, login); + if (account is null) + { + return null; + } + + using var connection = Connect(settings); + try + { + // Kerberos checks the password with the domain, sealed; a simple bind sends it inside TLS. + connection.Bind(settings.Security == LdapSecurity.Kerberos + ? new NetworkCredential(account.UserName, password, DomainOf(account.DistinguishedName)) + : new NetworkCredential(account.DistinguishedName, password)); + } + catch (LdapException exception) when (exception.ErrorCode == InvalidCredentials) + { + return null; + } + catch (LdapException exception) + { + throw new DirectoryException($"The directory could not check the password: {exception.Message}", exception); + } + + return account; + } + + /// RFC 4515 escaping, so a user name can never change the shape of the search filter. + public static string Escape(string value) + { + var builder = new StringBuilder(value.Length); + foreach (var character in value) + { + builder.Append(character switch + { + '\\' => @"\5c", + '*' => @"\2a", + '(' => @"\28", + ')' => @"\29", + '\0' => @"\00", + _ => character.ToString(), + }); + } + + return builder.ToString(); + } + + /// EXAMPLE\jdoe is looked up as jdoe; user principal names are kept for filters that match them. + public static string LoginName(string login) + { + var trimmed = login.Trim(); + var slash = trimmed.LastIndexOf('\\'); + return slash >= 0 ? trimmed[(slash + 1)..] : trimmed; + } + + public static bool IsLoopback(string host) => + host.Equals("localhost", StringComparison.OrdinalIgnoreCase) || (IPAddress.TryParse(host.Trim('[', ']'), out var address) && IPAddress.IsLoopback(address)); + + /// The DNS domain of an Active Directory entry: CN=Jane,OU=Staff,DC=corp,DC=example,DC=com is in corp.example.com. + public static string DomainOf(string distinguishedName) => + string.Join('.', distinguishedName.Split(',').Select(part => part.Trim()).Where(part => part.StartsWith("DC=", StringComparison.OrdinalIgnoreCase)) + .Select(part => part[3..])); + + private LdapConnection Connect(LdapSignInSettings settings) + { + var kerberos = settings.Security == LdapSecurity.Kerberos; + + // With Kerberos a domain name is found through the domain controller locator; otherwise each server is a host name. + var connection = new LdapConnection(new LdapDirectoryIdentifier([.. settings.Servers], settings.Port, fullyQualifiedDnsHostName: !kerberos, connectionless: false)) + { + AuthType = kerberos ? AuthType.Kerberos : AuthType.Basic, + Timeout = TimeSpan.FromSeconds(settings.TimeoutSeconds), + }; + connection.SessionOptions.ProtocolVersion = 3; + connection.SessionOptions.ReferralChasing = ReferralChasingOptions.None; + try + { + if (kerberos) + { + if (!OperatingSystem.IsWindows()) + { + throw new DirectoryException("Kerberos needs a Windows server in the domain."); + } + + connection.SessionOptions.Signing = true; + connection.SessionOptions.Sealing = true; + } + else if (settings.Security == LdapSecurity.Ldaps) + { + connection.SessionOptions.SecureSocketLayer = true; + } + else if (settings.Security == LdapSecurity.StartTls) + { + connection.SessionOptions.StartTransportLayerSecurity(null); + } + else if (!settings.Servers.All(IsLoopback)) + { + throw new DirectoryException("Plain LDAP is only allowed to a directory on this machine."); + } + } + catch (Exception exception) when (exception is LdapException or DirectoryOperationException) + { + connection.Dispose(); + throw new DirectoryException($"TLS to the directory could not be established: {exception.Message}", exception); + } + + return connection; + } + + private void BindService(LdapConnection connection, LdapSignInSettings settings) + { + try + { + if (settings.Security == LdapSecurity.Kerberos) + { + // The service's own network identity: the computer account when it runs as a system account; no password is stored. + connection.Bind(); + return; + } + + if (string.IsNullOrWhiteSpace(settings.BindDn)) + { + connection.AuthType = AuthType.Anonymous; + connection.Bind(); + connection.AuthType = AuthType.Basic; + return; + } + + var password = settings.BindPassword is { Length: > 0 } sealedPassword ? secrets.Open(sealedPassword, LdapSignInSettings.BindPasswordPurpose) : null; + connection.Bind(new NetworkCredential(settings.BindDn, password ?? string.Empty)); + } + catch (LdapException exception) + { + throw new DirectoryException(exception.ErrorCode == InvalidCredentials + ? "The directory refused the service account's DN or password." + : $"The directory could not be reached or refused the service account: {exception.Message}", exception); + } + } + + private static DirectoryResponse Send(LdapConnection connection, DirectoryRequest request) + { + try + { + return connection.SendRequest(request); + } + catch (Exception exception) when (exception is DirectoryOperationException or LdapException) + { + throw new DirectoryException($"The directory refused the request: {exception.Message}", exception); + } + } + + private static List Groups(LdapConnection connection, LdapSignInSettings settings, SearchResultEntry user, string name) + { + var direct = string.IsNullOrWhiteSpace(settings.GroupFilter) + ? Values(user, "memberOf").ToList() + : GroupsByFilter(connection, settings, user.DistinguishedName, name); + + var resolvedByServer = settings.GroupFilter?.Contains(InChainRule, StringComparison.Ordinal) == true; + if (!settings.NestedGroups || resolvedByServer) + { + return direct; + } + + var seen = new HashSet(direct, StringComparer.OrdinalIgnoreCase); + var pending = new Queue(seen); + while (pending.Count > 0 && seen.Count < MaxGroups) + { + var group = pending.Dequeue(); + var parents = string.IsNullOrWhiteSpace(settings.GroupFilter) ? MemberOf(connection, group) : GroupsByFilter(connection, settings, group, name); + foreach (var parent in parents.Where(seen.Add)) + { + pending.Enqueue(parent); + } + } + + return [.. seen.Take(MaxGroups)]; + } + + private static List GroupsByFilter(LdapConnection connection, LdapSignInSettings settings, string memberDn, string name) + { + var filter = settings.GroupFilter!.Replace("{dn}", Escape(memberDn), StringComparison.Ordinal).Replace("{0}", Escape(name), StringComparison.Ordinal); + var request = new SearchRequest(settings.GroupBaseDn is { Length: > 0 } groupBase ? groupBase : settings.BaseDn, filter, SearchScope.Subtree, "cn") + { + SizeLimit = MaxGroups, + }; + + try + { + return [.. ((SearchResponse)connection.SendRequest(request)).Entries.Cast().Select(entry => entry.DistinguishedName)]; + } + catch (DirectoryOperationException exception) when (exception.Response is SearchResponse partial) + { + return [.. partial.Entries.Cast().Select(entry => entry.DistinguishedName)]; + } + } + + private static List MemberOf(LdapConnection connection, string groupDn) + { + try + { + var response = (SearchResponse)connection.SendRequest(new SearchRequest(groupDn, "(objectClass=*)", SearchScope.Base, "memberOf")); + return response.Entries.Count == 1 ? [.. Values(response.Entries[0], "memberOf")] : []; + } + catch (DirectoryOperationException) + { + return []; + } + } + + private static string Subject(SearchResultEntry entry) + { + if (entry.Attributes["objectGUID"]?.GetValues(typeof(byte[])) is [byte[] { Length: 16 } guid, ..]) + { + return new Guid(guid).ToString("D"); + } + + return First(entry, "entryUUID") ?? entry.DistinguishedName.ToLowerInvariant(); + } + + private static string? First(SearchResultEntry entry, string attribute) => Values(entry, attribute).FirstOrDefault(value => value.Length > 0); + + private static IEnumerable Values(SearchResultEntry entry, string attribute) => + entry.Attributes[attribute]?.GetValues(typeof(string)).Cast() ?? []; +} diff --git a/src/Backend/Auth/SignIn/OidcSignIn.cs b/src/Backend/Auth/SignIn/OidcSignIn.cs new file mode 100644 index 0000000..ef2b0e8 --- /dev/null +++ b/src/Backend/Auth/SignIn/OidcSignIn.cs @@ -0,0 +1,381 @@ +using System.Collections.Concurrent; +using System.Net.Http.Headers; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.IdentityModel.JsonWebTokens; +using Microsoft.IdentityModel.Protocols; +using Microsoft.IdentityModel.Protocols.OpenIdConnect; +using Microsoft.IdentityModel.Tokens; +using Backend.Data; + +using Backend.Proxy; + +namespace Backend.Auth; + +/// What the identity provider said about the person, after the ID token checked out. +public sealed record OidcIdentity(SignInRequestEntity Request, string Subject, string UserName, string? DisplayName, string? Email, IReadOnlyList Groups) +{ + /// When the provider says the person last authenticated (the ID token's auth_time); null when it did not say. + public DateTimeOffset? AuthTime { get; init; } +} + +public static class SignInRequestStatus +{ + public const string Pending = "pending"; + public const string Passed = "passed"; + public const string Failed = "failed"; +} + +/// +/// OpenID Connect sign-in: authorization code with PKCE. The state, nonce and verifier are kept in the database so the callback can land +/// on any node, and each is used once. The redirect and post-logout URIs are computed per request from the detected base URL, so sign-in works +/// on whichever name the console was reached by. +/// +public sealed class OidcSignIn(SignInSettings settings, SignInSecrets secrets, IHttpClientFactory http, IServiceScopeFactory scopes, IConfiguration configuration) +{ + public const string HttpClientName = "oidc"; + public const string CallbackPath = "/api/auth/oidc/callback"; + public const string SignInPagePath = "/sign-in"; + public static readonly TimeSpan RequestLifetime = TimeSpan.FromMinutes(10); + + private readonly ConcurrentDictionary> _configurations = new(StringComparer.Ordinal); + + /// The base URL this server is reached by: PUBLIC_SERVER_URL, else the request (through trusted proxies). + public string BaseUrl(HttpContext context) => PublicUrl.Resolve(context, configuration); + + public string RedirectUri(HttpContext context) => BaseUrl(context) + CallbackPath; + + public string PostLogoutRedirectUri(HttpContext context) => BaseUrl(context) + SignInPagePath; + + /// Why the settings cannot be used, by field; empty when they can. + public static Dictionary Validate(OidcSignInSettings value) + { + var errors = new Dictionary(); + if (!TryAuthority(value.Authority, out _, out var problem)) + { + errors["authority"] = [problem]; + } + + if (string.IsNullOrWhiteSpace(value.ClientId)) + { + errors["clientId"] = ["Enter the client id the provider issued for this server."]; + } + + if (!value.Scopes.Contains("openid")) + { + errors["scopes"] = ["The scopes must include openid."]; + } + + if (string.IsNullOrWhiteSpace(value.UserNameClaim)) + { + errors["userNameClaim"] = ["Name the claim that holds the user name, for example preferred_username."]; + } + + return errors; + } + + /// An absolute https URL, or http to this machine's loopback for a provider under test. + public static bool TryAuthority(string? authority, out Uri uri, out string problem) + { + problem = "Enter the issuer URL, for example https://login.example.com/realms/main."; + if (string.IsNullOrWhiteSpace(authority) || !Uri.TryCreate(authority.Trim(), UriKind.Absolute, out uri!) || uri.Query.Length > 0 || uri.Fragment.Length > 0) + { + uri = null!; + return false; + } + + if (uri.Scheme != Uri.UriSchemeHttps && !(uri.Scheme == Uri.UriSchemeHttp && LdapDirectory.IsLoopback(uri.DnsSafeHost))) + { + problem = "The issuer must be an https URL."; + return false; + } + + return true; + } + + /// + /// Starts a sign-in (or a test sign-in for , or a step-up of ) and returns + /// the provider's authorization URL. A step-up asks the provider to authenticate the person afresh: prompt=login and max_age=0. + /// + public async Task BeginAsync(HttpContext context, string? returnUrl, string? testSessionId, CancellationToken cancellationToken, + string? stepUpSessionId = null) + { + var (value, etag) = await settings.OidcAsync(cancellationToken); + var configuration = await ConfigurationAsync(value, cancellationToken); + var now = DateTimeOffset.UtcNow; + var request = new SignInRequestEntity + { + Id = RandomText.UrlSafe(32), + Provider = SignInProviders.Oidc, + Status = SignInRequestStatus.Pending, + Nonce = RandomText.UrlSafe(32), + CodeVerifier = RandomText.UrlSafe(32), + ReturnUrl = returnUrl, + TestSessionId = testSessionId, + StepUpSessionId = stepUpSessionId, + SettingsEtag = etag, + CreatedUtc = now, + ExpiresUtc = now + RequestLifetime, + }; + + using (var scope = scopes.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.SignInRequests.Add(request); + await db.SaveChangesAsync(cancellationToken); + await db.SignInRequests.Where(r => r.ExpiresUtc < now && r.TestSessionId == null).ExecuteDeleteAsync(cancellationToken); + } + + var challenge = Base64UrlEncoder.Encode(SHA256.HashData(Encoding.ASCII.GetBytes(request.CodeVerifier))); + var query = new Dictionary + { + ["response_type"] = "code", + ["client_id"] = value.ClientId, + ["redirect_uri"] = RedirectUri(context), + ["scope"] = string.Join(' ', value.Scopes), + ["state"] = request.Id, + ["nonce"] = request.Nonce, + ["code_challenge"] = challenge, + ["code_challenge_method"] = "S256", + }; + if (stepUpSessionId is not null) + { + query["prompt"] = "login"; + query["max_age"] = "0"; + } + + return Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(configuration.AuthorizationEndpoint, query); + } + + /// + /// What the request named by is for, read before the callback takes it: the session it steps up (null for a sign-in or + /// a test), and whether it is a test sign-in. Nothing for no such request. + /// + public async Task<(string? StepUpSession, bool Test)> RequestKindAsync(string? state, CancellationToken cancellationToken) + { + if (string.IsNullOrEmpty(state)) + { + return (null, false); + } + + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var kind = await db.SignInRequests.AsNoTracking().Where(r => r.Id == state).Select(r => new { r.StepUpSessionId, r.TestSessionId }) + .FirstOrDefaultAsync(cancellationToken); + return (kind?.StepUpSessionId, kind?.TestSessionId is not null); + } + + /// + /// Takes the request named by (once: a replayed callback finds nothing), exchanges the code and validates the ID + /// token: issuer, audience, signature, lifetime and nonce. + /// + public async Task CompleteAsync(HttpContext context, string? code, string? state, CancellationToken cancellationToken) + { + var now = DateTimeOffset.UtcNow; + SignInRequestEntity? request; + using (var scope = scopes.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + request = string.IsNullOrEmpty(state) ? null : await db.SignInRequests.AsNoTracking() + .SingleOrDefaultAsync(r => r.Id == state && r.Provider == SignInProviders.Oidc && r.Status == SignInRequestStatus.Pending, cancellationToken); + if (request is null || now >= request.ExpiresUtc) + { + throw new OidcException("This sign-in has expired or was already used; start again."); + } + + var claimed = request.TestSessionId is null + ? await db.SignInRequests.Where(r => r.Id == request.Id && r.Status == SignInRequestStatus.Pending).ExecuteDeleteAsync(cancellationToken) + : await db.SignInRequests.Where(r => r.Id == request.Id && r.Status == SignInRequestStatus.Pending) + .ExecuteUpdateAsync(set => set.SetProperty(r => r.Status, SignInRequestStatus.Failed).SetProperty(r => r.CompletedUtc, now), cancellationToken); + if (claimed != 1) + { + throw new OidcException("This sign-in was already used; start again."); + } + } + + if (string.IsNullOrEmpty(code)) + { + throw new OidcException("The identity provider did not return an authorization code."); + } + + var (value, _) = await settings.OidcAsync(cancellationToken); + var configuration = await ConfigurationAsync(value, cancellationToken); + var idToken = await RedeemAsync(context, value, configuration, code, request.CodeVerifier!, cancellationToken); + + var validation = await new JsonWebTokenHandler().ValidateTokenAsync(idToken, new TokenValidationParameters + { + ValidIssuer = configuration.Issuer, + ValidAudience = value.ClientId, + IssuerSigningKeys = configuration.SigningKeys, + ValidateIssuerSigningKey = true, + RequireSignedTokens = true, + RequireExpirationTime = true, + ClockSkew = TimeSpan.FromMinutes(2), + }); + if (!validation.IsValid || validation.SecurityToken is not JsonWebToken token) + { + throw new OidcException($"The ID token was not valid: {validation.Exception?.Message ?? "unknown reason"}"); + } + + if (!token.TryGetPayloadValue("nonce", out var nonce) || nonce != request.Nonce) + { + throw new OidcException("The ID token was not issued for this sign-in."); + } + + var subject = token.Subject; + if (string.IsNullOrEmpty(subject)) + { + throw new OidcException("The ID token has no subject."); + } + + var claims = token.Claims.ToList(); + string? Claim(string type) => claims.FirstOrDefault(c => c.Type == type)?.Value is { Length: > 0 } v ? v : null; + var userName = Claim(value.UserNameClaim) ?? Claim("email") ?? subject; + var groups = value.GroupClaims + .SelectMany(type => claims.Where(c => c.Type == type).Select(c => new GroupRef(PrincipalKinds.OidcGroup, $"{type}={c.Value}", c.Value))) + .DistinctBy(g => g.Key) + .ToList(); + DateTimeOffset? authTime = token.TryGetPayloadValue("auth_time", out var seconds) ? DateTimeOffset.FromUnixTimeSeconds(seconds) : null; + return new OidcIdentity(request, subject, userName, Claim("name"), Claim("email"), groups) { AuthTime = authTime }; + } + + /// Records a test sign-in's outcome against the session that started it. + public async Task RecordTestAsync(string requestId, bool passed, string detail, CancellationToken cancellationToken) + { + var now = DateTimeOffset.UtcNow; + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await db.SignInRequests.Where(r => r.Id == requestId).ExecuteUpdateAsync(set => set + .SetProperty(r => r.Status, passed ? SignInRequestStatus.Passed : SignInRequestStatus.Failed) + .SetProperty(r => r.Detail, detail.Length > 2000 ? detail[..2000] : detail) + .SetProperty(r => r.CompletedUtc, now), cancellationToken); + } + + /// The provider's end-session URL for a sign-out, returning to the console's sign-in page; null when it has none. + public async Task EndSessionUrlAsync(HttpContext context, CancellationToken cancellationToken) + { + var (value, _) = await settings.OidcAsync(cancellationToken); + if (string.IsNullOrEmpty(value.ClientId)) + { + return null; + } + + try + { + var configuration = await ConfigurationAsync(value, cancellationToken); + return string.IsNullOrEmpty(configuration.EndSessionEndpoint) + ? null + : Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(configuration.EndSessionEndpoint, new Dictionary + { + ["client_id"] = value.ClientId, + ["post_logout_redirect_uri"] = PostLogoutRedirectUri(context), + }); + } + catch (OidcException) + { + return null; + } + } + + private async Task ConfigurationAsync(OidcSignInSettings value, CancellationToken cancellationToken) + { + if (!TryAuthority(value.Authority, out var authority, out var problem)) + { + throw new OidcException(problem); + } + + var metadata = authority.AbsoluteUri.TrimEnd('/') + "/.well-known/openid-configuration"; + if (_configurations.Count > 8) + { + _configurations.Clear(); + } + + var manager = _configurations.GetOrAdd(metadata, address => new ConfigurationManager(address, + new OpenIdConnectConfigurationRetriever(), + new HttpDocumentRetriever(http.CreateClient(HttpClientName)) { RequireHttps = authority.Scheme == Uri.UriSchemeHttps }) + { + AutomaticRefreshInterval = TimeSpan.FromHours(12), + RefreshInterval = TimeSpan.FromMinutes(1), + }); + + try + { + return await manager.GetConfigurationAsync(cancellationToken); + } + catch (Exception exception) when (exception is InvalidOperationException or IOException or HttpRequestException) + { + _configurations.TryRemove(metadata, out _); + throw new OidcException($"The identity provider's discovery document at {metadata} could not be read: {exception.Message}"); + } + } + + private async Task RedeemAsync(HttpContext context, OidcSignInSettings value, OpenIdConnectConfiguration configuration, string code, string verifier, + CancellationToken cancellationToken) + { + var secret = value.ClientSecret is { Length: > 0 } sealedSecret ? secrets.Open(sealedSecret, OidcSignInSettings.ClientSecretPurpose) : null; + var form = new Dictionary + { + ["grant_type"] = "authorization_code", + ["code"] = code, + ["redirect_uri"] = RedirectUri(context), + ["code_verifier"] = verifier, + ["client_id"] = value.ClientId!, + }; + + using var message = new HttpRequestMessage(HttpMethod.Post, configuration.TokenEndpoint); + var methods = configuration.TokenEndpointAuthMethodsSupported; + if (secret is not null) + { + if (methods.Count == 0 || methods.Contains("client_secret_basic")) + { + var pair = Uri.EscapeDataString(value.ClientId!) + ":" + Uri.EscapeDataString(secret); + message.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(pair))); + } + else + { + form["client_secret"] = secret; + } + } + + message.Content = new FormUrlEncodedContent(form); + message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + HttpResponseMessage response; + try + { + response = await http.CreateClient(HttpClientName).SendAsync(message, cancellationToken); + } + catch (HttpRequestException exception) + { + throw new OidcException($"The identity provider's token endpoint could not be reached: {exception.Message}"); + } + + using (response) + { + var body = await response.Content.ReadAsStringAsync(cancellationToken); + try + { + using var json = JsonDocument.Parse(body); + if (!response.IsSuccessStatusCode) + { + var error = json.RootElement.TryGetProperty("error", out var e) ? e.GetString() : null; + var description = json.RootElement.TryGetProperty("error_description", out var d) ? d.GetString() : null; + throw new OidcException($"The identity provider refused the code: {error ?? response.StatusCode.ToString()} {description}".Trim()); + } + + return json.RootElement.TryGetProperty("id_token", out var idToken) && idToken.GetString() is { Length: > 0 } text + ? text + : throw new OidcException("The identity provider returned no ID token; check that the openid scope is requested."); + } + catch (JsonException) + { + throw new OidcException($"The identity provider's token endpoint answered {(int)response.StatusCode} with a body that is not JSON."); + } + } + } +} + +/// A sign-in through the identity provider could not complete; the message says why, without secrets. +public sealed class OidcException(string message) : Exception(message); diff --git a/src/Backend/Auth/SignIn/PasswordHashing.cs b/src/Backend/Auth/SignIn/PasswordHashing.cs new file mode 100644 index 0000000..23f9f22 --- /dev/null +++ b/src/Backend/Auth/SignIn/PasswordHashing.cs @@ -0,0 +1,124 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using Backend.Data; +using Microsoft.AspNetCore.Identity; + +namespace Backend.Auth; + +public enum PasswordCheck +{ + Failed, + Succeeded, + + /// Correct, but hashed with older parameters (or the older ASP.NET format): hash it again now that the password is known. + SucceededNeedsRehash, +} + +/// +/// Password hashes as $pbkdf2-sha512$i=<iterations>$<salt>$<hash> +/// (unpadded base64). The algorithm and its cost are in the string, so a +/// stronger setting is adopted on the next successful sign-in. Hashes from +/// before this format (ASP.NET Identity's) still verify, and are replaced then. +/// +public static class PasswordHashing +{ + public const string Algorithm = "pbkdf2-sha512"; + + /// OWASP's current recommendation for PBKDF2-HMAC-SHA512. + public const int Iterations = 210_000; + + /// Longer input is refused before hashing, so a megabyte "password" cannot be used to burn CPU. + public const int MaxLength = 1024; + + private const int SaltBytes = 16; + private const int HashBytes = 64; + + private static readonly string Dummy = Hash("not-a-password-" + Convert.ToHexString(RandomNumberGenerator.GetBytes(8))); + private static readonly PasswordHasher Legacy = new(); + + public static string Hash(string password, int iterations = Iterations) + { + ArgumentNullException.ThrowIfNull(password); + ArgumentOutOfRangeException.ThrowIfGreaterThan(password.Length, MaxLength, nameof(password)); + var salt = RandomNumberGenerator.GetBytes(SaltBytes); + var hash = Derive(password, salt, iterations, HashBytes); + return string.Create(CultureInfo.InvariantCulture, $"${Algorithm}$i={iterations}${Encode(salt)}${Encode(hash)}"); + } + + public static PasswordCheck Verify(string password, string? stored) + { + if (!string.IsNullOrEmpty(password) && password.Length <= MaxLength && stored is { Length: > 0 } && !stored.StartsWith('$')) + { + // An ASP.NET Identity hash from before: correct means hash it again in the current format. + return Legacy.VerifyHashedPassword(null!, stored, password) == PasswordVerificationResult.Failed + ? PasswordCheck.Failed + : PasswordCheck.SucceededNeedsRehash; + } + + if (string.IsNullOrEmpty(password) || password.Length > MaxLength || !TryParse(stored, out var iterations, out var salt, out var expected)) + { + // The same work as a real check, so a missing account takes as long to refuse as a wrong password. + _ = TryParse(Dummy, out iterations, out salt, out expected); + _ = Derive(password ?? string.Empty, salt, iterations, expected.Length); + return PasswordCheck.Failed; + } + + var actual = Derive(password, salt, iterations, expected.Length); + if (!CryptographicOperations.FixedTimeEquals(actual, expected)) + { + return PasswordCheck.Failed; + } + + return iterations < Iterations ? PasswordCheck.SucceededNeedsRehash : PasswordCheck.Succeeded; + } + + /// A password nobody chose: characters from an alphabet without look-alikes. + public static string Generate(int length = 24) + { + const string Alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789"; + return RandomNumberGenerator.GetString(Alphabet, length); + } + + private static byte[] Derive(string password, byte[] salt, int iterations, int length) => + Rfc2898DeriveBytes.Pbkdf2(Encoding.UTF8.GetBytes(password), salt, iterations, HashAlgorithmName.SHA512, length); + + private static bool TryParse(string? stored, out int iterations, out byte[] salt, out byte[] hash) + { + iterations = 0; + salt = []; + hash = []; + var parts = stored?.Split('$'); + if (parts is not ["", Algorithm, var cost, var saltText, var hashText] || !cost.StartsWith("i=", StringComparison.Ordinal) + || !int.TryParse(cost.AsSpan(2), NumberStyles.None, CultureInfo.InvariantCulture, out iterations) || iterations < 1) + { + return false; + } + + try + { + salt = Decode(saltText); + hash = Decode(hashText); + return salt.Length > 0 && hash.Length > 0; + } + catch (FormatException) + { + return false; + } + } + + private static string Encode(byte[] bytes) => Convert.ToBase64String(bytes).TrimEnd('='); + + private static byte[] Decode(string text) => Convert.FromBase64String(text.PadRight(text.Length + ((4 - (text.Length % 4)) % 4), '=')); +} + +/// Random URL-safe text and digests for session ids, secrets and CSRF tokens. +public static class RandomText +{ + public static string UrlSafe(int bytes) => Convert.ToBase64String(RandomNumberGenerator.GetBytes(bytes)).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + + public static string Sha256Hex(string value) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(value))).ToLowerInvariant(); + + public static bool SameDigest(string? expected, string actual) => + expected is not null && CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(expected), Encoding.ASCII.GetBytes(actual)); +} diff --git a/src/Backend/Auth/SignIn/Sessions.cs b/src/Backend/Auth/SignIn/Sessions.cs new file mode 100644 index 0000000..348b429 --- /dev/null +++ b/src/Backend/Auth/SignIn/Sessions.cs @@ -0,0 +1,326 @@ +using System.Security.Claims; +using System.Text.Encodings.Web; +using Backend.Data; +using Backend.Proxy; +using Microsoft.AspNetCore.Authentication; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; + +namespace Backend.Auth; + +/// +/// The session and CSRF cookies. Over HTTPS they carry the __Host- +/// prefix and Secure; both names are read, so a request a proxy +/// forwards as HTTPS still finds a cookie set over plain HTTP in testing. +/// +public static class SessionCookies +{ + public const string SecureSession = "__Host-session"; + public const string PlainSession = "session"; + public const string SecureCsrf = "__Host-csrf"; + public const string PlainCsrf = "csrf"; + public const string CsrfHeader = "X-CSRF-Token"; + + public static string? ReadSession(HttpContext context) => + context.Request.Cookies[SecureSession] is { Length: > 0 } secure ? secure : context.Request.Cookies[PlainSession]; + + public static void Write(HttpContext context, string session, string csrf, DateTimeOffset expiresUtc) + { + var secure = context.Request.IsHttps; + context.Response.Cookies.Append(secure ? SecureSession : PlainSession, session, new CookieOptions + { + HttpOnly = true, + Secure = secure, + SameSite = SameSiteMode.Lax, + Path = "/", + Expires = expiresUtc, + IsEssential = true, + }); + + // Readable by the console, which sends it back as a header on every unsafe request. + context.Response.Cookies.Append(secure ? SecureCsrf : PlainCsrf, csrf, new CookieOptions + { + HttpOnly = false, + Secure = secure, + SameSite = SameSiteMode.Strict, + Path = "/", + Expires = expiresUtc, + IsEssential = true, + }); + } + + public static void Clear(HttpContext context) + { + foreach (var (name, secure) in new[] { (SecureSession, true), (PlainSession, false), (SecureCsrf, true), (PlainCsrf, false) }) + { + if (context.Request.Cookies.ContainsKey(name)) + { + context.Response.Cookies.Delete(name, new CookieOptions { Path = "/", Secure = secure }); + } + } + } +} + +/// Who is calling: the person, how they signed in, their groups and what those groups grant. +public sealed record Caller +{ + public required Guid UserId { get; init; } + public required string Name { get; init; } + public string? DisplayName { get; init; } + public required string Provider { get; init; } + public required IReadOnlyList Groups { get; init; } + public required EffectiveAccess Access { get; init; } + public bool BreakGlass { get; init; } + public bool PasswordChangeRequired { get; init; } + public string? SessionId { get; init; } +} + +public static class CallerContext +{ + private const string Key = "executer.caller"; + + public static Caller? Caller(this HttpContext context) => context.Items[Key] as Caller; + + public static Caller RequireCaller(this HttpContext context) => + context.Caller() ?? throw new AuthProblemException(new AuthProblem("unauthorized", StatusCodes.Status401Unauthorized, "Sign in first.")); + + public static void SetCaller(this HttpContext context, Caller caller) => context.Items[Key] = caller; + + /// The claims the rest of the backend reads: name, roles (for permissions and device scope), provider and session. + public static ClaimsPrincipal Principal(Caller caller) + { + var identity = new ClaimsIdentity(AuthConstants.SessionScheme, ClaimTypes.Name, ClaimTypes.Role); + identity.AddClaim(new Claim(ClaimTypes.Name, caller.Name)); + identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, caller.UserId.ToString("D"))); + identity.AddClaim(new Claim(AuthConstants.ProviderClaim, caller.Provider)); + if (!string.IsNullOrWhiteSpace(caller.DisplayName)) + { + identity.AddClaim(new Claim(AuthConstants.DisplayNameClaim, caller.DisplayName)); + } + + if (caller.SessionId is { } session) + { + identity.AddClaim(new Claim(AuthConstants.SessionClaim, session)); + } + + if (caller.BreakGlass) + { + identity.AddClaim(new Claim(AuthConstants.BreakGlassClaim, "true")); + } + + if (caller.PasswordChangeRequired) + { + identity.AddClaim(new Claim(AuthConstants.PasswordChangeClaim, "true")); + } + + foreach (var role in caller.Access.Roles) + { + identity.AddClaim(new Claim(AuthConstants.RoleIdClaim, role.Id.ToString("D"))); + identity.AddClaim(new Claim(ClaimTypes.Role, role.Name)); + } + + return new ClaimsPrincipal(identity); + } +} + +/// +/// Browser sessions as database rows: any node serves any request, and +/// sign-out is immediate everywhere because every request reads the row. +/// Expiry slides with use up to an absolute limit; the row is touched at most +/// once a minute. +/// +public sealed class SessionStore(IServiceScopeFactory scopes, SignInSettings settings, AccessResolver access) +{ + public static readonly TimeSpan TouchInterval = TimeSpan.FromMinutes(1); + + public async Task CreateAsync(HttpContext context, UserEntity user, string provider, IReadOnlyList groups, + CancellationToken cancellationToken) + { + var lifetimes = await settings.LifetimesAsync(cancellationToken); + var now = DateTimeOffset.UtcNow; + var secret = RandomText.UrlSafe(32); + var csrf = RandomText.UrlSafe(32); + var absolute = now + lifetimes.SessionMax; + var session = new SessionEntity + { + Id = RandomText.UrlSafe(16), + UserId = user.Id, + SecretHash = RandomText.Sha256Hex(secret), + CsrfHash = RandomText.Sha256Hex(csrf), + Provider = provider, + GroupsJson = GroupRefs.Serialize(groups), + CreatedUtc = now, + LastSeenUtc = now, + ExpiresUtc = Min(now + lifetimes.SessionIdle, absolute), + AbsoluteExpiresUtc = absolute, + ClientAddress = ClientIp.EffectiveText(context), + UserAgent = context.Request.Headers.UserAgent.ToString() is { Length: > 0 } agent ? agent[..Math.Min(agent.Length, 512)] : null, + }; + + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.Sessions.Add(session); + await db.SaveChangesAsync(cancellationToken); + + // Expired rows are swept here rather than by a job: sign-ins are the only thing that adds rows. + var stale = now - TimeSpan.FromDays(1); + await db.Sessions.Where(s => s.AbsoluteExpiresUtc < stale || s.ExpiresUtc < stale).ExecuteDeleteAsync(cancellationToken); + + SessionCookies.Write(context, $"{session.Id}.{secret}", csrf, absolute); + return session; + } + + /// The caller behind a session cookie, or null when the cookie names no live session. + public async Task<(Caller Caller, SessionEntity Session)?> AuthenticateAsync(string cookie, CancellationToken cancellationToken) + { + var dot = cookie.IndexOf('.', StringComparison.Ordinal); + if (dot <= 0 || dot > 64 || cookie.Length > 200) + { + return null; + } + + var id = cookie[..dot]; + var secret = cookie[(dot + 1)..]; + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var session = await db.Sessions.AsNoTracking().Include(s => s.User).SingleOrDefaultAsync(s => s.Id == id, cancellationToken); + var now = DateTimeOffset.UtcNow; + if (session?.User is not { Enabled: true } user || !RandomText.SameDigest(session.SecretHash, RandomText.Sha256Hex(secret)) + || session.RevokedUtc is not null || now >= session.ExpiresUtc || now >= session.AbsoluteExpiresUtc) + { + return null; + } + + var groups = GroupRefs.Parse(session.GroupsJson); + if (now - session.LastSeenUtc >= TouchInterval) + { + var lifetimes = await settings.LifetimesAsync(cancellationToken); + var expires = Min(now + lifetimes.SessionIdle, session.AbsoluteExpiresUtc); + if (user.Kind == SignInProviders.Local) + { + // Built-in memberships are this server's own, so they are refreshed with the session rather than only at sign-in. + groups = await GroupRefs.LocalAsync(db, user.Id, cancellationToken); + } + + var json = GroupRefs.Serialize(groups); + await db.Sessions.Where(s => s.Id == id && s.RevokedUtc == null).ExecuteUpdateAsync(set => set + .SetProperty(s => s.LastSeenUtc, now).SetProperty(s => s.ExpiresUtc, expires).SetProperty(s => s.GroupsJson, json), cancellationToken); + session.ExpiresUtc = expires; + } + + var caller = new Caller + { + UserId = user.Id, + Name = user.UserName, + DisplayName = user.DisplayName, + Provider = session.Provider, + Groups = groups, + Access = await access.ResolveAsync(groups, user.IsBreakGlass, cancellationToken), + BreakGlass = user.IsBreakGlass, + PasswordChangeRequired = user.MustChangePassword && user.Kind == SignInProviders.Local, + SessionId = session.Id, + }; + return (caller, session); + } + + public async Task RevokeAsync(string sessionId, CancellationToken cancellationToken) + { + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var now = DateTimeOffset.UtcNow; + await db.Sessions.Where(s => s.Id == sessionId && s.RevokedUtc == null).ExecuteUpdateAsync(set => set.SetProperty(s => s.RevokedUtc, now), cancellationToken); + } + + /// Ends every session of a person, except (the one making the change, when it is theirs). + public async Task RevokeAllAsync(Guid userId, string? except, CancellationToken cancellationToken) + { + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var now = DateTimeOffset.UtcNow; + return await db.Sessions.Where(s => s.UserId == userId && s.RevokedUtc == null && s.Id != except) + .ExecuteUpdateAsync(set => set.SetProperty(s => s.RevokedUtc, now), cancellationToken); + } + + public static bool CsrfMatches(SessionEntity session, string? header) => + !string.IsNullOrEmpty(header) && header.Length <= 128 && RandomText.SameDigest(session.CsrfHash, RandomText.Sha256Hex(header)); + + private static DateTimeOffset Min(DateTimeOffset a, DateTimeOffset b) => a < b ? a : b; +} + +/// +/// The session cookie as ASP.NET authentication: a live session becomes the +/// request's user (claims carry its roles), and its CSRF hash is checked on +/// every unsafe request. API calls are answered 401/403, never redirected. +/// +public sealed class SessionAuthenticationHandler( + IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, SessionStore sessions) + : AuthenticationHandler(options, logger, encoder) +{ + private const string SessionItem = "executer.session"; + + protected override async Task HandleAuthenticateAsync() + { + if (SessionCookies.ReadSession(Context) is not { } cookie) + { + return AuthenticateResult.NoResult(); + } + + var found = await sessions.AuthenticateAsync(cookie, Context.RequestAborted); + if (found is not { } live) + { + return AuthenticateResult.NoResult(); + } + + Context.SetCaller(live.Caller); + Context.Items[SessionItem] = live.Session; + return AuthenticateResult.Success(new AuthenticationTicket(CallerContext.Principal(live.Caller), Scheme.Name)); + } + + protected override Task HandleChallengeAsync(AuthenticationProperties properties) + { + Response.StatusCode = StatusCodes.Status401Unauthorized; + return Task.CompletedTask; + } + + protected override Task HandleForbiddenAsync(AuthenticationProperties properties) + { + Response.StatusCode = StatusCodes.Status403Forbidden; + return Task.CompletedTask; + } + + public static SessionEntity? Session(HttpContext context) => context.Items[SessionItem] as SessionEntity; +} + +/// +/// Request rules a signed-in session carries: the CSRF header on unsafe +/// requests (double submit, checked against the session's hash), and a +/// forced password change before anything but the session and the change. +/// +public static class SessionGuards +{ + private static readonly string[] AllowedBeforePasswordChange = + ["/api/auth/session", "/api/auth/password", "/api/auth/sign-out", "/api/auth/options", "/api/messaging"]; + + public static async Task Middleware(HttpContext context, RequestDelegate next) + { + var session = SessionAuthenticationHandler.Session(context); + if (session is not null && context.Request.Path.StartsWithSegments("/api")) + { + if (!HttpMethods.IsGet(context.Request.Method) && !HttpMethods.IsHead(context.Request.Method) && !HttpMethods.IsOptions(context.Request.Method) + && !SessionStore.CsrfMatches(session, context.Request.Headers[SessionCookies.CsrfHeader])) + { + await AuthProblemHandling.WriteAsync(context, new AuthProblemException(AuthProblems.Csrf)); + return; + } + + if (context.Caller() is { PasswordChangeRequired: true } + && !AllowedBeforePasswordChange.Any(p => context.Request.Path.StartsWithSegments(p, StringComparison.OrdinalIgnoreCase))) + { + await AuthProblemHandling.WriteAsync(context, new AuthProblemException(AuthProblems.PasswordChangeRequired)); + return; + } + } + + await next(context); + } +} diff --git a/src/Backend/Auth/SignIn/SettingsDocuments.cs b/src/Backend/Auth/SignIn/SettingsDocuments.cs new file mode 100644 index 0000000..17c40d0 --- /dev/null +++ b/src/Backend/Auth/SignIn/SettingsDocuments.cs @@ -0,0 +1,160 @@ +using System.Collections.Concurrent; +using System.Security.Cryptography; +using Backend.Data; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Serialization; + +namespace Backend.Auth; + +/// +/// Settings kept as whole JSON documents in the AppSettings table, each with an +/// etag that changes on every write so a page saves with If-Match and a +/// concurrent edit is refused instead of lost. Reads go through a short cache +/// (every request's sign-in check reads the methods), invalidated at once on +/// the node that writes. +/// +public sealed class SettingsDocuments(IServiceScopeFactory scopes) +{ + public const string InitialEtag = "0"; + private static readonly TimeSpan CacheLifetime = TimeSpan.FromSeconds(5); + + private readonly ConcurrentDictionary cache = new(StringComparer.Ordinal); + + public static string NewEtag() => Convert.ToHexString(RandomNumberGenerator.GetBytes(8)).ToLowerInvariant(); + + public async ValueTask<(T Value, string Etag)> GetAsync(string key, T defaults, CancellationToken cancellationToken) + where T : class + { + if (!cache.TryGetValue(key, out var entry) || DateTimeOffset.UtcNow - entry.Loaded > CacheLifetime) + { + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var row = await db.AppSettings.AsNoTracking().SingleOrDefaultAsync(s => s.Key == key, cancellationToken); + entry = (row?.Value, row?.Etag ?? InitialEtag, DateTimeOffset.UtcNow); + cache[key] = entry; + } + + return (Parse(entry.Json, defaults), entry.Etag); + } + + public static T Parse(string? json, T defaults) + where T : class + { + if (string.IsNullOrWhiteSpace(json)) + { + return defaults; + } + + try + { + return JsonDefaults.Deserialize(json) ?? defaults; + } + catch (System.Text.Json.JsonException) + { + return defaults; + } + } + + /// The stored document, or null when there is none (or it does not parse). + public static T? ParseOrNull(string? json) + where T : class + { + if (string.IsNullOrWhiteSpace(json)) + { + return null; + } + + try + { + return JsonDefaults.Deserialize(json); + } + catch (System.Text.Json.JsonException) + { + return null; + } + } + + public static Task LoadAsync(AppDbContext db, string key, CancellationToken cancellationToken) => + db.AppSettings.SingleOrDefaultAsync(s => s.Key == key, cancellationToken); + + /// + /// Writes onto the tracked row (adding it when + /// missing) with a new etag; nothing when unchanged unless + /// . The caller saves. True when written. + /// + public static bool Stage(AppDbContext db, AppSettingEntity? row, string key, T? before, T after, string? actor, bool always = false) + where T : class + { + var json = JsonDefaults.Serialize(after); + if (!always && before is not null && row is not null && json == JsonDefaults.Serialize(before)) + { + return false; + } + + if (row is null) + { + db.AppSettings.Add(new AppSettingEntity { Key = key, Value = json, Etag = NewEtag(), UpdatedUtc = DateTimeOffset.UtcNow, UpdatedBy = actor }); + } + else + { + row.Value = json; + row.Etag = NewEtag(); + row.UpdatedUtc = DateTimeOffset.UtcNow; + row.UpdatedBy = actor; + } + + return true; + } + + public void Invalidate(params string[] keys) + { + foreach (var key in keys) + { + cache.TryRemove(key, out _); + } + } +} + +/// +/// Seals sign-in secrets (the LDAP service account's password, the OIDC client +/// secret) with Data Protection under a purpose per secret, so the database +/// never holds them in the clear and one cannot be opened as the other. +/// +public sealed class SignInSecrets(IDataProtectionProvider provider) +{ + public string Seal(string value, string purpose) => provider.CreateProtector($"Backend.SignIn.{purpose}").Protect(value); + + /// The secret, or null when it can no longer be opened (the key ring was replaced). + public string? Open(string sealedValue, string purpose) + { + try + { + return provider.CreateProtector($"Backend.SignIn.{purpose}").Unprotect(sealedValue); + } + catch (CryptographicException) + { + return null; + } + } +} + +/// Quoted etags for ETag and If-Match. +public static class ETags +{ + public static string Quote(string etag) => $"\"{etag}\""; + + /// Refuses a save whose If-Match is missing (428) or names another version (412). + public static void RequireMatch(string? ifMatch, string current) + { + if (string.IsNullOrWhiteSpace(ifMatch)) + { + throw new AuthProblemException(AuthProblems.PreconditionRequired); + } + + if (ifMatch.Trim() != "*" && ifMatch.Trim().Trim('"') != current) + { + throw new AuthProblemException(AuthProblems.PreconditionFailed); + } + } +} diff --git a/src/Backend/Auth/SignIn/SignInEndpoints.cs b/src/Backend/Auth/SignIn/SignInEndpoints.cs new file mode 100644 index 0000000..344c4ef --- /dev/null +++ b/src/Backend/Auth/SignIn/SignInEndpoints.cs @@ -0,0 +1,209 @@ +using Backend.Data; +using Backend.Security; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Api; + +namespace Backend.Auth; + +/// Sign-in, sign-out and the session, through the built-in form and the providers that are on; and step-up. +public static class SignInEndpoints +{ + public const string DefaultReturnUrl = "/"; + + public static void Map(WebApplication app) + { + app.MapGet(ApiRoutes.AuthOptions, OptionsAsync).AllowAnonymous(); + app.MapPost(ApiRoutes.AuthSignIn, async (SignInBody body, SignInService signIn, HttpContext context) => + Results.Ok(await signIn.PasswordSignInAsync(context, body, context.RequestAborted))) + .AllowAnonymous() + .RequireRateLimiting(RateLimitPolicies.Auth); + app.MapGet(ApiRoutes.AuthSession, SessionAsync).RequireSignedIn(); + app.MapPost(ApiRoutes.AuthSignOut, SignOutAsync).RequireSignedIn(); + app.MapPost(ApiRoutes.AuthPassword, async (PasswordChangeBody body, SignInService signIn, HttpContext context) => + Results.Ok(await signIn.ChangePasswordAsync(context, body, context.RequestAborted))) + .RequireSignedIn() + .RequireRateLimiting(RateLimitPolicies.Auth); + app.MapGet(ApiRoutes.AuthOidcSignIn, OidcSignInAsync).AllowAnonymous(); + app.MapGet(ApiRoutes.AuthOidcCallback, OidcCallbackAsync).AllowAnonymous(); + + app.MapGet(ApiRoutes.AuthStepUp, async (StepUpService stepUp, HttpContext context) => + Results.Ok(await stepUp.StatusAsync(context.RequireCaller(), context.RequestAborted))).RequireSignedIn(); + app.MapPost(ApiRoutes.AuthStepUp, async (StepUpBody body, StepUpService stepUp, HttpContext context) => + Results.Ok(await stepUp.VerifyAsync(context, body, context.RequestAborted))) + .RequireSignedIn() + .RequireRateLimiting(RateLimitPolicies.Auth); + app.MapGet(ApiRoutes.AuthStepUpOidc, StepUpOidcAsync).RequireSignedIn(); + } + + /// A path on this console to return to: relative, rooted, and not protocol-relative, so it can never leave the server. + public static string SafeReturnUrl(string? returnUrl) => + returnUrl is { Length: > 0 and < 2000 } url && url.StartsWith('/') && !url.StartsWith("//", StringComparison.Ordinal) + && !url.StartsWith("/\\", StringComparison.Ordinal) && !url.Contains("://", StringComparison.Ordinal) + ? url + : DefaultReturnUrl; + + private static string SignInPage(string error) => $"/sign-in?error={Uri.EscapeDataString(error)}"; + + private static async Task OptionsAsync(SignInSettings settings, SignInService signIn, AuthenticationStore store, HttpContext context) + { + var ct = context.RequestAborted; + var providers = new List(); + foreach (var provider in SignInProviders.External) + { + if (await settings.IsUsableAsync(provider, ct)) + { + providers.Add(new SignInOption(provider, await settings.LabelAsync(provider, ct), provider == SignInProviders.Ldap ? "form" : "redirect")); + } + } + + context.Response.Headers.CacheControl = "no-store"; + return Results.Ok(new SignInOptions(await signIn.BuiltInAllowedAsync(ct), await settings.IsUsableAsync(SignInProviders.Windows, ct), providers, + await store.RedirectAsync(ct))); + } + + private static async Task SessionAsync(AppDbContext db, HttpContext context) + { + var caller = context.RequireCaller(); + var session = SessionAuthenticationHandler.Session(context); + var user = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == caller.UserId, context.RequestAborted); + context.Response.Headers.CacheControl = "no-store"; + return Results.Ok(SignInService.View(caller, session, user)); + } + + private static async Task SignOutAsync(SignInService signIn, OidcSignIn oidc, HttpContext context) + { + var caller = context.RequireCaller(); + await signIn.SignOutAsync(context, context.RequestAborted); + var endSession = caller.Provider == SignInProviders.Oidc ? await oidc.EndSessionUrlAsync(context, context.RequestAborted) : null; + return Results.Ok(new SignOutResult(endSession)); + } + + private static async Task OidcSignInAsync(HttpContext context, SignInSettings settings, OidcSignIn oidc, ILogger logger) + { + var ct = context.RequestAborted; + if (!await settings.IsUsableAsync(SignInProviders.Oidc, ct)) + { + return Results.Redirect(SignInPage("oidc-off")); + } + + try + { + return Results.Redirect(await oidc.BeginAsync(context, SafeReturnUrl(context.Request.Query["returnUrl"]), null, ct)); + } + catch (OidcException exception) + { + logger.LogWarning("OIDC sign-in could not start: {Error}", exception.Message); + return Results.Redirect(SignInPage("oidc-unavailable")); + } + } + + private static async Task OidcCallbackAsync(HttpContext context, OidcSignIn oidc, SignInService signIn, SignInSettings settings, + AccessResolver access, StepUpService stepUp, ILogger logger) + { + var ct = context.RequestAborted; + var query = context.Request.Query; + var (stepUpSession, test) = await oidc.RequestKindAsync(query["state"], ct); + OidcIdentity identity; + try + { + if (query["error"].ToString() is { Length: > 0 } error) + { + throw new OidcException($"The identity provider answered {error}: {query["error_description"]}"); + } + + identity = await oidc.CompleteAsync(context, query["code"], query["state"], ct); + } + catch (OidcException exception) + { + logger.LogWarning("OIDC sign-in failed: {Error}", exception.Message); + if (query["state"].ToString() is { Length: > 0 } state) + { + await oidc.RecordTestAsync(state, passed: false, exception.Message, ct); + } + + if (stepUpSession is not null) + { + await signIn.AuditAsync(context, "auth.step-up", SignInProviders.Oidc, context.Caller()?.Name ?? "(unknown)", "failed", exception.Message, ct); + return StepUpBack("/step-up/done", verified: false); + } + + if (test) + { + // A test sign-in the provider refused goes back to its tab, never to the sign-in page (which may send it straight to the provider). + return Results.Redirect($"{AuthenticationSettingsEndpoints.TabPath(SignInProviders.Oidc)}?test=failed"); + } + + await signIn.AuditAsync(context, "auth.sign-in", SignInProviders.Oidc, "(unknown)", "failed", exception.Message, ct); + return Results.Redirect(SignInPage("oidc-failed")); + } + + if (identity.Request.StepUpSessionId is not null) + { + var refused = await stepUp.CompleteOidcAsync(context, identity, ct); + if (refused is not null) + { + logger.LogWarning("An OIDC step-up was refused: {Reason}", refused); + } + + return StepUpBack(identity.Request.ReturnUrl, verified: refused is null); + } + + if (identity.Request.TestSessionId is not null) + { + var granted = await access.ResolveAsync(identity.Groups, breakGlass: false, ct); + var passed = granted.Any; + await oidc.RecordTestAsync(identity.Request.Id, passed, passed + ? $"Signed in as {identity.UserName}: {string.Join(", ", granted.Roles.Select(r => r.Name))} from {identity.Groups.Count} group claims." + : $"Signed in as {identity.UserName}, but none of the {identity.Groups.Count} group claims is bound to a role.", ct); + return Results.Redirect($"{AuthenticationSettingsEndpoints.TabPath(SignInProviders.Oidc)}?test={(passed ? "passed" : "failed")}"); + } + + if (!await settings.IsUsableAsync(SignInProviders.Oidc, ct)) + { + // Turned off while the person was at the provider. + return Results.Redirect(SignInPage("oidc-off")); + } + + try + { + var user = await signIn.UpsertExternalAsync(SignInProviders.Oidc, identity.Subject, identity.UserName, identity.DisplayName, identity.Email, ct); + await signIn.CompleteAsync(context, user, SignInProviders.Oidc, identity.Groups, ct); + } + catch (AuthProblemException problem) when (problem.Problem == AuthProblems.NoAccess) + { + return Results.Redirect(SignInPage("no-access")); + } + + return Results.Redirect(SafeReturnUrl(identity.Request.ReturnUrl)); + } + + /// Re-authentication with the identity provider: prompt=login and max_age=0, back at the shared callback. + private static async Task StepUpOidcAsync(HttpContext context, SignInSettings settings, OidcSignIn oidc, ILogger logger) + { + var ct = context.RequestAborted; + var caller = context.RequireCaller(); + var returnUrl = context.Request.Query["returnUrl"].ToString(); + if (caller is not { Provider: SignInProviders.Oidc, SessionId: { } session } || !await settings.IsUsableAsync(SignInProviders.Oidc, ct)) + { + return StepUpBack(returnUrl, verified: false); + } + + try + { + return Results.Redirect(await oidc.BeginAsync(context, SafeReturnUrl(returnUrl), null, ct, stepUpSessionId: session)); + } + catch (OidcException exception) + { + logger.LogWarning("An OIDC step-up could not start: {Error}", exception.Message); + return StepUpBack(returnUrl, verified: false); + } + } + + /// Back to the console page that asked, with how it went: stepUp=verified or stepUp=failed. + private static IResult StepUpBack(string? returnUrl, bool verified) + { + var path = SafeReturnUrl(returnUrl); + var separator = path.Contains('?', StringComparison.Ordinal) ? '&' : '?'; + return Results.Redirect($"{path}{separator}stepUp={(verified ? "verified" : "failed")}"); + } +} diff --git a/src/Backend/Auth/SignIn/SignInService.cs b/src/Backend/Auth/SignIn/SignInService.cs new file mode 100644 index 0000000..d7031fe --- /dev/null +++ b/src/Backend/Auth/SignIn/SignInService.cs @@ -0,0 +1,478 @@ +using System.Diagnostics; +using Backend.Data; +using Backend.Proxy; +using Backend.Security; +using Microsoft.EntityFrameworkCore; + +namespace Backend.Auth; + +public sealed record SignInBody(string? Provider, string? UserName, string? Password); + +public sealed record PasswordChangeBody(string? CurrentPassword, string? NewPassword); + +public sealed record GroupView(string Kind, string Id, string? Name); + +public sealed record RoleGrantView(Guid Id, string Name); + +/// +/// GET /api/auth/session: who is signed in, through what, in which +/// groups, holding which roles and permissions, until when. For a Windows +/// account also its description, SID and the server's local groups it is in. +/// +public sealed record SessionView( + string Id, + string UserName, + string? DisplayName, + string Provider, + bool BreakGlass, + bool PasswordChangeRequired, + IReadOnlyList Groups, + IReadOnlyList Roles, + IReadOnlyList Permissions, + DateTimeOffset? ExpiresUtc, + DateTimeOffset? AbsoluteExpiresUtc, + string? Description, + string? Sid, + IReadOnlyList WindowsGroups); + +public sealed record SignOutResult(string? EndSessionUrl); + +/// The groups and access a test sign-in found, shown on the settings page; nobody is signed in. +public sealed record SignInTestResult(bool Passed, string Provider, string? UserName, IReadOnlyList Groups, IReadOnlyList Roles, + IReadOnlyList Permissions, string? Detail); + +/// +/// Everything common to signing someone in, whichever provider vouched for +/// them: refusing a person whose groups grant nothing, creating the session, +/// and recording the sign-in (and every use of the break-glass account). +/// +public sealed class SignInService( + IServiceScopeFactory scopes, + SessionStore sessions, + AccessResolver access, + SignInThrottling throttling, + SignInSettings settings, + ILdapDirectory ldap, + ILocalAccounts localAccounts, + ILocalLogon localLogon, + AutomaticDirectory automaticDirectory, + SignInEnvironment environment, + ILogger logger) +{ + public const int MinPasswordLength = 12; + + /// + /// While local Windows accounts are on, a refused sign-in through the form + /// is answered no sooner than this after it began, so the answer takes as + /// long whether the name was a built-in account, a Windows account or neither. + /// + public static readonly TimeSpan UniformRefusal = TimeSpan.FromSeconds(1); + + /// + /// Sign-in with a name and a password, throttled per account and per client + /// address. local checks a name that is an enabled built-in account + /// as one, and otherwise (or always for .\name and MACHINE\name) + /// this server's local Windows accounts when they are on; ldap checks + /// the directory. With no provider (a script's credential) a domain or user + /// principal name goes to the directory, and a plain name to the local + /// checks, or to the directory when neither of those is on. + /// + public async Task PasswordSignInAsync(HttpContext context, SignInBody body, CancellationToken cancellationToken) + { + var requested = string.IsNullOrWhiteSpace(body.Provider) ? null : body.Provider.Trim().ToLowerInvariant(); + var userName = body.UserName?.Trim() ?? string.Empty; + var password = body.Password ?? string.Empty; + if (requested is not (null or SignInProviders.Local or SignInProviders.Ldap)) + { + throw AuthProblemException.InvalidFields(new Dictionary { ["provider"] = ["Sign in with a password through local or ldap, or name no provider."] }); + } + + if (userName.Length is 0 or > 256 || password.Length is 0 or > PasswordHashing.MaxLength) + { + throw AuthProblemException.InvalidFields(new Dictionary { ["userName"] = ["Enter a user name and a password."] }); + } + + var builtIn = await BuiltInAllowedAsync(cancellationToken); + var windows = await settings.IsUsableAsync(SignInProviders.Windows, cancellationToken); + var directory = await settings.IsUsableAsync(SignInProviders.Ldap, cancellationToken); + var provider = requested ?? Route(userName, builtIn, windows, directory); + if (provider == SignInProviders.Local && !builtIn && !windows) + { + throw new AuthProblemException(AuthProblems.Forbidden, "Built-in accounts are turned off here."); + } + + if (provider == SignInProviders.Ldap && !directory) + { + throw new AuthProblemException(AuthProblems.Forbidden, "Directory sign-in is not turned on."); + } + + // One key whichever check runs, so being held back says nothing about which kind of account a name is. + var accountKey = SignInThrottling.AccountKey(provider, + provider == SignInProviders.Local ? WindowsSignIn.ParseName(userName, Environment.MachineName)?.Name ?? userName : userName); + var addressKey = SignInThrottling.AddressKey(ClientIp.EffectiveText(context)); + if (await throttling.BlockedUntilAsync([accountKey, addressKey], cancellationToken) is { } until) + { + await AuditAsync(context, "auth.sign-in", provider, userName, "refused", "held back after repeated failures", cancellationToken); + throw new AuthProblemException(AuthProblems.TooManyAttempts) { RetryAfterSeconds = SignInThrottling.SecondsUntil(until) }; + } + + var started = Stopwatch.GetTimestamp(); + UserEntity? user; + IReadOnlyList groups; + try + { + (user, groups) = provider == SignInProviders.Local + ? await VerifyLocalAsync(userName, password, builtIn, windows, cancellationToken) + : await VerifyLdapAsync(userName, password, cancellationToken); + } + catch (AmbiguousAccountException ambiguous) + { + // Counted like a failure, so the answer cannot be used to probe which addresses are shared more cheaply than a password. + await throttling.FailedAsync(accountKey, addressKey, cancellationToken); + await AuditAsync(context, "auth.sign-in", provider, userName, "refused", "the name matches more than one directory account", cancellationToken); + throw new AuthProblemException(AuthProblems.SignInFailed, ambiguous.Message); + } + + if (user is null) + { + await throttling.FailedAsync(accountKey, addressKey, cancellationToken); + await AuditAsync(context, "auth.sign-in", provider, userName, "refused", "wrong user name or password", cancellationToken); + while (provider == SignInProviders.Local && windows && UniformRefusal - Stopwatch.GetElapsedTime(started) is { Ticks: > 0 } rest) + { + await Task.Delay(rest, cancellationToken); + } + + throw new AuthProblemException(AuthProblems.SignInFailed); + } + + await throttling.SucceededAsync(accountKey, cancellationToken); + return await CompleteAsync(context, user, user.Kind == SignInProviders.Windows ? SignInProviders.Windows : provider, groups, cancellationToken); + } + + /// Where a name with no provider goes: the directory for a domain or user principal name, otherwise the local checks when one is on. + public static string Route(string userName, bool builtIn, bool windows, bool directory) + { + if (WindowsSignIn.IsDirectoryName(userName, Environment.MachineName)) + { + return directory ? SignInProviders.Ldap : SignInProviders.Local; + } + + return builtIn || windows || !directory ? SignInProviders.Local : SignInProviders.Ldap; + } + + /// Signs a vouched-for person in: refuses one whose groups grant nothing, creates the session and records it. + public async Task CompleteAsync(HttpContext context, UserEntity user, string provider, IReadOnlyList groups, + CancellationToken cancellationToken) + { + var granted = await access.ResolveAsync(groups, user.IsBreakGlass, cancellationToken); + if (!granted.Any) + { + await AuditAsync(context, "auth.sign-in", provider, user.UserName, "refused", "no group of theirs is bound to a role", cancellationToken); + throw new AuthProblemException(AuthProblems.NoAccess); + } + + var session = await sessions.CreateAsync(context, user, provider, groups, cancellationToken); + using (var scope = scopes.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var now = DateTimeOffset.UtcNow; + await db.Users.Where(u => u.Id == user.Id).ExecuteUpdateAsync(set => set.SetProperty(u => u.LastSignInUtc, now), cancellationToken); + } + + var caller = new Caller + { + UserId = user.Id, + Name = user.UserName, + DisplayName = user.DisplayName, + Provider = provider, + Groups = groups, + Access = granted, + BreakGlass = user.IsBreakGlass, + PasswordChangeRequired = user.MustChangePassword && provider == SignInProviders.Local, + SessionId = session.Id, + }; + context.SetCaller(caller); + await AuditAsync(context, user.IsBreakGlass ? "auth.sign-in.break-glass" : "auth.sign-in", provider, user.UserName, "succeeded", null, cancellationToken); + logger.LogInformation("{User} signed in through {Provider}.", user.UserName, provider); + return View(caller, session, user); + } + + /// Changes the signed-in person's own built-in password, and ends their other sessions. + public async Task ChangePasswordAsync(HttpContext context, PasswordChangeBody body, CancellationToken cancellationToken) + { + var caller = context.RequireCaller(); + if (caller.Provider != SignInProviders.Local) + { + throw new AuthProblemException(AuthProblems.Conflict, + "Only a built-in account's password is changed here; directory and Windows passwords are changed where they live."); + } + + var errors = PasswordProblems(body.NewPassword, caller.Name, "newPassword"); + if (errors.Count > 0) + { + throw AuthProblemException.InvalidFields(errors); + } + + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var user = await db.Users.SingleAsync(u => u.Id == caller.UserId, cancellationToken); + if (PasswordHashing.Verify(body.CurrentPassword ?? string.Empty, user.PasswordHash) == PasswordCheck.Failed) + { + await AuditAsync(context, "auth.password.change", SignInProviders.Local, user.UserName, "refused", "the current password was wrong", cancellationToken); + throw AuthProblemException.InvalidFields(new Dictionary { ["currentPassword"] = ["The current password is not correct."] }); + } + + if (PasswordHashing.Verify(body.NewPassword!, user.PasswordHash) != PasswordCheck.Failed) + { + throw AuthProblemException.InvalidFields(new Dictionary { ["newPassword"] = ["Choose a password you have not used here before."] }); + } + + var now = DateTimeOffset.UtcNow; + user.PasswordHash = PasswordHashing.Hash(body.NewPassword!); + user.MustChangePassword = false; + user.PasswordChangedUtc = now; + user.UpdatedUtc = now; + await db.SaveChangesAsync(cancellationToken); + await sessions.RevokeAllAsync(user.Id, caller.SessionId, cancellationToken); + await AuditAsync(context, "auth.password.change", SignInProviders.Local, user.UserName, "succeeded", null, cancellationToken); + + var updated = caller with { PasswordChangeRequired = false }; + context.SetCaller(updated); + return View(updated, SessionAuthenticationHandler.Session(context), user); + } + + public async Task SignOutAsync(HttpContext context, CancellationToken cancellationToken) + { + var caller = context.RequireCaller(); + if (caller.SessionId is { } sessionId) + { + await sessions.RevokeAsync(sessionId, cancellationToken); + } + + SessionCookies.Clear(context); + await AuditAsync(context, "auth.sign-out", caller.Provider, caller.Name, "succeeded", null, cancellationToken); + } + + /// Whether the built-in form is offered and accepted: when Built-In is on, or always when the environment forces it. + public async ValueTask BuiltInAllowedAsync(CancellationToken cancellationToken) => + environment.ForceBuiltIn || (await settings.MethodsAsync(cancellationToken)).Value.BuiltIn; + + /// + /// Finds or creates the row for a person a directory or identity provider + /// vouched for, refreshing their names, and for a Windows account its + /// description and local groups. + /// + public async Task UpsertExternalAsync(string kind, string externalId, string userName, string? displayName, string? email, + CancellationToken cancellationToken, string? description = null, IReadOnlyList? windowsGroups = null) + { + var now = DateTimeOffset.UtcNow; + for (var attempt = 0; ; attempt++) + { + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var user = await db.Users.SingleOrDefaultAsync(u => u.Kind == kind && u.ExternalId == externalId, cancellationToken); + if (user is null) + { + // A renamed account keeps its row: the name is freed from any older row of the same provider that held it. + var holder = await db.Users.SingleOrDefaultAsync(u => u.Kind == kind && u.UserName == userName, cancellationToken); + if (holder is not null) + { + holder.UserName = $"{userName}~{holder.Id.ToString()[..8]}"; + } + + user = new UserEntity { Id = Guid.NewGuid(), Kind = kind, ExternalId = externalId, UserName = userName, Enabled = true, CreatedUtc = now }; + db.Users.Add(user); + } + else if (!user.Enabled) + { + throw new AuthProblemException(AuthProblems.NoAccess, "This account has been turned off here."); + } + + user.UserName = userName; + user.DisplayName = displayName; + user.Email = email; + user.Description = description; + user.WindowsGroupsJson = windowsGroups is null ? null : WindowsGroups.Serialize(windowsGroups); + user.UpdatedUtc = now; + try + { + await db.SaveChangesAsync(cancellationToken); + return user; + } + catch (DbUpdateException) when (attempt < 2) + { + // Two first sign-ins of the same person on two nodes: the second finds the first's row. + } + } + } + + public static Dictionary PasswordProblems(string? password, string userName, string field) + { + var errors = new Dictionary(); + if (string.IsNullOrEmpty(password) || password.Length < MinPasswordLength) + { + errors[field] = [$"Use at least {MinPasswordLength} characters."]; + } + else if (password.Length > PasswordHashing.MaxLength) + { + errors[field] = [$"Use at most {PasswordHashing.MaxLength} characters."]; + } + else if (password.Contains(userName, StringComparison.OrdinalIgnoreCase)) + { + errors[field] = ["The password must not contain the user name."]; + } + + return errors; + } + + /// The session as the caller sees it; adds a Windows account's description, SID and groups. + public static SessionView View(Caller caller, SessionEntity? session, UserEntity? user = null) => new( + caller.UserId.ToString("D"), + caller.Name, + caller.DisplayName, + caller.Provider, + caller.BreakGlass, + caller.PasswordChangeRequired, + [.. caller.Groups.Select(g => new GroupView(g.Kind, g.Id, g.Name))], + [.. caller.Access.Roles.Select(r => new RoleGrantView(r.Id, r.Name)).OrderBy(r => r.Name, StringComparer.OrdinalIgnoreCase)], + caller.Access.BreakGlass || caller.Access.Permissions.Contains(Permissions.All) + ? [.. Permissions.KnownKeys.Order(StringComparer.Ordinal)] + : [.. caller.Access.Permissions.Order(StringComparer.Ordinal)], + session?.ExpiresUtc, + session?.AbsoluteExpiresUtc, + user?.Description, + SidOf(user), + WindowsGroups.Parse(user?.WindowsGroupsJson)); + + /// A Windows account's SID, which is its provider id; null for every other kind of account. + public static string? SidOf(UserEntity? user) => user?.Kind == SignInProviders.Windows ? user.ExternalId : null; + + /// Finds or creates a local Windows account's row and refreshes its full name, description and local groups. + public async Task UpsertWindowsAsync(WindowsAccount account, CancellationToken cancellationToken) + { + var details = localAccounts.Read(account.UserName, account.Sid); + if (details is null) + { + logger.LogDebug("The details of {User} could not be read from this machine's account database.", account.UserName); + } + + return await UpsertExternalAsync(SignInProviders.Windows, account.Sid, account.UserName, Clip(details?.FullName, 256), null, cancellationToken, + Clip(details?.Description, 1024), [.. (details?.Groups ?? []).Select(g => new WindowsGroupView(g.Name, g.Sid))]); + } + + private static string? Clip(string? value, int length) => value is { Length: > 0 } text ? text.Length > length ? text[..length] : text : null; + + public async Task AuditAsync(HttpContext context, string action, string provider, string userName, string result, string? reason, + CancellationToken cancellationToken) + { + using var scope = scopes.CreateScope(); + var audit = scope.ServiceProvider.GetRequiredService(); + await audit.LogAsync(AuditCategories.Auth, action, userName, + detail: $"provider={provider} result={result}{(reason is null ? string.Empty : $" reason={reason}")}", + remoteIp: ClientIp.EffectiveText(context), cancellationToken: cancellationToken); + } + + /// + /// The local checks, in order: .\name and MACHINE\name go to + /// Windows; a name that is an enabled built-in account is checked as one; + /// any other name goes to Windows when local Windows accounts are on. Every + /// path costs one password hash, and a refusal is held to + /// , so the paths are not told apart by time. + /// + private async Task<(UserEntity? User, IReadOnlyList Groups)> VerifyLocalAsync(string userName, string password, bool builtIn, bool windows, + CancellationToken cancellationToken) + { + var windowsName = WindowsSignIn.ParseName(userName, Environment.MachineName); + if (windowsName is not { Explicit: true } && builtIn) + { + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var lowered = userName.ToLowerInvariant(); + var user = await db.Users.SingleOrDefaultAsync(u => u.Kind == SignInProviders.Local && u.Enabled && u.UserName.ToLower() == lowered, cancellationToken); + if (user is not null || !windows || windowsName is null) + { + var check = PasswordHashing.Verify(password, user?.PasswordHash); + if (user is null || check == PasswordCheck.Failed) + { + return (null, []); + } + + if (check == PasswordCheck.SucceededNeedsRehash) + { + user.PasswordHash = PasswordHashing.Hash(password); + await db.SaveChangesAsync(cancellationToken); + } + + return (user, await GroupRefs.LocalAsync(db, user.Id, cancellationToken)); + } + } + + if (!windows || windowsName is null) + { + _ = PasswordHashing.Verify(password, null); + return (null, []); + } + + return await VerifyWindowsAsync(windowsName.Name, password, cancellationToken); + } + + /// One of this server's local Windows accounts, checked by Windows; its bindings apply by its SID and its local groups' SIDs. + private async Task<(UserEntity? User, IReadOnlyList Groups)> VerifyWindowsAsync(string name, string password, CancellationToken cancellationToken) + { + // The same hash a built-in check costs, so a Windows name is not told apart by a quicker answer. + _ = PasswordHashing.Verify(password, null); + var result = localLogon.Validate(name, password); + if (result is not { Outcome: LocalLogonOutcome.Accepted, Sid: { } sid, AccountName: { } accountName }) + { + if (result.Outcome == LocalLogonOutcome.NotPermitted) + { + logger.LogInformation("Windows did not let {User} sign in here: the account needs the right to access this computer from the network.", name); + } + else if (result.Outcome == LocalLogonOutcome.Unavailable) + { + logger.LogWarning("Windows could not check the password of {User} just now.", name); + } + else + { + logger.LogDebug("Windows refused {User}: {Outcome}.", name, result.Outcome); + } + + return (null, []); + } + + var user = await UpsertWindowsAsync(new WindowsAccount(sid, accountName), cancellationToken); + return (user, WindowsSignIn.Principals(sid, user.UserName, WindowsGroups.Parse(user.WindowsGroupsJson))); + } + + private async Task<(UserEntity? User, IReadOnlyList Groups)> VerifyLdapAsync(string userName, string password, CancellationToken cancellationToken) + { + var (ldapSettings, _) = await settings.LdapAsync(cancellationToken); + DirectoryAccount? account; + try + { + account = ldap.Authenticate(ldapSettings, userName, password); + } + catch (DirectoryException exception) when (exception is not AmbiguousAccountException) + { + logger.LogWarning("Directory sign-in could not complete: {Error}", exception.Message); + await automaticDirectory.FailedAsync(cancellationToken); + throw new AuthProblemException(AuthProblems.NotReady, "The directory could not be reached; try again, or sign in another way."); + } + + if (account is null) + { + return (null, []); + } + + var user = await UpsertExternalAsync(SignInProviders.Ldap, account.Subject, account.UserName, account.DisplayName, account.Email, cancellationToken); + return (user, [.. account.Groups.Select(dn => new GroupRef(PrincipalKinds.LdapGroup, dn, FirstRdn(dn)))]); + } + + /// cn=helpdesk,ou=groups,dc=example,dc=com reads as helpdesk. + public static string FirstRdn(string dn) + { + var first = dn.Split(',')[0]; + var equals = first.IndexOf('=', StringComparison.Ordinal); + return equals >= 0 ? first[(equals + 1)..].Trim() : first.Trim(); + } +} diff --git a/src/Backend/Auth/SignIn/SignInSettings.cs b/src/Backend/Auth/SignIn/SignInSettings.cs new file mode 100644 index 0000000..c1400e4 --- /dev/null +++ b/src/Backend/Auth/SignIn/SignInSettings.cs @@ -0,0 +1,260 @@ +using System.Text.Json.Serialization; + +namespace Backend.Auth; + +/// +/// The sign-in methods. is ExecuteR's own accounts (the +/// console's Built-In), this Windows server's own +/// local accounts checked by Windows through the same form (Local Windows +/// Accounts), a directory, an +/// identity provider. +/// +public static class SignInProviders +{ + public const string Local = "local"; + public const string Windows = "windows"; + public const string Ldap = "ldap"; + public const string Oidc = "oidc"; + + /// The providers the sign-in page lists by name: the directory's form and the identity provider's redirect. + public static IReadOnlyList External { get; } = [Ldap, Oidc]; + + /// Every sign-in method, in the order the console's tabs show them. + public static IReadOnlyList Methods { get; } = [Local, Windows, Ldap, Oidc]; +} + +public static class LdapSecurity +{ + public const string Ldaps = "ldaps"; + public const string StartTls = "start-tls"; + + /// + /// Kerberos with signing and sealing, for Active Directory on Windows: the + /// server's lookups bind as its computer account, and a person's password + /// is checked by a Kerberos bind, never sent in the clear. + /// + public const string Kerberos = "kerberos"; + + /// No TLS at all: refused unless the directory is on this machine's loopback address. + public const string None = "none"; + + public static IReadOnlyList All { get; } = [Ldaps, StartTls, Kerberos, None]; +} + +/// +/// The authentication document: which sign-in methods are on, and +/// OIDC's redirect mode. One document, so the guard that keeps a way in holds +/// when two people change two methods at once. null is +/// the platform default: on, on Windows Server. +/// +public sealed record AuthenticationMethods(bool BuiltIn, bool? Windows, bool Ldap, bool Oidc, bool OidcRedirect) +{ + public const string Key = "authentication"; + + public static AuthenticationMethods Defaults { get; } = new(true, null, false, false, false); + + [JsonIgnore] + public bool WindowsOn => WindowsPlatform.Supported && (Windows ?? WindowsPlatform.IsWindowsServer); + + public bool IsOn(string method) => method switch + { + SignInProviders.Local => BuiltIn, + SignInProviders.Windows => WindowsOn, + SignInProviders.Ldap => Ldap, + SignInProviders.Oidc => Oidc, + _ => false, + }; + + /// The methods that are on, in tab order. + public IReadOnlyList On() => [.. SignInProviders.Methods.Where(IsOn)]; +} + +/// The authentication.lifetimes document: how long a browser session lasts, for every method. +public sealed record SignInLifetimes(int SessionIdleMinutes, int SessionMaxHours) +{ + public const string Key = "authentication.lifetimes"; + + public static SignInLifetimes Defaults { get; } = new(120, 12); + + [JsonIgnore] + public TimeSpan SessionIdle => TimeSpan.FromMinutes(SessionIdleMinutes); + + [JsonIgnore] + public TimeSpan SessionMax => TimeSpan.FromHours(SessionMaxHours); +} + +/// +/// The authentication.ldap document. is +/// sealed, never stored in the clear. : set up from +/// this server's domain join, until an administrator changes it. The breaker +/// turns automatic LDAP off after directory +/// failures within . +/// +public sealed record LdapSignInSettings( + string Label, + IReadOnlyList Servers, + int Port, + string Security, + string? BaseDn, + string? BindDn, + string? BindPassword, + string UserFilter, + string? GroupBaseDn, + string? GroupFilter, + bool NestedGroups, + int TimeoutSeconds, + bool Automatic = false, + int BreakerFailures = LdapSignInSettings.DefaultBreakerFailures, + int BreakerWindowMinutes = LdapSignInSettings.DefaultBreakerWindowMinutes, + DateTimeOffset? BreakerTrippedUtc = null) +{ + public const string Key = "authentication.ldap"; + public const int DefaultBreakerFailures = 10; + public const int DefaultBreakerWindowMinutes = 5; + public const string BindPasswordPurpose = "sign-in.ldap.bind-password"; + + /// Active Directory people, found by account name, user principal name or email address. + public const string DefaultUserFilter = "(&(objectCategory=person)(objectClass=user)(|(sAMAccountName={0})(userPrincipalName={0})(mail={0})))"; + + public static LdapSignInSettings Defaults { get; } = new("Directory", [], 636, LdapSecurity.Ldaps, null, null, null, DefaultUserFilter, null, null, + true, 10); +} + +/// The authentication.oidc document. is sealed. +public sealed record OidcSignInSettings( + string Label, + string? Authority, + string? ClientId, + string? ClientSecret, + IReadOnlyList Scopes, + string UserNameClaim, + IReadOnlyList GroupClaims) +{ + public const string Key = "authentication.oidc"; + public const string ClientSecretPurpose = "sign-in.oidc.client-secret"; + + public static OidcSignInSettings Defaults { get; } = new("Single sign-on", null, null, null, ["openid", "profile", "email"], "preferred_username", ["groups"]); +} + +/// One method on GET /api/settings/authentication. +public sealed record AuthenticationMethodView(string Id, string Label, bool Enabled, bool Supported, bool Configured); + +/// Every method, whether it is on and can sign anyone in, redirect mode and whether it is in effect, and the forced built-in form. +public sealed record AuthenticationView(IReadOnlyList Methods, bool OidcRedirect, bool RedirectActive, + bool BuiltInForcedByEnvironment, string ForceBuiltInVariable); + +/// The Built-In tab: its switch, the session lifetimes every method shares, and the break-glass account. +public sealed record BuiltInSignInView(bool Enabled, int SessionIdleMinutes, int SessionMaxHours, bool ForcedByEnvironment, string ForceVariable, + string? BreakGlassUserName); + +public sealed record BuiltInSignInUpdate(bool? Enabled, int? SessionIdleMinutes, int? SessionMaxHours); + +/// The Local Windows Accounts tab: its switch, whether it is on by default here, and whether this host can offer it. +public sealed record WindowsSignInView(bool Enabled, bool EnabledByDefault, bool Supported); + +public sealed record WindowsSignInUpdate(bool? Enabled); + +public sealed record LdapSignInView(bool Enabled, string Label, IReadOnlyList Servers, int Port, string Security, string? BaseDn, string? BindDn, + bool BindPasswordSet, string UserFilter, string? GroupBaseDn, string? GroupFilter, bool NestedGroups, int TimeoutSeconds, bool Automatic, + int BreakerFailures, int BreakerWindowMinutes, DateTimeOffset? BreakerTrippedUtc, bool KerberosSupported); + +/// An LDAP save. : null keeps the stored one, empty clears it, anything else replaces it. +public sealed record LdapSignInUpdate(bool? Enabled, string? Label, IReadOnlyList? Servers, int? Port, string? Security, string? BaseDn, string? BindDn, + string? BindPassword, string? UserFilter, string? GroupBaseDn, string? GroupFilter, bool? NestedGroups, int? TimeoutSeconds, int? BreakerFailures = null, + int? BreakerWindowMinutes = null); + +/// The OIDC tab: the document without its secret, redirect mode, and the callback and post-logout URLs to register. +public sealed record OidcSignInView(bool Enabled, bool Redirect, string Label, string? Authority, string? ClientId, bool ClientSecretSet, + IReadOnlyList Scopes, string UserNameClaim, IReadOnlyList GroupClaims, string CallbackUrl, string PostLogoutUrl); + +public sealed record OidcSignInUpdate(bool? Enabled, bool? Redirect, string? Label, string? Authority, string? ClientId, string? ClientSecret, + IReadOnlyList? Scopes, string? UserNameClaim, IReadOnlyList? GroupClaims); + +/// +/// What the sign-in page offers, as one anonymous answer: the built-in form, +/// whether the same form takes this server's local Windows accounts, the +/// providers that are on, and , the provider to go +/// straight to when it is the only way in and redirect mode is on. +/// +public sealed record SignInOptions(bool BuiltIn, bool WindowsAccounts, IReadOnlyList Providers, string? Redirect); + +/// Kind is form (a password through the page) or redirect (the provider's own page). +public sealed record SignInOption(string Id, string Label, string Kind); + +public static class WindowsPlatform +{ + /// Local Windows accounts (checked by Windows, with their local groups by SID) need a Windows server. + public static bool Supported => OperatingSystem.IsWindows(); + + /// Windows Server, where local Windows accounts are on by default. Read once from the product type the OS reports. + public static bool IsWindowsServer { get; } = OperatingSystem.IsWindows() && ReadIsServer(); + + private static bool ReadIsServer() + { + if (!OperatingSystem.IsWindows()) + { + return false; + } + + using var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\ProductOptions"); + return key?.GetValue("ProductType") is string type && !type.Equals("WinNT", StringComparison.OrdinalIgnoreCase); + } +} + +/// Environment switches for sign-in: only the forced built-in form, a way back in that the database cannot turn off. +public sealed class SignInEnvironment(IConfiguration configuration) +{ + public const string ForceBuiltInVariable = "AUTH_FORCE_LOCAL"; + + public bool ForceBuiltIn { get; } = configuration[ForceBuiltInVariable] is "1" or "true" or "True"; +} + +/// The authentication documents, read through . +public sealed class SignInSettings(SettingsDocuments documents) +{ + public ValueTask<(AuthenticationMethods Value, string Etag)> MethodsAsync(CancellationToken cancellationToken) => + documents.GetAsync(AuthenticationMethods.Key, AuthenticationMethods.Defaults, cancellationToken); + + public async ValueTask LifetimesAsync(CancellationToken cancellationToken) => + (await documents.GetAsync(SignInLifetimes.Key, SignInLifetimes.Defaults, cancellationToken)).Value; + + public ValueTask<(LdapSignInSettings Value, string Etag)> LdapAsync(CancellationToken cancellationToken) => + documents.GetAsync(LdapSignInSettings.Key, LdapSignInSettings.Defaults, cancellationToken); + + public ValueTask<(OidcSignInSettings Value, string Etag)> OidcAsync(CancellationToken cancellationToken) => + documents.GetAsync(OidcSignInSettings.Key, OidcSignInSettings.Defaults, cancellationToken); + + /// Whether a provider has what it needs to sign anyone in, switched on or not: a test sign-in needs only this. + public async ValueTask IsConfiguredAsync(string provider, CancellationToken cancellationToken) => provider switch + { + SignInProviders.Local => true, + SignInProviders.Windows => WindowsPlatform.Supported, + SignInProviders.Ldap => LdapDirectory.Validate((await LdapAsync(cancellationToken)).Value).Count == 0, + SignInProviders.Oidc => OidcSignIn.Validate((await OidcAsync(cancellationToken)).Value).Count == 0, + _ => false, + }; + + /// Whether a provider is switched on and has what it needs to sign anyone in. + public async ValueTask IsUsableAsync(string provider, CancellationToken cancellationToken) => + (await MethodsAsync(cancellationToken)).Value.IsOn(provider) && await IsConfiguredAsync(provider, cancellationToken); + + /// + /// The etag of a provider's own settings, which a test sign-in records so a + /// later edit needs a new test. Switching a method on or off is not an edit + /// of its settings. Windows has no settings of its own. + /// + public async ValueTask EtagAsync(string provider, CancellationToken cancellationToken) => provider switch + { + SignInProviders.Ldap => (await LdapAsync(cancellationToken)).Etag, + SignInProviders.Oidc => (await OidcAsync(cancellationToken)).Etag, + _ => SettingsDocuments.InitialEtag, + }; + + public async ValueTask LabelAsync(string provider, CancellationToken cancellationToken) => provider switch + { + SignInProviders.Windows => "Local Windows Accounts", + SignInProviders.Ldap => (await LdapAsync(cancellationToken)).Value.Label, + SignInProviders.Oidc => (await OidcAsync(cancellationToken)).Value.Label, + _ => "Built-In Account", + }; +} diff --git a/src/Backend/Auth/SignIn/SignInSetup.cs b/src/Backend/Auth/SignIn/SignInSetup.cs new file mode 100644 index 0000000..4cb0ab4 --- /dev/null +++ b/src/Backend/Auth/SignIn/SignInSetup.cs @@ -0,0 +1,67 @@ +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authorization; + +namespace Backend.Auth; + +/// Registers sign-in (sessions, the four methods, step-up, access) and maps its endpoints. +public static class SignInSetup +{ + public static void AddSignIn(this WebApplicationBuilder builder) + { + var services = builder.Services; + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddHostedService(); + services.AddHttpClient(OidcSignIn.HttpClientName, client => client.Timeout = TimeSpan.FromSeconds(15)); + + services.AddAuthentication(options => + { + options.DefaultScheme = AuthConstants.SessionScheme; + options.DefaultChallengeScheme = AuthConstants.SessionScheme; + }) + .AddScheme(AuthConstants.SessionScheme, _ => { }); + + // Permission-based authorization: endpoints demand "perm:{key}" and the + // handler resolves the roles the caller's groups are bound to. + services.AddAuthorization(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddScoped(); + services.AddScoped(); + } + + /// Authentication, authorization, the session guards (CSRF, forced password change) and problem answers, in order. + public static void UseSignIn(this WebApplication app) + { + app.Use(AuthProblemHandling.Middleware); + app.UseAuthentication(); + app.Use(SessionGuards.Middleware); + app.UseAuthorization(); + } + + public static void MapSignIn(this WebApplication app) + { + SignInEndpoints.Map(app); + AuthenticationSettingsEndpoints.Map(app); + AccessEndpoints.Map(app); + AccessControlEndpoints.Map(app); + } +} diff --git a/src/Backend/Auth/SignIn/SignInThrottling.cs b/src/Backend/Auth/SignIn/SignInThrottling.cs new file mode 100644 index 0000000..6e91201 --- /dev/null +++ b/src/Backend/Auth/SignIn/SignInThrottling.cs @@ -0,0 +1,100 @@ +using Backend.Data; +using Microsoft.EntityFrameworkCore; + +namespace Backend.Auth; + +/// +/// Back-off after failed sign-ins, per account and per client address, +/// counted in the database so every node sees the same count. Past a +/// threshold each further failure doubles the wait, up to ; +/// nothing is ever locked for good, so the break-glass account cannot be +/// locked out by someone guessing at it. +/// +public sealed class SignInThrottling(IServiceScopeFactory scopes) +{ + public const int AccountThreshold = 5; + public const int AddressThreshold = 20; + public static readonly TimeSpan Window = TimeSpan.FromMinutes(15); + public static readonly TimeSpan BaseDelay = TimeSpan.FromSeconds(30); + public static readonly TimeSpan MaxDelay = TimeSpan.FromMinutes(15); + + public static string AccountKey(string provider, string userName) => Bound($"account:{provider}:{userName.Trim().ToLowerInvariant()}"); + + public static string AddressKey(string? address) => Bound($"address:{address ?? "unknown"}"); + + /// When the soonest of these keys may try again, or null when none is held back. + public async Task BlockedUntilAsync(IReadOnlyList keys, CancellationToken cancellationToken) + { + var now = DateTimeOffset.UtcNow; + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var blocked = await db.SignInThrottles.AsNoTracking().Where(t => keys.Contains(t.Key) && t.BlockedUntilUtc > now).Select(t => t.BlockedUntilUtc) + .ToListAsync(cancellationToken); + return blocked.Count == 0 ? null : blocked.Max(); + } + + /// Seconds until a held-back key may try again (at least one). + public static int SecondsUntil(DateTimeOffset until) => Math.Max(1, (int)Math.Ceiling((until - DateTimeOffset.UtcNow).TotalSeconds)); + + public async Task FailedAsync(string accountKey, string addressKey, CancellationToken cancellationToken) + { + await CountAsync(accountKey, AccountThreshold, cancellationToken); + await CountAsync(addressKey, AddressThreshold, cancellationToken); + } + + public async Task SucceededAsync(string accountKey, CancellationToken cancellationToken) + { + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await db.SignInThrottles.Where(t => t.Key == accountKey).ExecuteDeleteAsync(cancellationToken); + } + + public static TimeSpan DelayAfter(int failures, int threshold) + { + if (failures < threshold) + { + return TimeSpan.Zero; + } + + var doublings = Math.Min(failures - threshold, 10); + var delay = BaseDelay * Math.Pow(2, doublings); + return delay < MaxDelay ? delay : MaxDelay; + } + + private async Task CountAsync(string key, int threshold, CancellationToken cancellationToken) + { + for (var attempt = 0; attempt < 3; attempt++) + { + var now = DateTimeOffset.UtcNow; + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var row = await db.SignInThrottles.SingleOrDefaultAsync(t => t.Key == key, cancellationToken); + if (row is null) + { + row = new SignInThrottleEntity { Key = key, FirstFailureUtc = now }; + db.SignInThrottles.Add(row); + } + else if (now - row.LastFailureUtc > Window && (row.BlockedUntilUtc is null || row.BlockedUntilUtc <= now)) + { + row.Failures = 0; + row.FirstFailureUtc = now; + } + + row.Failures++; + row.LastFailureUtc = now; + var delay = DelayAfter(row.Failures, threshold); + row.BlockedUntilUtc = delay > TimeSpan.Zero ? now + delay : null; + try + { + await db.SaveChangesAsync(cancellationToken); + return; + } + catch (DbUpdateException) + { + // Another node counted the same key at the same moment; count again on top of theirs. + } + } + } + + private static string Bound(string key) => key.Length <= 300 ? key : key[..300]; +} diff --git a/src/Backend/Auth/SignIn/StepUp.cs b/src/Backend/Auth/SignIn/StepUp.cs new file mode 100644 index 0000000..c45c568 --- /dev/null +++ b/src/Backend/Auth/SignIn/StepUp.cs @@ -0,0 +1,226 @@ +using Backend.Data; +using Backend.Proxy; +using Microsoft.EntityFrameworkCore; + +namespace Backend.Auth; + +public sealed record StepUpBody(string? Password); + +/// Whether the session has proved its person recently, until when, and how it can. +public sealed record StepUpView(bool Verified, DateTimeOffset? ValidUntilUtc, string Method, string? Unavailable); + +/// How a session confirms its person again (). +public static class StepUpMethods +{ + public const string Password = "password"; + public const string Oidc = "oidc"; + public const string None = "none"; +} + +/// +/// Step-up: a signed-in person proves themselves again, and for five minutes +/// the session may take actions that ask for it (switching sign-in methods). +/// Kept in the database against the session, so it holds on whichever node +/// serves the next request. Built-in, local Windows and directory accounts +/// re-enter their password; OIDC sessions re-authenticate with the provider +/// (prompt=login, max_age=0). +/// +public sealed class StepUpService(IServiceScopeFactory scopes, SignInSettings settings, ILdapDirectory ldap, ILocalLogon localLogon, + AutomaticDirectory automaticDirectory, SignInThrottling throttling, SignInService signIn) +{ + public static readonly TimeSpan Window = TimeSpan.FromMinutes(5); + + /// The time a provider's re-authentication may be off by, either way. + public static readonly TimeSpan AuthTimeSkew = TimeSpan.FromMinutes(2); + + public async Task StatusAsync(Caller caller, CancellationToken cancellationToken) + { + if (caller.SessionId is not { } sessionId) + { + return new StepUpView(false, null, StepUpMethods.None, AuthProblems.StepUpUnavailable.Title); + } + + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var row = await db.StepUps.AsNoTracking().SingleOrDefaultAsync(s => s.SessionId == sessionId, cancellationToken); + var until = row?.VerifiedUtc + Window; + var valid = until > DateTimeOffset.UtcNow; + return new StepUpView(valid, valid ? until : null, MethodFor(caller), UnavailableReason(caller)); + } + + /// Throws the step-up problem unless the caller's session confirmed its person within . + public async Task RequireAsync(HttpContext context, CancellationToken cancellationToken) + { + var caller = context.RequireCaller(); + if (caller.SessionId is null) + { + throw new AuthProblemException(AuthProblems.StepUpUnavailable); + } + + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var verified = await db.StepUps.AsNoTracking().Where(s => s.SessionId == caller.SessionId) + .Select(s => (DateTimeOffset?)s.VerifiedUtc).SingleOrDefaultAsync(cancellationToken); + if (verified is not { } at || at + Window <= DateTimeOffset.UtcNow) + { + throw new AuthProblemException(AuthProblems.StepUpRequired); + } + } + + public async Task VerifyAsync(HttpContext context, StepUpBody body, CancellationToken cancellationToken) + { + var caller = context.RequireCaller(); + if (caller.SessionId is null || UnavailableReason(caller) is { } unavailable) + { + throw new AuthProblemException(AuthProblems.StepUpUnavailable, UnavailableReason(caller)); + } + + if (MethodFor(caller) != StepUpMethods.Password) + { + throw new AuthProblemException(AuthProblems.StepUpUnavailable, "This session confirms its person with the identity provider, not a password."); + } + + var password = body.Password ?? string.Empty; + if (password.Length is 0 or > PasswordHashing.MaxLength) + { + throw AuthProblemException.InvalidFields(new Dictionary { ["password"] = ["Enter your password."] }); + } + + var accountKey = caller.Provider == SignInProviders.Windows + ? SignInThrottling.AccountKey(SignInProviders.Local, WindowsSignIn.ParseName(caller.Name, Environment.MachineName)?.Name ?? caller.Name) + : SignInThrottling.AccountKey(caller.Provider, caller.Name); + var addressKey = SignInThrottling.AddressKey(ClientIp.EffectiveText(context)); + if (await throttling.BlockedUntilAsync([accountKey, addressKey], cancellationToken) is { } blocked) + { + throw new AuthProblemException(AuthProblems.TooManyAttempts) { RetryAfterSeconds = SignInThrottling.SecondsUntil(blocked) }; + } + + if (!await CheckPasswordAsync(caller, password, cancellationToken)) + { + await throttling.FailedAsync(accountKey, addressKey, cancellationToken); + await signIn.AuditAsync(context, "auth.step-up", caller.Provider, caller.Name, "refused", "wrong password", cancellationToken); + throw AuthProblemException.InvalidFields(new Dictionary { ["password"] = ["The password is not correct."] }); + } + + await throttling.SucceededAsync(accountKey, cancellationToken); + return await RecordAsync(context, caller, StepUpMethods.Password, cancellationToken); + } + + /// + /// A step-up through the identity provider, back at the callback: it must + /// come in the very session that started it, for the same person, and the + /// provider must say the person authenticated afresh since then. Null when + /// recorded; otherwise why not. + /// + public async Task CompleteOidcAsync(HttpContext context, OidcIdentity identity, CancellationToken cancellationToken) + { + var caller = context.Caller(); + var started = identity.Request.CreatedUtc; + var refused = caller is not { Provider: SignInProviders.Oidc, SessionId: { } session } || session != identity.Request.StepUpSessionId + ? "the callback came in another session" + : !await IsUserAsync(caller, identity.Subject, cancellationToken) ? "the provider confirmed another person" + : identity.AuthTime is not { } at ? "the provider did not say when the person authenticated" + : at < started - AuthTimeSkew || at > DateTimeOffset.UtcNow + AuthTimeSkew ? "the provider did not authenticate the person afresh" + : null; + if (refused is not null) + { + await signIn.AuditAsync(context, "auth.step-up", SignInProviders.Oidc, caller?.Name ?? "(unknown)", "refused", refused, cancellationToken); + return refused; + } + + await RecordAsync(context, caller!, StepUpMethods.Oidc, cancellationToken); + return null; + } + + public static string MethodFor(Caller caller) => caller.Provider switch + { + SignInProviders.Local or SignInProviders.Windows or SignInProviders.Ldap => StepUpMethods.Password, + SignInProviders.Oidc => StepUpMethods.Oidc, + _ => StepUpMethods.None, + }; + + private static string? UnavailableReason(Caller caller) => caller.Provider switch + { + SignInProviders.Local or SignInProviders.Ldap or SignInProviders.Oidc or SignInProviders.Windows when caller.SessionId is not null => null, + _ => AuthProblems.StepUpUnavailable.Title, + }; + + private async Task IsUserAsync(Caller caller, string externalId, CancellationToken cancellationToken) + { + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.Users.AsNoTracking().AnyAsync( + u => u.Id == caller.UserId && u.Enabled && u.Kind == caller.Provider && u.ExternalId == externalId, cancellationToken); + } + + private async Task RecordAsync(HttpContext context, Caller caller, string method, CancellationToken cancellationToken) + { + var sessionId = caller.SessionId!; + var now = DateTimeOffset.UtcNow; + using (var scope = scopes.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var updated = await db.StepUps.Where(s => s.SessionId == sessionId) + .ExecuteUpdateAsync(set => set.SetProperty(s => s.VerifiedUtc, now).SetProperty(s => s.Method, method), cancellationToken); + if (updated == 0) + { + db.StepUps.Add(new StepUpEntity { SessionId = sessionId, Method = method, VerifiedUtc = now }); + try + { + await db.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateException) + { + // Two step-ups of one session at once; either row says the same. + } + } + + // Rows of sessions long gone are swept here: step-ups are the only thing that adds them. + var stale = now - TimeSpan.FromDays(1); + await db.StepUps.Where(s => s.VerifiedUtc < stale).ExecuteDeleteAsync(cancellationToken); + } + + await signIn.AuditAsync(context, "auth.step-up", caller.Provider, caller.Name, "succeeded", $"method={method}", cancellationToken); + return new StepUpView(true, now + Window, MethodFor(caller), null); + } + + private async Task CheckPasswordAsync(Caller caller, string password, CancellationToken cancellationToken) + { + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var user = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == caller.UserId, cancellationToken); + if (user is not { Enabled: true }) + { + return false; + } + + if (caller.Provider == SignInProviders.Local) + { + return PasswordHashing.Verify(password, user.PasswordHash) != PasswordCheck.Failed; + } + + if (caller.Provider == SignInProviders.Windows) + { + // Windows checks the password again, and the account it accepts must be the session's own (its SID). + return WindowsSignIn.ParseName(user.UserName, Environment.MachineName) is { } name + && localLogon.Validate(name.Name, password) is { Outcome: LocalLogonOutcome.Accepted, Sid: { } sid } + && sid.Equals(user.ExternalId, StringComparison.OrdinalIgnoreCase); + } + + var (ldapSettings, _) = await settings.LdapAsync(cancellationToken); + try + { + var account = ldap.Authenticate(ldapSettings, user.UserName, password); + return account is not null && account.Subject == user.ExternalId; + } + catch (AmbiguousAccountException) + { + return false; + } + catch (DirectoryException) + { + await automaticDirectory.FailedAsync(cancellationToken); + throw new AuthProblemException(AuthProblems.NotReady, "The directory could not be reached; try again."); + } + } +} diff --git a/src/Backend/Auth/SignIn/WindowsAccounts.cs b/src/Backend/Auth/SignIn/WindowsAccounts.cs new file mode 100644 index 0000000..18fde5c --- /dev/null +++ b/src/Backend/Auth/SignIn/WindowsAccounts.cs @@ -0,0 +1,461 @@ +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using System.Security.Principal; +using Microsoft.Win32.SafeHandles; +using Shared.Contracts.Serialization; + +namespace Backend.Auth; + +/// One of this server's local Windows accounts as Windows accepted it: its SID and MACHINE\name. +public sealed record WindowsAccount(string Sid, string UserName); + +/// One of the server's local groups a Windows account is in: its account name and SID. +public sealed record WindowsGroupView(string Name, string Sid); + +public static class WindowsGroups +{ + public static string Serialize(IReadOnlyList groups) => JsonDefaults.Serialize(groups); + + public static IReadOnlyList Parse(string? json) + { + if (string.IsNullOrEmpty(json)) + { + return []; + } + + try + { + return JsonDefaults.Deserialize>(json) ?? []; + } + catch (System.Text.Json.JsonException) + { + return []; + } + } +} + +/// How a name typed into the sign-in form reads as one of this server's local Windows accounts. +/// The bare account name. +/// Typed as .\name or MACHINE\name: always a local Windows account, never a built-in one. +public sealed record LocalWindowsName(string Name, bool Explicit); + +/// +/// Local Windows accounts: this server's own accounts, typed into the sign-in +/// form and checked by Windows. A binding applies by the account's own SID or +/// by the SID of one of its local groups, such as the machine's Administrators. +/// +public static class WindowsSignIn +{ + /// + /// name, .\name and MACHINE\name (this machine's name) + /// read as a local account; another domain's name, a user principal name or + /// anything else does not, and is null. + /// + public static LocalWindowsName? ParseName(string typed, string machineName) + { + var value = typed.Trim(); + var slash = value.IndexOf('\\', StringComparison.Ordinal); + if (slash < 0) + { + return IsAccountName(value) ? new LocalWindowsName(value, false) : null; + } + + var prefix = value[..slash]; + var name = value[(slash + 1)..]; + var local = prefix == "." || prefix.Equals(machineName, StringComparison.OrdinalIgnoreCase); + return local && IsAccountName(name) ? new LocalWindowsName(name, true) : null; + } + + /// Whether the name has a domain part that is not this machine's (EXAMPLE\jdoe) or is a user principal name. + public static bool IsDirectoryName(string typed, string machineName) + { + var value = typed.Trim(); + return value.Contains('@', StringComparison.Ordinal) || (value.Contains('\\', StringComparison.Ordinal) && ParseName(value, machineName) is null); + } + + /// The principals a local Windows account's bindings can name: its own SID and the SIDs of its local groups. + public static IReadOnlyList Principals(string sid, string userName, IReadOnlyList groups) => + [new GroupRef(PrincipalKinds.WindowsGroup, sid, userName), .. groups.Select(g => new GroupRef(PrincipalKinds.WindowsGroup, g.Sid, g.Name))]; + + // A local account name has no slash, at sign or control character, and SAM limits it to 20 characters. + private static bool IsAccountName(string name) => + name.Length is > 0 and <= 20 && !name.Any(c => char.IsControl(c) || c is '\\' or '/' or '@' or '"' or '[' or ']' or ':' or ';' or '|' or '=' or ',' or '+' or '*' or '?' or '<' or '>'); + + /// The account name of a SID on this machine, for display; null when it cannot be resolved. + public static string? NameOf(string sid) + { + if (!OperatingSystem.IsWindows()) + { + return null; + } + + try + { + return new SecurityIdentifier(sid).Translate(typeof(NTAccount)).Value; + } + catch (SystemException) + { + return null; + } + } + + /// The SID of a Windows account or group typed by name, or the SID itself when one was typed; null when it does not resolve. + public static string? SidOf(string nameOrSid) + { + var value = nameOrSid.Trim(); + if (value.StartsWith("S-1-", StringComparison.OrdinalIgnoreCase)) + { + try + { + return OperatingSystem.IsWindows() ? new SecurityIdentifier(value).Value : value.ToUpperInvariant(); + } + catch (ArgumentException) + { + return null; + } + } + + if (!OperatingSystem.IsWindows()) + { + return null; + } + + try + { + return ((SecurityIdentifier)new NTAccount(value).Translate(typeof(SecurityIdentifier))).Value; + } + catch (SystemException) + { + return null; + } + } +} + +/// What Windows answered for a local account's name and password. Only signs anyone in. +public enum LocalLogonOutcome +{ + Accepted, + + /// Unknown name, wrong password, or not one of this machine's own accounts. + Refused, + Disabled, + LockedOut, + Expired, + PasswordExpired, + PasswordMustChange, + + /// The account may not log on over the network here (user rights or logon hours). + NotPermitted, + + /// Not Windows, or the logon service could not answer. + Unavailable, +} + +/// The answer, with the account's SID and MACHINE\name when it was accepted. +public sealed record LocalLogonResult(LocalLogonOutcome Outcome, string? Sid = null, string? AccountName = null) +{ + public static LocalLogonResult Refused { get; } = new(LocalLogonOutcome.Refused); +} + +/// Checks a password against this machine's own account database; never creates, changes or unlocks an account. +public interface ILocalLogon +{ + /// is a bare account name (no machine or domain part); the password is used once and not kept. + LocalLogonResult Validate(string userName, string password); +} + +/// +/// LogonUser with a network logon against the local account database +/// (domain .): Windows refuses disabled, locked out and expired +/// accounts, applies its own lockout policy, and needs only the right to +/// access this computer from the network. The token's user SID must be the +/// named account's own, so an enabled Guest account never stands in for an +/// unknown name. +/// +public sealed partial class LocalLogon : ILocalLogon +{ + private const int LogonNetwork = 3; + private const int ProviderDefault = 0; + + public LocalLogonResult Validate(string userName, string password) => + OperatingSystem.IsWindows() ? ValidateWindows(userName, password) : new LocalLogonResult(LocalLogonOutcome.Unavailable); + + [SupportedOSPlatform("windows")] + private static LocalLogonResult ValidateWindows(string userName, string password) + { + if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password) || userName.IndexOfAny(['\\', '/', '@']) >= 0) + { + return LocalLogonResult.Refused; + } + + if (!LogonUser(userName, ".", password, LogonNetwork, ProviderDefault, out var token)) + { + return new LocalLogonResult(OutcomeOf(Marshal.GetLastPInvokeError())); + } + + using (token) + { + var accountName = $"{Environment.MachineName}\\{userName}"; + string? expected; + try + { + expected = ((SecurityIdentifier)new NTAccount(accountName).Translate(typeof(SecurityIdentifier))).Value; + } + catch (SystemException) + { + return LocalLogonResult.Refused; + } + + using var identity = new WindowsIdentity(token.DangerousGetHandle()); + return identity.User?.Value is { } sid && sid.Equals(expected, StringComparison.OrdinalIgnoreCase) + ? new LocalLogonResult(LocalLogonOutcome.Accepted, sid, accountName) + : LocalLogonResult.Refused; + } + } + + private static LocalLogonOutcome OutcomeOf(int error) => error switch + { + 1326 => LocalLogonOutcome.Refused, // ERROR_LOGON_FAILURE + 1331 => LocalLogonOutcome.Disabled, // ERROR_ACCOUNT_DISABLED + 1909 => LocalLogonOutcome.LockedOut, // ERROR_ACCOUNT_LOCKED_OUT + 1793 => LocalLogonOutcome.Expired, // ERROR_ACCOUNT_EXPIRED + 1330 => LocalLogonOutcome.PasswordExpired, // ERROR_PASSWORD_EXPIRED + 1907 => LocalLogonOutcome.PasswordMustChange, // ERROR_PASSWORD_MUST_CHANGE + 1385 or 1327 or 1328 or 1329 => LocalLogonOutcome.NotPermitted, // logon type not granted, restriction, hours, workstation + _ => LocalLogonOutcome.Unavailable, + }; + + [LibraryImport("advapi32.dll", EntryPoint = "LogonUserW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool LogonUser(string userName, string domain, string password, int logonType, int logonProvider, out SafeAccessTokenHandle token); +} + +/// A group on this machine, by its account name (BUILTIN\Administrators) and SID. +public sealed record LocalAccountGroup(string Name, string Sid); + +/// What this machine knows of a Windows account: its SID, full name and description, and its local groups (directly or through a domain group). +public sealed record LocalAccountDetails(string Sid, bool OnThisMachine, string? FullName, string? Description, IReadOnlyList Groups); + +/// Reads Windows accounts on this machine; read-only, it never creates or changes an account or a group. +public interface ILocalAccounts +{ + /// The account named DOMAIN\user (or MACHINE\user) with when known. Null off Windows or when it does not resolve. + LocalAccountDetails? Read(string accountName, string? sid = null); +} + +/// +/// The Windows account database through its own APIs: LookupAccountName/LookupAccountSid +/// for SIDs and names, NetUserGetInfo level 23 for the full name and +/// comment, and NetUserGetLocalGroups with LG_INCLUDE_INDIRECT +/// for the local groups. +/// +public sealed partial class LocalAccounts : ILocalAccounts +{ + private const int Success = 0; + private const int MaxPreferredLength = -1; + private const int IncludeIndirect = 1; + + public LocalAccountDetails? Read(string accountName, string? sid = null) => + OperatingSystem.IsWindows() && !string.IsNullOrWhiteSpace(accountName) ? ReadWindows(accountName.Trim(), sid) : null; + + [SupportedOSPlatform("windows")] + private static LocalAccountDetails? ReadWindows(string accountName, string? expectedSid) + { + var sid = SidOf(accountName); + if (sid is null || (expectedSid is not null && !sid.Value.Equals(expectedSid, StringComparison.OrdinalIgnoreCase))) + { + return null; + } + + var slash = accountName.LastIndexOf('\\'); + var (fullName, description, onThisMachine) = UserInfo(slash >= 0 ? accountName[(slash + 1)..] : accountName, sid); + return new LocalAccountDetails(sid.Value, onThisMachine, fullName, description, LocalGroups(accountName)); + } + + [SupportedOSPlatform("windows")] + private static SecurityIdentifier? SidOf(string name) + { + try + { + return (SecurityIdentifier)new NTAccount(name).Translate(typeof(SecurityIdentifier)); + } + catch (SystemException) + { + return null; + } + } + + [SupportedOSPlatform("windows")] + private static (string? FullName, string? Description, bool OnThisMachine) UserInfo(string userName, SecurityIdentifier sid) + { + if (NetUserGetInfo(null, userName, 23, out var buffer) != Success || buffer == IntPtr.Zero) + { + return (null, null, false); + } + + try + { + var info = Marshal.PtrToStructure(buffer); + if (info.UserSid == IntPtr.Zero || new SecurityIdentifier(info.UserSid) != sid) + { + return (null, null, false); + } + + return (Text(info.FullName), Text(info.Comment), true); + } + finally + { + _ = NetApiBufferFree(buffer); + } + } + + [SupportedOSPlatform("windows")] + private static List LocalGroups(string accountName) + { + var groups = new List(); + if (NetUserGetLocalGroups(null, accountName, 0, IncludeIndirect, out var buffer, MaxPreferredLength, out var read, out _) != Success + || buffer == IntPtr.Zero) + { + return groups; + } + + try + { + for (var i = 0; i < read; i++) + { + var name = Marshal.PtrToStringUni(Marshal.ReadIntPtr(buffer, i * IntPtr.Size)); + if (string.IsNullOrEmpty(name) || SidOf(name) is not { } sid) + { + continue; + } + + groups.Add(new LocalAccountGroup(NameOf(sid) ?? name, sid.Value)); + } + } + finally + { + _ = NetApiBufferFree(buffer); + } + + return [.. groups.DistinctBy(g => g.Sid, StringComparer.OrdinalIgnoreCase).OrderBy(g => g.Name, StringComparer.OrdinalIgnoreCase)]; + } + + [SupportedOSPlatform("windows")] + private static string? NameOf(SecurityIdentifier sid) + { + try + { + return sid.Translate(typeof(NTAccount)).Value; + } + catch (SystemException) + { + return null; + } + } + + private static string? Text(IntPtr pointer) => Marshal.PtrToStringUni(pointer) is { Length: > 0 } text ? text.Trim() : null; + + /// USER_INFO_23. + [StructLayout(LayoutKind.Sequential)] + private struct UserInfo23 + { + public IntPtr Name; + public IntPtr FullName; + public IntPtr Comment; + public int Flags; + public IntPtr UserSid; + } + + [LibraryImport("netapi32.dll", StringMarshalling = StringMarshalling.Utf16)] + private static partial int NetUserGetInfo(string? serverName, string userName, int level, out IntPtr buffer); + + [LibraryImport("netapi32.dll", StringMarshalling = StringMarshalling.Utf16)] + private static partial int NetUserGetLocalGroups(string? serverName, string userName, int level, int flags, out IntPtr buffer, int preferredMaxLength, + out int entriesRead, out int totalEntries); + + [LibraryImport("netapi32.dll")] + private static partial int NetApiBufferFree(IntPtr buffer); +} + +/// The domain this machine is joined to: its NetBIOS name, and its DNS name as the domain controller locator found it. +public sealed record DomainJoin(string NetBiosName, string? DnsName); + +/// Whether this machine is joined to a domain; read only. +public interface IDomainMembership +{ + /// The domain, or null on a workgroup machine and off Windows. is null while no controller answers. + DomainJoin? Read(); +} + +/// NetGetJoinInformation for the join, and the domain controller locator (DsGetDcName) for the domain's DNS name. +public sealed partial class DomainMembership : IDomainMembership +{ + private const int JoinedToDomain = 3; + private const uint DirectoryServiceRequired = 0x10; + private const uint ReturnDnsName = 0x40000000; + + public DomainJoin? Read() => OperatingSystem.IsWindows() ? ReadWindows() : null; + + [SupportedOSPlatform("windows")] + private static DomainJoin? ReadWindows() + { + if (NetGetJoinInformation(null, out var nameBuffer, out var status) != 0) + { + return null; + } + + string? netBios; + try + { + netBios = Marshal.PtrToStringUni(nameBuffer); + } + finally + { + _ = NetApiBufferFree(nameBuffer); + } + + if (status != JoinedToDomain || string.IsNullOrEmpty(netBios)) + { + return null; + } + + string? dns = null; + if (DsGetDcName(null, null, IntPtr.Zero, null, DirectoryServiceRequired | ReturnDnsName, out var info) == 0 && info != IntPtr.Zero) + { + try + { + dns = Marshal.PtrToStringUni(Marshal.PtrToStructure(info).DomainName)?.TrimEnd('.'); + } + finally + { + _ = NetApiBufferFree(info); + } + } + + return new DomainJoin(netBios, string.IsNullOrEmpty(dns) ? null : dns); + } + + /// DOMAIN_CONTROLLER_INFOW. + [StructLayout(LayoutKind.Sequential)] + private struct DomainControllerInfo + { + public IntPtr DomainControllerName; + public IntPtr DomainControllerAddress; + public uint DomainControllerAddressType; + public Guid DomainGuid; + public IntPtr DomainName; + public IntPtr DnsForestName; + public uint Flags; + public IntPtr DcSiteName; + public IntPtr ClientSiteName; + } + + [LibraryImport("netapi32.dll", StringMarshalling = StringMarshalling.Utf16)] + private static partial int NetGetJoinInformation(string? server, out IntPtr nameBuffer, out int status); + + [LibraryImport("netapi32.dll", EntryPoint = "DsGetDcNameW", StringMarshalling = StringMarshalling.Utf16)] + private static partial int DsGetDcName(string? computerName, string? domainName, IntPtr domainGuid, string? siteName, uint flags, out IntPtr info); + + [LibraryImport("netapi32.dll")] + private static partial int NetApiBufferFree(IntPtr buffer); +} diff --git a/src/Backend/Auth/UserService.cs b/src/Backend/Auth/UserService.cs deleted file mode 100644 index 04d5845..0000000 --- a/src/Backend/Auth/UserService.cs +++ /dev/null @@ -1,125 +0,0 @@ -using Backend.Data; -using Microsoft.AspNetCore.Identity; -using Microsoft.EntityFrameworkCore; -using Shared.Contracts.Models; - -namespace Backend.Auth; - -/// -/// Local user lifecycle and password verification. Passwords are hashed with -/// ASP.NET Core's ; there is no compiled default -/// password. Rehashes transparently when the hasher recommends it. -/// -public sealed class UserService(AppDbContext db, ILogger logger) -{ - private readonly PasswordHasher hasher = new(); - - /// - /// Creates the initial admin from environment secrets on first startup only. - /// Never overwrites an existing admin's password. Runs after system-role - /// seeding so the account lands on the Admin role. - /// - public async Task EnsureInitialAdminAsync( - string? username, string? password, bool mustChangePassword, CancellationToken cancellationToken) - { - if (await db.Users.AnyAsync(cancellationToken)) - { - return; - } - - if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password)) - { - logger.LogWarning( - "No users exist and INITIAL_ADMIN_USERNAME/PASSWORD are not set; create an admin to enable sign-in"); - return; - } - - var adminRoleId = await db.Roles - .Where(r => r.IsSystem && r.Name == nameof(UserRole.Admin)) - .Select(r => (Guid?)r.Id) - .SingleOrDefaultAsync(cancellationToken); - - var admin = new UserEntity - { - Id = Guid.NewGuid(), - Username = username.Trim(), - DisplayName = username.Trim(), - Role = UserRole.Admin, - RoleId = adminRoleId, - AuthProvider = AuthConstants.ProviderLocal, - MustChangePassword = mustChangePassword, - CreatedUtc = DateTimeOffset.UtcNow, - }; - admin.PasswordHash = hasher.HashPassword(admin, password); - db.Users.Add(admin); - await db.SaveChangesAsync(cancellationToken); - - logger.LogInformation("Initial admin '{Username}' created", admin.Username); - } - - /// Hashes a password for a (new or existing) local user. - public string HashPassword(UserEntity user, string password) => hasher.HashPassword(user, password); - - public async Task ValidateCredentialsAsync(string username, string password, CancellationToken cancellationToken) - { - var user = await db.Users.SingleOrDefaultAsync( - u => u.Username == username && u.AuthProvider == AuthConstants.ProviderLocal, cancellationToken); - if (user?.PasswordHash is null) - { - return null; - } - - var result = hasher.VerifyHashedPassword(user, user.PasswordHash, password); - if (result == PasswordVerificationResult.Failed) - { - return null; - } - - if (result == PasswordVerificationResult.SuccessRehashNeeded) - { - user.PasswordHash = hasher.HashPassword(user, password); - } - - user.LastLoginUtc = DateTimeOffset.UtcNow; - await db.SaveChangesAsync(cancellationToken); - return user; - } - - /// Upserts an OIDC-authenticated user, assigning the role mapped from claims. - public async Task UpsertOidcUserAsync( - string externalId, string username, string? displayName, RoleEntity role, CancellationToken cancellationToken) - { - var tier = Permissions.Tier( - RoleCache.ParseStrings(role.PermissionsJson).ToHashSet(StringComparer.OrdinalIgnoreCase)); - - var user = await db.Users.SingleOrDefaultAsync( - u => u.ExternalId == externalId && u.AuthProvider == AuthConstants.ProviderOidc, cancellationToken); - - if (user is null) - { - user = new UserEntity - { - Id = Guid.NewGuid(), - Username = username, - DisplayName = displayName ?? username, - Role = tier, - RoleId = role.Id, - AuthProvider = AuthConstants.ProviderOidc, - ExternalId = externalId, - CreatedUtc = DateTimeOffset.UtcNow, - }; - db.Users.Add(user); - } - else - { - user.Username = username; - user.DisplayName = displayName ?? username; - user.Role = tier; - user.RoleId = role.Id; - } - - user.LastLoginUtc = DateTimeOffset.UtcNow; - await db.SaveChangesAsync(cancellationToken); - return user; - } -} diff --git a/src/Backend/Backend.csproj b/src/Backend/Backend.csproj index ea166cb..6a61b4a 100644 --- a/src/Backend/Backend.csproj +++ b/src/Backend/Backend.csproj @@ -3,6 +3,8 @@ net10.0 Backend + + true backend-dev-secrets ExecuteR Server ExecuteR Server @@ -19,7 +21,8 @@ - + + diff --git a/src/Backend/Data/AppDbContext.cs b/src/Backend/Data/AppDbContext.cs index 0241bc0..8b8dd25 100644 --- a/src/Backend/Data/AppDbContext.cs +++ b/src/Backend/Data/AppDbContext.cs @@ -8,12 +8,19 @@ public class AppDbContext(DbContextOptions options) : DbContext(op { public DbSet Users => Set(); public DbSet Roles => Set(); - public DbSet OidcProviders => Set(); + public DbSet LocalGroups => Set(); + public DbSet LocalGroupMembers => Set(); + public DbSet RoleBindings => Set(); + public DbSet Sessions => Set(); + public DbSet SignInRequests => Set(); + public DbSet SignInThrottles => Set(); + public DbSet StepUps => Set(); public DbSet Devices => Set(); public DbSet DeviceInventory => Set(); public DbSet Scripts => Set(); public DbSet FunctionModules => Set(); public DbSet Jobs => Set(); + public DbSet Runs => Set(); public DbSet JobOutput => Set(); public DbSet BootstrapTokens => Set(); public DbSet AuditEvents => Set(); @@ -24,6 +31,8 @@ public class AppDbContext(DbContextOptions options) : DbContext(op public DbSet ScriptTriggerRuns => Set(); public DbSet AppSettings => Set(); public DbSet SecretsProviders => Set(); + public DbSet AgentPackages => Set(); + public DbSet AgentUpgrades => Set(); /// /// SQLite cannot ORDER BY / compare DateTimeOffset natively, so it stores @@ -44,14 +53,123 @@ public class AppDbContext(DbContextOptions options) : DbContext(op value => value.UtcTicks, ticks => new DateTimeOffset(ticks, TimeSpan.Zero)); + public override int SaveChanges(bool acceptAllChangesOnSuccess) + { + RenewConcurrencyStamps(); + return base.SaveChanges(acceptAllChangesOnSuccess); + } + + public override Task SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default) + { + RenewConcurrencyStamps(); + return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); + } + + /// + /// Every write to a trigger or an agent upgrade gets a fresh stamp; the + /// update is conditioned on the stamp it was read with, so a concurrent + /// write surfaces as DbUpdateConcurrencyException instead of silently winning. + /// + private void RenewConcurrencyStamps() + { + foreach (var entry in ChangeTracker.Entries()) + { + if (entry.State is EntityState.Added or EntityState.Modified) + { + entry.Entity.ConcurrencyStamp = Guid.NewGuid(); + } + } + + foreach (var entry in ChangeTracker.Entries()) + { + if (entry.State is EntityState.Added or EntityState.Modified) + { + entry.Entity.ConcurrencyStamp = Guid.NewGuid(); + } + } + } + protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity(entity => { entity.ToTable("Users"); entity.HasKey(e => e.Id); - entity.HasIndex(e => e.Username).IsUnique(); - entity.Property(e => e.Role).HasConversion(); + // One name per kind of account: a built-in jdoe and a directory jdoe are two people. + entity.HasIndex(e => new { e.Kind, e.UserName }).IsUnique(); + entity.HasIndex(e => new { e.Kind, e.ExternalId }); + entity.Property(e => e.Kind).HasMaxLength(16); + entity.Property(e => e.UserName).HasMaxLength(256); + entity.Property(e => e.ExternalId).HasMaxLength(450); + entity.Property(e => e.LegacyRole).HasMaxLength(32); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("LocalGroups"); + entity.HasKey(e => e.Id); + entity.Property(e => e.Name).HasMaxLength(128); + entity.HasIndex(e => e.Name).IsUnique(); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("LocalGroupMembers"); + entity.HasKey(e => new { e.GroupId, e.UserId }); + entity.HasIndex(e => e.UserId); + entity.HasOne().WithMany().HasForeignKey(e => e.GroupId).OnDelete(DeleteBehavior.Cascade); + entity.HasOne().WithMany().HasForeignKey(e => e.UserId).OnDelete(DeleteBehavior.Cascade); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("RoleBindings"); + entity.HasKey(e => e.Id); + entity.Property(e => e.PrincipalKind).HasMaxLength(32); + entity.Property(e => e.PrincipalId).HasMaxLength(450); + entity.HasIndex(e => new { e.PrincipalKind, e.PrincipalId, e.RoleId }).IsUnique(); + entity.HasOne().WithMany().HasForeignKey(e => e.RoleId).OnDelete(DeleteBehavior.Cascade); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("Sessions"); + entity.HasKey(e => e.Id); + entity.Property(e => e.Id).HasMaxLength(64); + entity.Property(e => e.SecretHash).HasMaxLength(128); + entity.Property(e => e.CsrfHash).HasMaxLength(128); + entity.Property(e => e.Provider).HasMaxLength(16); + entity.Property(e => e.UserAgent).HasMaxLength(512); + entity.HasIndex(e => e.UserId); + entity.HasIndex(e => e.AbsoluteExpiresUtc); + entity.HasOne(e => e.User).WithMany().HasForeignKey(e => e.UserId).OnDelete(DeleteBehavior.Cascade); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("SignInRequests"); + entity.HasKey(e => e.Id); + entity.Property(e => e.Id).HasMaxLength(64); + entity.Property(e => e.Provider).HasMaxLength(16); + entity.Property(e => e.Status).HasMaxLength(16); + entity.Property(e => e.Detail).HasMaxLength(2000); + entity.HasIndex(e => e.ExpiresUtc); + entity.HasIndex(e => e.TestSessionId); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("SignInThrottles"); + entity.HasKey(e => e.Key); + entity.Property(e => e.Key).HasMaxLength(300); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("StepUps"); + entity.HasKey(e => e.SessionId); + entity.Property(e => e.SessionId).HasMaxLength(64); + entity.Property(e => e.Method).HasMaxLength(16); }); modelBuilder.Entity(entity => @@ -61,17 +179,12 @@ public class AppDbContext(DbContextOptions options) : DbContext(op entity.HasIndex(e => e.Name).IsUnique(); }); - modelBuilder.Entity(entity => - { - entity.ToTable("OidcProviders"); - entity.HasKey(e => e.Id); - }); - modelBuilder.Entity(entity => { entity.ToTable("Devices"); entity.HasKey(e => e.ClientId); entity.HasIndex(e => e.Hostname); + entity.Property(e => e.AgentRuntime).HasMaxLength(32); entity.HasOne(e => e.Inventory) .WithOne() .HasForeignKey(e => e.ClientId) @@ -105,9 +218,21 @@ public class AppDbContext(DbContextOptions options) : DbContext(op entity.HasIndex(e => e.ClientId); entity.HasIndex(e => e.CreatedUtc); entity.HasIndex(e => new { e.ScriptId, e.RunId }); + entity.HasIndex(e => e.RunId); entity.Property(e => e.State).HasConversion(); }); + modelBuilder.Entity(entity => + { + entity.ToTable("Runs"); + entity.HasKey(e => e.RunId); + entity.HasIndex(e => e.CreatedUtc); + entity.HasIndex(e => e.ScriptId); + entity.Property(e => e.ScriptName).HasMaxLength(200); + entity.Property(e => e.Source).HasMaxLength(32); + entity.Property(e => e.TargetsLabel).HasMaxLength(400); + }); + modelBuilder.Entity(entity => { entity.ToTable("JobOutput"); @@ -161,6 +286,7 @@ public class AppDbContext(DbContextOptions options) : DbContext(op // The schedule sweep queries due scheduled triggers by next-run. entity.HasIndex(e => e.NextRunUtc); entity.Property(e => e.TriggerType).HasConversion(); + entity.Property(e => e.ConcurrencyStamp).IsConcurrencyToken(); }); modelBuilder.Entity(entity => @@ -183,5 +309,40 @@ public class AppDbContext(DbContextOptions options) : DbContext(op entity.HasIndex(e => e.Name).IsUnique(); }); + modelBuilder.Entity(entity => + { + entity.ToTable("AgentPackages"); + entity.HasKey(e => e.Id); + entity.Property(e => e.Version).HasMaxLength(64); + entity.Property(e => e.PackageType).HasMaxLength(32); + entity.Property(e => e.FileName).HasMaxLength(128); + entity.Property(e => e.Sha256).HasMaxLength(64); + entity.Property(e => e.StoragePath).HasMaxLength(512); + entity.Property(e => e.S3Key).HasMaxLength(512); + // One package per version and platform: replicas importing the same build race on this. + entity.HasIndex(e => new { e.Version, e.PackageType }).IsUnique(); + entity.HasIndex(e => e.Sha256); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("AgentUpgrades"); + entity.HasKey(e => e.Id); + entity.Property(e => e.FromVersion).HasMaxLength(64); + entity.Property(e => e.TargetVersion).HasMaxLength(64); + entity.Property(e => e.PackageType).HasMaxLength(32); + entity.Property(e => e.Sha256).HasMaxLength(64); + entity.Property(e => e.Source).HasMaxLength(16); + entity.Property(e => e.State).HasMaxLength(16); + entity.Property(e => e.Reason).HasMaxLength(32); + entity.Property(e => e.Detail).HasMaxLength(2000); + entity.Property(e => e.RequestedBy).HasMaxLength(256); + entity.HasIndex(e => new { e.ClientId, e.State }); + // The scheduler sweeps by state; listings page by creation. + entity.HasIndex(e => e.State); + entity.HasIndex(e => e.CreatedUtc); + entity.Property(e => e.ConcurrencyStamp).IsConcurrencyToken(); + }); + } } diff --git a/src/Backend/Data/Entities.cs b/src/Backend/Data/Entities.cs index c10889d..4f20e0f 100644 --- a/src/Backend/Data/Entities.cs +++ b/src/Backend/Data/Entities.cs @@ -2,24 +2,156 @@ using Shared.Contracts.Models; namespace Backend.Data; +/// +/// A person who signs in: a built-in account (local), one of this +/// server's local Windows accounts (windows, keyed by SID), or a +/// directory or identity-provider person (ldap, oidc, keyed by +/// their stable subject). Access never sits on the user: it comes from the +/// groups they are in, through role bindings. +/// public sealed class UserEntity { public Guid Id { get; set; } - public required string Username { get; set; } + + /// local, windows, ldap or oidc (SignInProviders). + public required string Kind { get; set; } + + public required string UserName { get; set; } public string? DisplayName { get; set; } - public string? PasswordHash { get; set; } - /// Coarse legacy tier kept in sync with the assigned role. - public UserRole Role { get; set; } - /// Assigned ; null falls back to the legacy tier. - public Guid? RoleId { get; set; } - /// Sign-in must set a new password first (e.g. the defaulted admin/admin). - public bool MustChangePassword { get; set; } - /// "local" or "oidc". - public required string AuthProvider { get; set; } - /// OIDC subject claim for external users. + public string? Email { get; set; } + + /// A Windows account's comment, refreshed at each sign-in. + public string? Description { get; set; } + + /// Windows SID, LDAP objectGUID/entryUUID/DN, or OIDC subject. public string? ExternalId { get; set; } + + /// A Windows account's local groups as read at its sign-in: JSON [{name, sid}], for display. + public string? WindowsGroupsJson { get; set; } + + /// PBKDF2-SHA512 ($pbkdf2-sha512$…), or an older ASP.NET Identity hash rehashed at the next sign-in. + public string? PasswordHash { get; set; } + + /// The one recovery account: full access through no binding, cannot be turned off or removed. + public bool IsBreakGlass { get; set; } + + public bool Enabled { get; set; } = true; + public bool MustChangePassword { get; set; } + public DateTimeOffset? PasswordChangedUtc { get; set; } public DateTimeOffset CreatedUtc { get; set; } - public DateTimeOffset? LastLoginUtc { get; set; } + public DateTimeOffset UpdatedUtc { get; set; } + public DateTimeOffset? LastSignInUtc { get; set; } + + /// Before role bindings: the user's own role. Moved into a built-in group at upgrade, then cleared. + public Guid? LegacyRoleId { get; set; } + + /// Before custom roles: the Admin/Operator/Viewer tier, used at upgrade when there is no LegacyRoleId. + public string? LegacyRole { get; set; } +} + +/// A group of built-in accounts, so they get access the way directory people do: through a group bound to a role. +public sealed class LocalGroupEntity +{ + public Guid Id { get; set; } + public required string Name { get; set; } + public string? Description { get; set; } + public DateTimeOffset CreatedUtc { get; set; } + public DateTimeOffset UpdatedUtc { get; set; } +} + +public sealed class LocalGroupMemberEntity +{ + public Guid GroupId { get; set; } + public Guid UserId { get; set; } +} + +/// +/// Joins a role and a principal: a built-in group, a Windows account or group +/// (SID), a directory group (DN) or an identity-provider claim (claim=value). +/// Never an individual person. +/// +public sealed class RoleBindingEntity +{ + public Guid Id { get; set; } + public Guid RoleId { get; set; } + public required string PrincipalKind { get; set; } + + /// Normalized (PrincipalKinds.Normalize) so equal principals compare equal. + public required string PrincipalId { get; set; } + + public string? PrincipalName { get; set; } + public DateTimeOffset CreatedUtc { get; set; } + public string? CreatedBy { get; set; } +} + +/// A browser session: the cookie carries the id and a secret whose hash is kept here, so sign-out is immediate on every node. +public sealed class SessionEntity +{ + public required string Id { get; set; } + public Guid UserId { get; set; } + public UserEntity? User { get; set; } + public required string SecretHash { get; set; } + public string? CsrfHash { get; set; } + + /// The provider the person signed in through. + public required string Provider { get; set; } + + /// The groups resolved at sign-in, as JSON: what the session's access comes from. + public string? GroupsJson { get; set; } + + public DateTimeOffset CreatedUtc { get; set; } + public DateTimeOffset LastSeenUtc { get; set; } + + /// Slides forward with use, never past . + public DateTimeOffset ExpiresUtc { get; set; } + + public DateTimeOffset AbsoluteExpiresUtc { get; set; } + public DateTimeOffset? RevokedUtc { get; set; } + public string? ClientAddress { get; set; } + public string? UserAgent { get; set; } +} + +/// A sign-in in flight through the identity provider (state, nonce, PKCE verifier), or a test sign-in's result. +public sealed class SignInRequestEntity +{ + public required string Id { get; set; } + public required string Provider { get; set; } + public required string Status { get; set; } + public string? Nonce { get; set; } + public string? CodeVerifier { get; set; } + public string? ReturnUrl { get; set; } + + /// For a test sign-in: the session that started it, which alone may rely on its result. + public string? TestSessionId { get; set; } + + /// For a step-up: the session whose person re-authenticates with the provider. + public string? StepUpSessionId { get; set; } + + /// For a test sign-in: the provider settings it ran against, so a later edit needs a new test. + public string? SettingsEtag { get; set; } + + public string? Detail { get; set; } + public DateTimeOffset CreatedUtc { get; set; } + public DateTimeOffset ExpiresUtc { get; set; } + public DateTimeOffset? CompletedUtc { get; set; } +} + +/// Failed sign-ins under one key (an account or a client address), for back-off that holds across nodes. +public sealed class SignInThrottleEntity +{ + public required string Key { get; set; } + public int Failures { get; set; } + public DateTimeOffset FirstFailureUtc { get; set; } + public DateTimeOffset LastFailureUtc { get; set; } + public DateTimeOffset? BlockedUntilUtc { get; set; } +} + +/// A session's person confirmed again (step-up), and how. +public sealed class StepUpEntity +{ + public required string SessionId { get; set; } + public required string Method { get; set; } + public DateTimeOffset VerifiedUtc { get; set; } } /// @@ -35,7 +167,7 @@ public sealed class RoleEntity public bool IsSystem { get; set; } /// JSON array of permission keys; ["*"] grants everything. public string? PermissionsJson { get; set; } - /// JSON array of IdP group/role claim values that map sign-ins to this role. + /// Before role bindings: IdP claim values mapped to this role. Moved into bindings at upgrade, then cleared. public string? OidcClaimValuesJson { get; set; } /// JSON array of device-group ids limiting what devices members can see and target; empty = all. public string? DeviceScopeGroupIdsJson { get; set; } @@ -44,15 +176,6 @@ public sealed class RoleEntity public string? UpdatedBy { get; set; } } -public sealed class OidcProviderEntity -{ - public Guid Id { get; set; } - public required string Name { get; set; } - public required string Authority { get; set; } - public required string ClientId { get; set; } - public bool Enabled { get; set; } -} - public sealed class DeviceEntity { public required string ClientId { get; set; } @@ -62,10 +185,18 @@ public sealed class DeviceEntity public string? OsCaption { get; set; } public string? OsVersion { get; set; } public string? AgentVersion { get; set; } + /// The agent build's runtime identifier from presence (e.g. win-x64); null from older agents. + public string? AgentRuntime { get; set; } /// Enrolled NATS user public key bound to this device. public required string NkeyPublic { get; set; } public Guid EnrollmentId { get; set; } public DateTimeOffset EnrolledUtc { get; set; } + /// + /// Bootstrap token of the last enrollment. Re-running the same install on + /// the same machine (redeploy, repair, reimage) re-enrolls with it without + /// spending another use, while it is still valid and not revoked. + /// + public Guid? BootstrapTokenId { get; set; } public DateTimeOffset? LastSeenUtc { get; set; } /// JSON array of current IP addresses (from presence/inventory). public string? IpAddressesJson { get; set; } @@ -89,10 +220,12 @@ public sealed class DeviceEntity public DeviceInventoryEntity? Inventory { get; set; } } -/// A static or rule-based dynamic device group. +/// A static, rule-based dynamic, or folder device group; groups nest via ParentId. public sealed class DeviceGroupEntity { public Guid Id { get; set; } + /// Enclosing group; null for a top-level group. + public Guid? ParentId { get; set; } public required string Name { get; set; } public string? Description { get; set; } public GroupKind Kind { get; set; } @@ -121,6 +254,9 @@ public sealed class ScriptTriggerEntity public Guid Id { get; set; } public Guid ScriptId { get; set; } + /// Operator label ("Nightly cleanup"); the script name stands in when unset. + public string? Name { get; set; } + // Target: a single device (ClientId), a group (GroupId), or all devices // when both are null. Event triggers historically used GroupId; scheduled // triggers can target either. @@ -148,6 +284,14 @@ public sealed class ScriptTriggerEntity public string? ArgumentsJson { get; set; } /// Human-readable outcome of the last scheduled firing. public string? LastResult { get; set; } + /// Execution (job RunId) the last firing created, for drill-in. + public Guid? LastRunId { get; set; } + + /// + /// Optimistic-concurrency token, renewed on every save (AppDbContext), so + /// a schedule edited while it is firing is not overwritten by the sweep. + /// + public Guid ConcurrencyStamp { get; set; } public DateTimeOffset CreatedUtc { get; set; } public string? CreatedBy { get; set; } @@ -222,6 +366,8 @@ public sealed class AppSettingEntity public required string Key { get; set; } public string? Value { get; set; } public bool IsSecret { get; set; } + /// Version of a settings document (SettingsDocuments): changes on every write, for If-Match. + public string? Etag { get; set; } public DateTimeOffset UpdatedUtc { get; set; } public string? UpdatedBy { get; set; } } @@ -238,6 +384,50 @@ public sealed class FunctionModuleEntity public string? UpdatedBy { get; set; } } +/// +/// One execution as it was asked for: what started it, which targets were +/// requested, and which devices were skipped (they have no job row), so a +/// run's progress can count every target, not only the jobs it created. +/// Runs from before this record existed are still derived from their jobs. +/// +public sealed class RunEntity +{ + public Guid RunId { get; set; } + public Guid ScriptId { get; set; } + public required string ScriptName { get; set; } + public DateTimeOffset CreatedUtc { get; set; } + public string? RequestedBy { get; set; } + + /// manual, schedule or trigger (see RunSources). + public required string Source { get; set; } + + public Guid? TriggerId { get; set; } + + /// What was targeted, for headers: "Group “Lab” and 3 devices". + public string? TargetsLabel { get; set; } + + public bool OnlineOnly { get; set; } + + /// JSON array of RunSkip: devices targeted but given no job. + public string SkippedJson { get; set; } = "[]"; +} + +/// A targeted device that got no job, and why (orphaned, offline). +public sealed record RunSkip(string ClientId, string Hostname, string Reason); + +public static class RunSources +{ + public const string Manual = "manual"; + public const string Schedule = "schedule"; + public const string Trigger = "trigger"; +} + +public static class SkipReasons +{ + public const string Orphaned = "orphaned"; + public const string Offline = "offline"; +} + public sealed class JobEntity { public Guid JobId { get; set; } @@ -297,6 +487,78 @@ public sealed class AuditEventEntity public string? RemoteIp { get; set; } } +/// +/// One package of an agent version in the server's catalog: a copy kept under +/// <data>/agent-packages/<version>/<file>, so upgrades and rollbacks +/// can still reach a version after the server image moves on. +/// +public sealed class AgentPackageEntity +{ + public Guid Id { get; set; } + public required string Version { get; set; } + + /// An AgentPackageTypes value (zip, linux-x64, …). + public required string PackageType { get; set; } + + public required string FileName { get; set; } + public required string Sha256 { get; set; } + public long SizeBytes { get; set; } + + /// Relative to the catalog root: "<version>/<file>". + public required string StoragePath { get; set; } + + /// Object key once offloaded to S3 (Agent offload on). + public string? S3Key { get; set; } + + public DateTimeOffset ImportedUtc { get; set; } +} + +/// +/// One device's agent upgrade attempt (or rollback); a device has at most one +/// open (AgentUpgradeStates.Open). The scheduler sends queued rows; the agent's +/// events move them on. +/// +public sealed class AgentUpgradeEntity +{ + public Guid Id { get; set; } + public required string ClientId { get; set; } + public string? FromVersion { get; set; } + public required string TargetVersion { get; set; } + public required string PackageType { get; set; } + public Guid? PackageId { get; set; } + public string? Sha256 { get; set; } + + /// manual, automatic or rollback (AgentUpgradeSources). + public required string Source { get; set; } + + /// An AgentUpgradeStates value. + public required string State { get; set; } + + /// An AgentUpgradeReasons value when it did not succeed. + public string? Reason { get; set; } + + public string? Detail { get; set; } + + /// JSON array of the watchdog's last log lines, from the outcome event. + public string? LastLogJson { get; set; } + + /// Times the command was handed to JetStream. + public int Attempts { get; set; } + + public string? RequestedBy { get; set; } + public DateTimeOffset CreatedUtc { get; set; } + public DateTimeOffset? SentUtc { get; set; } + public DateTimeOffset? LastEventUtc { get; set; } + public DateTimeOffset? FinishedUtc { get; set; } + + /// + /// Renewed on every save (AppDbContext): the scheduler, the event consumer + /// and an operator's cancel may touch the same row on different nodes, and + /// the later write is refused instead of silently winning. + /// + public Guid ConcurrencyStamp { get; set; } +} + public sealed class ShellSessionEntity { public Guid Id { get; set; } diff --git a/src/Backend/Data/Migrations/Postgres/20261023003329_AddTriggerNameAndLastRun.Designer.cs b/src/Backend/Data/Migrations/Postgres/20261023003329_AddTriggerNameAndLastRun.Designer.cs new file mode 100644 index 0000000..d97b3b4 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20261023003329_AddTriggerNameAndLastRun.Designer.cs @@ -0,0 +1,739 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + [DbContext(typeof(PostgresAppDbContext))] + [Migration("20261023003329_AddTriggerNameAndLastRun")] + partial class AddTriggerNameAndLastRun + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("text"); + + b.Property("IsSecret") + .HasColumnType("boolean"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("text"); + + b.Property("Actor") + .HasColumnType("text"); + + b.Property("Category") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("Detail") + .HasColumnType("text"); + + b.Property("RemoteIp") + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MaxUses") + .HasColumnType("integer"); + + b.Property("Note") + .HasColumnType("text"); + + b.Property("Revoked") + .HasColumnType("boolean"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("Uses") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("AgentVersion") + .HasColumnType("text"); + + b.Property("EnrolledUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentId") + .HasColumnType("uuid"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("text"); + + b.Property("IpAddressesJson") + .HasColumnType("text"); + + b.Property("IsOrphaned") + .HasColumnType("boolean"); + + b.Property("LastSeenUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Manufacturer") + .HasColumnType("text"); + + b.Property("Model") + .HasColumnType("text"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("text"); + + b.Property("OrphanedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OsCaption") + .HasColumnType("text"); + + b.Property("OsVersion") + .HasColumnType("text"); + + b.Property("PublicIp") + .HasColumnType("text"); + + b.Property("ReadyUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TagsJson") + .HasColumnType("text"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("RulesJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CompletedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExitCode") + .HasColumnType("integer"); + + b.Property("OutputSummary") + .HasColumnType("text"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("RunId") + .HasColumnType("uuid"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("text"); + + b.Property("StartedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("text"); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("text"); + + b.Property("IsSystem") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("text"); + + b.Property("PermissionsJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("FileBindingsJson") + .HasColumnType("text"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("text"); + + b.Property("Language") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParametersJson") + .HasColumnType("text"); + + b.Property("SecretBindingsJson") + .HasColumnType("text"); + + b.Property("SecretsVariableName") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ArgumentsJson") + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CronExpression") + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("LastResult") + .HasColumnType("text"); + + b.Property("LastRunId") + .HasColumnType("uuid"); + + b.Property("LastRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("NextRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OncePerDevice") + .HasColumnType("boolean"); + + b.Property("RunOnceUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("text"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("FiredUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("TriggerId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CloseReason") + .HasColumnType("text"); + + b.Property("ClosedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasColumnType("text"); + + b.Property("ExternalId") + .HasColumnType("text"); + + b.Property("LastLoginUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MustChangePassword") + .HasColumnType("boolean"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("Role") + .IsRequired() + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.Property("Username") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20261023003329_AddTriggerNameAndLastRun.cs b/src/Backend/Data/Migrations/Postgres/20261023003329_AddTriggerNameAndLastRun.cs new file mode 100644 index 0000000..472ee76 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20261023003329_AddTriggerNameAndLastRun.cs @@ -0,0 +1,39 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + /// + public partial class AddTriggerNameAndLastRun : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "LastRunId", + table: "ScriptTriggers", + type: "uuid", + nullable: true); + + migrationBuilder.AddColumn( + name: "Name", + table: "ScriptTriggers", + type: "text", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "LastRunId", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "Name", + table: "ScriptTriggers"); + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20261023004353_AddGroupNesting.Designer.cs b/src/Backend/Data/Migrations/Postgres/20261023004353_AddGroupNesting.Designer.cs new file mode 100644 index 0000000..a4017c5 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20261023004353_AddGroupNesting.Designer.cs @@ -0,0 +1,742 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + [DbContext(typeof(PostgresAppDbContext))] + [Migration("20261023004353_AddGroupNesting")] + partial class AddGroupNesting + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("text"); + + b.Property("IsSecret") + .HasColumnType("boolean"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("text"); + + b.Property("Actor") + .HasColumnType("text"); + + b.Property("Category") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("Detail") + .HasColumnType("text"); + + b.Property("RemoteIp") + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MaxUses") + .HasColumnType("integer"); + + b.Property("Note") + .HasColumnType("text"); + + b.Property("Revoked") + .HasColumnType("boolean"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("Uses") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("AgentVersion") + .HasColumnType("text"); + + b.Property("EnrolledUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentId") + .HasColumnType("uuid"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("text"); + + b.Property("IpAddressesJson") + .HasColumnType("text"); + + b.Property("IsOrphaned") + .HasColumnType("boolean"); + + b.Property("LastSeenUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Manufacturer") + .HasColumnType("text"); + + b.Property("Model") + .HasColumnType("text"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("text"); + + b.Property("OrphanedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OsCaption") + .HasColumnType("text"); + + b.Property("OsVersion") + .HasColumnType("text"); + + b.Property("PublicIp") + .HasColumnType("text"); + + b.Property("ReadyUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TagsJson") + .HasColumnType("text"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParentId") + .HasColumnType("uuid"); + + b.Property("RulesJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CompletedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExitCode") + .HasColumnType("integer"); + + b.Property("OutputSummary") + .HasColumnType("text"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("RunId") + .HasColumnType("uuid"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("text"); + + b.Property("StartedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("text"); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("text"); + + b.Property("IsSystem") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("text"); + + b.Property("PermissionsJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("FileBindingsJson") + .HasColumnType("text"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("text"); + + b.Property("Language") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParametersJson") + .HasColumnType("text"); + + b.Property("SecretBindingsJson") + .HasColumnType("text"); + + b.Property("SecretsVariableName") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ArgumentsJson") + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CronExpression") + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("LastResult") + .HasColumnType("text"); + + b.Property("LastRunId") + .HasColumnType("uuid"); + + b.Property("LastRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("NextRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OncePerDevice") + .HasColumnType("boolean"); + + b.Property("RunOnceUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("text"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("FiredUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("TriggerId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CloseReason") + .HasColumnType("text"); + + b.Property("ClosedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasColumnType("text"); + + b.Property("ExternalId") + .HasColumnType("text"); + + b.Property("LastLoginUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MustChangePassword") + .HasColumnType("boolean"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("Role") + .IsRequired() + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.Property("Username") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20261023004353_AddGroupNesting.cs b/src/Backend/Data/Migrations/Postgres/20261023004353_AddGroupNesting.cs new file mode 100644 index 0000000..f26f4b4 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20261023004353_AddGroupNesting.cs @@ -0,0 +1,29 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + /// + public partial class AddGroupNesting : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "ParentId", + table: "DeviceGroups", + type: "uuid", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "ParentId", + table: "DeviceGroups"); + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20261023021515_AddTriggerConcurrencyStamp.Designer.cs b/src/Backend/Data/Migrations/Postgres/20261023021515_AddTriggerConcurrencyStamp.Designer.cs new file mode 100644 index 0000000..49ae30b --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20261023021515_AddTriggerConcurrencyStamp.Designer.cs @@ -0,0 +1,746 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + [DbContext(typeof(PostgresAppDbContext))] + [Migration("20261023021515_AddTriggerConcurrencyStamp")] + partial class AddTriggerConcurrencyStamp + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("text"); + + b.Property("IsSecret") + .HasColumnType("boolean"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("text"); + + b.Property("Actor") + .HasColumnType("text"); + + b.Property("Category") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("Detail") + .HasColumnType("text"); + + b.Property("RemoteIp") + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MaxUses") + .HasColumnType("integer"); + + b.Property("Note") + .HasColumnType("text"); + + b.Property("Revoked") + .HasColumnType("boolean"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("Uses") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("AgentVersion") + .HasColumnType("text"); + + b.Property("EnrolledUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentId") + .HasColumnType("uuid"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("text"); + + b.Property("IpAddressesJson") + .HasColumnType("text"); + + b.Property("IsOrphaned") + .HasColumnType("boolean"); + + b.Property("LastSeenUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Manufacturer") + .HasColumnType("text"); + + b.Property("Model") + .HasColumnType("text"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("text"); + + b.Property("OrphanedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OsCaption") + .HasColumnType("text"); + + b.Property("OsVersion") + .HasColumnType("text"); + + b.Property("PublicIp") + .HasColumnType("text"); + + b.Property("ReadyUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TagsJson") + .HasColumnType("text"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParentId") + .HasColumnType("uuid"); + + b.Property("RulesJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CompletedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExitCode") + .HasColumnType("integer"); + + b.Property("OutputSummary") + .HasColumnType("text"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("RunId") + .HasColumnType("uuid"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("text"); + + b.Property("StartedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("text"); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("text"); + + b.Property("IsSystem") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("text"); + + b.Property("PermissionsJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("FileBindingsJson") + .HasColumnType("text"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("text"); + + b.Property("Language") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParametersJson") + .HasColumnType("text"); + + b.Property("SecretBindingsJson") + .HasColumnType("text"); + + b.Property("SecretsVariableName") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ArgumentsJson") + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CronExpression") + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("LastResult") + .HasColumnType("text"); + + b.Property("LastRunId") + .HasColumnType("uuid"); + + b.Property("LastRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("NextRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OncePerDevice") + .HasColumnType("boolean"); + + b.Property("RunOnceUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("text"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("FiredUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("TriggerId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CloseReason") + .HasColumnType("text"); + + b.Property("ClosedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasColumnType("text"); + + b.Property("ExternalId") + .HasColumnType("text"); + + b.Property("LastLoginUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MustChangePassword") + .HasColumnType("boolean"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("Role") + .IsRequired() + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.Property("Username") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20261023021515_AddTriggerConcurrencyStamp.cs b/src/Backend/Data/Migrations/Postgres/20261023021515_AddTriggerConcurrencyStamp.cs new file mode 100644 index 0000000..0042a14 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20261023021515_AddTriggerConcurrencyStamp.cs @@ -0,0 +1,30 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + /// + public partial class AddTriggerConcurrencyStamp : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "ConcurrencyStamp", + table: "ScriptTriggers", + type: "uuid", + nullable: false, + defaultValue: new Guid("00000000-0000-0000-0000-000000000000")); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "ConcurrencyStamp", + table: "ScriptTriggers"); + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20261023031204_AddDeviceBootstrapToken.Designer.cs b/src/Backend/Data/Migrations/Postgres/20261023031204_AddDeviceBootstrapToken.Designer.cs new file mode 100644 index 0000000..4d33df9 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20261023031204_AddDeviceBootstrapToken.Designer.cs @@ -0,0 +1,749 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + [DbContext(typeof(PostgresAppDbContext))] + [Migration("20261023031204_AddDeviceBootstrapToken")] + partial class AddDeviceBootstrapToken + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("text"); + + b.Property("IsSecret") + .HasColumnType("boolean"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("text"); + + b.Property("Actor") + .HasColumnType("text"); + + b.Property("Category") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("Detail") + .HasColumnType("text"); + + b.Property("RemoteIp") + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MaxUses") + .HasColumnType("integer"); + + b.Property("Note") + .HasColumnType("text"); + + b.Property("Revoked") + .HasColumnType("boolean"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("Uses") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("AgentVersion") + .HasColumnType("text"); + + b.Property("BootstrapTokenId") + .HasColumnType("uuid"); + + b.Property("EnrolledUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentId") + .HasColumnType("uuid"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("text"); + + b.Property("IpAddressesJson") + .HasColumnType("text"); + + b.Property("IsOrphaned") + .HasColumnType("boolean"); + + b.Property("LastSeenUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Manufacturer") + .HasColumnType("text"); + + b.Property("Model") + .HasColumnType("text"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("text"); + + b.Property("OrphanedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OsCaption") + .HasColumnType("text"); + + b.Property("OsVersion") + .HasColumnType("text"); + + b.Property("PublicIp") + .HasColumnType("text"); + + b.Property("ReadyUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TagsJson") + .HasColumnType("text"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParentId") + .HasColumnType("uuid"); + + b.Property("RulesJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CompletedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExitCode") + .HasColumnType("integer"); + + b.Property("OutputSummary") + .HasColumnType("text"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("RunId") + .HasColumnType("uuid"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("text"); + + b.Property("StartedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("text"); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("text"); + + b.Property("IsSystem") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("text"); + + b.Property("PermissionsJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("FileBindingsJson") + .HasColumnType("text"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("text"); + + b.Property("Language") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParametersJson") + .HasColumnType("text"); + + b.Property("SecretBindingsJson") + .HasColumnType("text"); + + b.Property("SecretsVariableName") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ArgumentsJson") + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CronExpression") + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("LastResult") + .HasColumnType("text"); + + b.Property("LastRunId") + .HasColumnType("uuid"); + + b.Property("LastRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("NextRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OncePerDevice") + .HasColumnType("boolean"); + + b.Property("RunOnceUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("text"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("FiredUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("TriggerId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CloseReason") + .HasColumnType("text"); + + b.Property("ClosedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasColumnType("text"); + + b.Property("ExternalId") + .HasColumnType("text"); + + b.Property("LastLoginUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MustChangePassword") + .HasColumnType("boolean"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("Role") + .IsRequired() + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.Property("Username") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20261023031204_AddDeviceBootstrapToken.cs b/src/Backend/Data/Migrations/Postgres/20261023031204_AddDeviceBootstrapToken.cs new file mode 100644 index 0000000..a155466 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20261023031204_AddDeviceBootstrapToken.cs @@ -0,0 +1,29 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + /// + public partial class AddDeviceBootstrapToken : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "BootstrapTokenId", + table: "Devices", + type: "uuid", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "BootstrapTokenId", + table: "Devices"); + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20261023123325_AddRuns.Designer.cs b/src/Backend/Data/Migrations/Postgres/20261023123325_AddRuns.Designer.cs new file mode 100644 index 0000000..0317dc6 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20261023123325_AddRuns.Designer.cs @@ -0,0 +1,799 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + [DbContext(typeof(PostgresAppDbContext))] + [Migration("20261023123325_AddRuns")] + partial class AddRuns + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("text"); + + b.Property("IsSecret") + .HasColumnType("boolean"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("text"); + + b.Property("Actor") + .HasColumnType("text"); + + b.Property("Category") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("Detail") + .HasColumnType("text"); + + b.Property("RemoteIp") + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MaxUses") + .HasColumnType("integer"); + + b.Property("Note") + .HasColumnType("text"); + + b.Property("Revoked") + .HasColumnType("boolean"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("Uses") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("AgentVersion") + .HasColumnType("text"); + + b.Property("BootstrapTokenId") + .HasColumnType("uuid"); + + b.Property("EnrolledUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentId") + .HasColumnType("uuid"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("text"); + + b.Property("IpAddressesJson") + .HasColumnType("text"); + + b.Property("IsOrphaned") + .HasColumnType("boolean"); + + b.Property("LastSeenUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Manufacturer") + .HasColumnType("text"); + + b.Property("Model") + .HasColumnType("text"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("text"); + + b.Property("OrphanedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OsCaption") + .HasColumnType("text"); + + b.Property("OsVersion") + .HasColumnType("text"); + + b.Property("PublicIp") + .HasColumnType("text"); + + b.Property("ReadyUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TagsJson") + .HasColumnType("text"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParentId") + .HasColumnType("uuid"); + + b.Property("RulesJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CompletedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExitCode") + .HasColumnType("integer"); + + b.Property("OutputSummary") + .HasColumnType("text"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("RunId") + .HasColumnType("uuid"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("text"); + + b.Property("StartedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("RunId"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("text"); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("text"); + + b.Property("IsSystem") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("text"); + + b.Property("PermissionsJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RunEntity", b => + { + b.Property("RunId") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OnlineOnly") + .HasColumnType("boolean"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("ScriptName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("SkippedJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("TargetsLabel") + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("TriggerId") + .HasColumnType("uuid"); + + b.HasKey("RunId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId"); + + b.ToTable("Runs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("FileBindingsJson") + .HasColumnType("text"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("text"); + + b.Property("Language") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParametersJson") + .HasColumnType("text"); + + b.Property("SecretBindingsJson") + .HasColumnType("text"); + + b.Property("SecretsVariableName") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ArgumentsJson") + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CronExpression") + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("LastResult") + .HasColumnType("text"); + + b.Property("LastRunId") + .HasColumnType("uuid"); + + b.Property("LastRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("NextRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OncePerDevice") + .HasColumnType("boolean"); + + b.Property("RunOnceUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("text"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("FiredUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("TriggerId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CloseReason") + .HasColumnType("text"); + + b.Property("ClosedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasColumnType("text"); + + b.Property("ExternalId") + .HasColumnType("text"); + + b.Property("LastLoginUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MustChangePassword") + .HasColumnType("boolean"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("Role") + .IsRequired() + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.Property("Username") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20261023123325_AddRuns.cs b/src/Backend/Data/Migrations/Postgres/20261023123325_AddRuns.cs new file mode 100644 index 0000000..77fecc7 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20261023123325_AddRuns.cs @@ -0,0 +1,61 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + /// + public partial class AddRuns : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Runs", + columns: table => new + { + RunId = table.Column(type: "uuid", nullable: false), + ScriptId = table.Column(type: "uuid", nullable: false), + ScriptName = table.Column(type: "character varying(200)", maxLength: 200, nullable: false), + CreatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + RequestedBy = table.Column(type: "text", nullable: true), + Source = table.Column(type: "character varying(32)", maxLength: 32, nullable: false), + TriggerId = table.Column(type: "uuid", nullable: true), + TargetsLabel = table.Column(type: "character varying(400)", maxLength: 400, nullable: true), + OnlineOnly = table.Column(type: "boolean", nullable: false), + SkippedJson = table.Column(type: "text", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Runs", x => x.RunId); + }); + + migrationBuilder.CreateIndex( + name: "IX_Jobs_RunId", + table: "Jobs", + column: "RunId"); + + migrationBuilder.CreateIndex( + name: "IX_Runs_CreatedUtc", + table: "Runs", + column: "CreatedUtc"); + + migrationBuilder.CreateIndex( + name: "IX_Runs_ScriptId", + table: "Runs", + column: "ScriptId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Runs"); + + migrationBuilder.DropIndex( + name: "IX_Jobs_RunId", + table: "Jobs"); + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20261023131502_SignInMethods.Designer.cs b/src/Backend/Data/Migrations/Postgres/20261023131502_SignInMethods.Designer.cs new file mode 100644 index 0000000..6a91506 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20261023131502_SignInMethods.Designer.cs @@ -0,0 +1,1073 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + [DbContext(typeof(PostgresAppDbContext))] + [Migration("20261023131502_SignInMethods")] + partial class SignInMethods + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("text"); + + b.Property("Etag") + .HasColumnType("text"); + + b.Property("IsSecret") + .HasColumnType("boolean"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("text"); + + b.Property("Actor") + .HasColumnType("text"); + + b.Property("Category") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("Detail") + .HasColumnType("text"); + + b.Property("RemoteIp") + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MaxUses") + .HasColumnType("integer"); + + b.Property("Note") + .HasColumnType("text"); + + b.Property("Revoked") + .HasColumnType("boolean"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("Uses") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("AgentVersion") + .HasColumnType("text"); + + b.Property("BootstrapTokenId") + .HasColumnType("uuid"); + + b.Property("EnrolledUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentId") + .HasColumnType("uuid"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("text"); + + b.Property("IpAddressesJson") + .HasColumnType("text"); + + b.Property("IsOrphaned") + .HasColumnType("boolean"); + + b.Property("LastSeenUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Manufacturer") + .HasColumnType("text"); + + b.Property("Model") + .HasColumnType("text"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("text"); + + b.Property("OrphanedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OsCaption") + .HasColumnType("text"); + + b.Property("OsVersion") + .HasColumnType("text"); + + b.Property("PublicIp") + .HasColumnType("text"); + + b.Property("ReadyUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TagsJson") + .HasColumnType("text"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParentId") + .HasColumnType("uuid"); + + b.Property("RulesJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CompletedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExitCode") + .HasColumnType("integer"); + + b.Property("OutputSummary") + .HasColumnType("text"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("RunId") + .HasColumnType("uuid"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("text"); + + b.Property("StartedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("RunId"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("text"); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.LocalGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("LocalGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.LocalGroupMemberEntity", b => + { + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("GroupId", "UserId"); + + b.HasIndex("UserId"); + + b.ToTable("LocalGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleBindingEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("PrincipalName") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.HasIndex("PrincipalKind", "PrincipalId", "RoleId") + .IsUnique(); + + b.ToTable("RoleBindings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("text"); + + b.Property("IsSystem") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("text"); + + b.Property("PermissionsJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RunEntity", b => + { + b.Property("RunId") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OnlineOnly") + .HasColumnType("boolean"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("ScriptName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("SkippedJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("TargetsLabel") + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("TriggerId") + .HasColumnType("uuid"); + + b.HasKey("RunId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId"); + + b.ToTable("Runs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("FileBindingsJson") + .HasColumnType("text"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("text"); + + b.Property("Language") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParametersJson") + .HasColumnType("text"); + + b.Property("SecretBindingsJson") + .HasColumnType("text"); + + b.Property("SecretsVariableName") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ArgumentsJson") + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CronExpression") + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("LastResult") + .HasColumnType("text"); + + b.Property("LastRunId") + .HasColumnType("uuid"); + + b.Property("LastRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("NextRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OncePerDevice") + .HasColumnType("boolean"); + + b.Property("RunOnceUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("text"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("FiredUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("TriggerId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SessionEntity", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("AbsoluteExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ClientAddress") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CsrfHash") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("GroupsJson") + .HasColumnType("text"); + + b.Property("LastSeenUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("RevokedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("SecretHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("UserAgent") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("AbsoluteExpiresUtc"); + + b.HasIndex("UserId"); + + b.ToTable("Sessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CloseReason") + .HasColumnType("text"); + + b.Property("ClosedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SignInRequestEntity", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CodeVerifier") + .HasColumnType("text"); + + b.Property("CompletedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Detail") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("ExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Nonce") + .HasColumnType("text"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("ReturnUrl") + .HasColumnType("text"); + + b.Property("SettingsEtag") + .HasColumnType("text"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("StepUpSessionId") + .HasColumnType("text"); + + b.Property("TestSessionId") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresUtc"); + + b.HasIndex("TestSessionId"); + + b.ToTable("SignInRequests", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SignInThrottleEntity", b => + { + b.Property("Key") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("BlockedUntilUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Failures") + .HasColumnType("integer"); + + b.Property("FirstFailureUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("LastFailureUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.ToTable("SignInThrottles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.StepUpEntity", b => + { + b.Property("SessionId") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Method") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("VerifiedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("SessionId"); + + b.ToTable("StepUps", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DisplayName") + .HasColumnType("text"); + + b.Property("Email") + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("ExternalId") + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("IsBreakGlass") + .HasColumnType("boolean"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("LastSignInUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("LegacyRole") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("LegacyRoleId") + .HasColumnType("uuid"); + + b.Property("MustChangePassword") + .HasColumnType("boolean"); + + b.Property("PasswordChangedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("UserName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("WindowsGroupsJson") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Kind", "ExternalId"); + + b.HasIndex("Kind", "UserName") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.LocalGroupMemberEntity", b => + { + b.HasOne("Backend.Data.LocalGroupEntity", null) + .WithMany() + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Backend.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.RoleBindingEntity", b => + { + b.HasOne("Backend.Data.RoleEntity", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.SessionEntity", b => + { + b.HasOne("Backend.Data.UserEntity", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20261023131502_SignInMethods.cs b/src/Backend/Data/Migrations/Postgres/20261023131502_SignInMethods.cs new file mode 100644 index 0000000..be2af79 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20261023131502_SignInMethods.cs @@ -0,0 +1,346 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + /// + public partial class SignInMethods : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "OidcProviders"); + + migrationBuilder.DropIndex( + name: "IX_Users_Username", + table: "Users"); + + migrationBuilder.RenameColumn( + name: "Username", + table: "Users", + newName: "UserName"); + + migrationBuilder.AlterColumn( + name: "UserName", + table: "Users", + type: "character varying(256)", + maxLength: 256, + nullable: false, + oldClrType: typeof(string), + oldType: "text"); + + migrationBuilder.AlterColumn( + name: "ExternalId", + table: "Users", + type: "character varying(450)", + maxLength: 450, + nullable: true, + oldClrType: typeof(string), + oldType: "text", + oldNullable: true); + + migrationBuilder.AddColumn( + name: "Kind", + table: "Users", + type: "character varying(16)", + maxLength: 16, + nullable: false, + defaultValue: "local"); + + migrationBuilder.AddColumn( + name: "Description", + table: "Users", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "Email", + table: "Users", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "WindowsGroupsJson", + table: "Users", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "Enabled", + table: "Users", + type: "boolean", + nullable: false, + defaultValue: true); + + migrationBuilder.AddColumn( + name: "IsBreakGlass", + table: "Users", + type: "boolean", + nullable: false, + defaultValue: false); + + migrationBuilder.AddColumn( + name: "LegacyRole", + table: "Users", + type: "character varying(32)", + maxLength: 32, + nullable: true); + + migrationBuilder.AddColumn( + name: "LegacyRoleId", + table: "Users", + type: "uuid", + nullable: true); + + migrationBuilder.AddColumn( + name: "LastSignInUtc", + table: "Users", + type: "timestamp with time zone", + nullable: true); + + migrationBuilder.AddColumn( + name: "PasswordChangedUtc", + table: "Users", + type: "timestamp with time zone", + nullable: true); + + migrationBuilder.AddColumn( + name: "UpdatedUtc", + table: "Users", + type: "timestamp with time zone", + nullable: false, + defaultValue: new DateTimeOffset(new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 0, 0, 0, 0))); + + // Carry the old columns over before they go: kind of account, the role (for the upgrade to groups), last sign-in. + migrationBuilder.Sql( + "UPDATE \"Users\" SET \"Kind\" = \"AuthProvider\", \"LegacyRole\" = \"Role\", \"LegacyRoleId\" = \"RoleId\", " + + "\"LastSignInUtc\" = \"LastLoginUtc\", \"UpdatedUtc\" = \"CreatedUtc\""); + + migrationBuilder.DropColumn( + name: "AuthProvider", + table: "Users"); + + migrationBuilder.DropColumn( + name: "Role", + table: "Users"); + + migrationBuilder.DropColumn( + name: "RoleId", + table: "Users"); + + migrationBuilder.DropColumn( + name: "LastLoginUtc", + table: "Users"); + + migrationBuilder.AddColumn( + name: "Etag", + table: "AppSettings", + type: "text", + nullable: true); + + migrationBuilder.CreateTable( + name: "LocalGroups", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Name = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + Description = table.Column(type: "text", nullable: true), + CreatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedUtc = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_LocalGroups", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "RoleBindings", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + RoleId = table.Column(type: "uuid", nullable: false), + PrincipalKind = table.Column(type: "character varying(32)", maxLength: 32, nullable: false), + PrincipalId = table.Column(type: "character varying(450)", maxLength: 450, nullable: false), + PrincipalName = table.Column(type: "text", nullable: true), + CreatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + CreatedBy = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_RoleBindings", x => x.Id); + table.ForeignKey( + name: "FK_RoleBindings_Roles_RoleId", + column: x => x.RoleId, + principalTable: "Roles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "Sessions", + columns: table => new + { + Id = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + UserId = table.Column(type: "uuid", nullable: false), + SecretHash = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + CsrfHash = table.Column(type: "character varying(128)", maxLength: 128, nullable: true), + Provider = table.Column(type: "character varying(16)", maxLength: 16, nullable: false), + GroupsJson = table.Column(type: "text", nullable: true), + CreatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + LastSeenUtc = table.Column(type: "timestamp with time zone", nullable: false), + ExpiresUtc = table.Column(type: "timestamp with time zone", nullable: false), + AbsoluteExpiresUtc = table.Column(type: "timestamp with time zone", nullable: false), + RevokedUtc = table.Column(type: "timestamp with time zone", nullable: true), + ClientAddress = table.Column(type: "text", nullable: true), + UserAgent = table.Column(type: "character varying(512)", maxLength: 512, nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Sessions", x => x.Id); + table.ForeignKey( + name: "FK_Sessions_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "SignInRequests", + columns: table => new + { + Id = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + Provider = table.Column(type: "character varying(16)", maxLength: 16, nullable: false), + Status = table.Column(type: "character varying(16)", maxLength: 16, nullable: false), + Nonce = table.Column(type: "text", nullable: true), + CodeVerifier = table.Column(type: "text", nullable: true), + ReturnUrl = table.Column(type: "text", nullable: true), + TestSessionId = table.Column(type: "text", nullable: true), + StepUpSessionId = table.Column(type: "text", nullable: true), + SettingsEtag = table.Column(type: "text", nullable: true), + Detail = table.Column(type: "character varying(2000)", maxLength: 2000, nullable: true), + CreatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + ExpiresUtc = table.Column(type: "timestamp with time zone", nullable: false), + CompletedUtc = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_SignInRequests", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "SignInThrottles", + columns: table => new + { + Key = table.Column(type: "character varying(300)", maxLength: 300, nullable: false), + Failures = table.Column(type: "integer", nullable: false), + FirstFailureUtc = table.Column(type: "timestamp with time zone", nullable: false), + LastFailureUtc = table.Column(type: "timestamp with time zone", nullable: false), + BlockedUntilUtc = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_SignInThrottles", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "StepUps", + columns: table => new + { + SessionId = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + Method = table.Column(type: "character varying(16)", maxLength: 16, nullable: false), + VerifiedUtc = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_StepUps", x => x.SessionId); + }); + + migrationBuilder.CreateTable( + name: "LocalGroupMembers", + columns: table => new + { + GroupId = table.Column(type: "uuid", nullable: false), + UserId = table.Column(type: "uuid", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_LocalGroupMembers", x => new { x.GroupId, x.UserId }); + table.ForeignKey( + name: "FK_LocalGroupMembers_LocalGroups_GroupId", + column: x => x.GroupId, + principalTable: "LocalGroups", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_LocalGroupMembers_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Users_Kind_ExternalId", + table: "Users", + columns: new[] { "Kind", "ExternalId" }); + + migrationBuilder.CreateIndex( + name: "IX_Users_Kind_UserName", + table: "Users", + columns: new[] { "Kind", "UserName" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_LocalGroupMembers_UserId", + table: "LocalGroupMembers", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_LocalGroups_Name", + table: "LocalGroups", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_RoleBindings_PrincipalKind_PrincipalId_RoleId", + table: "RoleBindings", + columns: new[] { "PrincipalKind", "PrincipalId", "RoleId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_RoleBindings_RoleId", + table: "RoleBindings", + column: "RoleId"); + + migrationBuilder.CreateIndex( + name: "IX_Sessions_AbsoluteExpiresUtc", + table: "Sessions", + column: "AbsoluteExpiresUtc"); + + migrationBuilder.CreateIndex( + name: "IX_Sessions_UserId", + table: "Sessions", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_SignInRequests_ExpiresUtc", + table: "SignInRequests", + column: "ExpiresUtc"); + + migrationBuilder.CreateIndex( + name: "IX_SignInRequests_TestSessionId", + table: "SignInRequests", + column: "TestSessionId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + throw new NotSupportedException("Sign-in methods and role bindings cannot be rolled back to per-user roles; restore a backup instead."); + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20261023212422_AgentUpgrades.Designer.cs b/src/Backend/Data/Migrations/Postgres/20261023212422_AgentUpgrades.Designer.cs new file mode 100644 index 0000000..3031649 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20261023212422_AgentUpgrades.Designer.cs @@ -0,0 +1,1214 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + [DbContext(typeof(PostgresAppDbContext))] + [Migration("20261023212422_AgentUpgrades")] + partial class AgentUpgrades + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Backend.Data.AgentPackageEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ImportedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("S3Key") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("SizeBytes") + .HasColumnType("bigint"); + + b.Property("StoragePath") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Id"); + + b.HasIndex("Sha256"); + + b.HasIndex("Version", "PackageType") + .IsUnique(); + + b.ToTable("AgentPackages", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AgentUpgradeEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Detail") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("FinishedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("FromVersion") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("LastEventUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("LastLogJson") + .HasColumnType("text"); + + b.Property("PackageId") + .HasColumnType("uuid"); + + b.Property("PackageType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Reason") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("RequestedBy") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("SentUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Sha256") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("State") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("TargetVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Id"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("State"); + + b.HasIndex("ClientId", "State"); + + b.ToTable("AgentUpgrades", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("text"); + + b.Property("Etag") + .HasColumnType("text"); + + b.Property("IsSecret") + .HasColumnType("boolean"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("text"); + + b.Property("Actor") + .HasColumnType("text"); + + b.Property("Category") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("Detail") + .HasColumnType("text"); + + b.Property("RemoteIp") + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MaxUses") + .HasColumnType("integer"); + + b.Property("Note") + .HasColumnType("text"); + + b.Property("Revoked") + .HasColumnType("boolean"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("Uses") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("AgentRuntime") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("AgentVersion") + .HasColumnType("text"); + + b.Property("BootstrapTokenId") + .HasColumnType("uuid"); + + b.Property("EnrolledUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentId") + .HasColumnType("uuid"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("text"); + + b.Property("IpAddressesJson") + .HasColumnType("text"); + + b.Property("IsOrphaned") + .HasColumnType("boolean"); + + b.Property("LastSeenUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Manufacturer") + .HasColumnType("text"); + + b.Property("Model") + .HasColumnType("text"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("text"); + + b.Property("OrphanedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OsCaption") + .HasColumnType("text"); + + b.Property("OsVersion") + .HasColumnType("text"); + + b.Property("PublicIp") + .HasColumnType("text"); + + b.Property("ReadyUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TagsJson") + .HasColumnType("text"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParentId") + .HasColumnType("uuid"); + + b.Property("RulesJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CompletedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExitCode") + .HasColumnType("integer"); + + b.Property("OutputSummary") + .HasColumnType("text"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("RunId") + .HasColumnType("uuid"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("text"); + + b.Property("StartedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("RunId"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("text"); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.LocalGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("LocalGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.LocalGroupMemberEntity", b => + { + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("GroupId", "UserId"); + + b.HasIndex("UserId"); + + b.ToTable("LocalGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleBindingEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("PrincipalName") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.HasIndex("PrincipalKind", "PrincipalId", "RoleId") + .IsUnique(); + + b.ToTable("RoleBindings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("text"); + + b.Property("IsSystem") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("text"); + + b.Property("PermissionsJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RunEntity", b => + { + b.Property("RunId") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OnlineOnly") + .HasColumnType("boolean"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("ScriptName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("SkippedJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("TargetsLabel") + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("TriggerId") + .HasColumnType("uuid"); + + b.HasKey("RunId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId"); + + b.ToTable("Runs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("FileBindingsJson") + .HasColumnType("text"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("text"); + + b.Property("Language") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParametersJson") + .HasColumnType("text"); + + b.Property("SecretBindingsJson") + .HasColumnType("text"); + + b.Property("SecretsVariableName") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ArgumentsJson") + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CronExpression") + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("LastResult") + .HasColumnType("text"); + + b.Property("LastRunId") + .HasColumnType("uuid"); + + b.Property("LastRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("NextRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OncePerDevice") + .HasColumnType("boolean"); + + b.Property("RunOnceUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("text"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("FiredUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("TriggerId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SessionEntity", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("AbsoluteExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ClientAddress") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CsrfHash") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("GroupsJson") + .HasColumnType("text"); + + b.Property("LastSeenUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("RevokedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("SecretHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("UserAgent") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("AbsoluteExpiresUtc"); + + b.HasIndex("UserId"); + + b.ToTable("Sessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CloseReason") + .HasColumnType("text"); + + b.Property("ClosedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SignInRequestEntity", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CodeVerifier") + .HasColumnType("text"); + + b.Property("CompletedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Detail") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("ExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Nonce") + .HasColumnType("text"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("ReturnUrl") + .HasColumnType("text"); + + b.Property("SettingsEtag") + .HasColumnType("text"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("StepUpSessionId") + .HasColumnType("text"); + + b.Property("TestSessionId") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresUtc"); + + b.HasIndex("TestSessionId"); + + b.ToTable("SignInRequests", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SignInThrottleEntity", b => + { + b.Property("Key") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("BlockedUntilUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Failures") + .HasColumnType("integer"); + + b.Property("FirstFailureUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("LastFailureUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.ToTable("SignInThrottles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.StepUpEntity", b => + { + b.Property("SessionId") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Method") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("VerifiedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("SessionId"); + + b.ToTable("StepUps", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DisplayName") + .HasColumnType("text"); + + b.Property("Email") + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("ExternalId") + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("IsBreakGlass") + .HasColumnType("boolean"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("LastSignInUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("LegacyRole") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("LegacyRoleId") + .HasColumnType("uuid"); + + b.Property("MustChangePassword") + .HasColumnType("boolean"); + + b.Property("PasswordChangedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("UserName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("WindowsGroupsJson") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Kind", "ExternalId"); + + b.HasIndex("Kind", "UserName") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.LocalGroupMemberEntity", b => + { + b.HasOne("Backend.Data.LocalGroupEntity", null) + .WithMany() + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Backend.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.RoleBindingEntity", b => + { + b.HasOne("Backend.Data.RoleEntity", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.SessionEntity", b => + { + b.HasOne("Backend.Data.UserEntity", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20261023212422_AgentUpgrades.cs b/src/Backend/Data/Migrations/Postgres/20261023212422_AgentUpgrades.cs new file mode 100644 index 0000000..a12c182 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20261023212422_AgentUpgrades.cs @@ -0,0 +1,110 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + /// + public partial class AgentUpgrades : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "AgentRuntime", + table: "Devices", + type: "character varying(32)", + maxLength: 32, + nullable: true); + + migrationBuilder.CreateTable( + name: "AgentPackages", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Version = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + PackageType = table.Column(type: "character varying(32)", maxLength: 32, nullable: false), + FileName = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + Sha256 = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + SizeBytes = table.Column(type: "bigint", nullable: false), + StoragePath = table.Column(type: "character varying(512)", maxLength: 512, nullable: false), + S3Key = table.Column(type: "character varying(512)", maxLength: 512, nullable: true), + ImportedUtc = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AgentPackages", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AgentUpgrades", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + ClientId = table.Column(type: "text", nullable: false), + FromVersion = table.Column(type: "character varying(64)", maxLength: 64, nullable: true), + TargetVersion = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + PackageType = table.Column(type: "character varying(32)", maxLength: 32, nullable: false), + PackageId = table.Column(type: "uuid", nullable: true), + Sha256 = table.Column(type: "character varying(64)", maxLength: 64, nullable: true), + Source = table.Column(type: "character varying(16)", maxLength: 16, nullable: false), + State = table.Column(type: "character varying(16)", maxLength: 16, nullable: false), + Reason = table.Column(type: "character varying(32)", maxLength: 32, nullable: true), + Detail = table.Column(type: "character varying(2000)", maxLength: 2000, nullable: true), + LastLogJson = table.Column(type: "text", nullable: true), + Attempts = table.Column(type: "integer", nullable: false), + RequestedBy = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + CreatedUtc = table.Column(type: "timestamp with time zone", nullable: false), + SentUtc = table.Column(type: "timestamp with time zone", nullable: true), + LastEventUtc = table.Column(type: "timestamp with time zone", nullable: true), + FinishedUtc = table.Column(type: "timestamp with time zone", nullable: true), + ConcurrencyStamp = table.Column(type: "uuid", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AgentUpgrades", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_AgentPackages_Sha256", + table: "AgentPackages", + column: "Sha256"); + + migrationBuilder.CreateIndex( + name: "IX_AgentPackages_Version_PackageType", + table: "AgentPackages", + columns: new[] { "Version", "PackageType" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_AgentUpgrades_ClientId_State", + table: "AgentUpgrades", + columns: new[] { "ClientId", "State" }); + + migrationBuilder.CreateIndex( + name: "IX_AgentUpgrades_CreatedUtc", + table: "AgentUpgrades", + column: "CreatedUtc"); + + migrationBuilder.CreateIndex( + name: "IX_AgentUpgrades_State", + table: "AgentUpgrades", + column: "State"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AgentPackages"); + + migrationBuilder.DropTable( + name: "AgentUpgrades"); + + migrationBuilder.DropColumn( + name: "AgentRuntime", + table: "Devices"); + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs b/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs index 624cffa..9729279 100644 --- a/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs +++ b/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs @@ -22,11 +22,151 @@ namespace Backend.Data.Migrations.Postgres NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + modelBuilder.Entity("Backend.Data.AgentPackageEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ImportedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("S3Key") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("SizeBytes") + .HasColumnType("bigint"); + + b.Property("StoragePath") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Id"); + + b.HasIndex("Sha256"); + + b.HasIndex("Version", "PackageType") + .IsUnique(); + + b.ToTable("AgentPackages", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AgentUpgradeEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Detail") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("FinishedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("FromVersion") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("LastEventUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("LastLogJson") + .HasColumnType("text"); + + b.Property("PackageId") + .HasColumnType("uuid"); + + b.Property("PackageType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Reason") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("RequestedBy") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("SentUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Sha256") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("State") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("TargetVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Id"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("State"); + + b.HasIndex("ClientId", "State"); + + b.ToTable("AgentUpgrades", (string)null); + }); + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => { b.Property("Key") .HasColumnType("text"); + b.Property("Etag") + .HasColumnType("text"); + b.Property("IsSecret") .HasColumnType("boolean"); @@ -126,9 +266,16 @@ namespace Backend.Data.Migrations.Postgres b.Property("ClientId") .HasColumnType("text"); + b.Property("AgentRuntime") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + b.Property("AgentVersion") .HasColumnType("text"); + b.Property("BootstrapTokenId") + .HasColumnType("uuid"); + b.Property("EnrolledUtc") .HasColumnType("timestamp with time zone"); @@ -203,6 +350,9 @@ namespace Backend.Data.Migrations.Postgres .IsRequired() .HasColumnType("text"); + b.Property("ParentId") + .HasColumnType("uuid"); + b.Property("RulesJson") .HasColumnType("text"); @@ -344,6 +494,8 @@ namespace Backend.Data.Migrations.Postgres b.HasIndex("CreatedUtc"); + b.HasIndex("RunId"); + b.HasIndex("ScriptId", "RunId"); b.ToTable("Jobs", (string)null); @@ -382,30 +534,85 @@ namespace Backend.Data.Migrations.Postgres b.ToTable("JobOutput", (string)null); }); - modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + modelBuilder.Entity("Backend.Data.LocalGroupEntity", b => { b.Property("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); - b.Property("Authority") - .IsRequired() - .HasColumnType("text"); + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); - b.Property("ClientId") - .IsRequired() + b.Property("Description") .HasColumnType("text"); - b.Property("Enabled") - .HasColumnType("boolean"); - b.Property("Name") .IsRequired() - .HasColumnType("text"); + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); b.HasKey("Id"); - b.ToTable("OidcProviders", (string)null); + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("LocalGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.LocalGroupMemberEntity", b => + { + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("GroupId", "UserId"); + + b.HasIndex("UserId"); + + b.ToTable("LocalGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleBindingEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("PrincipalKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("PrincipalName") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.HasIndex("PrincipalKind", "PrincipalId", "RoleId") + .IsUnique(); + + b.ToTable("RoleBindings", (string)null); }); modelBuilder.Entity("Backend.Data.RoleEntity", b => @@ -450,6 +657,54 @@ namespace Backend.Data.Migrations.Postgres b.ToTable("Roles", (string)null); }); + modelBuilder.Entity("Backend.Data.RunEntity", b => + { + b.Property("RunId") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OnlineOnly") + .HasColumnType("boolean"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("ScriptName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("SkippedJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("TargetsLabel") + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("TriggerId") + .HasColumnType("uuid"); + + b.HasKey("RunId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId"); + + b.ToTable("Runs", (string)null); + }); + modelBuilder.Entity("Backend.Data.ScriptEntity", b => { b.Property("Id") @@ -517,6 +772,10 @@ namespace Backend.Data.Migrations.Postgres b.Property("ClientId") .HasColumnType("text"); + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("uuid"); + b.Property("CreatedBy") .HasColumnType("text"); @@ -535,9 +794,15 @@ namespace Backend.Data.Migrations.Postgres b.Property("LastResult") .HasColumnType("text"); + b.Property("LastRunId") + .HasColumnType("uuid"); + b.Property("LastRunUtc") .HasColumnType("timestamp with time zone"); + b.Property("Name") + .HasColumnType("text"); + b.Property("NextRunUtc") .HasColumnType("timestamp with time zone"); @@ -631,6 +896,63 @@ namespace Backend.Data.Migrations.Postgres b.ToTable("SecretsProviders", (string)null); }); + modelBuilder.Entity("Backend.Data.SessionEntity", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("AbsoluteExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ClientAddress") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CsrfHash") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("GroupsJson") + .HasColumnType("text"); + + b.Property("LastSeenUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("RevokedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("SecretHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("UserAgent") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("AbsoluteExpiresUtc"); + + b.HasIndex("UserId"); + + b.ToTable("Sessions", (string)null); + }); + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => { b.Property("Id") @@ -664,48 +986,172 @@ namespace Backend.Data.Migrations.Postgres b.ToTable("ShellSessions", (string)null); }); + modelBuilder.Entity("Backend.Data.SignInRequestEntity", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CodeVerifier") + .HasColumnType("text"); + + b.Property("CompletedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Detail") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("ExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Nonce") + .HasColumnType("text"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("ReturnUrl") + .HasColumnType("text"); + + b.Property("SettingsEtag") + .HasColumnType("text"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("StepUpSessionId") + .HasColumnType("text"); + + b.Property("TestSessionId") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresUtc"); + + b.HasIndex("TestSessionId"); + + b.ToTable("SignInRequests", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SignInThrottleEntity", b => + { + b.Property("Key") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("BlockedUntilUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Failures") + .HasColumnType("integer"); + + b.Property("FirstFailureUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("LastFailureUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.ToTable("SignInThrottles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.StepUpEntity", b => + { + b.Property("SessionId") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Method") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("VerifiedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("SessionId"); + + b.ToTable("StepUps", (string)null); + }); + modelBuilder.Entity("Backend.Data.UserEntity", b => { b.Property("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); - b.Property("AuthProvider") - .IsRequired() - .HasColumnType("text"); - b.Property("CreatedUtc") .HasColumnType("timestamp with time zone"); + b.Property("Description") + .HasColumnType("text"); + b.Property("DisplayName") .HasColumnType("text"); - b.Property("ExternalId") + b.Property("Email") .HasColumnType("text"); - b.Property("LastLoginUtc") + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("ExternalId") + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("IsBreakGlass") + .HasColumnType("boolean"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("LastSignInUtc") .HasColumnType("timestamp with time zone"); + b.Property("LegacyRole") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("LegacyRoleId") + .HasColumnType("uuid"); + b.Property("MustChangePassword") .HasColumnType("boolean"); + b.Property("PasswordChangedUtc") + .HasColumnType("timestamp with time zone"); + b.Property("PasswordHash") .HasColumnType("text"); - b.Property("Role") - .IsRequired() - .HasColumnType("text"); + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); - b.Property("RoleId") - .HasColumnType("uuid"); - - b.Property("Username") + b.Property("UserName") .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("WindowsGroupsJson") .HasColumnType("text"); b.HasKey("Id"); - b.HasIndex("Username") + b.HasIndex("Kind", "ExternalId"); + + b.HasIndex("Kind", "UserName") .IsUnique(); b.ToTable("Users", (string)null); @@ -720,6 +1166,41 @@ namespace Backend.Data.Migrations.Postgres .IsRequired(); }); + modelBuilder.Entity("Backend.Data.LocalGroupMemberEntity", b => + { + b.HasOne("Backend.Data.LocalGroupEntity", null) + .WithMany() + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Backend.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.RoleBindingEntity", b => + { + b.HasOne("Backend.Data.RoleEntity", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.SessionEntity", b => + { + b.HasOne("Backend.Data.UserEntity", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + modelBuilder.Entity("Backend.Data.DeviceEntity", b => { b.Navigation("Inventory"); diff --git a/src/Backend/Data/Migrations/SqlServer/20261023003341_AddTriggerNameAndLastRun.Designer.cs b/src/Backend/Data/Migrations/SqlServer/20261023003341_AddTriggerNameAndLastRun.Designer.cs new file mode 100644 index 0000000..f422f99 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20261023003341_AddTriggerNameAndLastRun.Designer.cs @@ -0,0 +1,739 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + [DbContext(typeof(SqlServerAppDbContext))] + [Migration("20261023003341_AddTriggerNameAndLastRun")] + partial class AddTriggerNameAndLastRun + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("nvarchar(450)"); + + b.Property("IsSecret") + .HasColumnType("bit"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Actor") + .HasColumnType("nvarchar(max)"); + + b.Property("Category") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("Detail") + .HasColumnType("nvarchar(max)"); + + b.Property("RemoteIp") + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MaxUses") + .HasColumnType("int"); + + b.Property("Note") + .HasColumnType("nvarchar(max)"); + + b.Property("Revoked") + .HasColumnType("bit"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Uses") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("AgentVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("EnrolledUtc") + .HasColumnType("datetimeoffset"); + + b.Property("EnrollmentId") + .HasColumnType("uniqueidentifier"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("IpAddressesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsOrphaned") + .HasColumnType("bit"); + + b.Property("LastSeenUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Manufacturer") + .HasColumnType("nvarchar(max)"); + + b.Property("Model") + .HasColumnType("nvarchar(max)"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OrphanedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OsCaption") + .HasColumnType("nvarchar(max)"); + + b.Property("OsVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("PublicIp") + .HasColumnType("nvarchar(max)"); + + b.Property("ReadyUtc") + .HasColumnType("datetimeoffset"); + + b.Property("TagsJson") + .HasColumnType("nvarchar(max)"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("RulesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CompletedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExitCode") + .HasColumnType("int"); + + b.Property("OutputSummary") + .HasColumnType("nvarchar(max)"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("RunId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("StartedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Text") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsSystem") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("PermissionsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("FileBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("Language") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParametersJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretsVariableName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ArgumentsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CronExpression") + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("LastResult") + .HasColumnType("nvarchar(max)"); + + b.Property("LastRunId") + .HasColumnType("uniqueidentifier"); + + b.Property("LastRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Name") + .HasColumnType("nvarchar(max)"); + + b.Property("NextRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OncePerDevice") + .HasColumnType("bit"); + + b.Property("RunOnceUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("FiredUtc") + .HasColumnType("datetimeoffset"); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CloseReason") + .HasColumnType("nvarchar(max)"); + + b.Property("ClosedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("DisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("ExternalId") + .HasColumnType("nvarchar(max)"); + + b.Property("LastLoginUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MustChangePassword") + .HasColumnType("bit"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("Role") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("uniqueidentifier"); + + b.Property("Username") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20261023003341_AddTriggerNameAndLastRun.cs b/src/Backend/Data/Migrations/SqlServer/20261023003341_AddTriggerNameAndLastRun.cs new file mode 100644 index 0000000..c9a0ed0 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20261023003341_AddTriggerNameAndLastRun.cs @@ -0,0 +1,39 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + /// + public partial class AddTriggerNameAndLastRun : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "LastRunId", + table: "ScriptTriggers", + type: "uniqueidentifier", + nullable: true); + + migrationBuilder.AddColumn( + name: "Name", + table: "ScriptTriggers", + type: "nvarchar(max)", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "LastRunId", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "Name", + table: "ScriptTriggers"); + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20261023004406_AddGroupNesting.Designer.cs b/src/Backend/Data/Migrations/SqlServer/20261023004406_AddGroupNesting.Designer.cs new file mode 100644 index 0000000..78c1fc3 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20261023004406_AddGroupNesting.Designer.cs @@ -0,0 +1,742 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + [DbContext(typeof(SqlServerAppDbContext))] + [Migration("20261023004406_AddGroupNesting")] + partial class AddGroupNesting + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("nvarchar(450)"); + + b.Property("IsSecret") + .HasColumnType("bit"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Actor") + .HasColumnType("nvarchar(max)"); + + b.Property("Category") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("Detail") + .HasColumnType("nvarchar(max)"); + + b.Property("RemoteIp") + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MaxUses") + .HasColumnType("int"); + + b.Property("Note") + .HasColumnType("nvarchar(max)"); + + b.Property("Revoked") + .HasColumnType("bit"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Uses") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("AgentVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("EnrolledUtc") + .HasColumnType("datetimeoffset"); + + b.Property("EnrollmentId") + .HasColumnType("uniqueidentifier"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("IpAddressesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsOrphaned") + .HasColumnType("bit"); + + b.Property("LastSeenUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Manufacturer") + .HasColumnType("nvarchar(max)"); + + b.Property("Model") + .HasColumnType("nvarchar(max)"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OrphanedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OsCaption") + .HasColumnType("nvarchar(max)"); + + b.Property("OsVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("PublicIp") + .HasColumnType("nvarchar(max)"); + + b.Property("ReadyUtc") + .HasColumnType("datetimeoffset"); + + b.Property("TagsJson") + .HasColumnType("nvarchar(max)"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParentId") + .HasColumnType("uniqueidentifier"); + + b.Property("RulesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CompletedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExitCode") + .HasColumnType("int"); + + b.Property("OutputSummary") + .HasColumnType("nvarchar(max)"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("RunId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("StartedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Text") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsSystem") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("PermissionsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("FileBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("Language") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParametersJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretsVariableName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ArgumentsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CronExpression") + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("LastResult") + .HasColumnType("nvarchar(max)"); + + b.Property("LastRunId") + .HasColumnType("uniqueidentifier"); + + b.Property("LastRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Name") + .HasColumnType("nvarchar(max)"); + + b.Property("NextRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OncePerDevice") + .HasColumnType("bit"); + + b.Property("RunOnceUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("FiredUtc") + .HasColumnType("datetimeoffset"); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CloseReason") + .HasColumnType("nvarchar(max)"); + + b.Property("ClosedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("DisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("ExternalId") + .HasColumnType("nvarchar(max)"); + + b.Property("LastLoginUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MustChangePassword") + .HasColumnType("bit"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("Role") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("uniqueidentifier"); + + b.Property("Username") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20261023004406_AddGroupNesting.cs b/src/Backend/Data/Migrations/SqlServer/20261023004406_AddGroupNesting.cs new file mode 100644 index 0000000..9af70d8 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20261023004406_AddGroupNesting.cs @@ -0,0 +1,29 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + /// + public partial class AddGroupNesting : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "ParentId", + table: "DeviceGroups", + type: "uniqueidentifier", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "ParentId", + table: "DeviceGroups"); + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20261023021527_AddTriggerConcurrencyStamp.Designer.cs b/src/Backend/Data/Migrations/SqlServer/20261023021527_AddTriggerConcurrencyStamp.Designer.cs new file mode 100644 index 0000000..b1a4c2e --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20261023021527_AddTriggerConcurrencyStamp.Designer.cs @@ -0,0 +1,746 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + [DbContext(typeof(SqlServerAppDbContext))] + [Migration("20261023021527_AddTriggerConcurrencyStamp")] + partial class AddTriggerConcurrencyStamp + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("nvarchar(450)"); + + b.Property("IsSecret") + .HasColumnType("bit"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Actor") + .HasColumnType("nvarchar(max)"); + + b.Property("Category") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("Detail") + .HasColumnType("nvarchar(max)"); + + b.Property("RemoteIp") + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MaxUses") + .HasColumnType("int"); + + b.Property("Note") + .HasColumnType("nvarchar(max)"); + + b.Property("Revoked") + .HasColumnType("bit"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Uses") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("AgentVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("EnrolledUtc") + .HasColumnType("datetimeoffset"); + + b.Property("EnrollmentId") + .HasColumnType("uniqueidentifier"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("IpAddressesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsOrphaned") + .HasColumnType("bit"); + + b.Property("LastSeenUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Manufacturer") + .HasColumnType("nvarchar(max)"); + + b.Property("Model") + .HasColumnType("nvarchar(max)"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OrphanedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OsCaption") + .HasColumnType("nvarchar(max)"); + + b.Property("OsVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("PublicIp") + .HasColumnType("nvarchar(max)"); + + b.Property("ReadyUtc") + .HasColumnType("datetimeoffset"); + + b.Property("TagsJson") + .HasColumnType("nvarchar(max)"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParentId") + .HasColumnType("uniqueidentifier"); + + b.Property("RulesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CompletedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExitCode") + .HasColumnType("int"); + + b.Property("OutputSummary") + .HasColumnType("nvarchar(max)"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("RunId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("StartedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Text") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsSystem") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("PermissionsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("FileBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("Language") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParametersJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretsVariableName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ArgumentsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CronExpression") + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("LastResult") + .HasColumnType("nvarchar(max)"); + + b.Property("LastRunId") + .HasColumnType("uniqueidentifier"); + + b.Property("LastRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Name") + .HasColumnType("nvarchar(max)"); + + b.Property("NextRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OncePerDevice") + .HasColumnType("bit"); + + b.Property("RunOnceUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("FiredUtc") + .HasColumnType("datetimeoffset"); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CloseReason") + .HasColumnType("nvarchar(max)"); + + b.Property("ClosedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("DisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("ExternalId") + .HasColumnType("nvarchar(max)"); + + b.Property("LastLoginUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MustChangePassword") + .HasColumnType("bit"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("Role") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("uniqueidentifier"); + + b.Property("Username") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20261023021527_AddTriggerConcurrencyStamp.cs b/src/Backend/Data/Migrations/SqlServer/20261023021527_AddTriggerConcurrencyStamp.cs new file mode 100644 index 0000000..79b70ab --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20261023021527_AddTriggerConcurrencyStamp.cs @@ -0,0 +1,30 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + /// + public partial class AddTriggerConcurrencyStamp : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "ConcurrencyStamp", + table: "ScriptTriggers", + type: "uniqueidentifier", + nullable: false, + defaultValue: new Guid("00000000-0000-0000-0000-000000000000")); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "ConcurrencyStamp", + table: "ScriptTriggers"); + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20261023031219_AddDeviceBootstrapToken.Designer.cs b/src/Backend/Data/Migrations/SqlServer/20261023031219_AddDeviceBootstrapToken.Designer.cs new file mode 100644 index 0000000..65e1c77 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20261023031219_AddDeviceBootstrapToken.Designer.cs @@ -0,0 +1,749 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + [DbContext(typeof(SqlServerAppDbContext))] + [Migration("20261023031219_AddDeviceBootstrapToken")] + partial class AddDeviceBootstrapToken + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("nvarchar(450)"); + + b.Property("IsSecret") + .HasColumnType("bit"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Actor") + .HasColumnType("nvarchar(max)"); + + b.Property("Category") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("Detail") + .HasColumnType("nvarchar(max)"); + + b.Property("RemoteIp") + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MaxUses") + .HasColumnType("int"); + + b.Property("Note") + .HasColumnType("nvarchar(max)"); + + b.Property("Revoked") + .HasColumnType("bit"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Uses") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("AgentVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("BootstrapTokenId") + .HasColumnType("uniqueidentifier"); + + b.Property("EnrolledUtc") + .HasColumnType("datetimeoffset"); + + b.Property("EnrollmentId") + .HasColumnType("uniqueidentifier"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("IpAddressesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsOrphaned") + .HasColumnType("bit"); + + b.Property("LastSeenUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Manufacturer") + .HasColumnType("nvarchar(max)"); + + b.Property("Model") + .HasColumnType("nvarchar(max)"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OrphanedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OsCaption") + .HasColumnType("nvarchar(max)"); + + b.Property("OsVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("PublicIp") + .HasColumnType("nvarchar(max)"); + + b.Property("ReadyUtc") + .HasColumnType("datetimeoffset"); + + b.Property("TagsJson") + .HasColumnType("nvarchar(max)"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParentId") + .HasColumnType("uniqueidentifier"); + + b.Property("RulesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CompletedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExitCode") + .HasColumnType("int"); + + b.Property("OutputSummary") + .HasColumnType("nvarchar(max)"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("RunId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("StartedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Text") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsSystem") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("PermissionsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("FileBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("Language") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParametersJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretsVariableName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ArgumentsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CronExpression") + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("LastResult") + .HasColumnType("nvarchar(max)"); + + b.Property("LastRunId") + .HasColumnType("uniqueidentifier"); + + b.Property("LastRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Name") + .HasColumnType("nvarchar(max)"); + + b.Property("NextRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OncePerDevice") + .HasColumnType("bit"); + + b.Property("RunOnceUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("FiredUtc") + .HasColumnType("datetimeoffset"); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CloseReason") + .HasColumnType("nvarchar(max)"); + + b.Property("ClosedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("DisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("ExternalId") + .HasColumnType("nvarchar(max)"); + + b.Property("LastLoginUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MustChangePassword") + .HasColumnType("bit"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("Role") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("uniqueidentifier"); + + b.Property("Username") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20261023031219_AddDeviceBootstrapToken.cs b/src/Backend/Data/Migrations/SqlServer/20261023031219_AddDeviceBootstrapToken.cs new file mode 100644 index 0000000..d9d8a91 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20261023031219_AddDeviceBootstrapToken.cs @@ -0,0 +1,29 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + /// + public partial class AddDeviceBootstrapToken : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "BootstrapTokenId", + table: "Devices", + type: "uniqueidentifier", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "BootstrapTokenId", + table: "Devices"); + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20261023123347_AddRuns.Designer.cs b/src/Backend/Data/Migrations/SqlServer/20261023123347_AddRuns.Designer.cs new file mode 100644 index 0000000..1c381e5 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20261023123347_AddRuns.Designer.cs @@ -0,0 +1,799 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + [DbContext(typeof(SqlServerAppDbContext))] + [Migration("20261023123347_AddRuns")] + partial class AddRuns + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("nvarchar(450)"); + + b.Property("IsSecret") + .HasColumnType("bit"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Actor") + .HasColumnType("nvarchar(max)"); + + b.Property("Category") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("Detail") + .HasColumnType("nvarchar(max)"); + + b.Property("RemoteIp") + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MaxUses") + .HasColumnType("int"); + + b.Property("Note") + .HasColumnType("nvarchar(max)"); + + b.Property("Revoked") + .HasColumnType("bit"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Uses") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("AgentVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("BootstrapTokenId") + .HasColumnType("uniqueidentifier"); + + b.Property("EnrolledUtc") + .HasColumnType("datetimeoffset"); + + b.Property("EnrollmentId") + .HasColumnType("uniqueidentifier"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("IpAddressesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsOrphaned") + .HasColumnType("bit"); + + b.Property("LastSeenUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Manufacturer") + .HasColumnType("nvarchar(max)"); + + b.Property("Model") + .HasColumnType("nvarchar(max)"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OrphanedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OsCaption") + .HasColumnType("nvarchar(max)"); + + b.Property("OsVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("PublicIp") + .HasColumnType("nvarchar(max)"); + + b.Property("ReadyUtc") + .HasColumnType("datetimeoffset"); + + b.Property("TagsJson") + .HasColumnType("nvarchar(max)"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParentId") + .HasColumnType("uniqueidentifier"); + + b.Property("RulesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CompletedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExitCode") + .HasColumnType("int"); + + b.Property("OutputSummary") + .HasColumnType("nvarchar(max)"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("RunId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("StartedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("RunId"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Text") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsSystem") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("PermissionsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RunEntity", b => + { + b.Property("RunId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OnlineOnly") + .HasColumnType("bit"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("SkippedJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("TargetsLabel") + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("TriggerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("RunId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId"); + + b.ToTable("Runs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("FileBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("Language") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParametersJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretsVariableName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ArgumentsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CronExpression") + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("LastResult") + .HasColumnType("nvarchar(max)"); + + b.Property("LastRunId") + .HasColumnType("uniqueidentifier"); + + b.Property("LastRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Name") + .HasColumnType("nvarchar(max)"); + + b.Property("NextRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OncePerDevice") + .HasColumnType("bit"); + + b.Property("RunOnceUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("FiredUtc") + .HasColumnType("datetimeoffset"); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CloseReason") + .HasColumnType("nvarchar(max)"); + + b.Property("ClosedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("DisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("ExternalId") + .HasColumnType("nvarchar(max)"); + + b.Property("LastLoginUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MustChangePassword") + .HasColumnType("bit"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("Role") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("uniqueidentifier"); + + b.Property("Username") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20261023123347_AddRuns.cs b/src/Backend/Data/Migrations/SqlServer/20261023123347_AddRuns.cs new file mode 100644 index 0000000..f00a41c --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20261023123347_AddRuns.cs @@ -0,0 +1,61 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + /// + public partial class AddRuns : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Runs", + columns: table => new + { + RunId = table.Column(type: "uniqueidentifier", nullable: false), + ScriptId = table.Column(type: "uniqueidentifier", nullable: false), + ScriptName = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false), + CreatedUtc = table.Column(type: "datetimeoffset", nullable: false), + RequestedBy = table.Column(type: "nvarchar(max)", nullable: true), + Source = table.Column(type: "nvarchar(32)", maxLength: 32, nullable: false), + TriggerId = table.Column(type: "uniqueidentifier", nullable: true), + TargetsLabel = table.Column(type: "nvarchar(400)", maxLength: 400, nullable: true), + OnlineOnly = table.Column(type: "bit", nullable: false), + SkippedJson = table.Column(type: "nvarchar(max)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Runs", x => x.RunId); + }); + + migrationBuilder.CreateIndex( + name: "IX_Jobs_RunId", + table: "Jobs", + column: "RunId"); + + migrationBuilder.CreateIndex( + name: "IX_Runs_CreatedUtc", + table: "Runs", + column: "CreatedUtc"); + + migrationBuilder.CreateIndex( + name: "IX_Runs_ScriptId", + table: "Runs", + column: "ScriptId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Runs"); + + migrationBuilder.DropIndex( + name: "IX_Jobs_RunId", + table: "Jobs"); + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20261023131517_SignInMethods.Designer.cs b/src/Backend/Data/Migrations/SqlServer/20261023131517_SignInMethods.Designer.cs new file mode 100644 index 0000000..756e2c2 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20261023131517_SignInMethods.Designer.cs @@ -0,0 +1,1073 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + [DbContext(typeof(SqlServerAppDbContext))] + [Migration("20261023131517_SignInMethods")] + partial class SignInMethods + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("nvarchar(450)"); + + b.Property("Etag") + .HasColumnType("nvarchar(max)"); + + b.Property("IsSecret") + .HasColumnType("bit"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Actor") + .HasColumnType("nvarchar(max)"); + + b.Property("Category") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("Detail") + .HasColumnType("nvarchar(max)"); + + b.Property("RemoteIp") + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MaxUses") + .HasColumnType("int"); + + b.Property("Note") + .HasColumnType("nvarchar(max)"); + + b.Property("Revoked") + .HasColumnType("bit"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Uses") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("AgentVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("BootstrapTokenId") + .HasColumnType("uniqueidentifier"); + + b.Property("EnrolledUtc") + .HasColumnType("datetimeoffset"); + + b.Property("EnrollmentId") + .HasColumnType("uniqueidentifier"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("IpAddressesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsOrphaned") + .HasColumnType("bit"); + + b.Property("LastSeenUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Manufacturer") + .HasColumnType("nvarchar(max)"); + + b.Property("Model") + .HasColumnType("nvarchar(max)"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OrphanedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OsCaption") + .HasColumnType("nvarchar(max)"); + + b.Property("OsVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("PublicIp") + .HasColumnType("nvarchar(max)"); + + b.Property("ReadyUtc") + .HasColumnType("datetimeoffset"); + + b.Property("TagsJson") + .HasColumnType("nvarchar(max)"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParentId") + .HasColumnType("uniqueidentifier"); + + b.Property("RulesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CompletedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExitCode") + .HasColumnType("int"); + + b.Property("OutputSummary") + .HasColumnType("nvarchar(max)"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("RunId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("StartedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("RunId"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Text") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.LocalGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("LocalGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.LocalGroupMemberEntity", b => + { + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("UserId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("GroupId", "UserId"); + + b.HasIndex("UserId"); + + b.ToTable("LocalGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleBindingEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("PrincipalName") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.HasIndex("PrincipalKind", "PrincipalId", "RoleId") + .IsUnique(); + + b.ToTable("RoleBindings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsSystem") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("PermissionsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RunEntity", b => + { + b.Property("RunId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OnlineOnly") + .HasColumnType("bit"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("SkippedJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("TargetsLabel") + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("TriggerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("RunId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId"); + + b.ToTable("Runs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("FileBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("Language") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParametersJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretsVariableName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ArgumentsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CronExpression") + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("LastResult") + .HasColumnType("nvarchar(max)"); + + b.Property("LastRunId") + .HasColumnType("uniqueidentifier"); + + b.Property("LastRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Name") + .HasColumnType("nvarchar(max)"); + + b.Property("NextRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OncePerDevice") + .HasColumnType("bit"); + + b.Property("RunOnceUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("FiredUtc") + .HasColumnType("datetimeoffset"); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SessionEntity", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("AbsoluteExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ClientAddress") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CsrfHash") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("GroupsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("LastSeenUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("RevokedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("SecretHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("UserAgent") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("UserId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("AbsoluteExpiresUtc"); + + b.HasIndex("UserId"); + + b.ToTable("Sessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CloseReason") + .HasColumnType("nvarchar(max)"); + + b.Property("ClosedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SignInRequestEntity", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CodeVerifier") + .HasColumnType("nvarchar(max)"); + + b.Property("CompletedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Detail") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("ExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Nonce") + .HasColumnType("nvarchar(max)"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("ReturnUrl") + .HasColumnType("nvarchar(max)"); + + b.Property("SettingsEtag") + .HasColumnType("nvarchar(max)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("StepUpSessionId") + .HasColumnType("nvarchar(max)"); + + b.Property("TestSessionId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresUtc"); + + b.HasIndex("TestSessionId"); + + b.ToTable("SignInRequests", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SignInThrottleEntity", b => + { + b.Property("Key") + .HasMaxLength(300) + .HasColumnType("nvarchar(300)"); + + b.Property("BlockedUntilUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Failures") + .HasColumnType("int"); + + b.Property("FirstFailureUtc") + .HasColumnType("datetimeoffset"); + + b.Property("LastFailureUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Key"); + + b.ToTable("SignInThrottles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.StepUpEntity", b => + { + b.Property("SessionId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Method") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("VerifiedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("SessionId"); + + b.ToTable("StepUps", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("DisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("Email") + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("ExternalId") + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("IsBreakGlass") + .HasColumnType("bit"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("LastSignInUtc") + .HasColumnType("datetimeoffset"); + + b.Property("LegacyRole") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("LegacyRoleId") + .HasColumnType("uniqueidentifier"); + + b.Property("MustChangePassword") + .HasColumnType("bit"); + + b.Property("PasswordChangedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("UserName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("WindowsGroupsJson") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("Kind", "ExternalId"); + + b.HasIndex("Kind", "UserName") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.LocalGroupMemberEntity", b => + { + b.HasOne("Backend.Data.LocalGroupEntity", null) + .WithMany() + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Backend.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.RoleBindingEntity", b => + { + b.HasOne("Backend.Data.RoleEntity", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.SessionEntity", b => + { + b.HasOne("Backend.Data.UserEntity", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20261023131517_SignInMethods.cs b/src/Backend/Data/Migrations/SqlServer/20261023131517_SignInMethods.cs new file mode 100644 index 0000000..e34376e --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20261023131517_SignInMethods.cs @@ -0,0 +1,346 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + /// + public partial class SignInMethods : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "OidcProviders"); + + migrationBuilder.DropIndex( + name: "IX_Users_Username", + table: "Users"); + + migrationBuilder.RenameColumn( + name: "Username", + table: "Users", + newName: "UserName"); + + migrationBuilder.AlterColumn( + name: "UserName", + table: "Users", + type: "nvarchar(256)", + maxLength: 256, + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(450)"); + + migrationBuilder.AlterColumn( + name: "ExternalId", + table: "Users", + type: "nvarchar(450)", + maxLength: 450, + nullable: true, + oldClrType: typeof(string), + oldType: "nvarchar(max)", + oldNullable: true); + + migrationBuilder.AddColumn( + name: "Kind", + table: "Users", + type: "nvarchar(16)", + maxLength: 16, + nullable: false, + defaultValue: "local"); + + migrationBuilder.AddColumn( + name: "Description", + table: "Users", + type: "nvarchar(max)", + nullable: true); + + migrationBuilder.AddColumn( + name: "Email", + table: "Users", + type: "nvarchar(max)", + nullable: true); + + migrationBuilder.AddColumn( + name: "WindowsGroupsJson", + table: "Users", + type: "nvarchar(max)", + nullable: true); + + migrationBuilder.AddColumn( + name: "Enabled", + table: "Users", + type: "bit", + nullable: false, + defaultValue: true); + + migrationBuilder.AddColumn( + name: "IsBreakGlass", + table: "Users", + type: "bit", + nullable: false, + defaultValue: false); + + migrationBuilder.AddColumn( + name: "LegacyRole", + table: "Users", + type: "nvarchar(32)", + maxLength: 32, + nullable: true); + + migrationBuilder.AddColumn( + name: "LegacyRoleId", + table: "Users", + type: "uniqueidentifier", + nullable: true); + + migrationBuilder.AddColumn( + name: "LastSignInUtc", + table: "Users", + type: "datetimeoffset", + nullable: true); + + migrationBuilder.AddColumn( + name: "PasswordChangedUtc", + table: "Users", + type: "datetimeoffset", + nullable: true); + + migrationBuilder.AddColumn( + name: "UpdatedUtc", + table: "Users", + type: "datetimeoffset", + nullable: false, + defaultValue: new DateTimeOffset(new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 0, 0, 0, 0))); + + // Carry the old columns over before they go: kind of account, the role (for the upgrade to groups), last sign-in. + migrationBuilder.Sql( + "UPDATE \"Users\" SET \"Kind\" = \"AuthProvider\", \"LegacyRole\" = \"Role\", \"LegacyRoleId\" = \"RoleId\", " + + "\"LastSignInUtc\" = \"LastLoginUtc\", \"UpdatedUtc\" = \"CreatedUtc\""); + + migrationBuilder.DropColumn( + name: "AuthProvider", + table: "Users"); + + migrationBuilder.DropColumn( + name: "Role", + table: "Users"); + + migrationBuilder.DropColumn( + name: "RoleId", + table: "Users"); + + migrationBuilder.DropColumn( + name: "LastLoginUtc", + table: "Users"); + + migrationBuilder.AddColumn( + name: "Etag", + table: "AppSettings", + type: "nvarchar(max)", + nullable: true); + + migrationBuilder.CreateTable( + name: "LocalGroups", + columns: table => new + { + Id = table.Column(type: "uniqueidentifier", nullable: false), + Name = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + Description = table.Column(type: "nvarchar(max)", nullable: true), + CreatedUtc = table.Column(type: "datetimeoffset", nullable: false), + UpdatedUtc = table.Column(type: "datetimeoffset", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_LocalGroups", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "RoleBindings", + columns: table => new + { + Id = table.Column(type: "uniqueidentifier", nullable: false), + RoleId = table.Column(type: "uniqueidentifier", nullable: false), + PrincipalKind = table.Column(type: "nvarchar(32)", maxLength: 32, nullable: false), + PrincipalId = table.Column(type: "nvarchar(450)", maxLength: 450, nullable: false), + PrincipalName = table.Column(type: "nvarchar(max)", nullable: true), + CreatedUtc = table.Column(type: "datetimeoffset", nullable: false), + CreatedBy = table.Column(type: "nvarchar(max)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_RoleBindings", x => x.Id); + table.ForeignKey( + name: "FK_RoleBindings_Roles_RoleId", + column: x => x.RoleId, + principalTable: "Roles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "Sessions", + columns: table => new + { + Id = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + UserId = table.Column(type: "uniqueidentifier", nullable: false), + SecretHash = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + CsrfHash = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: true), + Provider = table.Column(type: "nvarchar(16)", maxLength: 16, nullable: false), + GroupsJson = table.Column(type: "nvarchar(max)", nullable: true), + CreatedUtc = table.Column(type: "datetimeoffset", nullable: false), + LastSeenUtc = table.Column(type: "datetimeoffset", nullable: false), + ExpiresUtc = table.Column(type: "datetimeoffset", nullable: false), + AbsoluteExpiresUtc = table.Column(type: "datetimeoffset", nullable: false), + RevokedUtc = table.Column(type: "datetimeoffset", nullable: true), + ClientAddress = table.Column(type: "nvarchar(max)", nullable: true), + UserAgent = table.Column(type: "nvarchar(512)", maxLength: 512, nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Sessions", x => x.Id); + table.ForeignKey( + name: "FK_Sessions_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "SignInRequests", + columns: table => new + { + Id = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + Provider = table.Column(type: "nvarchar(16)", maxLength: 16, nullable: false), + Status = table.Column(type: "nvarchar(16)", maxLength: 16, nullable: false), + Nonce = table.Column(type: "nvarchar(max)", nullable: true), + CodeVerifier = table.Column(type: "nvarchar(max)", nullable: true), + ReturnUrl = table.Column(type: "nvarchar(max)", nullable: true), + TestSessionId = table.Column(type: "nvarchar(450)", nullable: true), + StepUpSessionId = table.Column(type: "nvarchar(max)", nullable: true), + SettingsEtag = table.Column(type: "nvarchar(max)", nullable: true), + Detail = table.Column(type: "nvarchar(2000)", maxLength: 2000, nullable: true), + CreatedUtc = table.Column(type: "datetimeoffset", nullable: false), + ExpiresUtc = table.Column(type: "datetimeoffset", nullable: false), + CompletedUtc = table.Column(type: "datetimeoffset", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_SignInRequests", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "SignInThrottles", + columns: table => new + { + Key = table.Column(type: "nvarchar(300)", maxLength: 300, nullable: false), + Failures = table.Column(type: "int", nullable: false), + FirstFailureUtc = table.Column(type: "datetimeoffset", nullable: false), + LastFailureUtc = table.Column(type: "datetimeoffset", nullable: false), + BlockedUntilUtc = table.Column(type: "datetimeoffset", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_SignInThrottles", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "StepUps", + columns: table => new + { + SessionId = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + Method = table.Column(type: "nvarchar(16)", maxLength: 16, nullable: false), + VerifiedUtc = table.Column(type: "datetimeoffset", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_StepUps", x => x.SessionId); + }); + + migrationBuilder.CreateTable( + name: "LocalGroupMembers", + columns: table => new + { + GroupId = table.Column(type: "uniqueidentifier", nullable: false), + UserId = table.Column(type: "uniqueidentifier", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_LocalGroupMembers", x => new { x.GroupId, x.UserId }); + table.ForeignKey( + name: "FK_LocalGroupMembers_LocalGroups_GroupId", + column: x => x.GroupId, + principalTable: "LocalGroups", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_LocalGroupMembers_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Users_Kind_ExternalId", + table: "Users", + columns: new[] { "Kind", "ExternalId" }); + + migrationBuilder.CreateIndex( + name: "IX_Users_Kind_UserName", + table: "Users", + columns: new[] { "Kind", "UserName" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_LocalGroupMembers_UserId", + table: "LocalGroupMembers", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_LocalGroups_Name", + table: "LocalGroups", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_RoleBindings_PrincipalKind_PrincipalId_RoleId", + table: "RoleBindings", + columns: new[] { "PrincipalKind", "PrincipalId", "RoleId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_RoleBindings_RoleId", + table: "RoleBindings", + column: "RoleId"); + + migrationBuilder.CreateIndex( + name: "IX_Sessions_AbsoluteExpiresUtc", + table: "Sessions", + column: "AbsoluteExpiresUtc"); + + migrationBuilder.CreateIndex( + name: "IX_Sessions_UserId", + table: "Sessions", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_SignInRequests_ExpiresUtc", + table: "SignInRequests", + column: "ExpiresUtc"); + + migrationBuilder.CreateIndex( + name: "IX_SignInRequests_TestSessionId", + table: "SignInRequests", + column: "TestSessionId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + throw new NotSupportedException("Sign-in methods and role bindings cannot be rolled back to per-user roles; restore a backup instead."); + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20261023212443_AgentUpgrades.Designer.cs b/src/Backend/Data/Migrations/SqlServer/20261023212443_AgentUpgrades.Designer.cs new file mode 100644 index 0000000..1d2b883 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20261023212443_AgentUpgrades.Designer.cs @@ -0,0 +1,1214 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + [DbContext(typeof(SqlServerAppDbContext))] + [Migration("20261023212443_AgentUpgrades")] + partial class AgentUpgrades + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Backend.Data.AgentPackageEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ImportedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("PackageType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("S3Key") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("SizeBytes") + .HasColumnType("bigint"); + + b.Property("StoragePath") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Id"); + + b.HasIndex("Sha256"); + + b.HasIndex("Version", "PackageType") + .IsUnique(); + + b.ToTable("AgentPackages", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AgentUpgradeEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Attempts") + .HasColumnType("int"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Detail") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("FinishedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("FromVersion") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("LastEventUtc") + .HasColumnType("datetimeoffset"); + + b.Property("LastLogJson") + .HasColumnType("nvarchar(max)"); + + b.Property("PackageId") + .HasColumnType("uniqueidentifier"); + + b.Property("PackageType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Reason") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("RequestedBy") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("SentUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Sha256") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("State") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("TargetVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Id"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("State"); + + b.HasIndex("ClientId", "State"); + + b.ToTable("AgentUpgrades", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("nvarchar(450)"); + + b.Property("Etag") + .HasColumnType("nvarchar(max)"); + + b.Property("IsSecret") + .HasColumnType("bit"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Actor") + .HasColumnType("nvarchar(max)"); + + b.Property("Category") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("Detail") + .HasColumnType("nvarchar(max)"); + + b.Property("RemoteIp") + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MaxUses") + .HasColumnType("int"); + + b.Property("Note") + .HasColumnType("nvarchar(max)"); + + b.Property("Revoked") + .HasColumnType("bit"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Uses") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("AgentRuntime") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("AgentVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("BootstrapTokenId") + .HasColumnType("uniqueidentifier"); + + b.Property("EnrolledUtc") + .HasColumnType("datetimeoffset"); + + b.Property("EnrollmentId") + .HasColumnType("uniqueidentifier"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("IpAddressesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsOrphaned") + .HasColumnType("bit"); + + b.Property("LastSeenUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Manufacturer") + .HasColumnType("nvarchar(max)"); + + b.Property("Model") + .HasColumnType("nvarchar(max)"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OrphanedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OsCaption") + .HasColumnType("nvarchar(max)"); + + b.Property("OsVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("PublicIp") + .HasColumnType("nvarchar(max)"); + + b.Property("ReadyUtc") + .HasColumnType("datetimeoffset"); + + b.Property("TagsJson") + .HasColumnType("nvarchar(max)"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParentId") + .HasColumnType("uniqueidentifier"); + + b.Property("RulesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CompletedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExitCode") + .HasColumnType("int"); + + b.Property("OutputSummary") + .HasColumnType("nvarchar(max)"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("RunId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("StartedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("RunId"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Text") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.LocalGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("LocalGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.LocalGroupMemberEntity", b => + { + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("UserId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("GroupId", "UserId"); + + b.HasIndex("UserId"); + + b.ToTable("LocalGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleBindingEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("PrincipalName") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.HasIndex("PrincipalKind", "PrincipalId", "RoleId") + .IsUnique(); + + b.ToTable("RoleBindings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsSystem") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("PermissionsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RunEntity", b => + { + b.Property("RunId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OnlineOnly") + .HasColumnType("bit"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("SkippedJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("TargetsLabel") + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("TriggerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("RunId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId"); + + b.ToTable("Runs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("FileBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("Language") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParametersJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretsVariableName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ArgumentsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CronExpression") + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("LastResult") + .HasColumnType("nvarchar(max)"); + + b.Property("LastRunId") + .HasColumnType("uniqueidentifier"); + + b.Property("LastRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Name") + .HasColumnType("nvarchar(max)"); + + b.Property("NextRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OncePerDevice") + .HasColumnType("bit"); + + b.Property("RunOnceUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("FiredUtc") + .HasColumnType("datetimeoffset"); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SessionEntity", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("AbsoluteExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ClientAddress") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CsrfHash") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("GroupsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("LastSeenUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("RevokedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("SecretHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("UserAgent") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("UserId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("AbsoluteExpiresUtc"); + + b.HasIndex("UserId"); + + b.ToTable("Sessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CloseReason") + .HasColumnType("nvarchar(max)"); + + b.Property("ClosedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SignInRequestEntity", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CodeVerifier") + .HasColumnType("nvarchar(max)"); + + b.Property("CompletedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Detail") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("ExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Nonce") + .HasColumnType("nvarchar(max)"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("ReturnUrl") + .HasColumnType("nvarchar(max)"); + + b.Property("SettingsEtag") + .HasColumnType("nvarchar(max)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("StepUpSessionId") + .HasColumnType("nvarchar(max)"); + + b.Property("TestSessionId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresUtc"); + + b.HasIndex("TestSessionId"); + + b.ToTable("SignInRequests", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SignInThrottleEntity", b => + { + b.Property("Key") + .HasMaxLength(300) + .HasColumnType("nvarchar(300)"); + + b.Property("BlockedUntilUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Failures") + .HasColumnType("int"); + + b.Property("FirstFailureUtc") + .HasColumnType("datetimeoffset"); + + b.Property("LastFailureUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Key"); + + b.ToTable("SignInThrottles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.StepUpEntity", b => + { + b.Property("SessionId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Method") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("VerifiedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("SessionId"); + + b.ToTable("StepUps", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("DisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("Email") + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("ExternalId") + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("IsBreakGlass") + .HasColumnType("bit"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("LastSignInUtc") + .HasColumnType("datetimeoffset"); + + b.Property("LegacyRole") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("LegacyRoleId") + .HasColumnType("uniqueidentifier"); + + b.Property("MustChangePassword") + .HasColumnType("bit"); + + b.Property("PasswordChangedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("UserName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("WindowsGroupsJson") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("Kind", "ExternalId"); + + b.HasIndex("Kind", "UserName") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.LocalGroupMemberEntity", b => + { + b.HasOne("Backend.Data.LocalGroupEntity", null) + .WithMany() + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Backend.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.RoleBindingEntity", b => + { + b.HasOne("Backend.Data.RoleEntity", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.SessionEntity", b => + { + b.HasOne("Backend.Data.UserEntity", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20261023212443_AgentUpgrades.cs b/src/Backend/Data/Migrations/SqlServer/20261023212443_AgentUpgrades.cs new file mode 100644 index 0000000..3d4c46e --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20261023212443_AgentUpgrades.cs @@ -0,0 +1,110 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + /// + public partial class AgentUpgrades : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "AgentRuntime", + table: "Devices", + type: "nvarchar(32)", + maxLength: 32, + nullable: true); + + migrationBuilder.CreateTable( + name: "AgentPackages", + columns: table => new + { + Id = table.Column(type: "uniqueidentifier", nullable: false), + Version = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + PackageType = table.Column(type: "nvarchar(32)", maxLength: 32, nullable: false), + FileName = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + Sha256 = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + SizeBytes = table.Column(type: "bigint", nullable: false), + StoragePath = table.Column(type: "nvarchar(512)", maxLength: 512, nullable: false), + S3Key = table.Column(type: "nvarchar(512)", maxLength: 512, nullable: true), + ImportedUtc = table.Column(type: "datetimeoffset", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AgentPackages", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AgentUpgrades", + columns: table => new + { + Id = table.Column(type: "uniqueidentifier", nullable: false), + ClientId = table.Column(type: "nvarchar(450)", nullable: false), + FromVersion = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: true), + TargetVersion = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + PackageType = table.Column(type: "nvarchar(32)", maxLength: 32, nullable: false), + PackageId = table.Column(type: "uniqueidentifier", nullable: true), + Sha256 = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: true), + Source = table.Column(type: "nvarchar(16)", maxLength: 16, nullable: false), + State = table.Column(type: "nvarchar(16)", maxLength: 16, nullable: false), + Reason = table.Column(type: "nvarchar(32)", maxLength: 32, nullable: true), + Detail = table.Column(type: "nvarchar(2000)", maxLength: 2000, nullable: true), + LastLogJson = table.Column(type: "nvarchar(max)", nullable: true), + Attempts = table.Column(type: "int", nullable: false), + RequestedBy = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), + CreatedUtc = table.Column(type: "datetimeoffset", nullable: false), + SentUtc = table.Column(type: "datetimeoffset", nullable: true), + LastEventUtc = table.Column(type: "datetimeoffset", nullable: true), + FinishedUtc = table.Column(type: "datetimeoffset", nullable: true), + ConcurrencyStamp = table.Column(type: "uniqueidentifier", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AgentUpgrades", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_AgentPackages_Sha256", + table: "AgentPackages", + column: "Sha256"); + + migrationBuilder.CreateIndex( + name: "IX_AgentPackages_Version_PackageType", + table: "AgentPackages", + columns: new[] { "Version", "PackageType" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_AgentUpgrades_ClientId_State", + table: "AgentUpgrades", + columns: new[] { "ClientId", "State" }); + + migrationBuilder.CreateIndex( + name: "IX_AgentUpgrades_CreatedUtc", + table: "AgentUpgrades", + column: "CreatedUtc"); + + migrationBuilder.CreateIndex( + name: "IX_AgentUpgrades_State", + table: "AgentUpgrades", + column: "State"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AgentPackages"); + + migrationBuilder.DropTable( + name: "AgentUpgrades"); + + migrationBuilder.DropColumn( + name: "AgentRuntime", + table: "Devices"); + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/SqlServerAppDbContextModelSnapshot.cs b/src/Backend/Data/Migrations/SqlServer/SqlServerAppDbContextModelSnapshot.cs index ca89ef0..e19d559 100644 --- a/src/Backend/Data/Migrations/SqlServer/SqlServerAppDbContextModelSnapshot.cs +++ b/src/Backend/Data/Migrations/SqlServer/SqlServerAppDbContextModelSnapshot.cs @@ -22,11 +22,151 @@ namespace Backend.Data.Migrations.SqlServer SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + modelBuilder.Entity("Backend.Data.AgentPackageEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ImportedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("PackageType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("S3Key") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("SizeBytes") + .HasColumnType("bigint"); + + b.Property("StoragePath") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Id"); + + b.HasIndex("Sha256"); + + b.HasIndex("Version", "PackageType") + .IsUnique(); + + b.ToTable("AgentPackages", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AgentUpgradeEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Attempts") + .HasColumnType("int"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Detail") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("FinishedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("FromVersion") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("LastEventUtc") + .HasColumnType("datetimeoffset"); + + b.Property("LastLogJson") + .HasColumnType("nvarchar(max)"); + + b.Property("PackageId") + .HasColumnType("uniqueidentifier"); + + b.Property("PackageType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Reason") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("RequestedBy") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("SentUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Sha256") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("State") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("TargetVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Id"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("State"); + + b.HasIndex("ClientId", "State"); + + b.ToTable("AgentUpgrades", (string)null); + }); + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => { b.Property("Key") .HasColumnType("nvarchar(450)"); + b.Property("Etag") + .HasColumnType("nvarchar(max)"); + b.Property("IsSecret") .HasColumnType("bit"); @@ -126,9 +266,16 @@ namespace Backend.Data.Migrations.SqlServer b.Property("ClientId") .HasColumnType("nvarchar(450)"); + b.Property("AgentRuntime") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + b.Property("AgentVersion") .HasColumnType("nvarchar(max)"); + b.Property("BootstrapTokenId") + .HasColumnType("uniqueidentifier"); + b.Property("EnrolledUtc") .HasColumnType("datetimeoffset"); @@ -203,6 +350,9 @@ namespace Backend.Data.Migrations.SqlServer .IsRequired() .HasColumnType("nvarchar(450)"); + b.Property("ParentId") + .HasColumnType("uniqueidentifier"); + b.Property("RulesJson") .HasColumnType("nvarchar(max)"); @@ -344,6 +494,8 @@ namespace Backend.Data.Migrations.SqlServer b.HasIndex("CreatedUtc"); + b.HasIndex("RunId"); + b.HasIndex("ScriptId", "RunId"); b.ToTable("Jobs", (string)null); @@ -382,30 +534,85 @@ namespace Backend.Data.Migrations.SqlServer b.ToTable("JobOutput", (string)null); }); - modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + modelBuilder.Entity("Backend.Data.LocalGroupEntity", b => { b.Property("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); - b.Property("Authority") - .IsRequired() - .HasColumnType("nvarchar(max)"); + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); - b.Property("ClientId") - .IsRequired() + b.Property("Description") .HasColumnType("nvarchar(max)"); - b.Property("Enabled") - .HasColumnType("bit"); - b.Property("Name") .IsRequired() - .HasColumnType("nvarchar(max)"); + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); b.HasKey("Id"); - b.ToTable("OidcProviders", (string)null); + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("LocalGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.LocalGroupMemberEntity", b => + { + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("UserId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("GroupId", "UserId"); + + b.HasIndex("UserId"); + + b.ToTable("LocalGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleBindingEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("PrincipalKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("PrincipalName") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.HasIndex("PrincipalKind", "PrincipalId", "RoleId") + .IsUnique(); + + b.ToTable("RoleBindings", (string)null); }); modelBuilder.Entity("Backend.Data.RoleEntity", b => @@ -450,6 +657,54 @@ namespace Backend.Data.Migrations.SqlServer b.ToTable("Roles", (string)null); }); + modelBuilder.Entity("Backend.Data.RunEntity", b => + { + b.Property("RunId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OnlineOnly") + .HasColumnType("bit"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("SkippedJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("TargetsLabel") + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("TriggerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("RunId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId"); + + b.ToTable("Runs", (string)null); + }); + modelBuilder.Entity("Backend.Data.ScriptEntity", b => { b.Property("Id") @@ -517,6 +772,10 @@ namespace Backend.Data.Migrations.SqlServer b.Property("ClientId") .HasColumnType("nvarchar(max)"); + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("uniqueidentifier"); + b.Property("CreatedBy") .HasColumnType("nvarchar(max)"); @@ -535,9 +794,15 @@ namespace Backend.Data.Migrations.SqlServer b.Property("LastResult") .HasColumnType("nvarchar(max)"); + b.Property("LastRunId") + .HasColumnType("uniqueidentifier"); + b.Property("LastRunUtc") .HasColumnType("datetimeoffset"); + b.Property("Name") + .HasColumnType("nvarchar(max)"); + b.Property("NextRunUtc") .HasColumnType("datetimeoffset"); @@ -631,6 +896,63 @@ namespace Backend.Data.Migrations.SqlServer b.ToTable("SecretsProviders", (string)null); }); + modelBuilder.Entity("Backend.Data.SessionEntity", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("AbsoluteExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ClientAddress") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CsrfHash") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("GroupsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("LastSeenUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("RevokedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("SecretHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("UserAgent") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("UserId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("AbsoluteExpiresUtc"); + + b.HasIndex("UserId"); + + b.ToTable("Sessions", (string)null); + }); + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => { b.Property("Id") @@ -664,48 +986,172 @@ namespace Backend.Data.Migrations.SqlServer b.ToTable("ShellSessions", (string)null); }); + modelBuilder.Entity("Backend.Data.SignInRequestEntity", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CodeVerifier") + .HasColumnType("nvarchar(max)"); + + b.Property("CompletedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Detail") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("ExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Nonce") + .HasColumnType("nvarchar(max)"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("ReturnUrl") + .HasColumnType("nvarchar(max)"); + + b.Property("SettingsEtag") + .HasColumnType("nvarchar(max)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("StepUpSessionId") + .HasColumnType("nvarchar(max)"); + + b.Property("TestSessionId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresUtc"); + + b.HasIndex("TestSessionId"); + + b.ToTable("SignInRequests", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SignInThrottleEntity", b => + { + b.Property("Key") + .HasMaxLength(300) + .HasColumnType("nvarchar(300)"); + + b.Property("BlockedUntilUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Failures") + .HasColumnType("int"); + + b.Property("FirstFailureUtc") + .HasColumnType("datetimeoffset"); + + b.Property("LastFailureUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Key"); + + b.ToTable("SignInThrottles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.StepUpEntity", b => + { + b.Property("SessionId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Method") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("VerifiedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("SessionId"); + + b.ToTable("StepUps", (string)null); + }); + modelBuilder.Entity("Backend.Data.UserEntity", b => { b.Property("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); - b.Property("AuthProvider") - .IsRequired() - .HasColumnType("nvarchar(max)"); - b.Property("CreatedUtc") .HasColumnType("datetimeoffset"); + b.Property("Description") + .HasColumnType("nvarchar(max)"); + b.Property("DisplayName") .HasColumnType("nvarchar(max)"); - b.Property("ExternalId") + b.Property("Email") .HasColumnType("nvarchar(max)"); - b.Property("LastLoginUtc") + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("ExternalId") + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("IsBreakGlass") + .HasColumnType("bit"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("LastSignInUtc") .HasColumnType("datetimeoffset"); + b.Property("LegacyRole") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("LegacyRoleId") + .HasColumnType("uniqueidentifier"); + b.Property("MustChangePassword") .HasColumnType("bit"); + b.Property("PasswordChangedUtc") + .HasColumnType("datetimeoffset"); + b.Property("PasswordHash") .HasColumnType("nvarchar(max)"); - b.Property("Role") + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("UserName") .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("WindowsGroupsJson") .HasColumnType("nvarchar(max)"); - b.Property("RoleId") - .HasColumnType("uniqueidentifier"); - - b.Property("Username") - .IsRequired() - .HasColumnType("nvarchar(450)"); - b.HasKey("Id"); - b.HasIndex("Username") + b.HasIndex("Kind", "ExternalId"); + + b.HasIndex("Kind", "UserName") .IsUnique(); b.ToTable("Users", (string)null); @@ -720,6 +1166,41 @@ namespace Backend.Data.Migrations.SqlServer .IsRequired(); }); + modelBuilder.Entity("Backend.Data.LocalGroupMemberEntity", b => + { + b.HasOne("Backend.Data.LocalGroupEntity", null) + .WithMany() + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Backend.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.RoleBindingEntity", b => + { + b.HasOne("Backend.Data.RoleEntity", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.SessionEntity", b => + { + b.HasOne("Backend.Data.UserEntity", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + modelBuilder.Entity("Backend.Data.DeviceEntity", b => { b.Navigation("Inventory"); diff --git a/src/Backend/Data/Migrations/Sqlite/20261023003317_AddTriggerNameAndLastRun.Designer.cs b/src/Backend/Data/Migrations/Sqlite/20261023003317_AddTriggerNameAndLastRun.Designer.cs new file mode 100644 index 0000000..de3c021 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20261023003317_AddTriggerNameAndLastRun.Designer.cs @@ -0,0 +1,726 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + [DbContext(typeof(SqliteAppDbContext))] + [Migration("20261023003317_AddTriggerNameAndLastRun")] + partial class AddTriggerNameAndLastRun + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.10"); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("TEXT"); + + b.Property("IsSecret") + .HasColumnType("INTEGER"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasColumnType("TEXT"); + + b.Property("Category") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("Detail") + .HasColumnType("TEXT"); + + b.Property("RemoteIp") + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("MaxUses") + .HasColumnType("INTEGER"); + + b.Property("Note") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Uses") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("AgentVersion") + .HasColumnType("TEXT"); + + b.Property("EnrolledUtc") + .HasColumnType("INTEGER"); + + b.Property("EnrollmentId") + .HasColumnType("TEXT"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IpAddressesJson") + .HasColumnType("TEXT"); + + b.Property("IsOrphaned") + .HasColumnType("INTEGER"); + + b.Property("LastSeenUtc") + .HasColumnType("INTEGER"); + + b.Property("Manufacturer") + .HasColumnType("TEXT"); + + b.Property("Model") + .HasColumnType("TEXT"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OrphanedUtc") + .HasColumnType("INTEGER"); + + b.Property("OsCaption") + .HasColumnType("TEXT"); + + b.Property("OsVersion") + .HasColumnType("TEXT"); + + b.Property("PublicIp") + .HasColumnType("TEXT"); + + b.Property("ReadyUtc") + .HasColumnType("INTEGER"); + + b.Property("TagsJson") + .HasColumnType("TEXT"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RulesJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AddedUtc") + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CompletedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExitCode") + .HasColumnType("INTEGER"); + + b.Property("OutputSummary") + .HasColumnType("TEXT"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("RunId") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("StartedUtc") + .HasColumnType("INTEGER"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("Sequence") + .HasColumnType("INTEGER"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Text") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("TEXT"); + + b.Property("IsSystem") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("TEXT"); + + b.Property("PermissionsJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("FileBindingsJson") + .HasColumnType("TEXT"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("TEXT"); + + b.Property("Language") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ParametersJson") + .HasColumnType("TEXT"); + + b.Property("SecretBindingsJson") + .HasColumnType("TEXT"); + + b.Property("SecretsVariableName") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ArgumentsJson") + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("CronExpression") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("LastResult") + .HasColumnType("TEXT"); + + b.Property("LastRunId") + .HasColumnType("TEXT"); + + b.Property("LastRunUtc") + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("NextRunUtc") + .HasColumnType("INTEGER"); + + b.Property("OncePerDevice") + .HasColumnType("INTEGER"); + + b.Property("RunOnceUtc") + .HasColumnType("INTEGER"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FiredUtc") + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("TriggerId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CloseReason") + .HasColumnType("TEXT"); + + b.Property("ClosedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("ExternalId") + .HasColumnType("TEXT"); + + b.Property("LastLoginUtc") + .HasColumnType("INTEGER"); + + b.Property("MustChangePassword") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("Role") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("Username") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20261023003317_AddTriggerNameAndLastRun.cs b/src/Backend/Data/Migrations/Sqlite/20261023003317_AddTriggerNameAndLastRun.cs new file mode 100644 index 0000000..a7e2eb7 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20261023003317_AddTriggerNameAndLastRun.cs @@ -0,0 +1,39 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + /// + public partial class AddTriggerNameAndLastRun : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "LastRunId", + table: "ScriptTriggers", + type: "TEXT", + nullable: true); + + migrationBuilder.AddColumn( + name: "Name", + table: "ScriptTriggers", + type: "TEXT", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "LastRunId", + table: "ScriptTriggers"); + + migrationBuilder.DropColumn( + name: "Name", + table: "ScriptTriggers"); + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20261023004330_AddGroupNesting.Designer.cs b/src/Backend/Data/Migrations/Sqlite/20261023004330_AddGroupNesting.Designer.cs new file mode 100644 index 0000000..1764efa --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20261023004330_AddGroupNesting.Designer.cs @@ -0,0 +1,729 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + [DbContext(typeof(SqliteAppDbContext))] + [Migration("20261023004330_AddGroupNesting")] + partial class AddGroupNesting + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.10"); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("TEXT"); + + b.Property("IsSecret") + .HasColumnType("INTEGER"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasColumnType("TEXT"); + + b.Property("Category") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("Detail") + .HasColumnType("TEXT"); + + b.Property("RemoteIp") + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("MaxUses") + .HasColumnType("INTEGER"); + + b.Property("Note") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Uses") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("AgentVersion") + .HasColumnType("TEXT"); + + b.Property("EnrolledUtc") + .HasColumnType("INTEGER"); + + b.Property("EnrollmentId") + .HasColumnType("TEXT"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IpAddressesJson") + .HasColumnType("TEXT"); + + b.Property("IsOrphaned") + .HasColumnType("INTEGER"); + + b.Property("LastSeenUtc") + .HasColumnType("INTEGER"); + + b.Property("Manufacturer") + .HasColumnType("TEXT"); + + b.Property("Model") + .HasColumnType("TEXT"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OrphanedUtc") + .HasColumnType("INTEGER"); + + b.Property("OsCaption") + .HasColumnType("TEXT"); + + b.Property("OsVersion") + .HasColumnType("TEXT"); + + b.Property("PublicIp") + .HasColumnType("TEXT"); + + b.Property("ReadyUtc") + .HasColumnType("INTEGER"); + + b.Property("TagsJson") + .HasColumnType("TEXT"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ParentId") + .HasColumnType("TEXT"); + + b.Property("RulesJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AddedUtc") + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CompletedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExitCode") + .HasColumnType("INTEGER"); + + b.Property("OutputSummary") + .HasColumnType("TEXT"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("RunId") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("StartedUtc") + .HasColumnType("INTEGER"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("Sequence") + .HasColumnType("INTEGER"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Text") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("TEXT"); + + b.Property("IsSystem") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("TEXT"); + + b.Property("PermissionsJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("FileBindingsJson") + .HasColumnType("TEXT"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("TEXT"); + + b.Property("Language") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ParametersJson") + .HasColumnType("TEXT"); + + b.Property("SecretBindingsJson") + .HasColumnType("TEXT"); + + b.Property("SecretsVariableName") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ArgumentsJson") + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("CronExpression") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("LastResult") + .HasColumnType("TEXT"); + + b.Property("LastRunId") + .HasColumnType("TEXT"); + + b.Property("LastRunUtc") + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("NextRunUtc") + .HasColumnType("INTEGER"); + + b.Property("OncePerDevice") + .HasColumnType("INTEGER"); + + b.Property("RunOnceUtc") + .HasColumnType("INTEGER"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FiredUtc") + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("TriggerId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CloseReason") + .HasColumnType("TEXT"); + + b.Property("ClosedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("ExternalId") + .HasColumnType("TEXT"); + + b.Property("LastLoginUtc") + .HasColumnType("INTEGER"); + + b.Property("MustChangePassword") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("Role") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("Username") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20261023004330_AddGroupNesting.cs b/src/Backend/Data/Migrations/Sqlite/20261023004330_AddGroupNesting.cs new file mode 100644 index 0000000..fa5178c --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20261023004330_AddGroupNesting.cs @@ -0,0 +1,29 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + /// + public partial class AddGroupNesting : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "ParentId", + table: "DeviceGroups", + type: "TEXT", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "ParentId", + table: "DeviceGroups"); + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20261023021502_AddTriggerConcurrencyStamp.Designer.cs b/src/Backend/Data/Migrations/Sqlite/20261023021502_AddTriggerConcurrencyStamp.Designer.cs new file mode 100644 index 0000000..dbfad66 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20261023021502_AddTriggerConcurrencyStamp.Designer.cs @@ -0,0 +1,733 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + [DbContext(typeof(SqliteAppDbContext))] + [Migration("20261023021502_AddTriggerConcurrencyStamp")] + partial class AddTriggerConcurrencyStamp + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.10"); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("TEXT"); + + b.Property("IsSecret") + .HasColumnType("INTEGER"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasColumnType("TEXT"); + + b.Property("Category") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("Detail") + .HasColumnType("TEXT"); + + b.Property("RemoteIp") + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("MaxUses") + .HasColumnType("INTEGER"); + + b.Property("Note") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Uses") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("AgentVersion") + .HasColumnType("TEXT"); + + b.Property("EnrolledUtc") + .HasColumnType("INTEGER"); + + b.Property("EnrollmentId") + .HasColumnType("TEXT"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IpAddressesJson") + .HasColumnType("TEXT"); + + b.Property("IsOrphaned") + .HasColumnType("INTEGER"); + + b.Property("LastSeenUtc") + .HasColumnType("INTEGER"); + + b.Property("Manufacturer") + .HasColumnType("TEXT"); + + b.Property("Model") + .HasColumnType("TEXT"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OrphanedUtc") + .HasColumnType("INTEGER"); + + b.Property("OsCaption") + .HasColumnType("TEXT"); + + b.Property("OsVersion") + .HasColumnType("TEXT"); + + b.Property("PublicIp") + .HasColumnType("TEXT"); + + b.Property("ReadyUtc") + .HasColumnType("INTEGER"); + + b.Property("TagsJson") + .HasColumnType("TEXT"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ParentId") + .HasColumnType("TEXT"); + + b.Property("RulesJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AddedUtc") + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CompletedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExitCode") + .HasColumnType("INTEGER"); + + b.Property("OutputSummary") + .HasColumnType("TEXT"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("RunId") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("StartedUtc") + .HasColumnType("INTEGER"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("Sequence") + .HasColumnType("INTEGER"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Text") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("TEXT"); + + b.Property("IsSystem") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("TEXT"); + + b.Property("PermissionsJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("FileBindingsJson") + .HasColumnType("TEXT"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("TEXT"); + + b.Property("Language") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ParametersJson") + .HasColumnType("TEXT"); + + b.Property("SecretBindingsJson") + .HasColumnType("TEXT"); + + b.Property("SecretsVariableName") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ArgumentsJson") + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("CronExpression") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("LastResult") + .HasColumnType("TEXT"); + + b.Property("LastRunId") + .HasColumnType("TEXT"); + + b.Property("LastRunUtc") + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("NextRunUtc") + .HasColumnType("INTEGER"); + + b.Property("OncePerDevice") + .HasColumnType("INTEGER"); + + b.Property("RunOnceUtc") + .HasColumnType("INTEGER"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FiredUtc") + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("TriggerId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CloseReason") + .HasColumnType("TEXT"); + + b.Property("ClosedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("ExternalId") + .HasColumnType("TEXT"); + + b.Property("LastLoginUtc") + .HasColumnType("INTEGER"); + + b.Property("MustChangePassword") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("Role") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("Username") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20261023021502_AddTriggerConcurrencyStamp.cs b/src/Backend/Data/Migrations/Sqlite/20261023021502_AddTriggerConcurrencyStamp.cs new file mode 100644 index 0000000..bcb3cc8 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20261023021502_AddTriggerConcurrencyStamp.cs @@ -0,0 +1,30 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + /// + public partial class AddTriggerConcurrencyStamp : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "ConcurrencyStamp", + table: "ScriptTriggers", + type: "TEXT", + nullable: false, + defaultValue: new Guid("00000000-0000-0000-0000-000000000000")); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "ConcurrencyStamp", + table: "ScriptTriggers"); + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20261023031149_AddDeviceBootstrapToken.Designer.cs b/src/Backend/Data/Migrations/Sqlite/20261023031149_AddDeviceBootstrapToken.Designer.cs new file mode 100644 index 0000000..9a5b625 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20261023031149_AddDeviceBootstrapToken.Designer.cs @@ -0,0 +1,736 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + [DbContext(typeof(SqliteAppDbContext))] + [Migration("20261023031149_AddDeviceBootstrapToken")] + partial class AddDeviceBootstrapToken + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.10"); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("TEXT"); + + b.Property("IsSecret") + .HasColumnType("INTEGER"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasColumnType("TEXT"); + + b.Property("Category") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("Detail") + .HasColumnType("TEXT"); + + b.Property("RemoteIp") + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("MaxUses") + .HasColumnType("INTEGER"); + + b.Property("Note") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Uses") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("AgentVersion") + .HasColumnType("TEXT"); + + b.Property("BootstrapTokenId") + .HasColumnType("TEXT"); + + b.Property("EnrolledUtc") + .HasColumnType("INTEGER"); + + b.Property("EnrollmentId") + .HasColumnType("TEXT"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IpAddressesJson") + .HasColumnType("TEXT"); + + b.Property("IsOrphaned") + .HasColumnType("INTEGER"); + + b.Property("LastSeenUtc") + .HasColumnType("INTEGER"); + + b.Property("Manufacturer") + .HasColumnType("TEXT"); + + b.Property("Model") + .HasColumnType("TEXT"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OrphanedUtc") + .HasColumnType("INTEGER"); + + b.Property("OsCaption") + .HasColumnType("TEXT"); + + b.Property("OsVersion") + .HasColumnType("TEXT"); + + b.Property("PublicIp") + .HasColumnType("TEXT"); + + b.Property("ReadyUtc") + .HasColumnType("INTEGER"); + + b.Property("TagsJson") + .HasColumnType("TEXT"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ParentId") + .HasColumnType("TEXT"); + + b.Property("RulesJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AddedUtc") + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CompletedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExitCode") + .HasColumnType("INTEGER"); + + b.Property("OutputSummary") + .HasColumnType("TEXT"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("RunId") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("StartedUtc") + .HasColumnType("INTEGER"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("Sequence") + .HasColumnType("INTEGER"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Text") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("TEXT"); + + b.Property("IsSystem") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("TEXT"); + + b.Property("PermissionsJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("FileBindingsJson") + .HasColumnType("TEXT"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("TEXT"); + + b.Property("Language") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ParametersJson") + .HasColumnType("TEXT"); + + b.Property("SecretBindingsJson") + .HasColumnType("TEXT"); + + b.Property("SecretsVariableName") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ArgumentsJson") + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("CronExpression") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("LastResult") + .HasColumnType("TEXT"); + + b.Property("LastRunId") + .HasColumnType("TEXT"); + + b.Property("LastRunUtc") + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("NextRunUtc") + .HasColumnType("INTEGER"); + + b.Property("OncePerDevice") + .HasColumnType("INTEGER"); + + b.Property("RunOnceUtc") + .HasColumnType("INTEGER"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FiredUtc") + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("TriggerId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CloseReason") + .HasColumnType("TEXT"); + + b.Property("ClosedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("ExternalId") + .HasColumnType("TEXT"); + + b.Property("LastLoginUtc") + .HasColumnType("INTEGER"); + + b.Property("MustChangePassword") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("Role") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("Username") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20261023031149_AddDeviceBootstrapToken.cs b/src/Backend/Data/Migrations/Sqlite/20261023031149_AddDeviceBootstrapToken.cs new file mode 100644 index 0000000..b4840bf --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20261023031149_AddDeviceBootstrapToken.cs @@ -0,0 +1,29 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + /// + public partial class AddDeviceBootstrapToken : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "BootstrapTokenId", + table: "Devices", + type: "TEXT", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "BootstrapTokenId", + table: "Devices"); + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20261023123313_AddRuns.Designer.cs b/src/Backend/Data/Migrations/Sqlite/20261023123313_AddRuns.Designer.cs new file mode 100644 index 0000000..8bec681 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20261023123313_AddRuns.Designer.cs @@ -0,0 +1,786 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + [DbContext(typeof(SqliteAppDbContext))] + [Migration("20261023123313_AddRuns")] + partial class AddRuns + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.10"); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("TEXT"); + + b.Property("IsSecret") + .HasColumnType("INTEGER"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasColumnType("TEXT"); + + b.Property("Category") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("Detail") + .HasColumnType("TEXT"); + + b.Property("RemoteIp") + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("MaxUses") + .HasColumnType("INTEGER"); + + b.Property("Note") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Uses") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("AgentVersion") + .HasColumnType("TEXT"); + + b.Property("BootstrapTokenId") + .HasColumnType("TEXT"); + + b.Property("EnrolledUtc") + .HasColumnType("INTEGER"); + + b.Property("EnrollmentId") + .HasColumnType("TEXT"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IpAddressesJson") + .HasColumnType("TEXT"); + + b.Property("IsOrphaned") + .HasColumnType("INTEGER"); + + b.Property("LastSeenUtc") + .HasColumnType("INTEGER"); + + b.Property("Manufacturer") + .HasColumnType("TEXT"); + + b.Property("Model") + .HasColumnType("TEXT"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OrphanedUtc") + .HasColumnType("INTEGER"); + + b.Property("OsCaption") + .HasColumnType("TEXT"); + + b.Property("OsVersion") + .HasColumnType("TEXT"); + + b.Property("PublicIp") + .HasColumnType("TEXT"); + + b.Property("ReadyUtc") + .HasColumnType("INTEGER"); + + b.Property("TagsJson") + .HasColumnType("TEXT"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ParentId") + .HasColumnType("TEXT"); + + b.Property("RulesJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AddedUtc") + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CompletedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExitCode") + .HasColumnType("INTEGER"); + + b.Property("OutputSummary") + .HasColumnType("TEXT"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("RunId") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("StartedUtc") + .HasColumnType("INTEGER"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("RunId"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("Sequence") + .HasColumnType("INTEGER"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Text") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("TEXT"); + + b.Property("IsSystem") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("TEXT"); + + b.Property("PermissionsJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RunEntity", b => + { + b.Property("RunId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("OnlineOnly") + .HasColumnType("INTEGER"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("ScriptName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("SkippedJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("TargetsLabel") + .HasMaxLength(400) + .HasColumnType("TEXT"); + + b.Property("TriggerId") + .HasColumnType("TEXT"); + + b.HasKey("RunId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId"); + + b.ToTable("Runs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("FileBindingsJson") + .HasColumnType("TEXT"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("TEXT"); + + b.Property("Language") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ParametersJson") + .HasColumnType("TEXT"); + + b.Property("SecretBindingsJson") + .HasColumnType("TEXT"); + + b.Property("SecretsVariableName") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ArgumentsJson") + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("CronExpression") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("LastResult") + .HasColumnType("TEXT"); + + b.Property("LastRunId") + .HasColumnType("TEXT"); + + b.Property("LastRunUtc") + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("NextRunUtc") + .HasColumnType("INTEGER"); + + b.Property("OncePerDevice") + .HasColumnType("INTEGER"); + + b.Property("RunOnceUtc") + .HasColumnType("INTEGER"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FiredUtc") + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("TriggerId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CloseReason") + .HasColumnType("TEXT"); + + b.Property("ClosedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("ExternalId") + .HasColumnType("TEXT"); + + b.Property("LastLoginUtc") + .HasColumnType("INTEGER"); + + b.Property("MustChangePassword") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("Role") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("Username") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20261023123313_AddRuns.cs b/src/Backend/Data/Migrations/Sqlite/20261023123313_AddRuns.cs new file mode 100644 index 0000000..30c94f5 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20261023123313_AddRuns.cs @@ -0,0 +1,61 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + /// + public partial class AddRuns : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Runs", + columns: table => new + { + RunId = table.Column(type: "TEXT", nullable: false), + ScriptId = table.Column(type: "TEXT", nullable: false), + ScriptName = table.Column(type: "TEXT", maxLength: 200, nullable: false), + CreatedUtc = table.Column(type: "INTEGER", nullable: false), + RequestedBy = table.Column(type: "TEXT", nullable: true), + Source = table.Column(type: "TEXT", maxLength: 32, nullable: false), + TriggerId = table.Column(type: "TEXT", nullable: true), + TargetsLabel = table.Column(type: "TEXT", maxLength: 400, nullable: true), + OnlineOnly = table.Column(type: "INTEGER", nullable: false), + SkippedJson = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Runs", x => x.RunId); + }); + + migrationBuilder.CreateIndex( + name: "IX_Jobs_RunId", + table: "Jobs", + column: "RunId"); + + migrationBuilder.CreateIndex( + name: "IX_Runs_CreatedUtc", + table: "Runs", + column: "CreatedUtc"); + + migrationBuilder.CreateIndex( + name: "IX_Runs_ScriptId", + table: "Runs", + column: "ScriptId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Runs"); + + migrationBuilder.DropIndex( + name: "IX_Jobs_RunId", + table: "Jobs"); + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20261023131448_SignInMethods.Designer.cs b/src/Backend/Data/Migrations/Sqlite/20261023131448_SignInMethods.Designer.cs new file mode 100644 index 0000000..fcd56f8 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20261023131448_SignInMethods.Designer.cs @@ -0,0 +1,1060 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + [DbContext(typeof(SqliteAppDbContext))] + [Migration("20261023131448_SignInMethods")] + partial class SignInMethods + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.10"); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("TEXT"); + + b.Property("Etag") + .HasColumnType("TEXT"); + + b.Property("IsSecret") + .HasColumnType("INTEGER"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasColumnType("TEXT"); + + b.Property("Category") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("Detail") + .HasColumnType("TEXT"); + + b.Property("RemoteIp") + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("MaxUses") + .HasColumnType("INTEGER"); + + b.Property("Note") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Uses") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("AgentVersion") + .HasColumnType("TEXT"); + + b.Property("BootstrapTokenId") + .HasColumnType("TEXT"); + + b.Property("EnrolledUtc") + .HasColumnType("INTEGER"); + + b.Property("EnrollmentId") + .HasColumnType("TEXT"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IpAddressesJson") + .HasColumnType("TEXT"); + + b.Property("IsOrphaned") + .HasColumnType("INTEGER"); + + b.Property("LastSeenUtc") + .HasColumnType("INTEGER"); + + b.Property("Manufacturer") + .HasColumnType("TEXT"); + + b.Property("Model") + .HasColumnType("TEXT"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OrphanedUtc") + .HasColumnType("INTEGER"); + + b.Property("OsCaption") + .HasColumnType("TEXT"); + + b.Property("OsVersion") + .HasColumnType("TEXT"); + + b.Property("PublicIp") + .HasColumnType("TEXT"); + + b.Property("ReadyUtc") + .HasColumnType("INTEGER"); + + b.Property("TagsJson") + .HasColumnType("TEXT"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ParentId") + .HasColumnType("TEXT"); + + b.Property("RulesJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AddedUtc") + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CompletedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExitCode") + .HasColumnType("INTEGER"); + + b.Property("OutputSummary") + .HasColumnType("TEXT"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("RunId") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("StartedUtc") + .HasColumnType("INTEGER"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("RunId"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("Sequence") + .HasColumnType("INTEGER"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Text") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.LocalGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("LocalGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.LocalGroupMemberEntity", b => + { + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("GroupId", "UserId"); + + b.HasIndex("UserId"); + + b.ToTable("LocalGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleBindingEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("PrincipalName") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.HasIndex("PrincipalKind", "PrincipalId", "RoleId") + .IsUnique(); + + b.ToTable("RoleBindings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("TEXT"); + + b.Property("IsSystem") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("TEXT"); + + b.Property("PermissionsJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RunEntity", b => + { + b.Property("RunId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("OnlineOnly") + .HasColumnType("INTEGER"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("ScriptName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("SkippedJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("TargetsLabel") + .HasMaxLength(400) + .HasColumnType("TEXT"); + + b.Property("TriggerId") + .HasColumnType("TEXT"); + + b.HasKey("RunId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId"); + + b.ToTable("Runs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("FileBindingsJson") + .HasColumnType("TEXT"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("TEXT"); + + b.Property("Language") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ParametersJson") + .HasColumnType("TEXT"); + + b.Property("SecretBindingsJson") + .HasColumnType("TEXT"); + + b.Property("SecretsVariableName") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ArgumentsJson") + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("CronExpression") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("LastResult") + .HasColumnType("TEXT"); + + b.Property("LastRunId") + .HasColumnType("TEXT"); + + b.Property("LastRunUtc") + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("NextRunUtc") + .HasColumnType("INTEGER"); + + b.Property("OncePerDevice") + .HasColumnType("INTEGER"); + + b.Property("RunOnceUtc") + .HasColumnType("INTEGER"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FiredUtc") + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("TriggerId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SessionEntity", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("AbsoluteExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("ClientAddress") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("CsrfHash") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("GroupsJson") + .HasColumnType("TEXT"); + + b.Property("LastSeenUtc") + .HasColumnType("INTEGER"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("RevokedUtc") + .HasColumnType("INTEGER"); + + b.Property("SecretHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("UserAgent") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("AbsoluteExpiresUtc"); + + b.HasIndex("UserId"); + + b.ToTable("Sessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CloseReason") + .HasColumnType("TEXT"); + + b.Property("ClosedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SignInRequestEntity", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("CodeVerifier") + .HasColumnType("TEXT"); + + b.Property("CompletedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Detail") + .HasMaxLength(2000) + .HasColumnType("TEXT"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("Nonce") + .HasColumnType("TEXT"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ReturnUrl") + .HasColumnType("TEXT"); + + b.Property("SettingsEtag") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("StepUpSessionId") + .HasColumnType("TEXT"); + + b.Property("TestSessionId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresUtc"); + + b.HasIndex("TestSessionId"); + + b.ToTable("SignInRequests", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SignInThrottleEntity", b => + { + b.Property("Key") + .HasMaxLength(300) + .HasColumnType("TEXT"); + + b.Property("BlockedUntilUtc") + .HasColumnType("INTEGER"); + + b.Property("Failures") + .HasColumnType("INTEGER"); + + b.Property("FirstFailureUtc") + .HasColumnType("INTEGER"); + + b.Property("LastFailureUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.ToTable("SignInThrottles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.StepUpEntity", b => + { + b.Property("SessionId") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Method") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("VerifiedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("SessionId"); + + b.ToTable("StepUps", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("ExternalId") + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("IsBreakGlass") + .HasColumnType("INTEGER"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("LastSignInUtc") + .HasColumnType("INTEGER"); + + b.Property("LegacyRole") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("LegacyRoleId") + .HasColumnType("TEXT"); + + b.Property("MustChangePassword") + .HasColumnType("INTEGER"); + + b.Property("PasswordChangedUtc") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("WindowsGroupsJson") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Kind", "ExternalId"); + + b.HasIndex("Kind", "UserName") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.LocalGroupMemberEntity", b => + { + b.HasOne("Backend.Data.LocalGroupEntity", null) + .WithMany() + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Backend.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.RoleBindingEntity", b => + { + b.HasOne("Backend.Data.RoleEntity", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.SessionEntity", b => + { + b.HasOne("Backend.Data.UserEntity", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20261023131448_SignInMethods.cs b/src/Backend/Data/Migrations/Sqlite/20261023131448_SignInMethods.cs new file mode 100644 index 0000000..a5c5071 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20261023131448_SignInMethods.cs @@ -0,0 +1,327 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + /// + public partial class SignInMethods : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "OidcProviders"); + + migrationBuilder.DropIndex( + name: "IX_Users_Username", + table: "Users"); + + migrationBuilder.RenameColumn( + name: "Username", + table: "Users", + newName: "UserName"); + + migrationBuilder.AddColumn( + name: "Kind", + table: "Users", + type: "TEXT", + maxLength: 16, + nullable: false, + defaultValue: "local"); + + migrationBuilder.AddColumn( + name: "Description", + table: "Users", + type: "TEXT", + nullable: true); + + migrationBuilder.AddColumn( + name: "Email", + table: "Users", + type: "TEXT", + nullable: true); + + migrationBuilder.AddColumn( + name: "WindowsGroupsJson", + table: "Users", + type: "TEXT", + nullable: true); + + migrationBuilder.AddColumn( + name: "Enabled", + table: "Users", + type: "INTEGER", + nullable: false, + defaultValue: true); + + migrationBuilder.AddColumn( + name: "IsBreakGlass", + table: "Users", + type: "INTEGER", + nullable: false, + defaultValue: false); + + migrationBuilder.AddColumn( + name: "LegacyRole", + table: "Users", + type: "TEXT", + maxLength: 32, + nullable: true); + + migrationBuilder.AddColumn( + name: "LegacyRoleId", + table: "Users", + type: "TEXT", + nullable: true); + + migrationBuilder.AddColumn( + name: "LastSignInUtc", + table: "Users", + type: "INTEGER", + nullable: true); + + migrationBuilder.AddColumn( + name: "PasswordChangedUtc", + table: "Users", + type: "INTEGER", + nullable: true); + + migrationBuilder.AddColumn( + name: "UpdatedUtc", + table: "Users", + type: "INTEGER", + nullable: false, + defaultValue: 0L); + + // Carry the old columns over before they go: kind of account, the role (for the upgrade to groups), last sign-in. + migrationBuilder.Sql( + "UPDATE \"Users\" SET \"Kind\" = \"AuthProvider\", \"LegacyRole\" = \"Role\", \"LegacyRoleId\" = \"RoleId\", " + + "\"LastSignInUtc\" = \"LastLoginUtc\", \"UpdatedUtc\" = \"CreatedUtc\""); + + migrationBuilder.DropColumn( + name: "AuthProvider", + table: "Users"); + + migrationBuilder.DropColumn( + name: "Role", + table: "Users"); + + migrationBuilder.DropColumn( + name: "RoleId", + table: "Users"); + + migrationBuilder.DropColumn( + name: "LastLoginUtc", + table: "Users"); + + migrationBuilder.AddColumn( + name: "Etag", + table: "AppSettings", + type: "TEXT", + nullable: true); + + migrationBuilder.CreateTable( + name: "LocalGroups", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Name = table.Column(type: "TEXT", maxLength: 128, nullable: false), + Description = table.Column(type: "TEXT", nullable: true), + CreatedUtc = table.Column(type: "INTEGER", nullable: false), + UpdatedUtc = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_LocalGroups", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "RoleBindings", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + RoleId = table.Column(type: "TEXT", nullable: false), + PrincipalKind = table.Column(type: "TEXT", maxLength: 32, nullable: false), + PrincipalId = table.Column(type: "TEXT", maxLength: 450, nullable: false), + PrincipalName = table.Column(type: "TEXT", nullable: true), + CreatedUtc = table.Column(type: "INTEGER", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_RoleBindings", x => x.Id); + table.ForeignKey( + name: "FK_RoleBindings_Roles_RoleId", + column: x => x.RoleId, + principalTable: "Roles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "Sessions", + columns: table => new + { + Id = table.Column(type: "TEXT", maxLength: 64, nullable: false), + UserId = table.Column(type: "TEXT", nullable: false), + SecretHash = table.Column(type: "TEXT", maxLength: 128, nullable: false), + CsrfHash = table.Column(type: "TEXT", maxLength: 128, nullable: true), + Provider = table.Column(type: "TEXT", maxLength: 16, nullable: false), + GroupsJson = table.Column(type: "TEXT", nullable: true), + CreatedUtc = table.Column(type: "INTEGER", nullable: false), + LastSeenUtc = table.Column(type: "INTEGER", nullable: false), + ExpiresUtc = table.Column(type: "INTEGER", nullable: false), + AbsoluteExpiresUtc = table.Column(type: "INTEGER", nullable: false), + RevokedUtc = table.Column(type: "INTEGER", nullable: true), + ClientAddress = table.Column(type: "TEXT", nullable: true), + UserAgent = table.Column(type: "TEXT", maxLength: 512, nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Sessions", x => x.Id); + table.ForeignKey( + name: "FK_Sessions_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "SignInRequests", + columns: table => new + { + Id = table.Column(type: "TEXT", maxLength: 64, nullable: false), + Provider = table.Column(type: "TEXT", maxLength: 16, nullable: false), + Status = table.Column(type: "TEXT", maxLength: 16, nullable: false), + Nonce = table.Column(type: "TEXT", nullable: true), + CodeVerifier = table.Column(type: "TEXT", nullable: true), + ReturnUrl = table.Column(type: "TEXT", nullable: true), + TestSessionId = table.Column(type: "TEXT", nullable: true), + StepUpSessionId = table.Column(type: "TEXT", nullable: true), + SettingsEtag = table.Column(type: "TEXT", nullable: true), + Detail = table.Column(type: "TEXT", maxLength: 2000, nullable: true), + CreatedUtc = table.Column(type: "INTEGER", nullable: false), + ExpiresUtc = table.Column(type: "INTEGER", nullable: false), + CompletedUtc = table.Column(type: "INTEGER", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_SignInRequests", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "SignInThrottles", + columns: table => new + { + Key = table.Column(type: "TEXT", maxLength: 300, nullable: false), + Failures = table.Column(type: "INTEGER", nullable: false), + FirstFailureUtc = table.Column(type: "INTEGER", nullable: false), + LastFailureUtc = table.Column(type: "INTEGER", nullable: false), + BlockedUntilUtc = table.Column(type: "INTEGER", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_SignInThrottles", x => x.Key); + }); + + migrationBuilder.CreateTable( + name: "StepUps", + columns: table => new + { + SessionId = table.Column(type: "TEXT", maxLength: 64, nullable: false), + Method = table.Column(type: "TEXT", maxLength: 16, nullable: false), + VerifiedUtc = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_StepUps", x => x.SessionId); + }); + + migrationBuilder.CreateTable( + name: "LocalGroupMembers", + columns: table => new + { + GroupId = table.Column(type: "TEXT", nullable: false), + UserId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_LocalGroupMembers", x => new { x.GroupId, x.UserId }); + table.ForeignKey( + name: "FK_LocalGroupMembers_LocalGroups_GroupId", + column: x => x.GroupId, + principalTable: "LocalGroups", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_LocalGroupMembers_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Users_Kind_ExternalId", + table: "Users", + columns: new[] { "Kind", "ExternalId" }); + + migrationBuilder.CreateIndex( + name: "IX_Users_Kind_UserName", + table: "Users", + columns: new[] { "Kind", "UserName" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_LocalGroupMembers_UserId", + table: "LocalGroupMembers", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_LocalGroups_Name", + table: "LocalGroups", + column: "Name", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_RoleBindings_PrincipalKind_PrincipalId_RoleId", + table: "RoleBindings", + columns: new[] { "PrincipalKind", "PrincipalId", "RoleId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_RoleBindings_RoleId", + table: "RoleBindings", + column: "RoleId"); + + migrationBuilder.CreateIndex( + name: "IX_Sessions_AbsoluteExpiresUtc", + table: "Sessions", + column: "AbsoluteExpiresUtc"); + + migrationBuilder.CreateIndex( + name: "IX_Sessions_UserId", + table: "Sessions", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_SignInRequests_ExpiresUtc", + table: "SignInRequests", + column: "ExpiresUtc"); + + migrationBuilder.CreateIndex( + name: "IX_SignInRequests_TestSessionId", + table: "SignInRequests", + column: "TestSessionId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + throw new NotSupportedException("Sign-in methods and role bindings cannot be rolled back to per-user roles; restore a backup instead."); + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20261023212352_AgentUpgrades.Designer.cs b/src/Backend/Data/Migrations/Sqlite/20261023212352_AgentUpgrades.Designer.cs new file mode 100644 index 0000000..89a049f --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20261023212352_AgentUpgrades.Designer.cs @@ -0,0 +1,1201 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + [DbContext(typeof(SqliteAppDbContext))] + [Migration("20261023212352_AgentUpgrades")] + partial class AgentUpgrades + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.10"); + + modelBuilder.Entity("Backend.Data.AgentPackageEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ImportedUtc") + .HasColumnType("INTEGER"); + + b.Property("PackageType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("S3Key") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("SizeBytes") + .HasColumnType("INTEGER"); + + b.Property("StoragePath") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Sha256"); + + b.HasIndex("Version", "PackageType") + .IsUnique(); + + b.ToTable("AgentPackages", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AgentUpgradeEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Attempts") + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Detail") + .HasMaxLength(2000) + .HasColumnType("TEXT"); + + b.Property("FinishedUtc") + .HasColumnType("INTEGER"); + + b.Property("FromVersion") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("LastEventUtc") + .HasColumnType("INTEGER"); + + b.Property("LastLogJson") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .HasColumnType("TEXT"); + + b.Property("PackageType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Reason") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("RequestedBy") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("SentUtc") + .HasColumnType("INTEGER"); + + b.Property("Sha256") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("State") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("TargetVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("State"); + + b.HasIndex("ClientId", "State"); + + b.ToTable("AgentUpgrades", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("TEXT"); + + b.Property("Etag") + .HasColumnType("TEXT"); + + b.Property("IsSecret") + .HasColumnType("INTEGER"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasColumnType("TEXT"); + + b.Property("Category") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("Detail") + .HasColumnType("TEXT"); + + b.Property("RemoteIp") + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("MaxUses") + .HasColumnType("INTEGER"); + + b.Property("Note") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Uses") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("AgentRuntime") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("AgentVersion") + .HasColumnType("TEXT"); + + b.Property("BootstrapTokenId") + .HasColumnType("TEXT"); + + b.Property("EnrolledUtc") + .HasColumnType("INTEGER"); + + b.Property("EnrollmentId") + .HasColumnType("TEXT"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IpAddressesJson") + .HasColumnType("TEXT"); + + b.Property("IsOrphaned") + .HasColumnType("INTEGER"); + + b.Property("LastSeenUtc") + .HasColumnType("INTEGER"); + + b.Property("Manufacturer") + .HasColumnType("TEXT"); + + b.Property("Model") + .HasColumnType("TEXT"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OrphanedUtc") + .HasColumnType("INTEGER"); + + b.Property("OsCaption") + .HasColumnType("TEXT"); + + b.Property("OsVersion") + .HasColumnType("TEXT"); + + b.Property("PublicIp") + .HasColumnType("TEXT"); + + b.Property("ReadyUtc") + .HasColumnType("INTEGER"); + + b.Property("TagsJson") + .HasColumnType("TEXT"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ParentId") + .HasColumnType("TEXT"); + + b.Property("RulesJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AddedUtc") + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CompletedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExitCode") + .HasColumnType("INTEGER"); + + b.Property("OutputSummary") + .HasColumnType("TEXT"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("RunId") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("StartedUtc") + .HasColumnType("INTEGER"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("RunId"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("Sequence") + .HasColumnType("INTEGER"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Text") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.LocalGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("LocalGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.LocalGroupMemberEntity", b => + { + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("GroupId", "UserId"); + + b.HasIndex("UserId"); + + b.ToTable("LocalGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleBindingEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("PrincipalName") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.HasIndex("PrincipalKind", "PrincipalId", "RoleId") + .IsUnique(); + + b.ToTable("RoleBindings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("TEXT"); + + b.Property("IsSystem") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("TEXT"); + + b.Property("PermissionsJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RunEntity", b => + { + b.Property("RunId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("OnlineOnly") + .HasColumnType("INTEGER"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("ScriptName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("SkippedJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("TargetsLabel") + .HasMaxLength(400) + .HasColumnType("TEXT"); + + b.Property("TriggerId") + .HasColumnType("TEXT"); + + b.HasKey("RunId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId"); + + b.ToTable("Runs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("FileBindingsJson") + .HasColumnType("TEXT"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("TEXT"); + + b.Property("Language") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ParametersJson") + .HasColumnType("TEXT"); + + b.Property("SecretBindingsJson") + .HasColumnType("TEXT"); + + b.Property("SecretsVariableName") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ArgumentsJson") + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("CronExpression") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("LastResult") + .HasColumnType("TEXT"); + + b.Property("LastRunId") + .HasColumnType("TEXT"); + + b.Property("LastRunUtc") + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("NextRunUtc") + .HasColumnType("INTEGER"); + + b.Property("OncePerDevice") + .HasColumnType("INTEGER"); + + b.Property("RunOnceUtc") + .HasColumnType("INTEGER"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FiredUtc") + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("TriggerId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SessionEntity", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("AbsoluteExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("ClientAddress") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("CsrfHash") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("GroupsJson") + .HasColumnType("TEXT"); + + b.Property("LastSeenUtc") + .HasColumnType("INTEGER"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("RevokedUtc") + .HasColumnType("INTEGER"); + + b.Property("SecretHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("UserAgent") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("AbsoluteExpiresUtc"); + + b.HasIndex("UserId"); + + b.ToTable("Sessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CloseReason") + .HasColumnType("TEXT"); + + b.Property("ClosedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SignInRequestEntity", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("CodeVerifier") + .HasColumnType("TEXT"); + + b.Property("CompletedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Detail") + .HasMaxLength(2000) + .HasColumnType("TEXT"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("Nonce") + .HasColumnType("TEXT"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ReturnUrl") + .HasColumnType("TEXT"); + + b.Property("SettingsEtag") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("StepUpSessionId") + .HasColumnType("TEXT"); + + b.Property("TestSessionId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresUtc"); + + b.HasIndex("TestSessionId"); + + b.ToTable("SignInRequests", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SignInThrottleEntity", b => + { + b.Property("Key") + .HasMaxLength(300) + .HasColumnType("TEXT"); + + b.Property("BlockedUntilUtc") + .HasColumnType("INTEGER"); + + b.Property("Failures") + .HasColumnType("INTEGER"); + + b.Property("FirstFailureUtc") + .HasColumnType("INTEGER"); + + b.Property("LastFailureUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.ToTable("SignInThrottles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.StepUpEntity", b => + { + b.Property("SessionId") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Method") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("VerifiedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("SessionId"); + + b.ToTable("StepUps", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("ExternalId") + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("IsBreakGlass") + .HasColumnType("INTEGER"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("LastSignInUtc") + .HasColumnType("INTEGER"); + + b.Property("LegacyRole") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("LegacyRoleId") + .HasColumnType("TEXT"); + + b.Property("MustChangePassword") + .HasColumnType("INTEGER"); + + b.Property("PasswordChangedUtc") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("WindowsGroupsJson") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Kind", "ExternalId"); + + b.HasIndex("Kind", "UserName") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.LocalGroupMemberEntity", b => + { + b.HasOne("Backend.Data.LocalGroupEntity", null) + .WithMany() + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Backend.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.RoleBindingEntity", b => + { + b.HasOne("Backend.Data.RoleEntity", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.SessionEntity", b => + { + b.HasOne("Backend.Data.UserEntity", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20261023212352_AgentUpgrades.cs b/src/Backend/Data/Migrations/Sqlite/20261023212352_AgentUpgrades.cs new file mode 100644 index 0000000..9df7ad8 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20261023212352_AgentUpgrades.cs @@ -0,0 +1,110 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + /// + public partial class AgentUpgrades : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "AgentRuntime", + table: "Devices", + type: "TEXT", + maxLength: 32, + nullable: true); + + migrationBuilder.CreateTable( + name: "AgentPackages", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Version = table.Column(type: "TEXT", maxLength: 64, nullable: false), + PackageType = table.Column(type: "TEXT", maxLength: 32, nullable: false), + FileName = table.Column(type: "TEXT", maxLength: 128, nullable: false), + Sha256 = table.Column(type: "TEXT", maxLength: 64, nullable: false), + SizeBytes = table.Column(type: "INTEGER", nullable: false), + StoragePath = table.Column(type: "TEXT", maxLength: 512, nullable: false), + S3Key = table.Column(type: "TEXT", maxLength: 512, nullable: true), + ImportedUtc = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AgentPackages", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AgentUpgrades", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + ClientId = table.Column(type: "TEXT", nullable: false), + FromVersion = table.Column(type: "TEXT", maxLength: 64, nullable: true), + TargetVersion = table.Column(type: "TEXT", maxLength: 64, nullable: false), + PackageType = table.Column(type: "TEXT", maxLength: 32, nullable: false), + PackageId = table.Column(type: "TEXT", nullable: true), + Sha256 = table.Column(type: "TEXT", maxLength: 64, nullable: true), + Source = table.Column(type: "TEXT", maxLength: 16, nullable: false), + State = table.Column(type: "TEXT", maxLength: 16, nullable: false), + Reason = table.Column(type: "TEXT", maxLength: 32, nullable: true), + Detail = table.Column(type: "TEXT", maxLength: 2000, nullable: true), + LastLogJson = table.Column(type: "TEXT", nullable: true), + Attempts = table.Column(type: "INTEGER", nullable: false), + RequestedBy = table.Column(type: "TEXT", maxLength: 256, nullable: true), + CreatedUtc = table.Column(type: "INTEGER", nullable: false), + SentUtc = table.Column(type: "INTEGER", nullable: true), + LastEventUtc = table.Column(type: "INTEGER", nullable: true), + FinishedUtc = table.Column(type: "INTEGER", nullable: true), + ConcurrencyStamp = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AgentUpgrades", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_AgentPackages_Sha256", + table: "AgentPackages", + column: "Sha256"); + + migrationBuilder.CreateIndex( + name: "IX_AgentPackages_Version_PackageType", + table: "AgentPackages", + columns: new[] { "Version", "PackageType" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_AgentUpgrades_ClientId_State", + table: "AgentUpgrades", + columns: new[] { "ClientId", "State" }); + + migrationBuilder.CreateIndex( + name: "IX_AgentUpgrades_CreatedUtc", + table: "AgentUpgrades", + column: "CreatedUtc"); + + migrationBuilder.CreateIndex( + name: "IX_AgentUpgrades_State", + table: "AgentUpgrades", + column: "State"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AgentPackages"); + + migrationBuilder.DropTable( + name: "AgentUpgrades"); + + migrationBuilder.DropColumn( + name: "AgentRuntime", + table: "Devices"); + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/SqliteAppDbContextModelSnapshot.cs b/src/Backend/Data/Migrations/Sqlite/SqliteAppDbContextModelSnapshot.cs index 089c2dc..bbdc222 100644 --- a/src/Backend/Data/Migrations/Sqlite/SqliteAppDbContextModelSnapshot.cs +++ b/src/Backend/Data/Migrations/Sqlite/SqliteAppDbContextModelSnapshot.cs @@ -17,11 +17,151 @@ namespace Backend.Data.Migrations.Sqlite #pragma warning disable 612, 618 modelBuilder.HasAnnotation("ProductVersion", "10.0.10"); + modelBuilder.Entity("Backend.Data.AgentPackageEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ImportedUtc") + .HasColumnType("INTEGER"); + + b.Property("PackageType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("S3Key") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("SizeBytes") + .HasColumnType("INTEGER"); + + b.Property("StoragePath") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Sha256"); + + b.HasIndex("Version", "PackageType") + .IsUnique(); + + b.ToTable("AgentPackages", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AgentUpgradeEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Attempts") + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Detail") + .HasMaxLength(2000) + .HasColumnType("TEXT"); + + b.Property("FinishedUtc") + .HasColumnType("INTEGER"); + + b.Property("FromVersion") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("LastEventUtc") + .HasColumnType("INTEGER"); + + b.Property("LastLogJson") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .HasColumnType("TEXT"); + + b.Property("PackageType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Reason") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("RequestedBy") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("SentUtc") + .HasColumnType("INTEGER"); + + b.Property("Sha256") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("State") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("TargetVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("State"); + + b.HasIndex("ClientId", "State"); + + b.ToTable("AgentUpgrades", (string)null); + }); + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => { b.Property("Key") .HasColumnType("TEXT"); + b.Property("Etag") + .HasColumnType("TEXT"); + b.Property("IsSecret") .HasColumnType("INTEGER"); @@ -119,9 +259,16 @@ namespace Backend.Data.Migrations.Sqlite b.Property("ClientId") .HasColumnType("TEXT"); + b.Property("AgentRuntime") + .HasMaxLength(32) + .HasColumnType("TEXT"); + b.Property("AgentVersion") .HasColumnType("TEXT"); + b.Property("BootstrapTokenId") + .HasColumnType("TEXT"); + b.Property("EnrolledUtc") .HasColumnType("INTEGER"); @@ -196,6 +343,9 @@ namespace Backend.Data.Migrations.Sqlite .IsRequired() .HasColumnType("TEXT"); + b.Property("ParentId") + .HasColumnType("TEXT"); + b.Property("RulesJson") .HasColumnType("TEXT"); @@ -335,6 +485,8 @@ namespace Backend.Data.Migrations.Sqlite b.HasIndex("CreatedUtc"); + b.HasIndex("RunId"); + b.HasIndex("ScriptId", "RunId"); b.ToTable("Jobs", (string)null); @@ -371,30 +523,85 @@ namespace Backend.Data.Migrations.Sqlite b.ToTable("JobOutput", (string)null); }); - modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + modelBuilder.Entity("Backend.Data.LocalGroupEntity", b => { b.Property("Id") .ValueGeneratedOnAdd() .HasColumnType("TEXT"); - b.Property("Authority") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("ClientId") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("Enabled") + b.Property("CreatedUtc") .HasColumnType("INTEGER"); + b.Property("Description") + .HasColumnType("TEXT"); + b.Property("Name") .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("LocalGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.LocalGroupMemberEntity", b => + { + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("GroupId", "UserId"); + + b.HasIndex("UserId"); + + b.ToTable("LocalGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleBindingEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("PrincipalKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("PrincipalName") + .HasColumnType("TEXT"); + + b.Property("RoleId") .HasColumnType("TEXT"); b.HasKey("Id"); - b.ToTable("OidcProviders", (string)null); + b.HasIndex("RoleId"); + + b.HasIndex("PrincipalKind", "PrincipalId", "RoleId") + .IsUnique(); + + b.ToTable("RoleBindings", (string)null); }); modelBuilder.Entity("Backend.Data.RoleEntity", b => @@ -439,6 +646,54 @@ namespace Backend.Data.Migrations.Sqlite b.ToTable("Roles", (string)null); }); + modelBuilder.Entity("Backend.Data.RunEntity", b => + { + b.Property("RunId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("OnlineOnly") + .HasColumnType("INTEGER"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("ScriptName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("SkippedJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("TargetsLabel") + .HasMaxLength(400) + .HasColumnType("TEXT"); + + b.Property("TriggerId") + .HasColumnType("TEXT"); + + b.HasKey("RunId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId"); + + b.ToTable("Runs", (string)null); + }); + modelBuilder.Entity("Backend.Data.ScriptEntity", b => { b.Property("Id") @@ -506,6 +761,10 @@ namespace Backend.Data.Migrations.Sqlite b.Property("ClientId") .HasColumnType("TEXT"); + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + b.Property("CreatedBy") .HasColumnType("TEXT"); @@ -524,9 +783,15 @@ namespace Backend.Data.Migrations.Sqlite b.Property("LastResult") .HasColumnType("TEXT"); + b.Property("LastRunId") + .HasColumnType("TEXT"); + b.Property("LastRunUtc") .HasColumnType("INTEGER"); + b.Property("Name") + .HasColumnType("TEXT"); + b.Property("NextRunUtc") .HasColumnType("INTEGER"); @@ -618,6 +883,63 @@ namespace Backend.Data.Migrations.Sqlite b.ToTable("SecretsProviders", (string)null); }); + modelBuilder.Entity("Backend.Data.SessionEntity", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("AbsoluteExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("ClientAddress") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("CsrfHash") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("GroupsJson") + .HasColumnType("TEXT"); + + b.Property("LastSeenUtc") + .HasColumnType("INTEGER"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("RevokedUtc") + .HasColumnType("INTEGER"); + + b.Property("SecretHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("UserAgent") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("AbsoluteExpiresUtc"); + + b.HasIndex("UserId"); + + b.ToTable("Sessions", (string)null); + }); + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => { b.Property("Id") @@ -651,48 +973,172 @@ namespace Backend.Data.Migrations.Sqlite b.ToTable("ShellSessions", (string)null); }); + modelBuilder.Entity("Backend.Data.SignInRequestEntity", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("CodeVerifier") + .HasColumnType("TEXT"); + + b.Property("CompletedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Detail") + .HasMaxLength(2000) + .HasColumnType("TEXT"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("Nonce") + .HasColumnType("TEXT"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ReturnUrl") + .HasColumnType("TEXT"); + + b.Property("SettingsEtag") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("StepUpSessionId") + .HasColumnType("TEXT"); + + b.Property("TestSessionId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresUtc"); + + b.HasIndex("TestSessionId"); + + b.ToTable("SignInRequests", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SignInThrottleEntity", b => + { + b.Property("Key") + .HasMaxLength(300) + .HasColumnType("TEXT"); + + b.Property("BlockedUntilUtc") + .HasColumnType("INTEGER"); + + b.Property("Failures") + .HasColumnType("INTEGER"); + + b.Property("FirstFailureUtc") + .HasColumnType("INTEGER"); + + b.Property("LastFailureUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.ToTable("SignInThrottles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.StepUpEntity", b => + { + b.Property("SessionId") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Method") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("VerifiedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("SessionId"); + + b.ToTable("StepUps", (string)null); + }); + modelBuilder.Entity("Backend.Data.UserEntity", b => { b.Property("Id") .ValueGeneratedOnAdd() .HasColumnType("TEXT"); - b.Property("AuthProvider") - .IsRequired() - .HasColumnType("TEXT"); - b.Property("CreatedUtc") .HasColumnType("INTEGER"); + b.Property("Description") + .HasColumnType("TEXT"); + b.Property("DisplayName") .HasColumnType("TEXT"); - b.Property("ExternalId") + b.Property("Email") .HasColumnType("TEXT"); - b.Property("LastLoginUtc") + b.Property("Enabled") .HasColumnType("INTEGER"); + b.Property("ExternalId") + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.Property("IsBreakGlass") + .HasColumnType("INTEGER"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("LastSignInUtc") + .HasColumnType("INTEGER"); + + b.Property("LegacyRole") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("LegacyRoleId") + .HasColumnType("TEXT"); + b.Property("MustChangePassword") .HasColumnType("INTEGER"); + b.Property("PasswordChangedUtc") + .HasColumnType("INTEGER"); + b.Property("PasswordHash") .HasColumnType("TEXT"); - b.Property("Role") + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.Property("UserName") .IsRequired() + .HasMaxLength(256) .HasColumnType("TEXT"); - b.Property("RoleId") - .HasColumnType("TEXT"); - - b.Property("Username") - .IsRequired() + b.Property("WindowsGroupsJson") .HasColumnType("TEXT"); b.HasKey("Id"); - b.HasIndex("Username") + b.HasIndex("Kind", "ExternalId"); + + b.HasIndex("Kind", "UserName") .IsUnique(); b.ToTable("Users", (string)null); @@ -707,6 +1153,41 @@ namespace Backend.Data.Migrations.Sqlite .IsRequired(); }); + modelBuilder.Entity("Backend.Data.LocalGroupMemberEntity", b => + { + b.HasOne("Backend.Data.LocalGroupEntity", null) + .WithMany() + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Backend.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.RoleBindingEntity", b => + { + b.HasOne("Backend.Data.RoleEntity", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.SessionEntity", b => + { + b.HasOne("Backend.Data.UserEntity", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + modelBuilder.Entity("Backend.Data.DeviceEntity", b => { b.Navigation("Inventory"); diff --git a/src/Backend/Enrollment/EnrollmentEndpoints.cs b/src/Backend/Enrollment/EnrollmentEndpoints.cs index a8f6b86..152e230 100644 --- a/src/Backend/Enrollment/EnrollmentEndpoints.cs +++ b/src/Backend/Enrollment/EnrollmentEndpoints.cs @@ -70,9 +70,16 @@ public static class EnrollmentEndpoints var now = DateTimeOffset.UtcNow; var token = await db.BootstrapTokens.SingleOrDefaultAsync(t => t.TokenHash == tokenHash, cancellationToken); + var device = await db.Devices.SingleOrDefaultAsync(d => d.ClientId == request.ClientId, cancellationToken); + + // The same install run again on the same machine (rapid redeploy, + // repair, reimage) re-enrolls with the token that enrolled it without + // spending another use; any other device needs a use left. + var repeat = token is not null && device?.BootstrapTokenId == token.Id; + // MaxUses 0 = unlimited (expiry and revocation still gate it). if (token is null || token.Revoked || token.ExpiresUtc <= now - || (token.MaxUses > 0 && token.Uses >= token.MaxUses)) + || (!repeat && token.MaxUses > 0 && token.Uses >= token.MaxUses)) { await audit.LogAsync(AuditCategories.Enrollment, "bootstrap-rejected", clientId: request.ClientId, detail: "invalid, expired or consumed token", remoteIp: remoteIp, @@ -82,7 +89,6 @@ public static class EnrollmentEndpoints } // Idempotent enrollment by client id: re-enrollment rebinds the NKey. - var device = await db.Devices.SingleOrDefaultAsync(d => d.ClientId == request.ClientId, cancellationToken); var enrollmentId = Guid.NewGuid(); if (device is null) @@ -112,22 +118,40 @@ public static class EnrollmentEndpoints device.IsOrphaned = false; device.OrphanedUtc = null; - device.Hostname = request.Device.Hostname; + // Same hardware, new phase (Windows PE → installed OS, renamed on the + // way): one device row, with the transition kept in its history. + var newPhase = Api.DeviceHistory.Apply(db, device, request.Device.Hostname, + reportsOs: true, request.Device.OsCaption, request.Device.OsVersion); + Api.DeviceHistory.RecordEnrolled(db, device); + if (newPhase) + { + // The stored inventory describes the previous phase (Windows PE); + // drop it so group rules — and the on-enrollment triggers scoped + // to them — see the OS just enrolled until fresh inventory lands. + var stale = await db.DeviceInventory.SingleOrDefaultAsync(i => i.ClientId == request.ClientId, cancellationToken); + if (stale is not null) + { + db.DeviceInventory.Remove(stale); + } + } device.Manufacturer = request.Device.Manufacturer; device.Model = request.Device.Model; - device.OsCaption = request.Device.OsCaption; - device.OsVersion = request.Device.OsVersion; device.AgentVersion = request.AgentVersion; device.PublicIp = remoteIp; - token.Uses++; + if (!repeat) + { + token.Uses++; + } + + device.BootstrapTokenId = token.Id; var userJwt = issuer.IssueAgentCredential(request.ClientId, request.NkeyPublic); await db.SaveChangesAsync(cancellationToken); await audit.LogAsync(AuditCategories.Enrollment, "bootstrap-succeeded", clientId: request.ClientId, - detail: $"hostname={request.Device.Hostname} agentVersion={request.AgentVersion}", + detail: $"hostname={request.Device.Hostname} os=\"{Api.DeviceHistory.Describe(request.Device.OsCaption, request.Device.OsVersion)}\" agentVersion={request.AgentVersion} token={token.Id:D}{(repeat ? " (same install again; no use spent)" : string.Empty)}", remoteIp: remoteIp, cancellationToken: cancellationToken); diff --git a/src/Backend/Enrollment/InstallEndpoints.cs b/src/Backend/Enrollment/InstallEndpoints.cs index 93fb164..15dcb60 100644 --- a/src/Backend/Enrollment/InstallEndpoints.cs +++ b/src/Backend/Enrollment/InstallEndpoints.cs @@ -71,13 +71,16 @@ public static class InstallEndpoints // valid token is itself the enrollment gate. The Windows scripts run in // place — the operator launches them from an elevated PowerShell (the Add // device modal says so). There is no auto-elevation: the self-relaunch - // tripped AV/EDR ClickFix heuristics (Win32/ClickFix). + // tripped AV/EDR ClickFix heuristics (Win32/ClickFix). Both Windows + // scripts also work in Windows PE: there the MSI script switches to the + // portable package (Windows Installer does not run in WinPE). + var zipUrl = $"{baseUrl}{ApiRoutes.AgentPackage}?type=zip"; var script = type?.ToLowerInvariant() switch { "linux" => BuildUnixScript(baseUrl, token!, "linux", skipDownloadVerify), "osx" or "mac" or "macos" or "darwin" => BuildUnixScript(baseUrl, token!, "osx", skipDownloadVerify), - "zip" => BuildZipScript(baseUrl, token!, $"{baseUrl}{ApiRoutes.AgentPackage}?type=zip", skipDownloadVerify), - _ => BuildMsiScript(baseUrl, token!, $"{baseUrl}{ApiRoutes.AgentPackage}?type=msi", skipDownloadVerify), + "zip" => BuildZipScript(baseUrl, token!, zipUrl, skipDownloadVerify), + _ => BuildMsiScript(baseUrl, token!, $"{baseUrl}{ApiRoutes.AgentPackage}?type=msi", zipUrl, skipDownloadVerify), }; return Results.Text(script, "text/plain; charset=utf-8"); @@ -137,28 +140,82 @@ public static class InstallEndpoints // The install runs in place: no auto-elevation (the self-relaunch tripped // AV/EDR ClickFix heuristics), no -EncodedCommand. The operator runs it from // an elevated PowerShell — the Add device modal states this prerequisite. - private static string BuildMsiScript(string baseUrl, string token, string packageUrl, bool skipDownloadVerify) => $$""" + // Windows PE (the MiniNT key) has no Windows Installer, so there the MSI + // script takes the portable path instead — same service, same enrollment. + private static string BuildMsiScript( + string baseUrl, string token, string packageUrl, string zipUrl, bool skipDownloadVerify) => $$""" $ErrorActionPreference = 'Stop' - Write-Host 'Installing ExecuteR Agent...' {{PsDownloadTls}} {{(skipDownloadVerify ? PsAcceptCert : "")}} $server = '{{baseUrl}}' $token = '{{token}}' - $msi = Join-Path $env:TEMP ('ExecuteRAgent-' + [guid]::NewGuid().ToString('N') + '.msi') - try { - $wc = New-Object System.Net.WebClient - $wc.DownloadFile('{{packageUrl}}', $msi) - $wc.Dispose() - $arguments = @('/i', ('"' + $msi + '"'), '/qn', "SERVERURL=$server", "BOOTSTRAPTOKEN=$token") - $p = Start-Process msiexec.exe -ArgumentList $arguments -Wait -PassThru - if ($p.ExitCode -ne 0) { throw "msiexec exited with $($p.ExitCode)" } - Write-Host 'ExecuteR Agent installed. It will enroll and start automatically.' + if (Test-Path '{{PsWinPeKey}}') { + Write-Host 'Windows PE detected: installing ExecuteR Agent (portable)...' + {{PortableInstall(zipUrl)}} } - finally { - Remove-Item $msi -ErrorAction SilentlyContinue + else { + Write-Host 'Installing ExecuteR Agent...' + $msi = Join-Path $env:TEMP ('ExecuteRAgent-' + [guid]::NewGuid().ToString('N') + '.msi') + try { + $wc = New-Object System.Net.WebClient + $wc.DownloadFile('{{packageUrl}}', $msi) + $wc.Dispose() + $arguments = @('/i', ('"' + $msi + '"'), '/qn', "SERVERURL=$server", "BOOTSTRAPTOKEN=$token") + $p = Start-Process msiexec.exe -ArgumentList $arguments -Wait -PassThru + if ($p.ExitCode -ne 0) { throw "msiexec exited with $($p.ExitCode)" } + Write-Host 'ExecuteR Agent installed. It will enroll and start automatically.' + } + finally { + Remove-Item $msi -ErrorAction SilentlyContinue + } } """; + private const string PsWinPeKey = @"HKLM:\SYSTEM\CurrentControlSet\Control\MiniNT"; + + /// + /// The portable install body (expects $server/$token): unpack + /// the zip under Program Files (X:\ in Windows PE), seed enrollment, then + /// register and start the Windows service through the agent's own + /// initialize (Service Control Manager APIs, never sc.exe). Unzips + /// with System.IO.Compression rather than Expand-Archive, which a minimal + /// PowerShell (Windows PE) may lack; a re-run stops the running agent first + /// so its files can be replaced. ExtractToDirectory creates missing + /// parent folders. + /// + private static string PortableInstall(string packageUrl) => $$""" + $dest = Join-Path $env:ProgramFiles 'ExecuteR\Agent' + $exe = Join-Path $dest 'ExecuteR-Agent.exe' + $zip = Join-Path $env:TEMP ('ExecuteRAgent-' + [guid]::NewGuid().ToString('N') + '.zip') + $unpacked = $zip + '.d' + try { + $wc = New-Object System.Net.WebClient + $wc.DownloadFile('{{packageUrl}}', $zip) + $wc.Dispose() + Add-Type -AssemblyName System.IO.Compression.FileSystem + if (Test-Path $dest) { + [System.IO.Compression.ZipFile]::ExtractToDirectory($zip, $unpacked) + if (Test-Path $exe) { try { & $exe stop | Out-Null } catch { } } + Copy-Item -Path (Join-Path $unpacked '*') -Destination $dest -Recurse -Force + } + else { + # First install: unpack in place (Windows PE's RAM drive is small). + [System.IO.Compression.ZipFile]::ExtractToDirectory($zip, $dest) + } + # Seed configuration then install + start the service via the agent's own APIs. + New-Item -Path 'HKLM:\SOFTWARE\ExecuteR' -Force | Out-Null + Set-ItemProperty -Path 'HKLM:\SOFTWARE\ExecuteR' -Name 'ServerURL' -Value $server + Set-ItemProperty -Path 'HKLM:\SOFTWARE\ExecuteR' -Name 'BootstrapToken' -Value $token + & $exe initialize + if ($LASTEXITCODE -ne 0) { throw "ExecuteR-Agent initialize exited with $LASTEXITCODE" } + Write-Host 'ExecuteR Agent installed and starting.' + } + finally { + Remove-Item $zip -ErrorAction SilentlyContinue + Remove-Item $unpacked -Recurse -Force -ErrorAction SilentlyContinue + } + """; + /// /// linux/macOS installer: detects the architecture, downloads the matching /// agent zip, unpacks to /opt/executer/agent, configures enrollment via @@ -203,24 +260,6 @@ public static class InstallEndpoints {{(skipDownloadVerify ? PsAcceptCert : "")}} $server = '{{baseUrl}}' $token = '{{token}}' - $dest = Join-Path $env:ProgramFiles 'ExecuteR\Agent' - $zip = Join-Path $env:TEMP ('ExecuteRAgent-' + [guid]::NewGuid().ToString('N') + '.zip') - try { - $wc = New-Object System.Net.WebClient - $wc.DownloadFile('{{packageUrl}}', $zip) - $wc.Dispose() - New-Item -ItemType Directory -Force -Path $dest | Out-Null - Expand-Archive -Path $zip -DestinationPath $dest -Force - $exe = Join-Path $dest 'ExecuteR-Agent.exe' - # Seed configuration then install + start the service via the agent's own APIs. - New-Item -Path 'HKLM:\SOFTWARE\ExecuteR' -Force | Out-Null - Set-ItemProperty -Path 'HKLM:\SOFTWARE\ExecuteR' -Name 'ServerURL' -Value $server - Set-ItemProperty -Path 'HKLM:\SOFTWARE\ExecuteR' -Name 'BootstrapToken' -Value $token - & $exe initialize - Write-Host 'ExecuteR Agent installed and starting.' - } - finally { - Remove-Item $zip -ErrorAction SilentlyContinue - } + {{PortableInstall(packageUrl)}} """; } diff --git a/src/Backend/Files/AgentPackageService.cs b/src/Backend/Files/AgentPackageService.cs index eb90527..c236379 100644 --- a/src/Backend/Files/AgentPackageService.cs +++ b/src/Backend/Files/AgentPackageService.cs @@ -106,8 +106,24 @@ public sealed class AgentPackageService( ? "image" : "volume"; + /// + /// The upgradable packages visible right now (portable zip and the Unix + /// builds, not the MSI), each with the version from its VERSION marker: + /// what the agent catalog imports. + /// + public IEnumerable<(string PackageType, string Path, string? Version)> LocateUpgradePackages() + { + foreach (var packageType in Shared.Contracts.Models.AgentPackageTypes.Upgradable) + { + if (ResolveLocalPath(packageType) is { } path) + { + yield return (packageType, path, ReadVersionMarker(System.IO.Path.GetDirectoryName(path))); + } + } + } + /// CI writes a VERSION file beside the package. - private static string? ReadVersionMarker(string? directory) + public static string? ReadVersionMarker(string? directory) { if (directory is null) { @@ -192,6 +208,88 @@ public sealed class AgentPackageService( } } + /// + /// Uploads one agent catalog package under the same content-addressed key + /// layout as the install package (skipped when the object already exists). + /// The object key, or null when S3 is unusable or the upload failed. + /// + public async Task UploadCatalogPackageAsync( + string path, string fileName, string sha256, CancellationToken cancellationToken) + { + var options = await s3Settings.GetEffectiveAsync(cancellationToken); + if (!options.IsUsable) + { + return null; + } + + var objectKey = $"executer/agent/{sha256[..12]}/{fileName}"; + using var client = S3ClientFactory.Create(options); + try + { + try + { + var head = await client.GetObjectMetadataAsync(options.Bucket, objectKey, cancellationToken); + if (head.HttpStatusCode == System.Net.HttpStatusCode.OK) + { + return objectKey; + } + } + catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound) + { + // Expected on first upload. + } + + await client.PutObjectAsync(new PutObjectRequest + { + BucketName = options.Bucket, + Key = objectKey, + FilePath = path, + }, cancellationToken); + logger.LogInformation("Agent catalog package {File} uploaded to S3 as {Key}", fileName, objectKey); + return objectKey; + } + catch (Exception ex) + { + logger.LogWarning(ex, "Agent catalog package upload to S3 failed ({Key})", objectKey); + return null; + } + } + + /// + /// Presigned GET for an offloaded object, or null when offload is off or + /// S3 is unusable (the caller then serves the package itself). + /// + public async Task TryPresignOffloadedAsync(string objectKey, CancellationToken cancellationToken) + { + if (!await s3Settings.GetAgentOffloadEnabledAsync(cancellationToken)) + { + return null; + } + + var options = await s3Settings.GetEffectiveAsync(cancellationToken); + if (!options.IsUsable) + { + return null; + } + + try + { + using var client = S3ClientFactory.Create(options); + return client.GetPreSignedURL(new GetPreSignedUrlRequest + { + BucketName = options.Bucket, + Key = objectKey, + Verb = HttpVerb.GET, + Expires = DateTime.UtcNow.AddSeconds(options.PresignExpirySeconds), + }); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Presigning offloaded object {Key} failed; falling back to local delivery", objectKey); + return null; + } + } + /// /// Presigned URL for the offloaded package, or null when offload is off or /// nothing has been uploaded yet. diff --git a/src/Backend/Groups/DeviceGroupService.cs b/src/Backend/Groups/DeviceGroupService.cs index f8a9754..fb6f19f 100644 --- a/src/Backend/Groups/DeviceGroupService.cs +++ b/src/Backend/Groups/DeviceGroupService.cs @@ -11,13 +11,20 @@ namespace Backend.Groups; /// /// Resolves group membership. Static groups use the explicit member table; /// dynamic groups evaluate their rules against each device's field bag -/// (inventory + tags + status + identity). Inventory parsing goes through +/// (inventory + tags + status + identity); folders have no devices of their +/// own. Groups nest, and a group's effective membership also includes every +/// group nested under it. Inventory parsing goes through /// , so fleet-wide evaluation stays cheap at /// thousands of devices: snapshots are re-fetched and re-parsed only when /// their UpdatedUtc moved. /// public sealed class DeviceGroupService(AppDbContext db, InventoryReportCache inventoryCache) { + /// Deepest nesting allowed; keeps the tree navigable and evaluation bounded. + public const int MaxDepth = 8; + + private GroupMembership? membership; + /// Builds the rule field bag for one device. public static DeviceFieldBag BuildFields(DeviceEntity device, InventoryReport? inventory, DateTimeOffset now) => DeviceFieldBag.Build( @@ -118,24 +125,88 @@ public sealed class DeviceGroupService(AppDbContext db, InventoryReportCache inv } } - /// Client ids belonging to a group. + /// + /// Every group's direct and effective membership, evaluated once per + /// request (this service is scoped): one read of groups, static members, + /// devices and — only when a dynamic group exists — inventory. + /// + public async Task GetMembershipAsync(CancellationToken cancellationToken) + { + if (membership is not null) + { + return membership; + } + + var groups = await db.DeviceGroups.AsNoTracking().ToListAsync(cancellationToken); + var staticRows = await db.DeviceGroupMembers.AsNoTracking() + .Select(m => new { m.GroupId, m.ClientId }) + .ToListAsync(cancellationToken); + var devices = await db.Devices.AsNoTracking().ToListAsync(cancellationToken); + var known = devices.Select(d => d.ClientId).ToHashSet(StringComparer.Ordinal); + + var direct = groups.ToDictionary(g => g.Id, _ => new HashSet(StringComparer.Ordinal)); + var staticIds = groups.Where(g => g.Kind == GroupKind.Static).Select(g => g.Id).ToHashSet(); + foreach (var row in staticRows) + { + // Rows for deleted devices or non-static groups are ignored. + if (known.Contains(row.ClientId) && staticIds.Contains(row.GroupId)) + { + direct[row.GroupId].Add(row.ClientId); + } + } + + var dynamicGroups = groups + .Where(g => g.Kind == GroupKind.Dynamic) + .Select(g => (g.Id, Rules: ParseRules(g.RulesJson))) + .Where(g => g.Rules is not null) + .ToList(); + if (dynamicGroups.Count > 0) + { + var inventory = await GetAllInventoryAsync(cancellationToken); + var now = DateTimeOffset.UtcNow; + foreach (var device in devices) + { + var fields = BuildFields(device, inventory.GetValueOrDefault(device.ClientId), now); + foreach (var (id, rules) in dynamicGroups) + { + if (RuleEvaluator.Matches(rules!, fields)) + { + direct[id].Add(device.ClientId); + } + } + } + } + + return membership = new GroupMembership(groups, direct); + } + + /// Client ids belonging to a group, including its nested groups. public async Task> GetMembersAsync(DeviceGroupEntity group, CancellationToken cancellationToken) { - if (group.Kind == GroupKind.Static) + // Common case first: a leaf group needs no fleet-wide snapshot. + if (membership is null && !await db.DeviceGroups.AnyAsync(g => g.ParentId == group.Id, cancellationToken)) { - return await db.DeviceGroupMembers.AsNoTracking() - .Where(m => m.GroupId == group.Id) - .Select(m => m.ClientId) - .ToListAsync(cancellationToken); + return await GetDirectMembersAsync(group, cancellationToken); } - var rules = ParseRules(group.RulesJson); - if (rules is null) - { - return []; - } + return (await GetMembershipAsync(cancellationToken)).Effective(group.Id).ToList(); + } - return await EvaluateAsync(rules, cancellationToken); + private async Task> GetDirectMembersAsync( + DeviceGroupEntity group, CancellationToken cancellationToken) + { + switch (group.Kind) + { + case GroupKind.Static: + return await db.DeviceGroupMembers.AsNoTracking() + .Where(m => m.GroupId == group.Id && db.Devices.Any(d => d.ClientId == m.ClientId)) + .Select(m => m.ClientId) + .ToListAsync(cancellationToken); + case GroupKind.Dynamic when ParseRules(group.RulesJson) is { } rules: + return await EvaluateAsync(rules, cancellationToken); + default: + return []; + } } /// Evaluates a rule set against every enrolled device. @@ -152,7 +223,10 @@ public sealed class DeviceGroupService(AppDbContext db, InventoryReportCache inv .ToList(); } - /// Groups (static and dynamic) that a single device currently belongs to. + /// + /// Groups a single device belongs to: the ones it is directly in, plus + /// their ancestors (marked inherited, since nesting includes children). + /// public async Task> GetGroupsForDeviceAsync( string clientId, CancellationToken cancellationToken) { @@ -176,24 +250,37 @@ public sealed class DeviceGroupService(AppDbContext db, InventoryReportCache inv .ToListAsync(cancellationToken); var fields = BuildFields(device, inventory, DateTimeOffset.UtcNow); - var result = new List(); - - foreach (var group in groups) - { - var isMember = group.Kind == GroupKind.Static - ? staticGroupIds.Contains(group.Id) - : ParseRules(group.RulesJson) is { } rules && RuleEvaluator.Matches(rules, fields); - - if (isMember) + var directIds = groups + .Where(group => group.Kind switch { - result.Add(new DeviceGroupRefDto(group.Id, group.Name, group.Kind)); + GroupKind.Static => staticGroupIds.Contains(group.Id), + GroupKind.Dynamic => ParseRules(group.RulesJson) is { } rules && RuleEvaluator.Matches(rules, fields), + _ => false, + }) + .Select(g => g.Id) + .ToHashSet(); + + var byId = groups.ToDictionary(g => g.Id); + var inherited = new HashSet(); + foreach (var id in directIds) + { + foreach (var ancestor in GroupMembership.Ancestors(id, byId)) + { + if (!directIds.Contains(ancestor)) + { + inherited.Add(ancestor); + } } } - return result; + return groups + .Where(g => directIds.Contains(g.Id) || inherited.Contains(g.Id)) + .OrderBy(g => g.Name, StringComparer.OrdinalIgnoreCase) + .Select(g => new DeviceGroupRefDto(g.Id, g.Name, g.Kind, g.ParentId, inherited.Contains(g.Id))) + .ToList(); } - /// True when the device is in the group (null group means "all devices"). + /// True when the device is in the group or a group nested under it (null group means "all devices"). public async Task IsMemberAsync(Guid? groupId, string clientId, CancellationToken cancellationToken) { if (groupId is null) @@ -207,13 +294,18 @@ public sealed class DeviceGroupService(AppDbContext db, InventoryReportCache inv return false; } + if (await db.DeviceGroups.AnyAsync(g => g.ParentId == group.Id, cancellationToken)) + { + return (await GetMembershipAsync(cancellationToken)).Effective(group.Id).Contains(clientId); + } + if (group.Kind == GroupKind.Static) { return await db.DeviceGroupMembers.AsNoTracking() .AnyAsync(m => m.GroupId == group.Id && m.ClientId == clientId, cancellationToken); } - var rules = ParseRules(group.RulesJson); + var rules = group.Kind == GroupKind.Dynamic ? ParseRules(group.RulesJson) : null; if (rules is null) { return false; @@ -228,4 +320,136 @@ public sealed class DeviceGroupService(AppDbContext db, InventoryReportCache inv var inventory = await GetInventoryAsync(clientId, cancellationToken); return RuleEvaluator.Matches(rules, BuildFields(device, inventory, DateTimeOffset.UtcNow)); } + + /// + /// Why cannot hold + /// (missing, itself, inside its own subtree, too deep), or null when it can. + /// Pass a null for a group not yet created. + /// + public async Task ValidateParentAsync( + Guid? groupId, Guid? parentId, CancellationToken cancellationToken) + { + if (parentId is null) + { + return null; + } + + if (parentId == groupId) + { + return "A group cannot be nested inside itself."; + } + + var groups = await db.DeviceGroups.AsNoTracking() + .Select(g => new { g.Id, g.ParentId }) + .ToDictionaryAsync(g => g.Id, g => g.ParentId, cancellationToken); + if (!groups.ContainsKey(parentId.Value)) + { + return "The parent group no longer exists."; + } + + var depth = 1; + for (Guid? cursor = parentId; cursor is { } id; cursor = groups.GetValueOrDefault(id)) + { + if (id == groupId) + { + return "A group cannot be moved inside one of its own nested groups."; + } + + if (++depth > MaxDepth) + { + return $"Groups nest at most {MaxDepth} levels deep."; + } + } + + // The moved group's own subtree adds to the depth under its new parent. + if (groupId is { } moving) + { + var below = SubtreeHeight(moving, groups); + if (depth - 1 + below > MaxDepth) + { + return $"Groups nest at most {MaxDepth} levels deep."; + } + } + + return null; + } + + private static int SubtreeHeight(Guid id, Dictionary parents, int guard = 0) + { + if (guard > MaxDepth * 4) + { + return guard; + } + + var children = parents.Where(p => p.Value == id).Select(p => p.Key).ToList(); + return 1 + (children.Count == 0 ? 0 : children.Max(c => SubtreeHeight(c, parents, guard + 1))); + } +} + +/// +/// A point-in-time view of every group's membership: direct (the group's own +/// static list or rule matches) and effective (direct plus every nested +/// group's). Cycles — impossible past validation — are cut, not followed. +/// +public sealed class GroupMembership +{ + private readonly Dictionary groups; + private readonly Dictionary> direct; + private readonly Dictionary> children; + private readonly Dictionary> effective = []; + + public GroupMembership(IReadOnlyList groups, Dictionary> direct) + { + this.groups = groups.ToDictionary(g => g.Id); + this.direct = direct; + children = groups + .Where(g => g.ParentId is not null && this.groups.ContainsKey(g.ParentId.Value)) + .GroupBy(g => g.ParentId!.Value) + .ToDictionary(g => g.Key, g => g.Select(c => c.Id).ToList()); + } + + public IReadOnlyCollection Groups => groups.Values; + + public IReadOnlySet Direct(Guid groupId) + => direct.TryGetValue(groupId, out var set) ? set : new HashSet(); + + public IReadOnlySet Effective(Guid groupId) => Effective(groupId, []); + + private HashSet Effective(Guid groupId, HashSet visiting) + { + if (effective.TryGetValue(groupId, out var cached)) + { + return cached; + } + + var result = new HashSet(Direct(groupId), StringComparer.Ordinal); + if (visiting.Add(groupId)) + { + foreach (var child in children.GetValueOrDefault(groupId) ?? []) + { + result.UnionWith(Effective(child, visiting)); + } + + visiting.Remove(groupId); + } + + effective[groupId] = result; + return result; + } + + /// Groups the device is directly in (not inherited through nesting). + public IReadOnlyList DirectGroupsOf(string clientId) + => direct.Where(d => d.Value.Contains(clientId)).Select(d => d.Key).ToList(); + + /// Ancestors of a group, nearest first; stops on a cycle. + public static IEnumerable Ancestors(Guid groupId, IReadOnlyDictionary byId) + { + var seen = new HashSet { groupId }; + var cursor = byId.GetValueOrDefault(groupId)?.ParentId; + while (cursor is { } id && seen.Add(id) && byId.TryGetValue(id, out var parent)) + { + yield return id; + cursor = parent.ParentId; + } + } } diff --git a/src/Backend/Groups/GroupEndpoints.cs b/src/Backend/Groups/GroupEndpoints.cs index bbb59c9..fa51935 100644 --- a/src/Backend/Groups/GroupEndpoints.cs +++ b/src/Backend/Groups/GroupEndpoints.cs @@ -5,6 +5,7 @@ using Microsoft.EntityFrameworkCore; using Shared.Contracts.Api; using Shared.Contracts.Models; using Shared.Contracts.Serialization; +using Shared.Infrastructure.Constants; using Shared.Infrastructure.Nats; namespace Backend.Groups; @@ -18,6 +19,7 @@ public static class GroupEndpoints app.MapGet(ApiRoutes.Group, GetAsync).RequirePermission(Permissions.GroupsView); app.MapPut(ApiRoutes.Group, UpdateAsync).RequirePermission(Permissions.GroupsManage); app.MapDelete(ApiRoutes.Group, DeleteAsync).RequirePermission(Permissions.GroupsManage); + app.MapPost(ApiRoutes.GroupMove, MoveAsync).RequirePermission(Permissions.GroupsManage); app.MapGet(ApiRoutes.GroupMembers, MembersAsync).RequirePermission(Permissions.GroupsView); app.MapPost(ApiRoutes.GroupMembers, UpdateMembersAsync).RequirePermission(Permissions.GroupsManage); @@ -32,63 +34,58 @@ public static class GroupEndpoints private static async Task ListAsync( AppDbContext db, DeviceGroupService groups, CancellationToken cancellationToken) { - var entities = await db.DeviceGroups.AsNoTracking().OrderBy(g => g.Name).ToListAsync(cancellationToken); - var result = new List(entities.Count); - foreach (var entity in entities) - { - var members = await groups.GetMembersAsync(entity, cancellationToken); - result.Add(ToDto(entity, members.Count)); - } + var membership = await groups.GetMembershipAsync(cancellationToken); + var online = await OnlineClientIdsAsync(db, cancellationToken); - return Results.Ok(result); + return Results.Ok(membership.Groups + .OrderBy(g => g.Name, StringComparer.OrdinalIgnoreCase) + .Select(g => ToDto(g, membership, online)) + .ToList()); } private static async Task GetAsync( Guid id, AppDbContext db, DeviceGroupService groups, CancellationToken cancellationToken) { - var entity = await db.DeviceGroups.AsNoTracking().SingleOrDefaultAsync(g => g.Id == id, cancellationToken); - if (entity is null) - { - return Results.NotFound(); - } - - var members = await groups.GetMembersAsync(entity, cancellationToken); - return Results.Ok(ToDto(entity, members.Count)); + var membership = await groups.GetMembershipAsync(cancellationToken); + var entity = membership.Groups.FirstOrDefault(g => g.Id == id); + return entity is null + ? Results.NotFound() + : Results.Ok(ToDto(entity, membership, await OnlineClientIdsAsync(db, cancellationToken))); } private static async Task CreateAsync( - SaveDeviceGroupRequest request, AppDbContext db, AuditService audit, HttpContext context, CancellationToken cancellationToken) + SaveDeviceGroupRequest request, AppDbContext db, DeviceGroupService groups, AuditService audit, + HttpContext context, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(request.Name)) { return Results.BadRequest(new { error = "Group name is required." }); } + if (await groups.ValidateParentAsync(null, request.ParentId, cancellationToken) is { } parentError) + { + return Results.BadRequest(new { error = parentError }); + } + var now = DateTimeOffset.UtcNow; var entity = new DeviceGroupEntity { Id = Guid.NewGuid(), Name = request.Name.Trim(), - Description = request.Description, - Kind = request.Kind, - RulesJson = request.Kind == GroupKind.Dynamic && request.Rules is not null - ? JsonDefaults.Serialize(request.Rules) - : null, CreatedUtc = now, - UpdatedUtc = now, - UpdatedBy = context.User.Identity?.Name, }; + Apply(entity, request, context.User.Identity?.Name); db.DeviceGroups.Add(entity); await db.SaveChangesAsync(cancellationToken); await audit.LogAsync(AuditCategories.Admin, "group-created", entity.UpdatedBy, detail: $"{entity.Name} ({entity.Kind})", cancellationToken: cancellationToken); - return Results.Created(ApiRoutes.For.Group(entity.Id), ToDto(entity, 0)); + return Results.Created(ApiRoutes.For.Group(entity.Id), await DtoAsync(entity.Id, db, groups, cancellationToken)); } private static async Task UpdateAsync( - Guid id, SaveDeviceGroupRequest request, AppDbContext db, DeviceGroupService groups, + Guid id, SaveDeviceGroupRequest request, AppDbContext db, DeviceGroupService groups, AuditService audit, HttpContext context, CancellationToken cancellationToken) { var entity = await db.DeviceGroups.SingleOrDefaultAsync(g => g.Id == id, cancellationToken); @@ -102,21 +99,29 @@ public static class GroupEndpoints return Results.BadRequest(new { error = "Group name is required." }); } - entity.Name = request.Name.Trim(); - entity.Description = request.Description; - entity.Kind = request.Kind; - entity.RulesJson = request.Kind == GroupKind.Dynamic && request.Rules is not null - ? JsonDefaults.Serialize(request.Rules) - : null; - entity.UpdatedUtc = DateTimeOffset.UtcNow; - entity.UpdatedBy = context.User.Identity?.Name; + if (await groups.ValidateParentAsync(id, request.ParentId, cancellationToken) is { } parentError) + { + return Results.BadRequest(new { error = parentError }); + } + // Only static groups keep an explicit list; switching kind drops it so + // a later switch back does not resurrect stale members. + if (request.Kind != GroupKind.Static && entity.Kind == GroupKind.Static) + { + await db.DeviceGroupMembers.Where(m => m.GroupId == id).ExecuteDeleteAsync(cancellationToken); + } + + Apply(entity, request, context.User.Identity?.Name); await db.SaveChangesAsync(cancellationToken); - var members = await groups.GetMembersAsync(entity, cancellationToken); - return Results.Ok(ToDto(entity, members.Count)); + await audit.LogAsync(AuditCategories.Admin, "group-updated", entity.UpdatedBy, + detail: $"{entity.Name} ({entity.Kind})", cancellationToken: cancellationToken); + return Results.Ok(await DtoAsync(id, db, groups, cancellationToken)); } - private static async Task DeleteAsync(Guid id, AppDbContext db, CancellationToken cancellationToken) + /// Re-parents a group (drag and drop in the tree); null moves it to the top level. + private static async Task MoveAsync( + Guid id, MoveGroupRequest request, AppDbContext db, DeviceGroupService groups, AuditService audit, + HttpContext context, CancellationToken cancellationToken) { var entity = await db.DeviceGroups.SingleOrDefaultAsync(g => g.Id == id, cancellationToken); if (entity is null) @@ -124,13 +129,81 @@ public static class GroupEndpoints return Results.NotFound(); } - var members = db.DeviceGroupMembers.Where(m => m.GroupId == id); - db.DeviceGroupMembers.RemoveRange(members); - db.DeviceGroups.Remove(entity); + if (await groups.ValidateParentAsync(id, request.ParentId, cancellationToken) is { } error) + { + return Results.BadRequest(new { error }); + } + + entity.ParentId = request.ParentId; + entity.UpdatedUtc = DateTimeOffset.UtcNow; + entity.UpdatedBy = context.User.Identity?.Name; await db.SaveChangesAsync(cancellationToken); + await audit.LogAsync(AuditCategories.Admin, "group-moved", entity.UpdatedBy, + detail: $"{entity.Name} -> {request.ParentId?.ToString("D") ?? "top level"}", + cancellationToken: cancellationToken); + return Results.Ok(await DtoAsync(id, db, groups, cancellationToken)); + } + + /// + /// Deletes a group. Its nested groups move up to its parent, triggers that + /// targeted it are disabled (with the reason recorded), and a group that + /// scopes a role is refused: dropping it from the scope would silently + /// widen that role to every device. + /// + private static async Task DeleteAsync( + Guid id, AppDbContext db, AuditService audit, HttpContext context, CancellationToken cancellationToken) + { + var entity = await db.DeviceGroups.SingleOrDefaultAsync(g => g.Id == id, cancellationToken); + if (entity is null) + { + return Results.NotFound(); + } + + var scopingRoles = (await db.Roles.AsNoTracking().ToListAsync(cancellationToken)) + .Where(r => RoleCache.ParseGuids(r.DeviceScopeGroupIdsJson).Contains(id)) + .Select(r => r.Name) + .ToList(); + if (scopingRoles.Count > 0) + { + return Results.Conflict(new + { + error = $"This group limits the devices of the role(s) {string.Join(", ", scopingRoles)}. " + + "Remove it from their device scope first.", + }); + } + + var children = await db.DeviceGroups.Where(g => g.ParentId == id).ToListAsync(cancellationToken); + foreach (var child in children) + { + child.ParentId = entity.ParentId; + } + + var triggers = await db.ScriptTriggers.Where(t => t.GroupId == id).ToListAsync(cancellationToken); + foreach (var trigger in triggers) + { + trigger.Enabled = false; + trigger.LastResult = $"Disabled: its target group “{entity.Name}” was deleted."; + } + + db.DeviceGroupMembers.RemoveRange(db.DeviceGroupMembers.Where(m => m.GroupId == id)); + db.DeviceGroups.Remove(entity); + try + { + await db.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateConcurrencyException) + { + // A schedule aimed at the group fired between the read and this save. + return Results.Conflict(new { error = "A schedule on this group just changed. Try again." }); + } + + await audit.LogAsync(AuditCategories.Admin, "group-deleted", context.User.Identity?.Name, + detail: $"{entity.Name} children={children.Count} triggersDisabled={triggers.Count}", + cancellationToken: cancellationToken); return Results.NoContent(); } + /// Devices in the group, including those of its nested groups. private static async Task MembersAsync( Guid id, AppDbContext db, DeviceGroupService groups, CancellationToken cancellationToken) { @@ -143,6 +216,7 @@ public static class GroupEndpoints var clientIds = await groups.GetMembersAsync(entity, cancellationToken); var devices = await db.Devices.AsNoTracking() .Where(d => clientIds.Contains(d.ClientId)) + .OrderBy(d => d.Hostname) .ToListAsync(cancellationToken); var now = DateTimeOffset.UtcNow; @@ -150,7 +224,8 @@ public static class GroupEndpoints } private static async Task UpdateMembersAsync( - Guid id, UpdateGroupMembersRequest request, AppDbContext db, CancellationToken cancellationToken) + Guid id, UpdateGroupMembersRequest request, AppDbContext db, AuditService audit, HttpContext context, + CancellationToken cancellationToken) { var entity = await db.DeviceGroups.SingleOrDefaultAsync(g => g.Id == id, cancellationToken); if (entity is null) @@ -160,38 +235,49 @@ public static class GroupEndpoints if (entity.Kind != GroupKind.Static) { - return Results.BadRequest(new { error = "Membership of a dynamic group is determined by its rules." }); + return Results.BadRequest(new + { + error = entity.Kind == GroupKind.Dynamic + ? "Membership of a dynamic group is determined by its rules." + : "A folder holds groups, not devices. Add the devices to a static group inside it.", + }); } - foreach (var clientId in request.Remove ?? []) + var remove = (request.Remove ?? []).Distinct(StringComparer.Ordinal).ToList(); + var add = (request.Add ?? []).Where(SubjectIdentifier.IsValid).Distinct(StringComparer.Ordinal).ToList(); + + if (remove.Count > 0) { - var existing = await db.DeviceGroupMembers - .Where(m => m.GroupId == id && m.ClientId == clientId) + await db.DeviceGroupMembers + .Where(m => m.GroupId == id && remove.Contains(m.ClientId)) + .ExecuteDeleteAsync(cancellationToken); + } + + var added = 0; + if (add.Count > 0) + { + var existing = await db.DeviceGroupMembers.AsNoTracking() + .Where(m => m.GroupId == id && add.Contains(m.ClientId)) + .Select(m => m.ClientId) + .ToListAsync(cancellationToken); + var enrolled = await db.Devices.AsNoTracking() + .Where(d => add.Contains(d.ClientId)) + .Select(d => d.ClientId) .ToListAsync(cancellationToken); - db.DeviceGroupMembers.RemoveRange(existing); - } - foreach (var clientId in request.Add ?? []) - { - if (!SubjectIdentifier.IsValid(clientId)) + var now = DateTimeOffset.UtcNow; + foreach (var clientId in enrolled.Except(existing, StringComparer.Ordinal)) { - continue; - } - - var already = await db.DeviceGroupMembers - .AnyAsync(m => m.GroupId == id && m.ClientId == clientId, cancellationToken); - if (!already) - { - db.DeviceGroupMembers.Add(new DeviceGroupMemberEntity - { - GroupId = id, - ClientId = clientId, - AddedUtc = DateTimeOffset.UtcNow, - }); + db.DeviceGroupMembers.Add(new DeviceGroupMemberEntity { GroupId = id, ClientId = clientId, AddedUtc = now }); + added++; } } + entity.UpdatedUtc = DateTimeOffset.UtcNow; + entity.UpdatedBy = context.User.Identity?.Name; await db.SaveChangesAsync(cancellationToken); + await audit.LogAsync(AuditCategories.Admin, "group-members", entity.UpdatedBy, + detail: $"{entity.Name} added={added} removed={remove.Count}", cancellationToken: cancellationToken); return Results.NoContent(); } @@ -202,6 +288,7 @@ public static class GroupEndpoints var clientIds = await groups.EvaluateAsync(request.Rules, cancellationToken); var devices = await db.Devices.AsNoTracking() .Where(d => clientIds.Contains(d.ClientId)) + .OrderBy(d => d.Hostname) .ToListAsync(cancellationToken); var now = DateTimeOffset.UtcNow; @@ -233,8 +320,48 @@ public static class GroupEndpoints return Results.Ok(tags); } - private static DeviceGroupDto ToDto(DeviceGroupEntity entity, int memberCount) => new( - entity.Id, entity.Name, entity.Description, entity.Kind, - DeviceGroupService.ParseRules(entity.RulesJson), - memberCount, entity.CreatedUtc, entity.UpdatedUtc, entity.UpdatedBy); + private static void Apply(DeviceGroupEntity entity, SaveDeviceGroupRequest request, string? actor) + { + entity.Name = request.Name.Trim(); + entity.Description = string.IsNullOrWhiteSpace(request.Description) ? null : request.Description.Trim(); + entity.Kind = request.Kind; + entity.ParentId = request.ParentId; + entity.RulesJson = request.Kind == GroupKind.Dynamic && request.Rules is not null + ? JsonDefaults.Serialize(request.Rules) + : null; + entity.UpdatedUtc = DateTimeOffset.UtcNow; + entity.UpdatedBy = actor; + } + + private static async Task> OnlineClientIdsAsync(AppDbContext db, CancellationToken cancellationToken) + { + var now = DateTimeOffset.UtcNow; + var seen = await db.Devices.AsNoTracking() + .Select(d => new { d.ClientId, d.LastSeenUtc }) + .ToListAsync(cancellationToken); + return seen + .Where(d => ProtocolDefaults.CalculateStatus(d.LastSeenUtc, now) == DeviceStatus.Online) + .Select(d => d.ClientId) + .ToHashSet(StringComparer.Ordinal); + } + + /// DTO after a write; the snapshot is built lazily, so it already reflects the change. + private static async Task DtoAsync( + Guid id, AppDbContext db, DeviceGroupService groups, CancellationToken cancellationToken) + { + var membership = await groups.GetMembershipAsync(cancellationToken); + return ToDto(membership.Groups.First(g => g.Id == id), membership, await OnlineClientIdsAsync(db, cancellationToken)); + } + + private static DeviceGroupDto ToDto(DeviceGroupEntity entity, GroupMembership membership, IReadOnlySet online) + { + var effective = membership.Effective(entity.Id); + return new DeviceGroupDto( + entity.Id, entity.Name, entity.Description, entity.Kind, + DeviceGroupService.ParseRules(entity.RulesJson), + effective.Count, entity.CreatedUtc, entity.UpdatedUtc, entity.UpdatedBy, + ParentId: entity.ParentId, + DirectMemberCount: membership.Direct(entity.Id).Count, + OnlineCount: effective.Count(online.Contains)); + } } diff --git a/src/Backend/Groups/ScriptTriggerService.cs b/src/Backend/Groups/ScriptTriggerService.cs index 64a00e9..283bf35 100644 --- a/src/Backend/Groups/ScriptTriggerService.cs +++ b/src/Backend/Groups/ScriptTriggerService.cs @@ -68,8 +68,12 @@ public sealed class ScriptTriggerService( continue; } + var runId = Guid.NewGuid(); + await runner.RecordRunAsync( + runId, script, $"trigger:{triggerType}", Backend.Data.RunSources.Trigger, device.Hostname, [], + cancellationToken, triggerId: trigger.Id); var job = await runner.CreateJobAsync( - script, clientId, $"trigger:{triggerType}", cancellationToken, Guid.NewGuid()); + script, clientId, $"trigger:{triggerType}", cancellationToken, runId); if (trigger.OncePerDevice) { @@ -100,7 +104,7 @@ public sealed class ScriptTriggerService( } await runner.DispatchAsync( - prepared, job, arguments: null, + prepared, job, TriggerExecutor.ParseArguments(trigger.ArgumentsJson), $"Trigger ({triggerType}) queued “{script.Name}” for {device.Hostname}", cancellationToken); diff --git a/src/Backend/Groups/TriggerEndpoints.cs b/src/Backend/Groups/TriggerEndpoints.cs index 845a518..ac6a08e 100644 --- a/src/Backend/Groups/TriggerEndpoints.cs +++ b/src/Backend/Groups/TriggerEndpoints.cs @@ -1,6 +1,8 @@ +using System.Security.Claims; using Backend.Auth; using Backend.Data; using Backend.Jobs; +using Backend.Security; using Microsoft.EntityFrameworkCore; using Shared.Contracts.Api; using Shared.Contracts.Models; @@ -10,12 +12,18 @@ namespace Backend.Groups; public static class TriggerEndpoints { + /// Clock skew tolerated for a one-shot time picked "a moment from now". + private static readonly TimeSpan OneShotGrace = TimeSpan.FromMinutes(1); + public static void Map(WebApplication app) { app.MapGet(ApiRoutes.Triggers, ListAsync).RequirePermission(Permissions.AutomationView); app.MapPost(ApiRoutes.Triggers, CreateAsync).RequirePermission(Permissions.AutomationManage); + app.MapPost(ApiRoutes.TriggerPreview, Preview).RequirePermission(Permissions.AutomationView); + app.MapPut(ApiRoutes.Trigger, UpdateAsync).RequirePermission(Permissions.AutomationManage); app.MapPatch(ApiRoutes.Trigger, SetEnabledAsync).RequirePermission(Permissions.AutomationManage); app.MapDelete(ApiRoutes.Trigger, DeleteAsync).RequirePermission(Permissions.AutomationManage); + app.MapPost(ApiRoutes.TriggerRun, RunNowAsync).RequirePermission(Permissions.JobsRun); } private static async Task ListAsync(AppDbContext db, CancellationToken cancellationToken) @@ -36,82 +44,44 @@ public static class TriggerEndpoints t.ClientId is null ? null : hostnames.GetValueOrDefault(t.ClientId, t.ClientId), t.TriggerType, t.Enabled, t.CronExpression, t.RunOnceUtc, t.TimeZoneId, t.NextRunUtc, t.LastRunUtc, t.LastResult, - t.CreatedUtc)).ToList()); + t.CreatedUtc, + Name: t.Name, + LastRunId: t.LastRunId, + Arguments: TriggerExecutor.ParseArguments(t.ArgumentsJson), + CreatedBy: t.CreatedBy)).ToList()); } private static async Task CreateAsync( - SaveScriptTriggerRequest request, AppDbContext db, HttpContext context, CancellationToken cancellationToken) + SaveScriptTriggerRequest request, AppDbContext db, DeviceScopeService scope, DeviceGroupService groups, + AuditService audit, HttpContext context, CancellationToken cancellationToken) { - if (!await db.Scripts.AnyAsync(s => s.Id == request.ScriptId, cancellationToken)) + if (await ValidateTargetAsync(request, db, scope, groups, context.User, cancellationToken) is { } invalid) { - return Results.NotFound(new { error = "Script not found." }); - } - - if (request.GroupId is not null && request.ClientId is not null) - { - return Results.BadRequest(new { error = "A trigger targets a group OR a device, not both." }); - } - - if (request.GroupId is not null - && !await db.DeviceGroups.AnyAsync(g => g.Id == request.GroupId, cancellationToken)) - { - return Results.NotFound(new { error = "Group not found." }); - } - - if (request.ClientId is not null - && !await db.Devices.AnyAsync(d => d.ClientId == request.ClientId, cancellationToken)) - { - return Results.NotFound(new { error = "Device not found." }); + return invalid; } var entity = new ScriptTriggerEntity { Id = Guid.NewGuid(), - ScriptId = request.ScriptId, - GroupId = request.GroupId, - ClientId = request.ClientId, - TriggerType = request.TriggerType, - Enabled = request.Enabled, - TimeZoneId = string.IsNullOrWhiteSpace(request.TimeZoneId) ? "UTC" : request.TimeZoneId!, - ArgumentsJson = request.Arguments is { Count: > 0 } ? JsonDefaults.Serialize(request.Arguments) : null, CreatedUtc = DateTimeOffset.UtcNow, CreatedBy = context.User.Identity?.Name, }; - if (request.TriggerType == ScriptTriggerType.Scheduled) + if (Apply(entity, request) is { } error) { - // Recurring (cron) or one-shot (runOnce); compute the first run. - if (!string.IsNullOrWhiteSpace(request.CronExpression)) - { - try - { - entity.CronExpression = request.CronExpression; - entity.NextRunUtc = ScheduleCron.NextOccurrence( - request.CronExpression!, entity.TimeZoneId, DateTimeOffset.UtcNow); - } - catch (Exception ex) - { - return Results.BadRequest(new { error = $"Invalid cron expression: {ex.Message}" }); - } - } - else if (request.RunOnceUtc is { } runOnce) - { - entity.RunOnceUtc = runOnce; - entity.NextRunUtc = runOnce; - } - else - { - return Results.BadRequest(new { error = "A scheduled trigger needs a cron expression or a one-shot time." }); - } + return Results.BadRequest(new { error }); } db.ScriptTriggers.Add(entity); await db.SaveChangesAsync(cancellationToken); + await audit.LogAsync(AuditCategories.Automation, "trigger-created", entity.CreatedBy, + clientId: entity.ClientId, detail: Describe(entity), cancellationToken: cancellationToken); return Results.Created(ApiRoutes.For.Trigger(entity.Id), new { id = entity.Id }); } - private static async Task SetEnabledAsync( - Guid id, SetTriggerEnabledRequest request, AppDbContext db, CancellationToken cancellationToken) + private static async Task UpdateAsync( + Guid id, SaveScriptTriggerRequest request, AppDbContext db, DeviceScopeService scope, + DeviceGroupService groups, AuditService audit, HttpContext context, CancellationToken cancellationToken) { var entity = await db.ScriptTriggers.SingleOrDefaultAsync(t => t.Id == id, cancellationToken); if (entity is null) @@ -119,6 +89,78 @@ public static class TriggerEndpoints return Results.NotFound(); } + // Both ends must be in scope: the target it has, and the one it gets. + if (await CheckScopeAsync(entity.ClientId, entity.GroupId, db, scope, groups, context.User, cancellationToken) is { } outside) + { + return outside; + } + + if (await ValidateTargetAsync(request, db, scope, groups, context.User, cancellationToken) is { } invalid) + { + return invalid; + } + + if (Apply(entity, request) is { } error) + { + return Results.BadRequest(new { error }); + } + + if (await SaveOrConflictAsync(db, cancellationToken) is { } conflict) + { + return conflict; + } + await audit.LogAsync(AuditCategories.Automation, "trigger-updated", context.User.Identity?.Name, + clientId: entity.ClientId, detail: Describe(entity), cancellationToken: cancellationToken); + return Results.NoContent(); + } + + /// Upcoming fire times of a cron cadence in its time zone (DST-aware). + private static IResult Preview(SchedulePreviewRequest request) + { + if (string.IsNullOrWhiteSpace(request.CronExpression)) + { + return Results.Ok(new SchedulePreviewDto([], "Enter a cron expression.")); + } + + var cron = request.CronExpression.Trim(); + var timeZone = string.IsNullOrWhiteSpace(request.TimeZoneId) ? "UTC" : request.TimeZoneId.Trim(); + if (ScheduleCron.Validate(cron, timeZone) is { } error) + { + return Results.Ok(new SchedulePreviewDto([], error)); + } + + var occurrences = ScheduleCron.NextOccurrences( + cron, timeZone, DateTimeOffset.UtcNow, Math.Clamp(request.Count, 1, 20)); + return Results.Ok(new SchedulePreviewDto( + occurrences, occurrences.Count == 0 ? "This expression never fires." : null)); + } + + private static async Task SetEnabledAsync( + Guid id, SetTriggerEnabledRequest request, AppDbContext db, DeviceScopeService scope, DeviceGroupService groups, + AuditService audit, HttpContext context, CancellationToken cancellationToken) + { + var entity = await db.ScriptTriggers.SingleOrDefaultAsync(t => t.Id == id, cancellationToken); + if (entity is null) + { + return Results.NotFound(); + } + + if (await CheckScopeAsync(entity.ClientId, entity.GroupId, db, scope, groups, context.User, cancellationToken) is { } outside) + { + return outside; + } + + // A one-shot whose time has passed would fire on the next sweep; the + // same mistake Apply refuses on save. + if (request.Enabled + && entity.TriggerType == ScriptTriggerType.Scheduled + && string.IsNullOrWhiteSpace(entity.CronExpression) + && entity.RunOnceUtc is { } at + && at < DateTimeOffset.UtcNow - OneShotGrace) + { + return Results.BadRequest(new { error = "This one-shot time has passed. Edit the schedule to pick a new time." }); + } + entity.Enabled = request.Enabled; // Re-enabling a recurring schedule whose next run already passed would @@ -139,11 +181,19 @@ public static class TriggerEndpoints } } - await db.SaveChangesAsync(cancellationToken); + if (await SaveOrConflictAsync(db, cancellationToken) is { } conflict) + { + return conflict; + } + await audit.LogAsync(AuditCategories.Automation, request.Enabled ? "trigger-enabled" : "trigger-disabled", + context.User.Identity?.Name, clientId: entity.ClientId, detail: Describe(entity), + cancellationToken: cancellationToken); return Results.NoContent(); } - private static async Task DeleteAsync(Guid id, AppDbContext db, CancellationToken cancellationToken) + private static async Task DeleteAsync( + Guid id, AppDbContext db, DeviceScopeService scope, DeviceGroupService groups, AuditService audit, + HttpContext context, CancellationToken cancellationToken) { var entity = await db.ScriptTriggers.SingleOrDefaultAsync(t => t.Id == id, cancellationToken); if (entity is null) @@ -151,8 +201,223 @@ public static class TriggerEndpoints return Results.NotFound(); } + if (await CheckScopeAsync(entity.ClientId, entity.GroupId, db, scope, groups, context.User, cancellationToken) is { } outside) + { + return outside; + } + + db.ScriptTriggerRuns.RemoveRange(db.ScriptTriggerRuns.Where(r => r.TriggerId == id)); db.ScriptTriggers.Remove(entity); - await db.SaveChangesAsync(cancellationToken); + if (await SaveOrConflictAsync(db, cancellationToken) is { } conflict) + { + return conflict; + } + await audit.LogAsync(AuditCategories.Automation, "trigger-deleted", context.User.Identity?.Name, + clientId: entity.ClientId, detail: Describe(entity), cancellationToken: cancellationToken); return Results.NoContent(); } + + /// + /// Fires the trigger now against its current target, as one execution, + /// without touching its cadence (NextRunUtc) or enabled state. + /// + private static async Task RunNowAsync( + Guid id, AppDbContext db, TriggerExecutor executor, DeviceScopeService scope, DeviceGroupService groups, + AuditService audit, HttpContext context, CancellationToken cancellationToken) + { + var entity = await db.ScriptTriggers.SingleOrDefaultAsync(t => t.Id == id, cancellationToken); + if (entity is null) + { + return Results.NotFound(); + } + + var target = new SaveScriptTriggerRequest(entity.ScriptId, entity.TriggerType, entity.ClientId, entity.GroupId); + if (await ValidateTargetAsync(target, db, scope, groups, context.User, cancellationToken) is { } invalid) + { + return invalid; + } + + var actor = context.User.Identity?.Name; + var firing = await executor.FireAsync(entity, actor ?? "trigger", cancellationToken); + await executor.SaveFiringAsync(entity, cancellationToken); + await audit.LogAsync(AuditCategories.Automation, "trigger-run", actor, + clientId: entity.ClientId, detail: $"{Describe(entity)} result={firing.Message}", + cancellationToken: cancellationToken); + + return Results.Ok(new TriggerRunResultDto(firing.RunId, firing.Queued, firing.Message)); + } + + /// + /// Script and target exist, and a device-scoped role only aims inside its + /// scope: a device it can see, or a group whose members it can all see — + /// never "all devices", which would fire beyond the scope later. + /// + private static async Task ValidateTargetAsync( + SaveScriptTriggerRequest request, AppDbContext db, DeviceScopeService scope, DeviceGroupService groups, + ClaimsPrincipal user, CancellationToken cancellationToken) + { + if (!await db.Scripts.AnyAsync(s => s.Id == request.ScriptId, cancellationToken)) + { + return Results.NotFound(new { error = "Script not found." }); + } + + if (request.GroupId is not null && request.ClientId is not null) + { + return Results.BadRequest(new { error = "A trigger targets a group OR a device, not both." }); + } + + var group = request.GroupId is { } groupId + ? await db.DeviceGroups.AsNoTracking().SingleOrDefaultAsync(g => g.Id == groupId, cancellationToken) + : null; + if (request.GroupId is not null && group is null) + { + return Results.NotFound(new { error = "Group not found." }); + } + + if (request.ClientId is not null + && !await db.Devices.AnyAsync(d => d.ClientId == request.ClientId, cancellationToken)) + { + return Results.NotFound(new { error = "Device not found." }); + } + + return await CheckScopeAsync(request.ClientId, request.GroupId, db, scope, groups, user, cancellationToken); + } + + /// + /// A device-scoped role may only act on targets inside its scope: a device + /// it can see, or a group whose members it can all see — never "all + /// devices" (or a group that is gone), which would reach beyond the scope. + /// Applied to new targets and to the stored target of existing triggers. + /// + private static async Task CheckScopeAsync( + string? clientId, Guid? groupId, AppDbContext db, DeviceScopeService scope, DeviceGroupService groups, + ClaimsPrincipal user, CancellationToken cancellationToken) + { + var allowed = await scope.GetAllowedClientIdsAsync(user, cancellationToken); + if (allowed is null) + { + return null; + } + + if (clientId is not null) + { + return allowed.Contains(clientId) ? null : Results.NotFound(new { error = "Device not found." }); + } + + var group = groupId is { } id + ? await db.DeviceGroups.AsNoTracking().SingleOrDefaultAsync(g => g.Id == id, cancellationToken) + : null; + if (group is null) + { + return Results.Json( + new { error = "Your role is limited to specific devices; target a device or a group." }, + statusCode: StatusCodes.Status403Forbidden); + } + + var members = await groups.GetMembersAsync(group, cancellationToken); + return members.All(allowed.Contains) + ? null + : Results.Json( + new { error = "That group reaches devices outside your role's scope." }, + statusCode: StatusCodes.Status403Forbidden); + } + + + /// + /// Saves, or answers 409 when the trigger was changed underneath this + /// request (typically by the schedule sweep firing it). + /// + private static async Task SaveOrConflictAsync(AppDbContext db, CancellationToken cancellationToken) + { + try + { + await db.SaveChangesAsync(cancellationToken); + return null; + } + catch (DbUpdateConcurrencyException) + { + return Results.Conflict(new { error = "This schedule changed a moment ago (it may have just fired). Reload and try again." }); + } + } + /// Copies the request onto the entity and computes the first run; returns an error message. + private static string? Apply(ScriptTriggerEntity entity, SaveScriptTriggerRequest request) + { + var name = request.Name?.Trim(); + if (name is { Length: > 200 }) + { + return "Name must be 200 characters or fewer."; + } + + var timeZone = string.IsNullOrWhiteSpace(request.TimeZoneId) ? "UTC" : request.TimeZoneId.Trim(); + string? cron = null; + DateTimeOffset? runOnce = null; + DateTimeOffset? nextRun = null; + var now = DateTimeOffset.UtcNow; + + if (request.TriggerType == ScriptTriggerType.Scheduled) + { + if (!string.IsNullOrWhiteSpace(request.CronExpression)) + { + cron = request.CronExpression.Trim(); + if (ScheduleCron.Validate(cron, timeZone) is { } invalid) + { + return invalid; + } + + nextRun = ScheduleCron.NextOccurrence(cron, timeZone, now); + if (nextRun is null) + { + return "This cron expression never fires."; + } + } + else if (request.RunOnceUtc is { } at) + { + if (ScheduleCron.ValidateTimeZone(timeZone) is { } invalid) + { + return invalid; + } + + // An enabled one-shot in the past would fire the moment it is + // saved — almost always a mistake in the picker, so refuse it. + if (request.Enabled && at < now - OneShotGrace) + { + return "The one-shot time is in the past."; + } + + runOnce = at; + nextRun = at < now - OneShotGrace ? null : at; + } + else + { + return "A scheduled trigger needs a cron expression or a one-shot time."; + } + } + else + { + // Event triggers have no cadence; the time zone is meaningless. + timeZone = "UTC"; + } + + entity.Name = string.IsNullOrEmpty(name) ? null : name; + entity.ScriptId = request.ScriptId; + entity.GroupId = request.GroupId; + entity.ClientId = request.ClientId; + entity.TriggerType = request.TriggerType; + entity.Enabled = request.Enabled; + entity.TimeZoneId = timeZone; + entity.CronExpression = cron; + entity.RunOnceUtc = runOnce; + entity.NextRunUtc = nextRun; + entity.ArgumentsJson = request.Arguments is { Count: > 0 } ? JsonDefaults.Serialize(request.Arguments) : null; + return null; + } + + private static string Describe(ScriptTriggerEntity trigger) + { + var target = trigger.ClientId is { } clientId ? $"device={clientId}" + : trigger.GroupId is { } groupId ? $"group={groupId:D}" + : "target=all"; + var cadence = trigger.CronExpression ?? trigger.RunOnceUtc?.ToString("O") ?? trigger.TriggerType.ToString(); + return $"trigger={trigger.Id:D} name={trigger.Name ?? "-"} script={trigger.ScriptId:D} {target} when={cadence}"; + } } diff --git a/src/Backend/Jobs/CommandDispatcher.cs b/src/Backend/Jobs/CommandDispatcher.cs index 316d8a9..02aed0e 100644 --- a/src/Backend/Jobs/CommandDispatcher.cs +++ b/src/Backend/Jobs/CommandDispatcher.cs @@ -5,14 +5,32 @@ using Shared.Infrastructure.Nats; namespace Backend.Jobs; +/// Sends agent upgrade commands (the upgrade scheduler's seam; tests record instead). +public interface IAgentUpgradeSender +{ + Task DispatchAgentUpgradeAsync(string clientId, AgentUpgradeCommandPayload command, CancellationToken cancellationToken); +} + /// /// Publishes durable agent commands through JetStream (awaiting stream acks) /// so script dispatch survives agent disconnects and backend restarts. /// -public sealed class CommandDispatcher(NatsHub hub, ILogger logger) +public sealed class CommandDispatcher(NatsHub hub, ILogger logger) : IAgentUpgradeSender { private static readonly EndpointRef BackendSource = new(EndpointKinds.Backend, "backend"); + public async Task DispatchAgentUpgradeAsync( + string clientId, AgentUpgradeCommandPayload command, CancellationToken cancellationToken) + { + var envelope = MessageEnvelope.Create( + MessageTypes.CommandAgentUpgrade, + BackendSource, + command, + new EndpointRef(EndpointKinds.Agent, clientId)); + + return await PublishAsync(NatsSubjects.AgentCommandUpgrade(clientId), envelope, cancellationToken); + } + public async Task DispatchScriptAsync( string clientId, ScriptCommandPayload command, CancellationToken cancellationToken) { diff --git a/src/Backend/Jobs/JobEndpoints.cs b/src/Backend/Jobs/JobEndpoints.cs index b8f50ff..49ae055 100644 --- a/src/Backend/Jobs/JobEndpoints.cs +++ b/src/Backend/Jobs/JobEndpoints.cs @@ -1,7 +1,9 @@ +using System.IO.Compression; using Backend.Auth; using Backend.Data; using Backend.Messaging; using Backend.Security; +using Microsoft.AspNetCore.Http.Features; using Microsoft.EntityFrameworkCore; using Shared.Contracts.Api; using Shared.Contracts.Messages; @@ -20,45 +22,265 @@ public static class JobEndpoints app.MapGet(ApiRoutes.Job, GetAsync).RequirePermission(Permissions.JobsView); app.MapGet(ApiRoutes.JobOutput, GetOutputAsync).RequirePermission(Permissions.JobsView); app.MapGet(ApiRoutes.ScriptExecutions, ListExecutionsAsync).RequirePermission(Permissions.JobsView); + app.MapGet(ApiRoutes.Executions, ListAllExecutionsAsync).RequirePermission(Permissions.JobsView); app.MapGet(ApiRoutes.Execution, GetExecutionAsync).RequirePermission(Permissions.JobsView); + app.MapGet(ApiRoutes.JobOutputDownload, DownloadJobOutputAsync).RequirePermission(Permissions.JobsView); + app.MapGet(ApiRoutes.ExecutionOutputDownload, DownloadExecutionOutputAsync).RequirePermission(Permissions.JobsView); + app.MapPost(ApiRoutes.ExecutionOutputArchive, DownloadExecutionArchiveAsync).RequirePermission(Permissions.JobsView); + } + + /// One job's complete stored output as a text file. + private static async Task DownloadJobOutputAsync( + Guid jobId, AppDbContext db, DeviceScopeService scope, HttpContext context, bool? timestamps, + CancellationToken cancellationToken) + { + var job = await (await ScopedJobsAsync(db, scope, context, cancellationToken)) + .SingleOrDefaultAsync(j => j.JobId == jobId, cancellationToken); + if (job is null) + { + return Results.NotFound(); + } + + var hostnames = await HostnamesAsync(db, [job], cancellationToken); + var hostname = hostnames.GetValueOrDefault(job.ClientId) ?? job.ClientId; + var fileName = OutputFileName(hostname, job.JobId, job.CreatedUtc); + + return Results.Stream(async stream => + { + await using var writer = new StreamWriter(stream, new System.Text.UTF8Encoding(false)); + await WriteJobFileAsync(writer, db, job, hostname, timestamps == true, context.RequestAborted); + }, "text/plain; charset=utf-8", fileName); + } + + /// + /// The chosen jobs of one execution (all of them when none are named) as a + /// zip of the same per-device .log files a single job downloads as, named + /// "{script}.{runId}.….zip". Jobs outside the run or the caller's device + /// scope are left out; 404 when nothing is left. + /// + private static async Task DownloadExecutionArchiveAsync( + Guid runId, OutputArchiveRequest? input, AppDbContext db, DeviceScopeService scope, HttpContext context, + CancellationToken cancellationToken) + { + var query = (await ScopedJobsAsync(db, scope, context, cancellationToken)) + .Where(j => j.RunId == runId || j.JobId == runId); + if (input?.JobIds is { Count: > 0 } chosen) + { + var ids = chosen.Distinct().ToList(); + query = query.Where(j => ids.Contains(j.JobId)); + } + + var jobs = await query.ToListAsync(cancellationToken); + if (jobs.Count == 0) + { + return Results.NotFound(); + } + + var hostnames = await HostnamesAsync(db, jobs, cancellationToken); + var ordered = jobs.OrderBy(j => hostnames.GetValueOrDefault(j.ClientId) ?? j.ClientId, StringComparer.OrdinalIgnoreCase).ToList(); + var first = jobs.MinBy(j => j.CreatedUtc)!; + var fileName = Path.ChangeExtension(OutputFileName(first.ScriptName, runId, first.CreatedUtc), ".zip"); + + return Results.Stream(async stream => + { + // Entries are written in sequence straight to the response; nothing is buffered. + // An entry's stream writes its 16-byte data descriptor synchronously when + // disposed, the one synchronous write here, so this response allows it. + context.Features.Get()!.AllowSynchronousIO = true; + await using var archive = await ZipArchive.CreateAsync( + stream, ZipArchiveMode.Create, leaveOpen: true, entryNameEncoding: null, context.RequestAborted); + foreach (var job in ordered) + { + var hostname = hostnames.GetValueOrDefault(job.ClientId) ?? job.ClientId; + var entry = archive.CreateEntry(OutputFileName(hostname, job.JobId, job.CreatedUtc), CompressionLevel.Optimal); + entry.LastWriteTime = job.CompletedUtc ?? job.StartedUtc ?? job.CreatedUtc; + await using var entryStream = await entry.OpenAsync(context.RequestAborted); + await using var writer = new StreamWriter(entryStream, new System.Text.UTF8Encoding(false)); + await WriteJobFileAsync(writer, db, job, hostname, input?.Timestamps == true, context.RequestAborted); + } + }, "application/zip", fileName); + } + + /// One job's .log file: a title line, then its header and output. + private static async Task WriteJobFileAsync( + StreamWriter writer, AppDbContext db, JobEntity job, string hostname, bool timestamps, + CancellationToken cancellationToken) + { + await writer.WriteLineAsync($"# ExecuteR job output — {job.ScriptName} on {hostname}"); + await WriteJobAsync(writer, db, job, hostname, timestamps, cancellationToken); + } + + /// + /// Every target's complete stored output for one execution, as one text + /// file with a section per device (state and exit code in its header). + /// + private static async Task DownloadExecutionOutputAsync( + Guid runId, AppDbContext db, DeviceScopeService scope, HttpContext context, bool? timestamps, + CancellationToken cancellationToken) + { + var jobs = await (await ScopedJobsAsync(db, scope, context, cancellationToken)) + .Where(j => j.RunId == runId || j.JobId == runId) + .ToListAsync(cancellationToken); + if (jobs.Count == 0) + { + return Results.NotFound(); + } + + var hostnames = await HostnamesAsync(db, jobs, cancellationToken); + var ordered = jobs.OrderBy(j => hostnames.GetValueOrDefault(j.ClientId) ?? j.ClientId, StringComparer.OrdinalIgnoreCase).ToList(); + var first = jobs.MinBy(j => j.CreatedUtc)!; + var fileName = OutputFileName(first.ScriptName, runId, first.CreatedUtc); + + return Results.Stream(async stream => + { + await using var writer = new StreamWriter(stream, new System.Text.UTF8Encoding(false)); + await writer.WriteLineAsync($"# ExecuteR execution output — {first.ScriptName} on {jobs.Count} device(s)"); + await writer.WriteLineAsync($"# Run: {runId:D}"); + await writer.WriteLineAsync($"# Started: {first.CreatedUtc:u}{(first.RequestedBy is { } by ? $" by {by}" : string.Empty)}"); + foreach (var job in ordered) + { + var hostname = hostnames.GetValueOrDefault(job.ClientId) ?? job.ClientId; + await writer.WriteLineAsync(); + await writer.WriteLineAsync($"===== {hostname} — {job.State}{(job.ExitCode is { } code ? $", exit {code}" : string.Empty)} ====="); + await WriteJobAsync(writer, db, job, hostname, timestamps == true, context.RequestAborted); + } + }, "text/plain; charset=utf-8", fileName); + } + + /// + /// A job's header and its stored output, streamed from the database in + /// sequence order (no size cap, nothing held in memory). Lines from other + /// than the output stream are tagged, e.g. "[ERROR] …". + /// + private static async Task WriteJobAsync( + StreamWriter writer, AppDbContext db, JobEntity job, string hostname, bool timestamps, + CancellationToken cancellationToken) + { + await writer.WriteLineAsync($"# Device: {hostname} ({job.ClientId})"); + await writer.WriteLineAsync($"# Job: {job.JobId:D}"); + await writer.WriteLineAsync($"# State: {job.State}{(job.ExitCode is { } code ? $" (exit {code})" : string.Empty)}"); + await writer.WriteLineAsync($"# Queued: {job.CreatedUtc:u}"); + if (job.StartedUtc is { } started) + { + await writer.WriteLineAsync($"# Started: {started:u}"); + } + + if (job.CompletedUtc is { } completed) + { + await writer.WriteLineAsync($"# Completed: {completed:u}"); + } + + await writer.WriteLineAsync(); + var records = db.JobOutput.AsNoTracking() + .Where(o => o.JobId == job.JobId) + .OrderBy(o => o.Sequence) + .Select(o => new { o.Stream, o.TimestampUtc, o.Text }) + .AsAsyncEnumerable(); + await foreach (var record in records.WithCancellation(cancellationToken)) + { + var prefix = timestamps ? $"{record.TimestampUtc:yyyy-MM-ddTHH:mm:ss.fffZ} " : string.Empty; + var tag = record.Stream == OutputStreamKind.Output ? string.Empty : $"[{record.Stream.ToString().ToUpperInvariant()}] "; + await writer.WriteLineAsync(prefix + tag + record.Text); + } + } + + /// + /// "LAB-VM-27.{jobId}.2026.10.22.210455.log" for a job, "{script}.{runId}.….log" + /// for a whole run; UTC, 24-hour. Dots only separate fields (an FQDN or + /// script name has its dots and other symbols turned into dashes). + /// + private static string OutputFileName(string subject, Guid id, DateTimeOffset when) + { + static string Safe(string value) => + string.Concat(value.Select(c => char.IsLetterOrDigit(c) ? c : '-')).Trim('-'); + return $"{Safe(subject)}.{id:D}.{when.UtcDateTime:yyyy.MM.dd.HHmmss}.log"; + } + + /// + /// Jobs a device-scoped role may read: only those on devices inside its + /// scope (output can hold anything the script printed). Null = unrestricted. + /// + private static async Task> ScopedJobsAsync( + AppDbContext db, DeviceScopeService scope, HttpContext context, CancellationToken cancellationToken) + { + var jobs = db.Jobs.AsNoTracking(); + var allowed = await scope.GetAllowedClientIdsAsync(context.User, cancellationToken); + if (allowed is null) + { + return jobs; + } + + var allowedIds = allowed.ToList(); + return jobs.Where(j => allowedIds.Contains(j.ClientId)); } /// Executions of a script: its per-device jobs grouped by run (newest first). private static async Task ListExecutionsAsync( - Guid scriptId, AppDbContext db, CancellationToken cancellationToken) + Guid scriptId, AppDbContext db, DeviceScopeService scope, HttpContext context, CancellationToken cancellationToken) + => Results.Ok(await SummariesAsync(db, scope, context, scriptId, 50, cancellationToken)); + + /// Recent executions across every script (or one, with ?scriptId). + private static async Task ListAllExecutionsAsync( + AppDbContext db, DeviceScopeService scope, HttpContext context, Guid? scriptId, int? limit, + CancellationToken cancellationToken) + => Results.Ok(await SummariesAsync(db, scope, context, scriptId, Math.Clamp(limit ?? 50, 1, 200), cancellationToken)); + + private static async Task> SummariesAsync( + AppDbContext db, DeviceScopeService scope, HttpContext context, Guid? scriptId, int limit, + CancellationToken cancellationToken) { - var jobs = await db.Jobs.AsNoTracking() - .Where(j => j.ScriptId == scriptId) + var query = await ScopedJobsAsync(db, scope, context, cancellationToken); + if (scriptId is { } id) + { + query = query.Where(j => j.ScriptId == id); + } + + var jobs = await query .OrderByDescending(j => j.CreatedUtc) - .Take(2000) - .Select(j => new { j.JobId, j.RunId, j.State, j.CreatedUtc, j.RequestedBy }) + .Take(5000) .ToListAsync(cancellationToken); // Null RunId (legacy jobs) is treated as a single-target run keyed by its // own JobId. Grouping is in-memory to keep the coalesce provider-agnostic. - var executions = jobs + var groups = jobs .GroupBy(j => j.RunId ?? j.JobId) - .Select(g => new ExecutionSummaryDto( - g.Key, - scriptId, - g.Min(j => j.CreatedUtc), - g.Select(j => j.RequestedBy).FirstOrDefault(r => r is not null), - g.Count(), - g.Count(j => j.State == JobState.Succeeded), - g.Count(j => j.State is JobState.Failed or JobState.TimedOut), - g.Count(j => j.State is JobState.Queued or JobState.Running))) - .OrderByDescending(e => e.StartedUtc) - .Take(50) + .OrderByDescending(g => g.Min(j => j.CreatedUtc)) + .Take(limit) .ToList(); - return Results.Ok(executions); + var runIds = groups.Select(g => g.Key).ToList(); + var runs = await db.Runs.AsNoTracking() + .Where(r => runIds.Contains(r.RunId)) + .ToDictionaryAsync(r => r.RunId, cancellationToken); + var allowed = await scope.GetAllowedClientIdsAsync(context.User, cancellationToken); + var online = await OnlineAsync(db, groups.SelectMany(g => g).Select(j => j.ClientId), cancellationToken); + + return groups.Select(g => + { + var run = runs.GetValueOrDefault(g.Key); + var counts = Count(g.ToList(), SkipsOf(run, allowed), online); + var first = g.MinBy(j => j.CreatedUtc)!; + return new ExecutionSummaryDto( + g.Key, + first.ScriptId, + first.CreatedUtc, + run?.RequestedBy ?? g.Select(j => j.RequestedBy).FirstOrDefault(r => r is not null), + g.Count(), + counts.Succeeded, + counts.Failed, + counts.Pending + counts.Running, + run?.ScriptName ?? first.ScriptName, + run?.Source, + run?.TargetsLabel, + counts); + }).ToList(); } - /// A single execution and the targets (devices) it ran on. + /// A single execution: every target with its state, the skipped devices and the counts. private static async Task GetExecutionAsync( - Guid runId, AppDbContext db, CancellationToken cancellationToken) + Guid runId, AppDbContext db, DeviceScopeService scope, HttpContext context, CancellationToken cancellationToken) { - var jobs = await db.Jobs.AsNoTracking() + var jobs = await (await ScopedJobsAsync(db, scope, context, cancellationToken)) .Where(j => j.RunId == runId || j.JobId == runId) .OrderBy(j => j.CreatedUtc) .ToListAsync(cancellationToken); @@ -67,24 +289,70 @@ public static class JobEndpoints return Results.NotFound(); } - var hostnames = await db.Devices.AsNoTracking() - .Where(d => jobs.Select(j => j.ClientId).Contains(d.ClientId)) - .ToDictionaryAsync(d => d.ClientId, d => d.Hostname, cancellationToken); - + var run = await db.Runs.AsNoTracking().SingleOrDefaultAsync(r => r.RunId == runId, cancellationToken); + var allowed = await scope.GetAllowedClientIdsAsync(context.User, cancellationToken); + var skipped = SkipsOf(run, allowed); + var hostnames = await HostnamesAsync(db, jobs, cancellationToken); + var online = await OnlineAsync(db, jobs.Select(j => j.ClientId), cancellationToken); var targets = jobs.Select(j => new ExecutionTargetDto( j.JobId, j.ClientId, hostnames.GetValueOrDefault(j.ClientId), j.State, j.ExitCode, - j.CreatedUtc, j.StartedUtc, j.CompletedUtc)).ToList(); + j.CreatedUtc, j.StartedUtc, j.CompletedUtc, online.Contains(j.ClientId), j.OutputSummary)).ToList(); var first = jobs[0]; return Results.Ok(new ExecutionDetailDto( - runId, first.ScriptId, first.ScriptName, jobs.Min(j => j.CreatedUtc), - jobs.Select(j => j.RequestedBy).FirstOrDefault(r => r is not null), targets)); + runId, first.ScriptId, run?.ScriptName ?? first.ScriptName, jobs.Min(j => j.CreatedUtc), + run?.RequestedBy ?? jobs.Select(j => j.RequestedBy).FirstOrDefault(r => r is not null), targets, + run?.Source, run?.TargetsLabel, run?.OnlineOnly ?? false, + skipped.Select(s => new ExecutionSkipDto(s.ClientId, s.Hostname, s.Reason)).ToList(), + Count(jobs, skipped, online))); } - private static async Task ListAsync( - AppDbContext db, string? clientId, Guid? scriptId, int? limit, CancellationToken cancellationToken) + /// The run's skipped devices a scoped role may see. + private static List SkipsOf(RunEntity? run, IReadOnlySet? allowed) { - var query = db.Jobs.AsNoTracking().OrderByDescending(j => j.CreatedUtc).AsQueryable(); + if (run is null) + { + return []; + } + + var skips = Shared.Contracts.Serialization.JsonDefaults.Deserialize>(run.SkippedJson) ?? []; + return allowed is null ? skips : skips.Where(s => allowed.Contains(s.ClientId)).ToList(); + } + + /// Client ids among these that are online now. + private static async Task> OnlineAsync( + AppDbContext db, IEnumerable clientIds, CancellationToken cancellationToken) + { + var ids = clientIds.Distinct(StringComparer.Ordinal).ToList(); + var seen = await db.Devices.AsNoTracking() + .Where(d => ids.Contains(d.ClientId)) + .Select(d => new { d.ClientId, d.LastSeenUtc }) + .ToListAsync(cancellationToken); + var now = DateTimeOffset.UtcNow; + return seen + .Where(d => ProtocolDefaults.CalculateStatus(d.LastSeenUtc, now) == DeviceStatus.Online) + .Select(d => d.ClientId) + .ToHashSet(StringComparer.Ordinal); + } + + private static RunCountsDto Count(IReadOnlyCollection jobs, IReadOnlyCollection skipped, HashSet online) + => new( + Targets: jobs.Count + skipped.Count, + Pending: jobs.Count(j => j.State is JobState.Queued or JobState.Dispatched), + Running: jobs.Count(j => j.State == JobState.Running), + Succeeded: jobs.Count(j => j.State == JobState.Succeeded), + Failed: jobs.Count(j => j.State is JobState.Failed or JobState.TimedOut), + Cancelled: jobs.Count(j => j.State == JobState.Cancelled), + Skipped: skipped.Count, + Online: jobs.Select(j => j.ClientId).Distinct().Count(online.Contains)); + + private static async Task ListAsync( + AppDbContext db, DeviceScopeService scope, HttpContext context, string? clientId, Guid? scriptId, int? limit, + CancellationToken cancellationToken) + { + var query = (await ScopedJobsAsync(db, scope, context, cancellationToken)) + .OrderByDescending(j => j.CreatedUtc) + .AsQueryable(); if (!string.IsNullOrEmpty(clientId)) { query = query.Where(j => j.ClientId == clientId); @@ -96,16 +364,15 @@ public static class JobEndpoints } var jobs = await query.Take(Math.Clamp(limit ?? 100, 1, 500)).ToListAsync(cancellationToken); - var hostnames = await db.Devices.AsNoTracking() - .Where(d => jobs.Select(j => j.ClientId).Contains(d.ClientId)) - .ToDictionaryAsync(d => d.ClientId, d => d.Hostname, cancellationToken); - + var hostnames = await HostnamesAsync(db, jobs, cancellationToken); return Results.Ok(jobs.Select(j => ToDto(j, hostnames.GetValueOrDefault(j.ClientId))).ToList()); } - private static async Task GetAsync(Guid jobId, AppDbContext db, CancellationToken cancellationToken) + private static async Task GetAsync( + Guid jobId, AppDbContext db, DeviceScopeService scope, HttpContext context, CancellationToken cancellationToken) { - var job = await db.Jobs.AsNoTracking().SingleOrDefaultAsync(j => j.JobId == jobId, cancellationToken); + var job = await (await ScopedJobsAsync(db, scope, context, cancellationToken)) + .SingleOrDefaultAsync(j => j.JobId == jobId, cancellationToken); if (job is null) { return Results.NotFound(); @@ -120,9 +387,11 @@ public static class JobEndpoints } private static async Task GetOutputAsync( - Guid jobId, AppDbContext db, long? afterSequence, CancellationToken cancellationToken) + Guid jobId, AppDbContext db, DeviceScopeService scope, HttpContext context, long? afterSequence, + CancellationToken cancellationToken) { - var exists = await db.Jobs.AnyAsync(j => j.JobId == jobId, cancellationToken); + var exists = await (await ScopedJobsAsync(db, scope, context, cancellationToken)) + .AnyAsync(j => j.JobId == jobId, cancellationToken); if (!exists) { return Results.NotFound(); @@ -138,6 +407,15 @@ public static class JobEndpoints return Results.Ok(records); } + private static Task> HostnamesAsync( + AppDbContext db, IReadOnlyCollection jobs, CancellationToken cancellationToken) + { + var clientIds = jobs.Select(j => j.ClientId).Distinct().ToList(); + return db.Devices.AsNoTracking() + .Where(d => clientIds.Contains(d.ClientId)) + .ToDictionaryAsync(d => d.ClientId, d => d.Hostname, cancellationToken); + } + private static async Task CreateAsync( CreateJobRequest request, AppDbContext db, @@ -148,9 +426,22 @@ public static class JobEndpoints HttpContext context, CancellationToken cancellationToken) { - if ((request.ClientId is null) == (request.GroupId is null)) + var groupIds = (request.GroupIds ?? []) + .Concat(request.GroupId is { } single ? [single] : []) + .Distinct() + .ToList(); + var clientIds = (request.ClientIds ?? []) + .Concat(request.ClientId is { } one ? [one] : []) + .Distinct(StringComparer.Ordinal) + .ToList(); + if (groupIds.Count == 0 && clientIds.Count == 0) { - return Results.BadRequest(new { error = "Target exactly one of clientId or groupId." }); + return Results.BadRequest(new { error = "Choose at least one device or group to run on." }); + } + + if (clientIds.FirstOrDefault(id => !SubjectIdentifier.IsValid(id)) is not null) + { + return Results.BadRequest(new { error = "Invalid client id." }); } var script = await db.Scripts.AsNoTracking() @@ -160,6 +451,14 @@ public static class JobEndpoints return Results.NotFound(new { error = "Script not found." }); } + // The original single-device contract: 404/409 on the device itself + // and the created JobDto back (CLI and older UIs depend on it). + var singleDevice = groupIds.Count == 0 && clientIds.Count == 1 && request.ClientIds is not { Count: > 0 }; + if (singleDevice && await CheckSingleDeviceAsync(clientIds[0], db, scope, context, cancellationToken) is { } refused) + { + return refused; + } + var actor = context.User.Identity?.Name; // Secrets, file presigns and the prelude are prepared once, before any @@ -176,182 +475,145 @@ public static class JobEndpoints return Results.Problem(ex.Message, statusCode: StatusCodes.Status502BadGateway); } - if (request.GroupIds is { Count: > 0 } groupIds) + var selected = await db.DeviceGroups.AsNoTracking() + .Where(g => groupIds.Contains(g.Id)) + .ToListAsync(cancellationToken); + if (selected.Count < groupIds.Count) { - return await RunOnGroupsAsync( - groupIds, prepared, request, db, runner, groups, scope, audit, actor, context, cancellationToken); + return Results.NotFound(new { error = groupIds.Count == 1 ? "Group not found." : "Some groups no longer exist." }); } - if (request.GroupId is { } groupId) + var targetIds = new HashSet(clientIds, StringComparer.Ordinal); + foreach (var group in selected) { - return await RunOnGroupAsync( - groupId, prepared, request, db, runner, groups, scope, audit, actor, context, cancellationToken); + targetIds.UnionWith(await groups.GetMembersAsync(group, cancellationToken)); } - if (!SubjectIdentifier.IsValid(request.ClientId)) + // A scoped role only reaches the devices inside its own scope. + var allowed = await scope.GetAllowedClientIdsAsync(context.User, cancellationToken); + if (allowed is not null) { - return Results.BadRequest(new { error = "Invalid client id." }); + targetIds.IntersectWith(allowed); } - if (!await scope.IsAllowedAsync(context.User, request.ClientId!, cancellationToken)) + var devices = await db.Devices.AsNoTracking() + .Where(d => targetIds.Contains(d.ClientId)) + .OrderBy(d => d.Hostname) + .ToListAsync(cancellationToken); + + var now = DateTimeOffset.UtcNow; + var jobs = new List(); + var runId = Guid.NewGuid(); + var via = selected.Count == 1 && clientIds.Count == 0 ? $" (group “{selected[0].Name}”)" : string.Empty; + + // Devices currently offline still get a job unless OnlineOnly: dispatch + // is durable (JetStream holds it until they return). + var skipped = new List(); + var eligible = new List(); + foreach (var device in devices) + { + if (device.IsOrphaned) + { + skipped.Add(new RunSkip(device.ClientId, device.Hostname, SkipReasons.Orphaned)); + } + else if (request.OnlineOnly && ProtocolDefaults.CalculateStatus(device.LastSeenUtc, now) != DeviceStatus.Online) + { + skipped.Add(new RunSkip(device.ClientId, device.Hostname, SkipReasons.Offline)); + } + else + { + eligible.Add(device); + } + } + + var skippedOrphaned = skipped.Where(s => s.Reason == SkipReasons.Orphaned).Select(s => s.Hostname).ToList(); + var skippedOffline = skipped.Where(s => s.Reason == SkipReasons.Offline).Select(s => s.Hostname).ToList(); + if (eligible.Count > 0) + { + await runner.RecordRunAsync( + runId, script, actor, RunSources.Manual, TargetsLabel(selected, clientIds, devices), skipped, + cancellationToken, request.OnlineOnly); + } + + foreach (var device in eligible) + { + var job = await runner.CreateJobAsync(script, device.ClientId, actor, cancellationToken, runId); + await runner.DispatchAsync( + prepared, job, request.Arguments, + $"Job “{script.Name}” queued for {device.Hostname}{via}", cancellationToken); + jobs.Add(ToDto(job, device.Hostname)); + } + + if (singleDevice && jobs.Count == 0) + { + // Keeps the single-device contract (a JobDto or a refusal) when + // OnlineOnly skipped the one device asked for. + return Results.Conflict(new { error = "The device is not online." }); + } + + if (singleDevice && jobs.Count == 1) + { + await audit.LogAsync(AuditCategories.Jobs, "created", actor, + clientId: jobs[0].ClientId, detail: $"script={script.Name} job={jobs[0].JobId}", + cancellationToken: cancellationToken); + return Results.Created(ApiRoutes.For.Job(jobs[0].JobId), jobs[0]); + } + + await audit.LogAsync(AuditCategories.Jobs, "group-run", actor, + detail: $"script={script.Name} run={runId} groups={selected.Count} devices={clientIds.Count} " + + $"jobs={jobs.Count} skippedOrphaned={skippedOrphaned.Count} skippedOffline={skippedOffline.Count}", + cancellationToken: cancellationToken); + + return Results.Ok(new GroupRunDto( + jobs, skippedOrphaned, jobs.Count > 0 ? runId : null, skippedOffline)); + } + + /// "Group “Lab” and 3 devices", or a lone device's hostname. + private static string? TargetsLabel( + IReadOnlyList groups, IReadOnlyList clientIds, IReadOnlyList devices) + { + var parts = new List(); + if (groups.Count > 0) + { + var names = string.Join(", ", groups.Take(3).Select(g => $"“{g.Name}”")) + (groups.Count > 3 ? $" +{groups.Count - 3}" : string.Empty); + parts.Add((groups.Count == 1 ? "Group " : "Groups ") + names); + } + + if (clientIds.Count == 1 && devices.FirstOrDefault(d => d.ClientId == clientIds[0]) is { } device) + { + parts.Add(device.Hostname); + } + else if (clientIds.Count > 1) + { + parts.Add($"{clientIds.Count} devices"); + } + + return parts.Count > 0 ? string.Join(" and ", parts) : null; + } + + /// Refusal for a single-device run (unknown, out of scope, orphaned), or null. + private static async Task CheckSingleDeviceAsync( + string clientId, AppDbContext db, DeviceScopeService scope, HttpContext context, + CancellationToken cancellationToken) + { + if (!await scope.IsAllowedAsync(context.User, clientId, cancellationToken)) { return Results.NotFound(new { error = "Device not found." }); } var device = await db.Devices.AsNoTracking() - .SingleOrDefaultAsync(d => d.ClientId == request.ClientId, cancellationToken); + .SingleOrDefaultAsync(d => d.ClientId == clientId, cancellationToken); if (device is null) { return Results.NotFound(new { error = "Device not found." }); } - if (device.IsOrphaned) - { - return Results.Conflict(new + return device.IsOrphaned + ? Results.Conflict(new { error = "Device is orphaned. Push a new bootstrap token to the endpoint so the agent re-enrolls.", - }); - } - - var job = await runner.CreateJobAsync(script, device.ClientId, actor, cancellationToken, Guid.NewGuid()); - await runner.DispatchAsync( - prepared, job, request.Arguments, - $"Job “{script.Name}” queued for {device.Hostname}", cancellationToken); - - await audit.LogAsync(AuditCategories.Jobs, "created", actor, - clientId: device.ClientId, detail: $"script={script.Name} job={job.JobId}", - cancellationToken: cancellationToken); - - return Results.Created(ApiRoutes.For.Job(job.JobId), ToDto(job, device.Hostname)); - } - - /// One job per non-orphaned member; devices currently offline still - /// get one because dispatch is durable (JetStream holds it until they return). - private static async Task RunOnGroupAsync( - Guid groupId, - PreparedScript prepared, - CreateJobRequest request, - AppDbContext db, - JobRunner runner, - Backend.Groups.DeviceGroupService groups, - DeviceScopeService scope, - AuditService audit, - string? actor, - HttpContext context, - CancellationToken cancellationToken) - { - var group = await db.DeviceGroups.AsNoTracking() - .SingleOrDefaultAsync(g => g.Id == groupId, cancellationToken); - if (group is null) - { - return Results.NotFound(new { error = "Group not found." }); - } - - var memberIds = await groups.GetMembersAsync(group, cancellationToken); - - // A scoped role can only reach the members inside its own device scope. - var allowed = await scope.GetAllowedClientIdsAsync(context.User, cancellationToken); - if (allowed is not null) - { - memberIds = memberIds.Where(allowed.Contains).ToList(); - } - - var devices = await db.Devices.AsNoTracking() - .Where(d => memberIds.Contains(d.ClientId)) - .ToListAsync(cancellationToken); - - var jobs = new List(); - var skipped = new List(); - var runId = Guid.NewGuid(); - - foreach (var device in devices) - { - if (device.IsOrphaned) - { - skipped.Add(device.Hostname); - continue; - } - - var job = await runner.CreateJobAsync(prepared.Script, device.ClientId, actor, cancellationToken, runId); - await runner.DispatchAsync( - prepared, job, request.Arguments, - $"Job “{prepared.Script.Name}” queued for {device.Hostname} (group “{group.Name}”)", - cancellationToken); - jobs.Add(ToDto(job, device.Hostname)); - } - - await audit.LogAsync(AuditCategories.Jobs, "group-run", actor, - detail: $"script={prepared.Script.Name} group={group.Name} jobs={jobs.Count} skipped={skipped.Count}", - cancellationToken: cancellationToken); - - return Results.Ok(new GroupRunDto(jobs, skipped)); - } - - /// Run across the deduped union of several groups' members, as one execution. - private static async Task RunOnGroupsAsync( - IReadOnlyList groupIds, - PreparedScript prepared, - CreateJobRequest request, - AppDbContext db, - JobRunner runner, - Backend.Groups.DeviceGroupService groups, - DeviceScopeService scope, - AuditService audit, - string? actor, - HttpContext context, - CancellationToken cancellationToken) - { - var selected = await db.DeviceGroups.AsNoTracking() - .Where(g => groupIds.Contains(g.Id)) - .ToListAsync(cancellationToken); - if (selected.Count == 0) - { - return Results.NotFound(new { error = "No matching groups." }); - } - - var memberIds = new HashSet(); - foreach (var group in selected) - { - foreach (var member in await groups.GetMembersAsync(group, cancellationToken)) - { - memberIds.Add(member); - } - } - - var allowed = await scope.GetAllowedClientIdsAsync(context.User, cancellationToken); - if (allowed is not null) - { - memberIds.IntersectWith(allowed); - } - - var devices = await db.Devices.AsNoTracking() - .Where(d => memberIds.Contains(d.ClientId)) - .ToListAsync(cancellationToken); - - var jobs = new List(); - var skipped = new List(); - var runId = Guid.NewGuid(); - - foreach (var device in devices) - { - if (device.IsOrphaned) - { - skipped.Add(device.Hostname); - continue; - } - - var job = await runner.CreateJobAsync(prepared.Script, device.ClientId, actor, cancellationToken, runId); - await runner.DispatchAsync( - prepared, job, request.Arguments, - $"Job “{prepared.Script.Name}” queued for {device.Hostname}", cancellationToken); - jobs.Add(ToDto(job, device.Hostname)); - } - - await audit.LogAsync(AuditCategories.Jobs, "group-run", actor, - detail: $"script={prepared.Script.Name} groups={selected.Count} jobs={jobs.Count} skipped={skipped.Count}", - cancellationToken: cancellationToken); - - return Results.Ok(new GroupRunDto(jobs, skipped)); + }) + : null; } private static JobDto ToDto(JobEntity job, string? hostname) => new( diff --git a/src/Backend/Jobs/JobRunner.cs b/src/Backend/Jobs/JobRunner.cs index 2a6fee5..4003424 100644 --- a/src/Backend/Jobs/JobRunner.cs +++ b/src/Backend/Jobs/JobRunner.cs @@ -5,6 +5,7 @@ using Backend.Secrets; using Microsoft.EntityFrameworkCore; using Shared.Contracts.Messages; using Shared.Contracts.Models; +using Shared.Contracts.Serialization; using Shared.Infrastructure.Constants; namespace Backend.Jobs; @@ -124,6 +125,33 @@ public sealed class JobRunner( return deliveries; } + /// Records a run before its jobs: its source, targets and the devices it skipped. + public async Task RecordRunAsync( + Guid runId, ScriptEntity script, string? requestedBy, string source, string? targetsLabel, + IReadOnlyList skipped, CancellationToken cancellationToken, bool onlineOnly = false, Guid? triggerId = null) + { + db.Runs.Add(new RunEntity + { + RunId = runId, + ScriptId = script.Id, + ScriptName = script.Name, + CreatedUtc = DateTimeOffset.UtcNow, + RequestedBy = requestedBy, + Source = source, + TriggerId = triggerId, + TargetsLabel = targetsLabel is { Length: > 400 } ? targetsLabel[..399] + "…" : targetsLabel, + OnlineOnly = onlineOnly, + SkippedJson = JsonDefaults.Serialize(skipped), + }); + await db.SaveChangesAsync(cancellationToken); + + // Runs follow their jobs' retention: one whose jobs were all pruned has nothing left to show. + var cutoff = DateTimeOffset.UtcNow.AddDays(-7); + await db.Runs + .Where(r => r.CreatedUtc < cutoff && !db.Jobs.Any(j => j.RunId == r.RunId)) + .ExecuteDeleteAsync(cancellationToken); + } + public async Task CreateJobAsync( ScriptEntity script, string clientId, string? requestedBy, CancellationToken cancellationToken, Guid? runId = null) diff --git a/src/Backend/Jobs/ScheduleCron.cs b/src/Backend/Jobs/ScheduleCron.cs index 0533c1b..de9bab0 100644 --- a/src/Backend/Jobs/ScheduleCron.cs +++ b/src/Backend/Jobs/ScheduleCron.cs @@ -21,6 +21,12 @@ public static class ScheduleCron return $"Invalid cron expression: {ex.Message}"; } + return ValidateTimeZone(timeZoneId); + } + + /// Returns an error message, or null when the IANA/Windows zone id resolves. + public static string? ValidateTimeZone(string timeZoneId) + { try { TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); diff --git a/src/Backend/Jobs/ScheduleWorker.cs b/src/Backend/Jobs/ScheduleWorker.cs index 69b7bbc..b471222 100644 --- a/src/Backend/Jobs/ScheduleWorker.cs +++ b/src/Backend/Jobs/ScheduleWorker.cs @@ -1,10 +1,6 @@ -using System.Text.Json; using Backend.Data; -using Backend.Groups; -using Backend.Secrets; using Microsoft.EntityFrameworkCore; using Shared.Contracts.Models; -using Shared.Contracts.Serialization; namespace Backend.Jobs; @@ -53,8 +49,7 @@ public sealed class ScheduleWorker(IServiceScopeFactory scopeFactory, ILogger(); - var runner = scope.ServiceProvider.GetRequiredService(); - var groups = scope.ServiceProvider.GetRequiredService(); + var executor = scope.ServiceProvider.GetRequiredService(); var now = DateTimeOffset.UtcNow; var due = await db.ScriptTriggers @@ -66,7 +61,7 @@ public sealed class ScheduleWorker(IServiceScopeFactory scopeFactory, ILogger s.Id == trigger.ScriptId, cancellationToken); - if (script is null) - { - trigger.Enabled = false; - trigger.LastResult = "Disabled: the script no longer exists."; - return; - } - - var devices = await ResolveTargetsAsync(trigger, db, groups, cancellationToken); - if (devices.Count == 0) - { - trigger.LastResult = "No eligible devices at fire time."; - return; - } - - PreparedScript prepared; - try - { - prepared = await runner.PrepareAsync(script, cancellationToken); - } - catch (Exception ex) when (ex is SecretResolutionException or Backend.Files.FileResolutionException) - { - trigger.LastResult = ex.Message; - logger.LogWarning("Scheduled trigger {TriggerId}: {Message}", trigger.Id, ex.Message); - return; - } - - var arguments = string.IsNullOrWhiteSpace(trigger.ArgumentsJson) - ? null - : JsonDefaults.Deserialize>(trigger.ArgumentsJson); - - var queued = 0; - var runId = Guid.NewGuid(); - foreach (var device in devices) - { - var job = await runner.CreateJobAsync(script, device.ClientId, "schedule", cancellationToken, runId); - await runner.DispatchAsync( - prepared, job, arguments, - $"Scheduled trigger queued “{script.Name}” for {device.Hostname}", - cancellationToken); - queued++; - } - - trigger.LastResult = $"{queued} job(s) queued"; - logger.LogInformation( - "Scheduled trigger {TriggerId} queued {Count} job(s) of “{Script}”", trigger.Id, queued, script.Name); - } - - private static async Task> ResolveTargetsAsync( - ScriptTriggerEntity trigger, - AppDbContext db, - DeviceGroupService groups, - CancellationToken cancellationToken) - { - if (trigger.ClientId is { } clientId) - { - var device = await db.Devices.AsNoTracking() - .SingleOrDefaultAsync(d => d.ClientId == clientId && !d.IsOrphaned, cancellationToken); - return device is null ? [] : [device]; - } - - if (trigger.GroupId is { } groupId) - { - var group = await db.DeviceGroups.AsNoTracking() - .SingleOrDefaultAsync(g => g.Id == groupId, cancellationToken); - if (group is null) - { - return []; - } - - var memberIds = await groups.GetMembersAsync(group, cancellationToken); - return await db.Devices.AsNoTracking() - .Where(d => memberIds.Contains(d.ClientId) && !d.IsOrphaned) - .ToListAsync(cancellationToken); - } - - // No target = all devices. - return await db.Devices.AsNoTracking() - .Where(d => !d.IsOrphaned) - .ToListAsync(cancellationToken); - } - private static void Advance(ScriptTriggerEntity trigger) { - trigger.LastRunUtc = DateTimeOffset.UtcNow; - if (trigger.CronExpression is { } cron) { try diff --git a/src/Backend/Jobs/TriggerExecutor.cs b/src/Backend/Jobs/TriggerExecutor.cs new file mode 100644 index 0000000..9cb163b --- /dev/null +++ b/src/Backend/Jobs/TriggerExecutor.cs @@ -0,0 +1,172 @@ +using System.Text.Json; +using Backend.Data; +using Backend.Groups; +using Backend.Secrets; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Serialization; + +namespace Backend.Jobs; + +/// What one firing of a trigger did. +public sealed record TriggerFiring(Guid? RunId, int Queued, string Message); + +/// +/// Fires a trigger against its current target (device, group or all devices) +/// as one execution. The schedule sweep and the operator's "Run now" share +/// this, so both record the same LastResult/LastRunId and pass the trigger's +/// captured arguments. The caller owns saving the trigger entity. +/// +public sealed class TriggerExecutor( + AppDbContext db, + JobRunner runner, + DeviceGroupService groups, + ILogger logger) +{ + public async Task FireAsync( + ScriptTriggerEntity trigger, string requestedBy, CancellationToken cancellationToken) + { + trigger.LastRunUtc = DateTimeOffset.UtcNow; + + var script = await db.Scripts.AsNoTracking() + .SingleOrDefaultAsync(s => s.Id == trigger.ScriptId, cancellationToken); + if (script is null) + { + trigger.Enabled = false; + return Record(trigger, new TriggerFiring(null, 0, "Disabled: the script no longer exists.")); + } + + var (targetsLabel, targeted) = await ResolveTargetsAsync(trigger, cancellationToken); + var devices = targeted.Where(d => !d.IsOrphaned).ToList(); + if (devices.Count == 0) + { + return Record(trigger, new TriggerFiring(null, 0, "No eligible devices at fire time.")); + } + + PreparedScript prepared; + try + { + prepared = await runner.PrepareAsync(script, cancellationToken); + } + catch (Exception ex) when (ex is SecretResolutionException or Backend.Files.FileResolutionException) + { + logger.LogWarning("Trigger {TriggerId}: {Message}", trigger.Id, ex.Message); + return Record(trigger, new TriggerFiring(null, 0, ex.Message)); + } + + var arguments = ParseArguments(trigger.ArgumentsJson); + var label = string.IsNullOrWhiteSpace(trigger.Name) ? "Scheduled trigger" : $"Schedule “{trigger.Name}”"; + var runId = Guid.NewGuid(); + var skipped = targeted + .Where(d => d.IsOrphaned) + .Select(d => new RunSkip(d.ClientId, d.Hostname, SkipReasons.Orphaned)) + .ToList(); + await runner.RecordRunAsync( + runId, script, requestedBy, RunSources.Schedule, targetsLabel, skipped, cancellationToken, triggerId: trigger.Id); + foreach (var device in devices) + { + var job = await runner.CreateJobAsync(script, device.ClientId, requestedBy, cancellationToken, runId); + await runner.DispatchAsync( + prepared, job, arguments, + $"{label} queued “{script.Name}” for {device.Hostname}", + cancellationToken); + } + + logger.LogInformation( + "Trigger {TriggerId} queued {Count} job(s) of “{Script}”", trigger.Id, devices.Count, script.Name); + return Record(trigger, new TriggerFiring(runId, devices.Count, $"{devices.Count} job(s) queued")); + } + + /// + /// Saves a fired trigger. If it was edited (or toggled, or its group was + /// deleted) while firing, that change wins — the sweep's cadence advance + /// is dropped — and only the firing's outcome is recorded onto it. If it + /// was deleted, there is nothing left to record. Returns false then. + /// + public async Task SaveFiringAsync(ScriptTriggerEntity trigger, CancellationToken cancellationToken) + { + try + { + await db.SaveChangesAsync(cancellationToken); + return true; + } + catch (DbUpdateConcurrencyException) + { + var entry = db.Entry(trigger); + var (lastRunUtc, lastResult, lastRunId) = (trigger.LastRunUtc, trigger.LastResult, trigger.LastRunId); + var current = await entry.GetDatabaseValuesAsync(cancellationToken); + if (current is null) + { + entry.State = EntityState.Detached; + logger.LogInformation("Trigger {TriggerId} was deleted while firing", trigger.Id); + return false; + } + + entry.OriginalValues.SetValues(current); + entry.CurrentValues.SetValues(current); + trigger.LastRunUtc = lastRunUtc; + trigger.LastResult = lastResult; + trigger.LastRunId = lastRunId ?? trigger.LastRunId; + try + { + await db.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateConcurrencyException) + { + // Changed yet again: its newest state stands; this firing's note is lost. + entry.State = EntityState.Detached; + logger.LogWarning("Trigger {TriggerId} kept changing while firing; outcome not recorded", trigger.Id); + return false; + } + + logger.LogInformation("Trigger {TriggerId} changed while firing; kept the change", trigger.Id); + return true; + } + } + + /// Captured argument values, or null when none were saved. + public static Dictionary? ParseArguments(string? argumentsJson) + => string.IsNullOrWhiteSpace(argumentsJson) + ? null + : JsonDefaults.Deserialize>(argumentsJson); + + private static TriggerFiring Record(ScriptTriggerEntity trigger, TriggerFiring firing) + { + trigger.LastResult = firing.Message; + if (firing.RunId is not null) + { + trigger.LastRunId = firing.RunId; + } + + return firing; + } + + /// The devices the trigger targets right now (orphaned ones included, to be skipped), and a label. + private async Task<(string Label, List Devices)> ResolveTargetsAsync( + ScriptTriggerEntity trigger, CancellationToken cancellationToken) + { + if (trigger.ClientId is { } clientId) + { + var device = await db.Devices.AsNoTracking() + .SingleOrDefaultAsync(d => d.ClientId == clientId, cancellationToken); + return device is null ? (clientId, []) : (device.Hostname, [device]); + } + + if (trigger.GroupId is { } groupId) + { + var group = await db.DeviceGroups.AsNoTracking() + .SingleOrDefaultAsync(g => g.Id == groupId, cancellationToken); + if (group is null) + { + return ("Group", []); + } + + var memberIds = await groups.GetMembersAsync(group, cancellationToken); + return ($"Group “{group.Name}”", await db.Devices.AsNoTracking() + .Where(d => memberIds.Contains(d.ClientId)) + .ToListAsync(cancellationToken)); + } + + // No target = all devices. + return ("All Devices", await db.Devices.AsNoTracking().ToListAsync(cancellationToken)); + } +} diff --git a/src/Backend/Messaging/MessagingWorkers.cs b/src/Backend/Messaging/MessagingWorkers.cs index 7f648d0..0fb1985 100644 --- a/src/Backend/Messaging/MessagingWorkers.cs +++ b/src/Backend/Messaging/MessagingWorkers.cs @@ -107,8 +107,10 @@ public sealed class MessagingWorkers( var previous = ProtocolDefaults.CalculateStatus(device.LastSeenUtc, DateTimeOffset.UtcNow); device.LastSeenUtc = DateTimeOffset.UtcNow; - device.Hostname = payload.Hostname; + Api.DeviceHistory.Apply(db, device, payload.Hostname); device.AgentVersion = payload.AgentVersion; + // Older agents send no runtime; what a newer build reported stands. + device.AgentRuntime = payload.Runtime ?? device.AgentRuntime; await db.SaveChangesAsync(cancellationToken); lock (lastKnownStatus) @@ -160,11 +162,10 @@ public sealed class MessagingWorkers( continue; } - device.Hostname = report.Identity.Hostname; + Api.DeviceHistory.Apply(db, device, report.Identity.Hostname, + reportsOs: true, report.Os.Caption, report.Os.Version); device.Manufacturer = report.Identity.Manufacturer; device.Model = report.Identity.Model; - device.OsCaption = report.Os.Caption; - device.OsVersion = report.Os.Version; device.LastSeenUtc = DateTimeOffset.UtcNow; var addresses = report.Network @@ -205,12 +206,38 @@ public sealed class MessagingWorkers( /// /// Agent lifecycle events. A "ready" notice means the agent is connected /// and consuming job commands, which fires OnAgentReady script triggers. + /// Agent upgrade progress and outcomes share the subject, told apart by + /// the envelope's message type. /// private async Task ConsumeAgentEventsAsync(CancellationToken cancellationToken) { await foreach (var msg in hub.Require().SubscribeAsync(NatsSubjects.AllAgentEvents, queueGroup: WorkerQueueGroup, cancellationToken: cancellationToken)) { - var payload = Parse(msg.Data); + var envelope = ParseEnvelope(msg.Data); + if (envelope?.MessageType == MessageTypes.AgentUpgrade) + { + try + { + await Upgrades.AgentUpgradeEvents.HandleAsync(scopeFactory, msg.Subject, envelope, cancellationToken); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + logger.LogError(ex, "Agent upgrade event from {Subject} failed", msg.Subject); + } + + continue; + } + + AgentEventPayload? payload = null; + try + { + payload = envelope?.GetPayload(); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to parse agent event"); + } + if (payload is null || !SubjectIdentifier.IsValid(payload.ClientId) || payload.Kind != AgentEventKinds.Ready) @@ -428,6 +455,24 @@ public sealed class MessagingWorkers( } } + private MessageEnvelope? ParseEnvelope(byte[]? data) + { + if (data is null || data.Length == 0) + { + return null; + } + + try + { + return MessageEnvelope.FromUtf8Bytes(data); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to parse message envelope"); + return null; + } + } + private T? Parse(byte[]? data) where T : class { if (data is null || data.Length == 0) diff --git a/src/Backend/Program.cs b/src/Backend/Program.cs index 3717748..38aecde 100644 --- a/src/Backend/Program.cs +++ b/src/Backend/Program.cs @@ -131,12 +131,10 @@ builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddScoped(); -// ── Authentication / authorization ───────────────────────────────────────── -// Environment values bootstrap authentication; the Settings UI overrides them -// and the OIDC handler is rebuilt on save without a restart. -var authBootstrap = AuthBootstrap.FromConfiguration(builder.Configuration); -builder.Services.AddScoped(); -builder.AddControlPlaneAuth(authBootstrap); +// ── Sign-in and access ───────────────────────────────────────────────────── +// Built-In accounts, local Windows accounts, LDAP and OIDC (Settings › +// Authentication), database sessions, and group → role bindings. +builder.AddSignIn(); // ── Messaging ──────────────────────────────────────────────────────────── builder.Services.AddSingleton(); @@ -146,6 +144,7 @@ builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddScoped(); +builder.Services.AddScoped(); // S3: environment values are the bootstrap defaults; anything saved from the // Settings UI overrides them, so these are resolved per-request. builder.Services.AddSingleton(S3Options.FromConfiguration(builder.Configuration)); @@ -158,6 +157,17 @@ builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); +// Agent upgrades: the version catalog (every node keeps its copies current), +// upgrade planning and events, and the paced sender (with the schedules). +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddSingleton(sp => sp.GetRequiredService()); +if (builder.Configuration["AGENT_CATALOG_SYNC"] != "0") +{ + builder.Services.AddHostedService(); +} // Standalone single-binary: supervise the bundled NATS server when enabled // (started explicitly before the NATS client connects; see below). if (Backend.Standalone.NatsSidecar.IsEnabled(builder.Configuration)) @@ -172,11 +182,13 @@ builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddHostedService(); -// SCHEDULE_WORKER=0 keeps the background sweep out of test hosts, where it -// races the tests' deterministic manual sweeps. +// SCHEDULE_WORKER=0 keeps the background sweeps (schedules, agent upgrades) +// out of test hosts, where they race the tests' deterministic manual sweeps, +// and off all but the one worker replica in a scaled deployment. if (builder.Configuration["SCHEDULE_WORKER"] != "0") { builder.Services.AddHostedService(); + builder.Services.AddHostedService(); } builder.Services.AddHostedService(sp => sp.GetRequiredService()); @@ -234,20 +246,12 @@ using (var scope = app.Services.CreateScope()) db.Database.Migrate(); app.Logger.LogInformation("Database ready ({Provider})", databaseOptions.Provider); - // System roles must exist before any user is created or resolved. - await scope.ServiceProvider.GetRequiredService().EnsureSystemRolesAsync(CancellationToken.None); - // First-boot defaults: platform dynamic groups + starter schedules. await DefaultSeeder.SeedAsync(db, CancellationToken.None); - // First-boot initial admin from environment secrets. INITIAL_ADMIN_MUST_CHANGE - // (set by standalone `setup` when the admin/admin default was used) forces a - // password reset on the first sign-in. - await scope.ServiceProvider.GetRequiredService().EnsureInitialAdminAsync( - builder.Configuration["INITIAL_ADMIN_USERNAME"], - builder.Configuration["INITIAL_ADMIN_PASSWORD"], - builder.Configuration["INITIAL_ADMIN_MUST_CHANGE"] == "1", - CancellationToken.None); + // System roles, the break-glass account on an empty database (from + // INITIAL_ADMIN_* when set), and the move of an older install onto role bindings. + await app.Services.GetRequiredService().RunAsync(CancellationToken.None); if (app.Environment.IsDevelopment() && !db.Scripts.Any()) { @@ -322,9 +326,7 @@ if (staticUiPath is not null) } app.UseRateLimiter(); -app.UseAuthentication(); -app.UseAuthorization(); -app.Use(CsrfProtection.Middleware); +app.UseSignIn(); // Standalone single-binary: relay /messaging/* to the (sidecar) NATS // WebSocket listener — the role nginx plays in the container deployment. @@ -385,9 +387,7 @@ app.MapGet(ApiRoutes.Ready, async (AppDbContext db, NatsHub hub, NatsCredentialI return ready ? Results.Ok(payload) : Results.Json(payload, statusCode: StatusCodes.Status503ServiceUnavailable); }); -AuthEndpoints.Map(app); -AuthSettingsEndpoints.Map(app); -AccessControlEndpoints.Map(app); +app.MapSignIn(); EnrollmentEndpoints.Map(app); InstallEndpoints.Map(app); DeviceEndpoints.Map(app); @@ -402,6 +402,7 @@ FileDeliveryEndpoints.Map(app); GroupEndpoints.Map(app); TriggerEndpoints.Map(app); SettingsEndpoints.Map(app); +Backend.Upgrades.AgentUpgradeEndpoints.Map(app); Backend.Secrets.SecretsEndpoints.Map(app); if (staticUiPath is not null) diff --git a/src/Backend/Security/AuditService.cs b/src/Backend/Security/AuditService.cs index ea40494..53276d8 100644 --- a/src/Backend/Security/AuditService.cs +++ b/src/Backend/Security/AuditService.cs @@ -38,4 +38,8 @@ public static class AuditCategories public const string Shell = "shell"; public const string Admin = "admin"; public const string Settings = "settings"; + public const string Automation = "automation"; + + /// A device's own trail: enrolled, renamed, OS changed (see DeviceHistory). + public const string Device = "device"; } diff --git a/src/Backend/Shell/ShellBridge.cs b/src/Backend/Shell/ShellBridge.cs index 27a29b0..bcc6f9a 100644 --- a/src/Backend/Shell/ShellBridge.cs +++ b/src/Backend/Shell/ShellBridge.cs @@ -36,13 +36,13 @@ public sealed class ShellBridge( return binding; } - /// Publishes the privileged shell.open command to the agent. - public async Task OpenAsync(ShellBinding binding, int cols, int rows, CancellationToken cancellationToken) + /// Publishes the privileged shell.open command to the agent (: a value). + public async Task OpenAsync(ShellBinding binding, int cols, int rows, string? shell, CancellationToken cancellationToken) { var envelope = MessageEnvelope.Create( MessageTypes.CommandShellOpen, BackendSource, - new ShellOpenCommandPayload(binding.ShellId, cols, rows), + new ShellOpenCommandPayload(binding.ShellId, cols, rows, shell), new EndpointRef(EndpointKinds.Agent, binding.ClientId)); await hub.Require().PublishAsync( diff --git a/src/Backend/Shell/ShellEndpoints.cs b/src/Backend/Shell/ShellEndpoints.cs index b733278..694b2f1 100644 --- a/src/Backend/Shell/ShellEndpoints.cs +++ b/src/Backend/Shell/ShellEndpoints.cs @@ -38,6 +38,12 @@ public static class ShellEndpoints return Results.BadRequest(new { error = "Invalid request." }); } + var shell = ShellKinds.Normalize(request.Shell); + if (shell is null) + { + return Results.BadRequest(new { error = $"Unknown shell '{request.Shell}'. Use one of: {string.Join(", ", ShellKinds.All)}." }); + } + if (!await scope.IsAllowedAsync(context.User, clientId, cancellationToken)) { return Results.NotFound(); @@ -69,10 +75,11 @@ public static class ShellEndpoints await db.SaveChangesAsync(cancellationToken); var binding = bridge.Register(shellId, clientId, request.BrowserSessionId); - await bridge.OpenAsync(binding, Math.Clamp(request.Cols, 1, 500), Math.Clamp(request.Rows, 1, 200), cancellationToken); + await bridge.OpenAsync(binding, Math.Clamp(request.Cols, 1, 500), Math.Clamp(request.Rows, 1, 200), shell, cancellationToken); + // The requested shell lives in the audit detail (the session row has no column for it). await audit.LogAsync(AuditCategories.Shell, "opened", actor, - clientId: clientId, detail: $"shell={shellId}", + clientId: clientId, detail: $"shell={shellId} kind={shell}", remoteIp: Proxy.ClientIp.EffectiveText(context), cancellationToken: cancellationToken); return Results.Ok(new CreateShellResponse( diff --git a/src/Backend/Upgrades/AgentCatalog.cs b/src/Backend/Upgrades/AgentCatalog.cs new file mode 100644 index 0000000..b6469db --- /dev/null +++ b/src/Backend/Upgrades/AgentCatalog.cs @@ -0,0 +1,414 @@ +using Backend.Data; +using Backend.Files; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Api; +using Shared.Contracts.Models; + +namespace Backend.Upgrades; + +/// +/// Where catalog packages live on this node: <DATA_PATH>/agent-packages +/// (DATA_PATH unset: beside the database), one folder per version. +/// +public sealed class AgentCatalogStorage(IConfiguration configuration) +{ + public string Root { get; } = Path.Combine(DataRoot(configuration), "agent-packages"); + + /// The same data root the TLS store uses. + public static string DataRoot(IConfiguration configuration) + => configuration["DATA_PATH"] is { Length: > 0 } dataRoot + ? Path.GetFullPath(dataRoot) + : Path.GetDirectoryName(Path.GetFullPath( + configuration["DATABASE_PATH"] is { Length: > 0 } db ? db : "data/app.db")) ?? "data"; + + public string FullPath(string storagePath) + => Path.Combine(Root, storagePath.Replace('/', Path.DirectorySeparatorChar)); +} + +/// +/// The agent version catalog: every upgradable package of every version the +/// server has carried, so devices can be upgraded to the newest and rolled back +/// to an earlier one after the server image moves on. Each server release brings +/// its agent packages (baked in, or dropped into AGENT_PACKAGE_PATH); the +/// catalog worker imports them, and old versions are pruned to KeepVersions — +/// never the newest, one an open upgrade targets, or one a device's last +/// upgrade came from (its rollback target). +/// +public sealed class AgentCatalogService( + AppDbContext db, + AgentPackageService packages, + AgentCatalogStorage storage, + AgentUpgradeSettingsStore settings, + S3SettingsService s3Settings, + ILogger logger) +{ + /// A real release version (four numeric parts); a development 0.0.0.0 or a label is never catalogued. + public static bool IsCatalogVersion(string? version) + => !string.IsNullOrWhiteSpace(version) + && version.Length <= 64 + && Version.TryParse(version, out var parsed) + && parsed.Major > 0 + && version.All(c => char.IsAsciiDigit(c) || c == '.'); + + /// One pass: import what this node can see, offload to S3 when on, prune. + public async Task SyncAsync(CancellationToken cancellationToken) + { + foreach (var (packageType, path, version) in packages.LocateUpgradePackages()) + { + try + { + await ImportAsync(packageType, path, version, cancellationToken); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + logger.LogWarning(ex, "Importing agent package {Path} into the catalog failed", path); + } + } + + await OffloadAsync(cancellationToken); + await PruneAsync(cancellationToken); + } + + /// + /// Adds a package to the catalog (a copy under the catalog root) unless its + /// version and type are already there; an existing row whose file this node + /// lacks gets the copy when the source is the same build. Unknown versions, + /// and versions older than everything the catalog keeps, are skipped. + /// + public async Task ImportAsync( + string packageType, string sourcePath, string? version, CancellationToken cancellationToken) + { + if (!IsCatalogVersion(version) || !AgentPackageTypes.Upgradable.Contains(packageType) || !File.Exists(sourcePath)) + { + return null; + } + + var existing = await db.AgentPackages + .SingleOrDefaultAsync(p => p.Version == version && p.PackageType == packageType, cancellationToken); + if (existing is not null) + { + // Another node imported it (no shared data volume): keep a local copy too. + var localPath = storage.FullPath(existing.StoragePath); + if (!File.Exists(localPath) + && await AgentPackageService.ComputeSha256Async(sourcePath, cancellationToken) == existing.Sha256) + { + await CopyAsync(sourcePath, localPath, cancellationToken); + } + + return existing; + } + + var keep = (await settings.GetAsync(cancellationToken)).Settings.KeepVersions; + var versions = await VersionsNewestFirstAsync(cancellationToken); + if (versions.Count >= keep && AgentVersions.Compare(version, versions[keep - 1]) < 0) + { + return null; // Would be pruned straight away. + } + + var fileName = AgentPackageService.FileNameFor(packageType); + var storagePath = $"{version}/{fileName}"; + var sha = await AgentPackageService.ComputeSha256Async(sourcePath, cancellationToken); + await CopyAsync(sourcePath, storage.FullPath(storagePath), cancellationToken); + + var entity = new AgentPackageEntity + { + Id = Guid.NewGuid(), + Version = version!, + PackageType = packageType, + FileName = fileName, + Sha256 = sha, + SizeBytes = new FileInfo(sourcePath).Length, + StoragePath = storagePath, + ImportedUtc = DateTimeOffset.UtcNow, + }; + db.AgentPackages.Add(entity); + try + { + await db.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateException) + { + // Another replica imported the same version and type first. + db.Entry(entity).State = EntityState.Detached; + return await db.AgentPackages.AsNoTracking() + .SingleOrDefaultAsync(p => p.Version == version && p.PackageType == packageType, cancellationToken); + } + + logger.LogInformation("Agent {Version} ({Type}) added to the catalog", version, packageType); + return entity; + } + + private static async Task CopyAsync(string source, string destination, CancellationToken cancellationToken) + { + Directory.CreateDirectory(Path.GetDirectoryName(destination)!); + var temporary = destination + $".{Guid.NewGuid():N}.tmp"; + try + { + await using (var input = File.OpenRead(source)) + await using (var output = File.Create(temporary)) + { + await input.CopyToAsync(output, cancellationToken); + } + + File.Move(temporary, destination, overwrite: true); + } + finally + { + File.Delete(temporary); + } + } + + /// With agent offload on, every package this node holds goes to S3 too, and upgrades download from there. + private async Task OffloadAsync(CancellationToken cancellationToken) + { + if (!await s3Settings.GetAgentOffloadEnabledAsync(cancellationToken)) + { + return; + } + + var pending = await db.AgentPackages.Where(p => p.S3Key == null).ToListAsync(cancellationToken); + foreach (var package in pending) + { + var path = storage.FullPath(package.StoragePath); + if (File.Exists(path) + && await packages.UploadCatalogPackageAsync(path, package.FileName, package.Sha256, cancellationToken) is { } key) + { + package.S3Key = key; + await db.SaveChangesAsync(cancellationToken); + } + } + } + + public async Task> VersionsNewestFirstAsync(CancellationToken cancellationToken) + => (await db.AgentPackages.AsNoTracking().Select(p => p.Version).Distinct().ToListAsync(cancellationToken)) + .OrderByDescending(v => v, AgentVersions.Comparer) + .ToList(); + + /// + /// Why each version cannot be removed: the newest, one an open upgrade + /// targets, or one some device's latest successful upgrade came from. + /// + public async Task> GetRemoveBlockedReasonsAsync(CancellationToken cancellationToken) + { + var reasons = new Dictionary(StringComparer.Ordinal); + var versions = await VersionsNewestFirstAsync(cancellationToken); + if (versions.Count > 0) + { + reasons[versions[0]] = "The newest version: upgrades go to it."; + } + + var open = AgentUpgradeStates.Open.ToList(); + var targeted = await db.AgentUpgrades.AsNoTracking() + .Where(u => open.Contains(u.State)) + .Select(u => u.TargetVersion) + .Distinct() + .ToListAsync(cancellationToken); + foreach (var version in targeted) + { + reasons.TryAdd(version, "An open upgrade goes to it."); + } + + foreach (var (version, devices) in await RollbackTargetsAsync(cancellationToken)) + { + reasons.TryAdd(version, devices == 1 + ? "1 device can roll back to it." + : $"{devices} devices can roll back to it."); + } + + return reasons; + } + + /// Per version: how many devices' latest successful upgrade came from it. + private async Task> RollbackTargetsAsync(CancellationToken cancellationToken) + { + var succeeded = await db.AgentUpgrades.AsNoTracking() + .Where(u => u.State == AgentUpgradeStates.Succeeded) + .Select(u => new { u.ClientId, u.FromVersion, u.FinishedUtc, u.CreatedUtc }) + .ToListAsync(cancellationToken); + + return succeeded + .GroupBy(u => u.ClientId, StringComparer.Ordinal) + .Select(g => g.MaxBy(u => u.FinishedUtc ?? u.CreatedUtc)!.FromVersion) + .Where(v => !string.IsNullOrWhiteSpace(v)) + .GroupBy(v => v!, StringComparer.Ordinal) + .ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal); + } + + /// Drops versions past the newest KeepVersions, except the ones still needed. + public async Task PruneAsync(CancellationToken cancellationToken) + { + var keep = (await settings.GetAsync(cancellationToken)).Settings.KeepVersions; + var versions = await VersionsNewestFirstAsync(cancellationToken); + if (versions.Count > keep) + { + var blocked = await GetRemoveBlockedReasonsAsync(cancellationToken); + foreach (var version in versions.Skip(keep).Where(v => !blocked.ContainsKey(v))) + { + await RemoveAsync(version, cancellationToken); + logger.LogInformation("Agent {Version} pruned from the catalog", version); + } + } + + DeleteUnlistedFolders(await VersionsNewestFirstAsync(cancellationToken)); + } + + /// + /// Removes a version (operator request): refused with the reason while it + /// is still needed. Null when removed; "not-found" when it is not there. + /// + public async Task TryRemoveAsync(string version, CancellationToken cancellationToken) + { + if (!await db.AgentPackages.AnyAsync(p => p.Version == version, cancellationToken)) + { + return "not-found"; + } + + if ((await GetRemoveBlockedReasonsAsync(cancellationToken)).TryGetValue(version, out var reason)) + { + return reason; + } + + await RemoveAsync(version, cancellationToken); + return null; + } + + private async Task RemoveAsync(string version, CancellationToken cancellationToken) + { + var rows = await db.AgentPackages.Where(p => p.Version == version).ToListAsync(cancellationToken); + db.AgentPackages.RemoveRange(rows); + await db.SaveChangesAsync(cancellationToken); + DeleteFolder(version); + } + + /// Folders of versions no longer catalogued (removed on another node, or a failed copy). + private void DeleteUnlistedFolders(IReadOnlyCollection versions) + { + if (!Directory.Exists(storage.Root)) + { + return; + } + + var listed = versions.ToHashSet(StringComparer.Ordinal); + foreach (var folder in Directory.EnumerateDirectories(storage.Root)) + { + var name = Path.GetFileName(folder); + if (!listed.Contains(name)) + { + DeleteFolder(name); + } + } + } + + private void DeleteFolder(string version) + { + var folder = Path.Combine(storage.Root, version); + try + { + if (Directory.Exists(folder)) + { + Directory.Delete(folder, recursive: true); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // In use (a download in progress): the next pass retries. + logger.LogDebug(ex, "Could not delete agent catalog folder {Folder}", folder); + } + } + + /// The package of exactly this version for the platform, or null. + public Task FindAsync(string version, string packageType, CancellationToken cancellationToken) + => db.AgentPackages.AsNoTracking() + .SingleOrDefaultAsync(p => p.Version == version && p.PackageType == packageType, cancellationToken); + + /// The newest package per platform (what upgrades default to). + public async Task> NewestByTypeAsync(CancellationToken cancellationToken) + => (await db.AgentPackages.AsNoTracking().ToListAsync(cancellationToken)) + .GroupBy(p => p.PackageType, StringComparer.Ordinal) + .ToDictionary( + g => g.Key, + g => g.OrderByDescending(p => p.Version, AgentVersions.Comparer).First(), + StringComparer.Ordinal); + + /// + /// What the agent downloads: a presigned object-store URL when offload is + /// on and the package is there, else this server's package route (a path + /// the agent resolves against its server URL). + /// + public async Task DownloadUrlAsync(AgentPackageEntity package, CancellationToken cancellationToken) + => package.S3Key is { } key && await packages.TryPresignOffloadedAsync(key, cancellationToken) is { } url + ? url + : ApiRoutes.For.AgentPackageBySha(package.Sha256); + + /// Every version newest first, with its packages, device count (within the caller's scope) and removal block. + public async Task> ListAsync( + IReadOnlySet? allowedClientIds, CancellationToken cancellationToken) + { + var rows = await db.AgentPackages.AsNoTracking().ToListAsync(cancellationToken); + var blocked = await GetRemoveBlockedReasonsAsync(cancellationToken); + var running = (await db.Devices.AsNoTracking() + .Where(d => d.AgentVersion != null) + .Select(d => new { d.ClientId, d.AgentVersion }) + .ToListAsync(cancellationToken)) + .Where(d => allowedClientIds is null || allowedClientIds.Contains(d.ClientId)) + .GroupBy(d => d.AgentVersion!, StringComparer.Ordinal) + .ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal); + + var versions = rows + .GroupBy(p => p.Version, StringComparer.Ordinal) + .OrderByDescending(g => g.Key, AgentVersions.Comparer) + .ToList(); + + return versions.Select((g, index) => new AgentVersionDto( + g.Key, + Newest: index == 0, + g.OrderBy(p => p.PackageType, StringComparer.Ordinal) + .Select(p => new AgentPackageDto(p.Version, p.PackageType, p.FileName, p.SizeBytes, p.Sha256, p.ImportedUtc)) + .ToList(), + running.GetValueOrDefault(g.Key), + g.Min(p => p.ImportedUtc), + blocked.GetValueOrDefault(g.Key))) + .ToList(); + } +} + +/// +/// Keeps the catalog current on every node: at startup and every few minutes it +/// imports the packages this node can see (each node keeps its own copy when +/// replicas share no data volume), offloads them when S3 offload is on, and +/// prunes. AGENT_CATALOG_SYNC=0 turns it off (test hosts drive it directly). +/// +public sealed class AgentCatalogWorker(IServiceScopeFactory scopeFactory, ILogger logger) + : BackgroundService +{ + private static readonly TimeSpan Interval = TimeSpan.FromMinutes(5); + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + try + { + using var scope = scopeFactory.CreateScope(); + await scope.ServiceProvider.GetRequiredService().SyncAsync(stoppingToken); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + return; + } + catch (Exception ex) + { + logger.LogError(ex, "Agent catalog sync failed"); + } + + try + { + await Task.Delay(Interval, stoppingToken); + } + catch (OperationCanceledException) + { + return; + } + } + } +} diff --git a/src/Backend/Upgrades/AgentUpgradeEndpoints.cs b/src/Backend/Upgrades/AgentUpgradeEndpoints.cs new file mode 100644 index 0000000..686a91d --- /dev/null +++ b/src/Backend/Upgrades/AgentUpgradeEndpoints.cs @@ -0,0 +1,396 @@ +using System.Collections.Concurrent; +using Backend.Auth; +using Backend.Data; +using Backend.Files; +using Backend.Groups; +using Backend.Messaging; +using Backend.Security; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Api; +using Shared.Contracts.Messages; +using Shared.Contracts.Models; +using Shared.Contracts.Serialization; +using Shared.Infrastructure.Nats; + +namespace Backend.Upgrades; + +/// +/// The agent version catalog, per-device upgrades and roll backs, Settings › +/// Agent Upgrades, and the package download upgrade commands point at. +/// +public static class AgentUpgradeEndpoints +{ + public const int DefaultListLimit = 200; + + public static void Map(WebApplication app) + { + app.MapGet(ApiRoutes.AgentVersions, ListVersionsAsync).RequirePermission(Permissions.DevicesView); + app.MapDelete(ApiRoutes.AgentVersion, RemoveVersionAsync).RequirePermission(Permissions.SettingsManage); + + app.MapGet(ApiRoutes.AgentUpgrades, ListAsync).RequirePermission(Permissions.DevicesView); + app.MapPost(ApiRoutes.AgentUpgrades, StartAsync).RequirePermission(Permissions.DevicesManage); + app.MapPost(ApiRoutes.AgentUpgradesRollback, RollBackAsync).RequirePermission(Permissions.DevicesManage); + app.MapPost(ApiRoutes.AgentUpgradeCancel, CancelAsync).RequirePermission(Permissions.DevicesManage); + + app.MapGet(ApiRoutes.AgentUpgradeSettings, GetSettingsAsync).RequirePermission(Permissions.DevicesView); + app.MapPut(ApiRoutes.AgentUpgradeSettings, SaveSettingsAsync).RequirePermission(Permissions.SettingsManage); + + // The public agent binary, like the install package, but with no + // per-address limit: a fleet behind one NAT upgrades through it. + app.MapGet(ApiRoutes.AgentPackageBySha, DownloadAsync).AllowAnonymous(); + } + + private static async Task ListVersionsAsync( + AgentCatalogService catalog, DeviceScopeService scope, HttpContext context, CancellationToken cancellationToken) + => Results.Ok(await catalog.ListAsync( + await scope.GetAllowedClientIdsAsync(context.User, cancellationToken), cancellationToken)); + + private static async Task RemoveVersionAsync( + string version, AgentCatalogService catalog, AuditService audit, HttpContext context, + CancellationToken cancellationToken) + { + switch (await catalog.TryRemoveAsync(version, cancellationToken)) + { + case null: + await audit.LogAsync(AuditCategories.Settings, "agent-version-removed", context.User.Identity?.Name, + detail: $"version={version}", cancellationToken: cancellationToken); + return Results.NoContent(); + case "not-found": + return Results.NotFound(); + case var reason: + return Results.Conflict(new { error = reason }); + } + } + + private static async Task ListAsync( + string? clientId, bool? open, int? limit, AppDbContext db, DeviceScopeService scope, HttpContext context, + CancellationToken cancellationToken) + { + var query = db.AgentUpgrades.AsNoTracking(); + if (!string.IsNullOrWhiteSpace(clientId)) + { + if (!await scope.IsAllowedAsync(context.User, clientId, cancellationToken)) + { + return Results.Ok(Array.Empty()); + } + + query = query.Where(u => u.ClientId == clientId); + } + + if (open == true) + { + var states = AgentUpgradeStates.Open.ToList(); + query = query.Where(u => states.Contains(u.State)); + } + + var allowed = await scope.GetAllowedClientIdsAsync(context.User, cancellationToken); + if (allowed is not null) + { + var ids = allowed.ToList(); + query = query.Where(u => ids.Contains(u.ClientId)); + } + + var rows = await query + .OrderByDescending(u => u.CreatedUtc) + .Take(Math.Clamp(limit ?? DefaultListLimit, 1, 5000)) + .ToListAsync(cancellationToken); + var hostnames = await HostnamesAsync(db, rows.Select(r => r.ClientId), cancellationToken); + return Results.Ok(rows.Select(r => AgentUpgradeService.ToDto(r, hostnames.GetValueOrDefault(r.ClientId))).ToList()); + } + + private static async Task StartAsync( + StartAgentUpgradeRequest request, AppDbContext db, AgentUpgradeService upgrades, DeviceGroupService groups, + DeviceScopeService scope, AuditService audit, BrowserEventBroadcaster broadcaster, HttpContext context, + CancellationToken cancellationToken) + { + var version = string.IsNullOrWhiteSpace(request.Version) ? null : request.Version.Trim(); + if (version is not null && !await db.AgentPackages.AnyAsync(p => p.Version == version, cancellationToken)) + { + return Results.NotFound(new { error = $"The server holds no agent {version}." }); + } + + var (devices, refused) = await ResolveTargetsAsync(request.ClientIds, request.GroupIds, db, groups, scope, context, cancellationToken); + if (refused is not null) + { + return refused; + } + + var actor = context.User.Identity?.Name; + var batch = await upgrades.StartAsync(devices, version, AgentUpgradeSources.Manual, actor, cancellationToken); + await AuditAndAnnounceAsync("agent-upgrade-started", $"version={version ?? "newest"}", batch, actor, audit, broadcaster, cancellationToken); + return Results.Ok(batch); + } + + private static async Task RollBackAsync( + RollBackAgentRequest request, AppDbContext db, AgentUpgradeService upgrades, DeviceGroupService groups, + DeviceScopeService scope, AuditService audit, BrowserEventBroadcaster broadcaster, HttpContext context, + CancellationToken cancellationToken) + { + var (devices, refused) = await ResolveTargetsAsync(request.ClientIds, request.GroupIds, db, groups, scope, context, cancellationToken); + if (refused is not null) + { + return refused; + } + + var actor = context.User.Identity?.Name; + var batch = await upgrades.RollBackAsync(devices, actor, cancellationToken); + await AuditAndAnnounceAsync("agent-rollback-started", null, batch, actor, audit, broadcaster, cancellationToken); + return Results.Ok(batch); + } + + private static async Task AuditAndAnnounceAsync( + string action, string? detail, AgentUpgradeBatchDto batch, string? actor, AuditService audit, + BrowserEventBroadcaster broadcaster, CancellationToken cancellationToken) + { + var skipped = string.Join(' ', batch.Skipped.GroupBy(s => s.Reason).Select(g => $"{g.Key}={g.Count()}")); + await audit.LogAsync(AuditCategories.Admin, action, actor, + detail: $"{(detail is null ? string.Empty : detail + " ")}queued={batch.Upgrades.Count}{(skipped.Length > 0 ? " skipped: " + skipped : string.Empty)}", + cancellationToken: cancellationToken); + + if (batch.Upgrades.Count > 0) + { + await broadcaster.BroadcastActivityAsync(new ActivityEventPayload( + AgentUpgradeService.ActivityKinds.Progress, + $"Agent {(action == "agent-rollback-started" ? "roll back" : "upgrade")} queued for {batch.Upgrades.Count} device(s)", + batch.Upgrades.Count == 1 ? batch.Upgrades[0].ClientId : null, null, DateTimeOffset.UtcNow), cancellationToken); + } + } + + /// + /// The named devices plus every member of the named groups (nested groups + /// and folders included), within the caller's device scope. + /// + private static async Task<(List Devices, IResult? Refused)> ResolveTargetsAsync( + IReadOnlyList? requestedClientIds, IReadOnlyList? requestedGroupIds, AppDbContext db, + DeviceGroupService groups, DeviceScopeService scope, HttpContext context, CancellationToken cancellationToken) + { + var clientIds = (requestedClientIds ?? []).Distinct(StringComparer.Ordinal).ToList(); + var groupIds = (requestedGroupIds ?? []).Distinct().ToList(); + if (clientIds.Count == 0 && groupIds.Count == 0) + { + return ([], Results.BadRequest(new { error = "Choose at least one device or group." })); + } + + if (clientIds.Any(id => !SubjectIdentifier.IsValid(id))) + { + return ([], Results.BadRequest(new { error = "Invalid client id." })); + } + + var selected = await db.DeviceGroups.AsNoTracking() + .Where(g => groupIds.Contains(g.Id)) + .ToListAsync(cancellationToken); + if (selected.Count < groupIds.Count) + { + return ([], Results.NotFound(new { error = groupIds.Count == 1 ? "Group not found." : "Some groups no longer exist." })); + } + + var targetIds = new HashSet(clientIds, StringComparer.Ordinal); + foreach (var group in selected) + { + targetIds.UnionWith(await groups.GetMembersAsync(group, cancellationToken)); + } + + // A scoped role only reaches the devices inside its own scope. + var allowed = await scope.GetAllowedClientIdsAsync(context.User, cancellationToken); + if (allowed is not null) + { + targetIds.IntersectWith(allowed); + } + + var ids = targetIds.ToList(); + var devices = await db.Devices.AsNoTracking() + .Where(d => ids.Contains(d.ClientId)) + .OrderBy(d => d.Hostname) + .ToListAsync(cancellationToken); + return (devices, null); + } + + private static async Task CancelAsync( + Guid id, AppDbContext db, AgentUpgradeService upgrades, DeviceScopeService scope, AuditService audit, + BrowserEventBroadcaster broadcaster, HttpContext context, CancellationToken cancellationToken) + { + var row = await db.AgentUpgrades.SingleOrDefaultAsync(u => u.Id == id, cancellationToken); + if (row is null || !await scope.IsAllowedAsync(context.User, row.ClientId, cancellationToken)) + { + return Results.NotFound(); + } + + if (row.State != AgentUpgradeStates.Queued) + { + return Results.Conflict(new { error = $"Only a queued upgrade can be cancelled; this one is {row.State}." }); + } + + upgrades.Finish(row, AgentUpgradeStates.Cancelled, AgentUpgradeReasons.Cancelled, null, DateTimeOffset.UtcNow); + try + { + await db.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateConcurrencyException) + { + return Results.Conflict(new { error = "The upgrade was sent meanwhile." }); + } + + var actor = context.User.Identity?.Name; + await audit.LogAsync(AuditCategories.Admin, "agent-upgrade-cancelled", actor, clientId: row.ClientId, + detail: $"upgrade={row.Id} target={row.TargetVersion}", cancellationToken: cancellationToken); + var hostname = (await HostnamesAsync(db, [row.ClientId], cancellationToken)).GetValueOrDefault(row.ClientId); + await broadcaster.BroadcastActivityAsync(new ActivityEventPayload( + AgentUpgradeService.ActivityKinds.Progress, $"{hostname ?? row.ClientId} agent upgrade cancelled", + row.ClientId, null, DateTimeOffset.UtcNow), cancellationToken); + return Results.Ok(AgentUpgradeService.ToDto(row, hostname)); + } + + private static Task> HostnamesAsync( + AppDbContext db, IEnumerable clientIds, CancellationToken cancellationToken) + { + var ids = clientIds.Distinct(StringComparer.Ordinal).ToList(); + return db.Devices.AsNoTracking() + .Where(d => ids.Contains(d.ClientId)) + .ToDictionaryAsync(d => d.ClientId, d => d.Hostname, cancellationToken); + } + + private static async Task GetSettingsAsync( + AgentUpgradeSettingsStore settings, HttpContext context, CancellationToken cancellationToken) + { + var (value, etag) = await settings.GetAsync(cancellationToken); + context.Response.Headers.ETag = ETags.Quote(etag); + return Results.Ok(value); + } + + /// Saves Settings › Agent Upgrades; If-Match (the GET's ETag) is honoured when sent. + private static async Task SaveSettingsAsync( + AgentUpgradeSettingsDto request, AppDbContext db, AgentUpgradeSettingsStore settings, AuditService audit, + HttpContext context, CancellationToken cancellationToken) + { + var errors = await AgentUpgradeSettingsStore.ValidateAsync(request, db, cancellationToken); + if (errors.Count > 0) + { + return Results.ValidationProblem(errors); + } + + var row = await SettingsDocuments.LoadAsync(db, AgentUpgradeSettingsStore.Key, cancellationToken); + if (context.Request.Headers.IfMatch.ToString() is { Length: > 0 } ifMatch) + { + ETags.RequireMatch(ifMatch, row?.Etag ?? SettingsDocuments.InitialEtag); + } + + var before = AgentUpgradeSettingsStore.Normalize( + SettingsDocuments.Parse(row?.Value, AgentUpgradeSettingsStore.Defaults)); + var after = AgentUpgradeSettingsStore.Normalize(request); + var actor = context.User.Identity?.Name; + if (SettingsDocuments.Stage(db, row, AgentUpgradeSettingsStore.Key, row is null ? null : before, after, actor)) + { + await db.SaveChangesAsync(cancellationToken); + settings.Invalidate(); + await audit.LogAsync(AuditCategories.Settings, "agent-upgrade-settings-updated", actor, + detail: Describe(before, after), cancellationToken: cancellationToken); + } + + return await GetSettingsAsync(settings, context, cancellationToken); + } + + private static string Describe(AgentUpgradeSettingsDto before, AgentUpgradeSettingsDto after) + { + var changes = new List(); + void Add(string name, T was, T now) + { + if (!EqualityComparer.Default.Equals(was, now)) + { + changes.Add($"{name}: {was} → {now}"); + } + } + + Add("automatic", before.AutomaticUpgrades, after.AutomaticUpgrades); + Add("startWithinMinutes", before.StartWithinMinutes, after.StartWithinMinutes); + Add("healthDeadlineMinutes", before.HealthDeadlineMinutes, after.HealthDeadlineMinutes); + Add("keepVersions", before.KeepVersions, after.KeepVersions); + Add("excludedGroups", string.Join(',', before.ExcludedGroupIds.Order()), string.Join(',', after.ExcludedGroupIds.Order())); + return changes.Count == 0 ? "no change" : string.Join("; ", changes); + } + + /// Hashes of the install packages on this node, keyed by path, size and write time (hashing per download would not scale). + private static readonly ConcurrentDictionary<(string Path, long Size, DateTime Written), string> InstallPackageHashes = new(); + + /// + /// GET /api/agent-packages/{sha256}: a catalog package by content hash, + /// with range support so an interrupted download resumes. Served from this + /// node's catalog copy; if this node has none (replicas without a shared + /// data volume), the install package when it is the same build, else the + /// S3 copy when one exists. + /// + private static async Task DownloadAsync( + string sha256, AppDbContext db, AgentCatalogStorage storage, AgentPackageService packages, + CancellationToken cancellationToken) + { + if (sha256.Length != 64 || !sha256.All(char.IsAsciiHexDigitLower)) + { + return Results.NotFound(); + } + + var package = await db.AgentPackages.AsNoTracking() + .Where(p => p.Sha256 == sha256) + .OrderBy(p => p.ImportedUtc) + .FirstOrDefaultAsync(cancellationToken); + if (package is null) + { + return Results.NotFound(); + } + + var path = storage.FullPath(package.StoragePath); + if (!File.Exists(path)) + { + path = packages.ResolveLocalPath(package.PackageType) is { } installPackage + && await HashAsync(installPackage, cancellationToken) == sha256 + ? installPackage + : null; + } + + if (path is null) + { + return package.S3Key is { } key && await packages.TryPresignOffloadedAsync(key, cancellationToken) is { } url + ? Results.Redirect(url, permanent: false) + : Results.NotFound(new { error = "This server node does not hold the package." }); + } + + return Results.File(path, "application/zip", package.FileName, enableRangeProcessing: true); + } + + private static async Task HashAsync(string path, CancellationToken cancellationToken) + { + var info = new FileInfo(path); + var key = (path, info.Length, info.LastWriteTimeUtc); + if (InstallPackageHashes.TryGetValue(key, out var hash)) + { + return hash; + } + + hash = await AgentPackageService.ComputeSha256Async(path, cancellationToken); + InstallPackageHashes[key] = hash; + return hash; + } +} + +/// Upgrade events on the agent event subject (MessageTypes.AgentUpgrade). +public static class AgentUpgradeEvents +{ + /// The client id in an agent subject ("agent.<clientId>.event"), or null. + public static string? SubjectClientId(string? subject) + { + var parts = subject?.Split('.'); + return parts is { Length: >= 3 } && parts[0] == "agent" ? parts[1] : null; + } + + public static async Task HandleAsync( + IServiceScopeFactory scopeFactory, string? subject, MessageEnvelope envelope, CancellationToken cancellationToken) + { + var payload = envelope.GetPayload(); + if (payload is null) + { + return; + } + + using var scope = scopeFactory.CreateScope(); + await scope.ServiceProvider.GetRequiredService() + .ApplyEventAsync(SubjectClientId(subject), payload, cancellationToken); + } +} diff --git a/src/Backend/Upgrades/AgentUpgradeScheduler.cs b/src/Backend/Upgrades/AgentUpgradeScheduler.cs new file mode 100644 index 0000000..c3bfd21 --- /dev/null +++ b/src/Backend/Upgrades/AgentUpgradeScheduler.cs @@ -0,0 +1,378 @@ +using Backend.Data; +using Backend.Groups; +using Backend.Jobs; +using Backend.Messaging; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Messages; +using Shared.Contracts.Models; +using Shared.Infrastructure.Constants; + +namespace Backend.Upgrades; + +/// What one scheduler pass did (for tests and logs). +public sealed record UpgradePass(int Sent, int Queued, int Finished); + +/// +/// Drives agent upgrades every 15 seconds: +/// +/// Sends queued upgrades of online devices in paced batches, so a large +/// fleet never downloads at once: each queued online device starts within +/// StartWithinMinutes of becoming ready (at least 10 a batch), and each agent +/// adds a random 0–15 s jitter. Only downloads are paced; devices installing +/// have finished theirs. +/// Closes rows the device stopped reporting on (no-report), rows whose +/// device already shows the target version (the outcome may have been lost), +/// and queued rows older than 7 days (expired: the device never came back). +/// With Automatic Upgrades on, queues online devices outside the +/// excluded groups that run an older version than the newest held for their +/// platform; never a downgrade, never a version that already failed or rolled +/// back on that device. +/// +/// Like the schedule worker it runs on the node with SCHEDULE_WORKER on; every +/// write is guarded by the row's concurrency stamp, so a second scheduler, an +/// event on another node or an operator's cancel can never double-send a row. +/// +public sealed class AgentUpgradeScheduler( + IServiceScopeFactory scopeFactory, + IAgentUpgradeSender sender, + ILogger logger) : BackgroundService +{ + public static readonly TimeSpan Tick = TimeSpan.FromSeconds(15); + public static readonly TimeSpan QueuedExpiry = TimeSpan.FromDays(7); + /// Sent or downloading with no event this long ⇒ no-report. + public static readonly TimeSpan ReportDeadline = TimeSpan.FromMinutes(30); + /// Installing: the health deadline plus this, with no outcome ⇒ no-report. + public static readonly TimeSpan InstallGrace = TimeSpan.FromMinutes(15); + public const int MinimumBatch = 10; + public const int StartJitterSeconds = 15; + public const string AutomaticRequester = "automatic"; + + /// When each queued row was first seen ready (queued, device online): its start window runs from here. + private readonly Dictionary readySince = []; + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + try + { + await RunPassAsync(DateTimeOffset.UtcNow, stoppingToken); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + return; + } + catch (Exception ex) + { + logger.LogError(ex, "Agent upgrade pass failed"); + } + + try + { + await Task.Delay(Tick, stoppingToken); + } + catch (OperationCanceledException) + { + return; + } + } + } + + internal async Task RunPassAsync(DateTimeOffset now, CancellationToken cancellationToken) + { + using var scope = scopeFactory.CreateScope(); + var services = scope.ServiceProvider; + var db = services.GetRequiredService(); + var upgrades = services.GetRequiredService(); + var catalog = services.GetRequiredService(); + var settings = (await services.GetRequiredService().GetAsync(cancellationToken)).Settings; + + var open = AgentUpgradeStates.Open.ToList(); + var rows = await db.AgentUpgrades.Where(u => open.Contains(u.State)).ToListAsync(cancellationToken); + var devices = await db.Devices.AsNoTracking().ToDictionaryAsync(d => d.ClientId, StringComparer.Ordinal, cancellationToken); + bool Online(string clientId) => devices.TryGetValue(clientId, out var d) + && !d.IsOrphaned + && ProtocolDefaults.CalculateStatus(d.LastSeenUtc, now) == DeviceStatus.Online; + + var finished = new List(); + var healthDeadline = TimeSpan.FromMinutes(settings.HealthDeadlineMinutes); + foreach (var row in rows) + { + var device = devices.GetValueOrDefault(row.ClientId); + var lastHeard = row.LastEventUtc ?? row.SentUtc ?? row.CreatedUtc; + if (device is null) + { + upgrades.Finish(row, AgentUpgradeStates.Cancelled, AgentUpgradeReasons.Cancelled, "The device was removed.", now); + } + else if (row.State == AgentUpgradeStates.Queued && now - row.CreatedUtc > QueuedExpiry) + { + upgrades.Finish(row, AgentUpgradeStates.Cancelled, AgentUpgradeReasons.Expired, + $"The device did not come online within {QueuedExpiry.TotalDays:0} days.", now); + } + else if (AgentVersions.Compare(device.AgentVersion, row.TargetVersion) == 0) + { + // Queued: nothing to do. Started: the outcome event may have been lost. + if (row.State == AgentUpgradeStates.Queued) + { + upgrades.Finish(row, AgentUpgradeStates.Succeeded, AgentUpgradeReasons.Already, null, now); + } + else + { + upgrades.Finish(row, AgentUpgradeStates.Succeeded, null, AgentUpgradeService.PresenceConfirmed, now); + } + } + else if (row.State is AgentUpgradeStates.Sent or AgentUpgradeStates.Downloading + && now - lastHeard > ReportDeadline) + { + upgrades.Finish(row, AgentUpgradeStates.Failed, AgentUpgradeReasons.NoReport, + $"No report from the device for {ReportDeadline.TotalMinutes:0} minutes.", now); + } + else if (row.State == AgentUpgradeStates.Installing && now - lastHeard > healthDeadline + InstallGrace) + { + upgrades.Finish(row, AgentUpgradeStates.Failed, AgentUpgradeReasons.NoReport, + "No outcome from the device after the health deadline.", now); + } + else + { + continue; + } + + finished.Add(row); + } + + // A device has one open upgrade; two queued at once (concurrent requests) keep the newest. + foreach (var group in rows.Where(r => AgentUpgradeStates.Open.Contains(r.State)).GroupBy(r => r.ClientId).Where(g => g.Count() > 1)) + { + var keep = group.Where(r => r.State != AgentUpgradeStates.Queued).MinBy(r => r.SentUtc) + ?? group.MaxBy(r => r.CreatedUtc)!; + foreach (var row in group.Where(r => r != keep && r.State == AgentUpgradeStates.Queued)) + { + upgrades.Finish(row, AgentUpgradeStates.Cancelled, AgentUpgradeReasons.Superseded, null, now); + finished.Add(row); + } + } + + var queued = settings.AutomaticUpgrades + ? await QueueAutomaticAsync(db, services, upgrades, catalog, settings, rows, devices.Values, Online, cancellationToken) + : []; + rows.AddRange(queued); + + if (!await SaveAsync(db, cancellationToken)) + { + return new UpgradePass(0, 0, 0); + } + + foreach (var row in finished.Where(r => r.State != AgentUpgradeStates.Cancelled)) + { + await upgrades.BroadcastAsync(row, devices.GetValueOrDefault(row.ClientId)?.Hostname ?? row.ClientId, cancellationToken); + } + + var sent = await SendBatchAsync(db, upgrades, catalog, settings, rows, Online, now, cancellationToken); + if (sent > 0 || queued.Count > 0) + { + await services.GetRequiredService().BroadcastActivityAsync(new ActivityEventPayload( + AgentUpgradeService.ActivityKinds.Progress, + sent > 0 ? $"Agent upgrade started on {sent} device(s)" : $"Agent upgrade queued for {queued.Count} device(s)", + null, null, DateTimeOffset.UtcNow), cancellationToken); + } + + return new UpgradePass(sent, queued.Count, finished.Count); + } + + /// + /// The next batch: queued rows of online devices, oldest-ready first. The + /// size is the smallest rate (at least ) at which + /// every waiting row still starts within its window: the j-th row must be + /// out within the ticks its window has left, so the batch is the largest + /// ceil(j / ticksLeft(j)). + /// + private async Task SendBatchAsync( + AppDbContext db, AgentUpgradeService upgrades, AgentCatalogService catalog, Shared.Contracts.Api.AgentUpgradeSettingsDto settings, + List rows, Func online, DateTimeOffset now, CancellationToken cancellationToken) + { + var ready = rows.Where(r => r.State == AgentUpgradeStates.Queued && online(r.ClientId)).ToList(); + var readyIds = ready.Select(r => r.Id).ToHashSet(); + foreach (var id in readySince.Keys.Where(id => !readyIds.Contains(id)).ToList()) + { + readySince.Remove(id); // Sent, closed, or the device went offline (its window restarts on return). + } + + foreach (var row in ready) + { + readySince.TryAdd(row.Id, now); + } + + var windowTicks = Math.Max(1, (int)(TimeSpan.FromMinutes(settings.StartWithinMinutes) / Tick)); + var ordered = ready.OrderBy(r => readySince[r.Id]).ThenBy(r => r.CreatedUtc).ToList(); + var batch = MinimumBatch; + for (var j = 1; j <= ordered.Count; j++) + { + var elapsed = (int)((now - readySince[ordered[j - 1].Id]) / Tick); + var ticksLeft = Math.Max(1, windowTicks - elapsed); + batch = Math.Max(batch, (j + ticksLeft - 1) / ticksLeft); + } + + var packages = new Dictionary(); + var sent = 0; + foreach (var row in ordered.Take(batch)) + { + if (row.PackageId is not { } packageId) + { + continue; + } + + if (!packages.TryGetValue(packageId, out var package)) + { + packages[packageId] = package = await db.AgentPackages.AsNoTracking() + .SingleOrDefaultAsync(p => p.Id == packageId, cancellationToken); + } + + if (package is null) + { + upgrades.Finish(row, AgentUpgradeStates.Failed, AgentUpgradeReasons.NoPackage, + "The version was removed from the server.", now); + await TrySaveRowAsync(db, row, cancellationToken); + continue; + } + + // Mark it sent first: a row is never handed to JetStream twice. + row.State = AgentUpgradeStates.Sent; + row.SentUtc = now; + row.LastEventUtc = null; + row.Attempts++; + if (!await TrySaveRowAsync(db, row, cancellationToken)) + { + continue; // Cancelled or taken meanwhile. + } + + var command = new AgentUpgradeCommandPayload( + row.Id, row.TargetVersion, row.PackageType, + await catalog.DownloadUrlAsync(package, cancellationToken), + package.Sha256, package.SizeBytes, + Revert: row.Source == AgentUpgradeSources.Rollback, + HealthDeadlineSeconds: settings.HealthDeadlineMinutes * 60, + StartJitterSeconds: StartJitterSeconds); + + if (!await sender.DispatchAgentUpgradeAsync(row.ClientId, command, cancellationToken)) + { + // Messaging is down: back to the queue, the next pass tries again. + row.State = AgentUpgradeStates.Queued; + row.SentUtc = null; + row.Attempts--; + await TrySaveRowAsync(db, row, cancellationToken); + logger.LogWarning("Agent upgrade {UpgradeId} could not be sent; retrying next pass", row.Id); + break; + } + + readySince.Remove(row.Id); + sent++; + } + + return sent; + } + + private async Task> QueueAutomaticAsync( + AppDbContext db, IServiceProvider services, AgentUpgradeService upgrades, AgentCatalogService catalog, + Shared.Contracts.Api.AgentUpgradeSettingsDto settings, List rows, + IEnumerable devices, Func online, CancellationToken cancellationToken) + { + var newest = await catalog.NewestByTypeAsync(cancellationToken); + if (newest.Count == 0) + { + return []; + } + + var excluded = new HashSet(StringComparer.Ordinal); + if (settings.ExcludedGroupIds.Count > 0) + { + var membership = await services.GetRequiredService().GetMembershipAsync(cancellationToken); + foreach (var groupId in settings.ExcludedGroupIds) + { + excluded.UnionWith(membership.Effective(groupId)); + } + } + + var busy = rows.Where(r => AgentUpgradeStates.Open.Contains(r.State)).Select(r => r.ClientId).ToHashSet(StringComparer.Ordinal); + var candidates = devices + .Where(d => online(d.ClientId) && !excluded.Contains(d.ClientId) && !busy.Contains(d.ClientId)) + .ToList(); + if (candidates.Count == 0) + { + return []; + } + + // Never again to a version that already failed, rolled back or was cancelled by an operator on that device. + var targets = newest.Values.Select(p => p.Version).Distinct().ToList(); + var refused = (await db.AgentUpgrades.AsNoTracking() + .Where(u => targets.Contains(u.TargetVersion) + && (u.State == AgentUpgradeStates.Failed + || u.State == AgentUpgradeStates.RolledBack + || (u.State == AgentUpgradeStates.Cancelled && u.Reason == AgentUpgradeReasons.Cancelled))) + .Select(u => new { u.ClientId, u.TargetVersion }) + .ToListAsync(cancellationToken)) + .Select(u => (u.ClientId, u.TargetVersion)) + .ToHashSet(); + + var types = await upgrades.ResolvePackageTypesAsync(candidates, cancellationToken); + var queued = new List(); + foreach (var device in candidates) + { + if (types.GetValueOrDefault(device.ClientId) is not { } type + || newest.GetValueOrDefault(type) is not { } package + || !AgentVersions.IsNewer(package.Version, device.AgentVersion) + || refused.Contains((device.ClientId, package.Version))) + { + continue; + } + + queued.Add(upgrades.Queue(device, package, AgentUpgradeSources.Automatic, AutomaticRequester)); + } + + if (queued.Count > 0) + { + logger.LogInformation("Automatic upgrades queued for {Count} device(s)", queued.Count); + } + + return queued; + } + + /// + /// Saves the pass's changes; false when a row changed elsewhere meanwhile + /// (an event, a cancel), and then nothing is kept: the next pass decides + /// again from what is stored. + /// + private async Task SaveAsync(AppDbContext db, CancellationToken cancellationToken) + { + try + { + await db.SaveChangesAsync(cancellationToken); + return true; + } + catch (DbUpdateConcurrencyException) + { + db.ChangeTracker.Clear(); + logger.LogDebug("Agent upgrades changed during the pass; deciding again next pass"); + return false; + } + } + + /// Saves one row's change; false (the row re-read, its history dropped) when it changed elsewhere first. + private static async Task TrySaveRowAsync(AppDbContext db, AgentUpgradeEntity row, CancellationToken cancellationToken) + { + try + { + await db.SaveChangesAsync(cancellationToken); + return true; + } + catch (DbUpdateConcurrencyException) + { + foreach (var added in db.ChangeTracker.Entries().Where(e => e.State == EntityState.Added).ToList()) + { + added.State = EntityState.Detached; + } + + await db.Entry(row).ReloadAsync(cancellationToken); + return false; + } + } +} diff --git a/src/Backend/Upgrades/AgentUpgradeService.cs b/src/Backend/Upgrades/AgentUpgradeService.cs new file mode 100644 index 0000000..bde8a48 --- /dev/null +++ b/src/Backend/Upgrades/AgentUpgradeService.cs @@ -0,0 +1,478 @@ +using Backend.Api; +using Backend.Data; +using Backend.Messaging; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Api; +using Shared.Contracts.Messages; +using Shared.Contracts.Models; +using Shared.Contracts.Serialization; +using Shared.Infrastructure.Grouping; +using Shared.Infrastructure.Nats; + +namespace Backend.Upgrades; + +/// +/// Agent upgrades: planning (who gets which version, who is left out and why), +/// the agent's progress and outcome events, and the device-history trail. The +/// scheduler sends what is planned here; nothing is sent from this class. +/// +public sealed class AgentUpgradeService( + AppDbContext db, + AgentCatalogService catalog, + BrowserEventBroadcaster broadcaster, + ILogger logger) +{ + /// Skip reasons beyond AgentUpgradeReasons. + public const string SkipOrphaned = SkipReasons.Orphaned; + public const string SkipNoPrevious = "no-previous"; + + /// Detail of a row the scheduler closed because presence already showed the target version. + public const string PresenceConfirmed = "Confirmed by presence: the device reports the target version."; + + /// States an agent may report. + private static readonly IReadOnlySet AgentStates = new HashSet(StringComparer.Ordinal) + { + AgentUpgradeStates.Downloading, AgentUpgradeStates.Installing, + AgentUpgradeStates.Succeeded, AgentUpgradeStates.Failed, AgentUpgradeStates.RolledBack, + }; + + private static readonly IReadOnlySet Outcomes = new HashSet(StringComparer.Ordinal) + { + AgentUpgradeStates.Succeeded, AgentUpgradeStates.Failed, AgentUpgradeStates.RolledBack, + }; + + /// + /// The package a device upgrades from: its reported runtime, or for older + /// agents that do not report one, the OS platform and architecture from + /// inventory (Windows is only built for x64). Null when there is no build. + /// + public static string? ResolvePackageType(string? runtime, string? osCaption, string? architecture) + { + if (AgentPackageTypes.ForRuntime(runtime) is { } fromRuntime) + { + return fromRuntime; + } + + if (!string.IsNullOrWhiteSpace(runtime)) + { + return null; // A runtime no package is built for (win-arm64, …). + } + + var arch = NormalizeArchitecture(architecture); + return DeviceFieldBag.DerivePlatform(osCaption) switch + { + "windows" => arch is null or "x64" ? AgentPackageTypes.WindowsZip : null, + "linux" => arch switch { "x64" => AgentPackageTypes.LinuxX64, "arm64" => AgentPackageTypes.LinuxArm64, _ => null }, + "macos" => arch switch { "x64" => AgentPackageTypes.MacX64, "arm64" => AgentPackageTypes.MacArm64, _ => null }, + _ => null, + }; + } + + /// x64, arm64, "other", or null when unknown ("64-bit", "X64", "x86_64", "ARM 64-bit Processor", "Arm64", …). + public static string? NormalizeArchitecture(string? architecture) + { + if (string.IsNullOrWhiteSpace(architecture)) + { + return null; + } + + var value = architecture.ToLowerInvariant(); + if (value.Contains("arm64") || value.Contains("aarch64") || value.Contains("arm 64")) + { + return "arm64"; + } + + if (value.Contains("arm")) + { + return "other"; + } + + return value.Contains("x64") || value.Contains("amd64") || value.Contains("x86_64") + || value.Contains("x86-64") || value.Contains("64-bit") || value.Contains("64 bit") + ? "x64" + : "other"; + } + + /// Package type per device, reading inventory only for devices that report no runtime. + public async Task> ResolvePackageTypesAsync( + IReadOnlyCollection devices, CancellationToken cancellationToken) + { + var withoutRuntime = devices.Where(d => string.IsNullOrWhiteSpace(d.AgentRuntime)).Select(d => d.ClientId).ToList(); + var inventory = withoutRuntime.Count == 0 + ? [] + : await db.DeviceInventory.AsNoTracking() + .Where(i => withoutRuntime.Contains(i.ClientId)) + .ToDictionaryAsync(i => i.ClientId, i => i.ReportJson, cancellationToken); + + var result = new Dictionary(StringComparer.Ordinal); + foreach (var device in devices) + { + InventoryReport? report = null; + if (inventory.TryGetValue(device.ClientId, out var json)) + { + try + { + report = JsonDefaults.Deserialize(json); + } + catch (System.Text.Json.JsonException) + { + // Corrupt snapshot: platform from the device row only. + } + } + + result[device.ClientId] = ResolvePackageType( + device.AgentRuntime, + report?.Os.Caption ?? device.OsCaption, + report?.Os.Architecture ?? report?.Identity.SystemType); + } + + return result; + } + + /// Client ids that already have an open upgrade. + public async Task> BusyAsync(IReadOnlyCollection clientIds, CancellationToken cancellationToken) + { + var open = AgentUpgradeStates.Open.ToList(); + var ids = clientIds.ToList(); + return (await db.AgentUpgrades.AsNoTracking() + .Where(u => open.Contains(u.State) && ids.Contains(u.ClientId)) + .Select(u => u.ClientId) + .ToListAsync(cancellationToken)) + .ToHashSet(StringComparer.Ordinal); + } + + /// + /// Queues an upgrade for each device to (null = + /// the newest the catalog holds for its platform). Offline devices are + /// queued too; they start when they come back. + /// + public async Task StartAsync( + IReadOnlyList devices, string? version, string source, string? requestedBy, + CancellationToken cancellationToken) + { + var types = await ResolvePackageTypesAsync(devices, cancellationToken); + var busy = await BusyAsync(devices.Select(d => d.ClientId).ToList(), cancellationToken); + var newest = await catalog.NewestByTypeAsync(cancellationToken); + var exact = version is null + ? [] + : (await db.AgentPackages.AsNoTracking().Where(p => p.Version == version).ToListAsync(cancellationToken)) + .ToDictionary(p => p.PackageType, StringComparer.Ordinal); + + var created = new List<(AgentUpgradeEntity Row, DeviceEntity Device)>(); + var skipped = new List(); + foreach (var device in devices) + { + var skip = PreCheck(device, types, busy); + AgentPackageEntity? package = null; + if (skip is null) + { + var type = types[device.ClientId]!; + package = version is null ? newest.GetValueOrDefault(type) : exact.GetValueOrDefault(type); + if (package is null) + { + skip = AgentUpgradeReasons.NoPackage; + } + else if (AgentVersions.Compare(device.AgentVersion, package.Version) == 0 + || (version is null && AgentVersions.IsNewer(device.AgentVersion, package.Version))) + { + // Already there (or, without an explicit version, ahead of the newest held). + skip = AgentUpgradeReasons.Already; + } + } + + if (skip is not null) + { + skipped.Add(new AgentUpgradeSkipDto(device.ClientId, device.Hostname, skip)); + continue; + } + + created.Add((Queue(device, package!, source, requestedBy), device)); + } + + await db.SaveChangesAsync(cancellationToken); + return new AgentUpgradeBatchDto(created.Select(c => ToDto(c.Row, c.Device.Hostname)).ToList(), skipped); + } + + /// + /// Queues a roll back for each device to the version its latest successful + /// upgrade came from (skipped "no-previous" when there is none, or the + /// catalog no longer holds that version for its platform). + /// + public async Task RollBackAsync( + IReadOnlyList devices, string? requestedBy, CancellationToken cancellationToken) + { + var types = await ResolvePackageTypesAsync(devices, cancellationToken); + var ids = devices.Select(d => d.ClientId).ToList(); + var busy = await BusyAsync(ids, cancellationToken); + var previous = (await db.AgentUpgrades.AsNoTracking() + .Where(u => u.State == AgentUpgradeStates.Succeeded && ids.Contains(u.ClientId)) + .Select(u => new { u.ClientId, u.FromVersion, u.FinishedUtc, u.CreatedUtc }) + .ToListAsync(cancellationToken)) + .GroupBy(u => u.ClientId, StringComparer.Ordinal) + .ToDictionary(g => g.Key, g => g.MaxBy(u => u.FinishedUtc ?? u.CreatedUtc)!.FromVersion, StringComparer.Ordinal); + + var created = new List<(AgentUpgradeEntity Row, DeviceEntity Device)>(); + var skipped = new List(); + foreach (var device in devices) + { + var skip = PreCheck(device, types, busy); + AgentPackageEntity? package = null; + if (skip is null) + { + var from = previous.GetValueOrDefault(device.ClientId); + if (string.IsNullOrWhiteSpace(from)) + { + skip = SkipNoPrevious; + } + else if (AgentVersions.Compare(device.AgentVersion, from) == 0) + { + skip = AgentUpgradeReasons.Already; + } + else if ((package = await catalog.FindAsync(from, types[device.ClientId]!, cancellationToken)) is null) + { + skip = SkipNoPrevious; + } + } + + if (skip is not null) + { + skipped.Add(new AgentUpgradeSkipDto(device.ClientId, device.Hostname, skip)); + continue; + } + + created.Add((Queue(device, package!, AgentUpgradeSources.Rollback, requestedBy), device)); + } + + await db.SaveChangesAsync(cancellationToken); + return new AgentUpgradeBatchDto(created.Select(c => ToDto(c.Row, c.Device.Hostname)).ToList(), skipped); + } + + private static string? PreCheck(DeviceEntity device, Dictionary types, HashSet busy) + { + if (device.IsOrphaned) + { + return SkipOrphaned; // Refuses commands until it re-enrolls. + } + + if (types.GetValueOrDefault(device.ClientId) is null) + { + return AgentUpgradeReasons.Unsupported; + } + + return busy.Contains(device.ClientId) ? AgentUpgradeReasons.Busy : null; + } + + /// Adds a queued row (the caller saves). + public AgentUpgradeEntity Queue(DeviceEntity device, AgentPackageEntity package, string source, string? requestedBy) + { + var row = new AgentUpgradeEntity + { + Id = Guid.NewGuid(), + ClientId = device.ClientId, + FromVersion = device.AgentVersion, + TargetVersion = package.Version, + PackageType = package.PackageType, + PackageId = package.Id, + Sha256 = package.Sha256, + Source = source, + State = AgentUpgradeStates.Queued, + RequestedBy = requestedBy, + CreatedUtc = DateTimeOffset.UtcNow, + }; + db.AgentUpgrades.Add(row); + return row; + } + + public static AgentUpgradeDto ToDto(AgentUpgradeEntity row, string? hostname) => new( + row.Id, row.ClientId, hostname, row.FromVersion, row.TargetVersion, row.Source, row.State, + row.Reason, row.Detail, ParseLog(row.LastLogJson), row.Attempts, row.RequestedBy, + row.CreatedUtc, row.SentUtc, row.FinishedUtc); + + private static IReadOnlyList? ParseLog(string? json) + { + if (string.IsNullOrWhiteSpace(json)) + { + return null; + } + + try + { + return JsonDefaults.Deserialize>(json); + } + catch (System.Text.Json.JsonException) + { + return null; + } + } + + /// + /// Closes a row with an outcome, writing the device-history event for a + /// device-side outcome (the caller saves). Cancelled and expired rows never + /// reached the device and leave no history. + /// + public void Finish(AgentUpgradeEntity row, string state, string? reason, string? detail, DateTimeOffset now) + { + row.State = state; + row.Reason = reason; + row.Detail = detail; + row.FinishedUtc = now; + RecordHistory(row); + } + + private void RecordHistory(AgentUpgradeEntity row) + { + var from = row.FromVersion ?? "unknown"; + switch (row.State) + { + case AgentUpgradeStates.Succeeded when row.Reason != AgentUpgradeReasons.Already: + DeviceHistory.RecordAgentUpgrade(db, row.ClientId, + row.Source == AgentUpgradeSources.Rollback ? DeviceHistory.AgentRolledBack : DeviceHistory.AgentUpgraded, + $"{from} → {row.TargetVersion}"); + break; + case AgentUpgradeStates.RolledBack: + // The watchdog put the previous version back. + DeviceHistory.RecordAgentUpgrade(db, row.ClientId, DeviceHistory.AgentRolledBack, + $"{row.TargetVersion} → {from} · {row.Reason ?? "rolled back"}"); + break; + case AgentUpgradeStates.Failed: + DeviceHistory.RecordAgentUpgrade(db, row.ClientId, DeviceHistory.AgentUpgradeFailed, + $"{from} → {row.TargetVersion} · {row.Reason ?? "failed"}" + + (string.IsNullOrWhiteSpace(row.Detail) ? string.Empty : $": {row.Detail}")); + break; + } + } + + /// + /// Applies an agent's upgrade event. Ignored: unknown ids, another device's + /// row, states only the server sets, and anything that would move a row + /// backwards. A finished row only takes a late outcome when it was closed + /// by the server without one (no report, or presence-confirmed). True when + /// the row changed. + /// + public async Task ApplyEventAsync( + string? subjectClientId, AgentUpgradeEventPayload payload, CancellationToken cancellationToken) + { + if (!SubjectIdentifier.IsValid(payload.ClientId) + || (subjectClientId is not null && !string.Equals(subjectClientId, payload.ClientId, StringComparison.Ordinal)) + || !AgentStates.Contains(payload.State)) + { + return false; + } + + for (var attempt = 0; attempt < 3; attempt++) + { + var row = await db.AgentUpgrades.SingleOrDefaultAsync(u => u.Id == payload.UpgradeId, cancellationToken); + if (row is null || !string.Equals(row.ClientId, payload.ClientId, StringComparison.Ordinal)) + { + return false; + } + + if (!Accepts(row, payload.State)) + { + return false; + } + + var now = DateTimeOffset.UtcNow; + row.LastEventUtc = now; + row.FromVersion ??= payload.FromVersion; + if (payload.LastLog is { Count: > 0 } log) + { + row.LastLogJson = JsonDefaults.Serialize(log.TakeLast(40).ToList()); + } + + if (Outcomes.Contains(payload.State)) + { + Finish(row, payload.State, payload.Reason, Truncate(payload.Detail), now); + } + else + { + row.State = payload.State; + row.Detail = Truncate(payload.Detail); + } + + try + { + await db.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateConcurrencyException) + { + // Changed on another node meanwhile (the scheduler's deadline): re-read and decide again. + db.ChangeTracker.Clear(); + continue; + } + + var hostname = await db.Devices.AsNoTracking() + .Where(d => d.ClientId == row.ClientId) + .Select(d => d.Hostname) + .SingleOrDefaultAsync(cancellationToken) ?? row.ClientId; + await BroadcastAsync(row, hostname, cancellationToken); + return true; + } + + logger.LogWarning("Upgrade {UpgradeId} kept changing; event {State} dropped", payload.UpgradeId, payload.State); + return false; + } + + private static bool Accepts(AgentUpgradeEntity row, string state) + { + if (row.State == AgentUpgradeStates.Failed && row.Reason == AgentUpgradeReasons.NoReport) + { + return Outcomes.Contains(state); // The real outcome, late. + } + + if (row.State == AgentUpgradeStates.Succeeded && row.Detail == PresenceConfirmed) + { + // Presence saw the new version before the watchdog decided; a success only confirms it. + return state is AgentUpgradeStates.Failed or AgentUpgradeStates.RolledBack; + } + + if (AgentUpgradeStates.Finished.Contains(row.State)) + { + return false; + } + + // Open: outcomes always; progress only forwards (or a repeat, e.g. download percentage). + return Outcomes.Contains(state) || Rank(state) >= Rank(row.State); + } + + private static int Rank(string state) => state switch + { + AgentUpgradeStates.Queued => 0, + AgentUpgradeStates.Sent => 1, + AgentUpgradeStates.Downloading => 2, + AgentUpgradeStates.Installing => 3, + _ => 4, + }; + + private static string? Truncate(string? value) => value is { Length: > 2000 } ? value[..2000] : value; + + /// + /// Tells consoles a row changed: "agent-upgrade" for outcomes (with a line + /// for the activity feed), "agent-upgrade-progress" for everything else. + /// + public async Task BroadcastAsync(AgentUpgradeEntity row, string hostname, CancellationToken cancellationToken) + { + var text = row.State switch + { + AgentUpgradeStates.Succeeded => row.Source == AgentUpgradeSources.Rollback + ? $"{hostname} agent rolled back to {row.TargetVersion}" + : $"{hostname} agent upgraded to {row.TargetVersion}", + AgentUpgradeStates.RolledBack => $"{hostname} agent upgrade to {row.TargetVersion} rolled back ({row.Reason ?? "unknown"})", + AgentUpgradeStates.Failed => $"{hostname} agent upgrade to {row.TargetVersion} failed ({row.Reason ?? "unknown"})", + AgentUpgradeStates.Downloading => $"{hostname} downloading agent {row.TargetVersion}", + AgentUpgradeStates.Installing => $"{hostname} installing agent {row.TargetVersion}", + _ => $"{hostname} agent upgrade {row.State}", + }; + + await broadcaster.BroadcastActivityAsync(new ActivityEventPayload( + Outcomes.Contains(row.State) ? ActivityKinds.Outcome : ActivityKinds.Progress, + text, row.ClientId, null, DateTimeOffset.UtcNow), cancellationToken); + } + + /// Activity kinds consoles refresh devices and upgrades on. + public static class ActivityKinds + { + public const string Outcome = "agent-upgrade"; + public const string Progress = "agent-upgrade-progress"; + } +} diff --git a/src/Backend/Upgrades/AgentUpgradeSettings.cs b/src/Backend/Upgrades/AgentUpgradeSettings.cs new file mode 100644 index 0000000..7d3ca7f --- /dev/null +++ b/src/Backend/Upgrades/AgentUpgradeSettings.cs @@ -0,0 +1,78 @@ +using Backend.Auth; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Shared.Contracts.Api; + +namespace Backend.Upgrades; + +/// +/// Settings › Agent Upgrades, kept as one versioned settings document. Values +/// outside their range (an older or hand-edited document) read as the default. +/// +public sealed class AgentUpgradeSettingsStore(SettingsDocuments documents) +{ + public const string Key = "agentUpgrades"; + + public static readonly AgentUpgradeSettingsDto Defaults = new( + AutomaticUpgrades: false, + StartWithinMinutes: 3, + HealthDeadlineMinutes: 10, + ExcludedGroupIds: [], + KeepVersions: 5); + + public static readonly (int Min, int Max) StartWithinRange = (1, 30); + public static readonly (int Min, int Max) HealthDeadlineRange = (2, 60); + public static readonly (int Min, int Max) KeepVersionsRange = (2, 50); + + public async Task<(AgentUpgradeSettingsDto Settings, string Etag)> GetAsync(CancellationToken cancellationToken) + { + var (value, etag) = await documents.GetAsync(Key, Defaults, cancellationToken); + return (Normalize(value), etag); + } + + public void Invalidate() => documents.Invalidate(Key); + + public static AgentUpgradeSettingsDto Normalize(AgentUpgradeSettingsDto value) => new( + value.AutomaticUpgrades, + InRange(value.StartWithinMinutes, StartWithinRange) ? value.StartWithinMinutes : Defaults.StartWithinMinutes, + InRange(value.HealthDeadlineMinutes, HealthDeadlineRange) ? value.HealthDeadlineMinutes : Defaults.HealthDeadlineMinutes, + value.ExcludedGroupIds?.Distinct().ToList() ?? [], + InRange(value.KeepVersions, KeepVersionsRange) ? value.KeepVersions : Defaults.KeepVersions); + + /// Field errors for a save (empty when valid); excluded groups must exist. + public static async Task> ValidateAsync( + AgentUpgradeSettingsDto value, AppDbContext db, CancellationToken cancellationToken) + { + var errors = new Dictionary(StringComparer.Ordinal); + if (!InRange(value.StartWithinMinutes, StartWithinRange)) + { + errors["startWithinMinutes"] = [$"Between {StartWithinRange.Min} and {StartWithinRange.Max} minutes."]; + } + + if (!InRange(value.HealthDeadlineMinutes, HealthDeadlineRange)) + { + errors["healthDeadlineMinutes"] = [$"Between {HealthDeadlineRange.Min} and {HealthDeadlineRange.Max} minutes."]; + } + + if (!InRange(value.KeepVersions, KeepVersionsRange)) + { + errors["keepVersions"] = [$"Between {KeepVersionsRange.Min} and {KeepVersionsRange.Max} versions."]; + } + + var excluded = value.ExcludedGroupIds?.Distinct().ToList() ?? []; + if (excluded.Count > 0) + { + var known = await db.DeviceGroups.AsNoTracking() + .Where(g => excluded.Contains(g.Id)) + .CountAsync(cancellationToken); + if (known < excluded.Count) + { + errors["excludedGroupIds"] = ["Some excluded groups no longer exist."]; + } + } + + return errors; + } + + private static bool InRange(int value, (int Min, int Max) range) => value >= range.Min && value <= range.Max; +} diff --git a/src/Infra/backend/Dockerfile b/src/Infra/backend/Dockerfile index f26c91a..1c4fd60 100644 --- a/src/Infra/backend/Dockerfile +++ b/src/Infra/backend/Dockerfile @@ -35,7 +35,7 @@ LABEL org.opencontainers.image.title="ExecuteR Control Plane Backend" \ org.opencontainers.image.url="${SOURCE_URL}" \ org.opencontainers.image.documentation="${SOURCE_URL}/wiki" \ org.opencontainers.image.vendor="ExecuteR" \ - org.opencontainers.image.licenses="AGPL-3.0" + org.opencontainers.image.licenses="LicenseRef-GraceSolutions-Proprietary" # curl is used by the compose health check. RUN apt-get update \ diff --git a/src/Infra/webui/Dockerfile b/src/Infra/webui/Dockerfile index 1896e23..01cc4f3 100644 --- a/src/Infra/webui/Dockerfile +++ b/src/Infra/webui/Dockerfile @@ -5,12 +5,12 @@ FROM node:24-alpine AS build ARG UNIFIED_VERSION=0.0.0.0 WORKDIR /app -COPY src/WebUI/package.json src/WebUI/package-lock.json ./ +COPY src/WebUI/package.json src/WebUI/package-lock.json src/WebUI/.npmrc ./ RUN npm ci COPY src/WebUI/ . ENV PUBLIC_BUILD_VERSION=${UNIFIED_VERSION} -RUN npm run build && npm prune --omit=dev +RUN npm run build FROM node:24-alpine ARG UNIFIED_VERSION=0.0.0.0 @@ -20,7 +20,7 @@ ARG GIT_COMMIT_SHORT="" ARG BUILD_DATE="" ARG SOURCE_URL="https://prod.git.gracesolution.info/gsadmin/ExecuteR" LABEL org.opencontainers.image.title="ExecuteR Control Plane WebUI" \ - org.opencontainers.image.description="ExecuteR web console: SvelteKit UI for devices, scripts, jobs and settings" \ + org.opencontainers.image.description="ExecuteR web console: React (MUI) UI for devices, groups, scripts, schedules and jobs" \ org.opencontainers.image.version="${UNIFIED_VERSION}" \ org.opencontainers.image.revision="${GIT_COMMIT}" \ executer.revision.short="${GIT_COMMIT_SHORT}" \ @@ -29,12 +29,13 @@ LABEL org.opencontainers.image.title="ExecuteR Control Plane WebUI" \ org.opencontainers.image.url="${SOURCE_URL}" \ org.opencontainers.image.documentation="${SOURCE_URL}/wiki" \ org.opencontainers.image.vendor="ExecuteR" \ - org.opencontainers.image.licenses="AGPL-3.0" + org.opencontainers.image.licenses="LicenseRef-GraceSolutions-Proprietary" +# The console is a static SPA; server.mjs (no dependencies) serves dist/ with +# an index.html fallback for client-side routes. WORKDIR /app -COPY --from=build /app/build ./build -COPY --from=build /app/node_modules ./node_modules -COPY --from=build /app/package.json . +COPY --from=build /app/dist ./dist +COPY --from=build /app/server.mjs . ENV PORT=3000 \ NODE_ENV=production @@ -42,4 +43,4 @@ ENV PORT=3000 \ EXPOSE 3000 USER node -CMD ["node", "build"] +CMD ["node", "server.mjs"] diff --git a/src/Installer/Product.wxs b/src/Installer/Product.wxs index 5242e05..84ed5e4 100644 --- a/src/Installer/Product.wxs +++ b/src/Installer/Product.wxs @@ -116,6 +116,37 @@ Wait="yes" /> + + + + + + + + + + + /// A role: a named permission set optionally restricted to a device scope. /// System roles (Admin/Operator/Viewer) are seeded and immutable; custom roles -/// are fully operator-defined. lists the -/// identity-provider group/role claim values that map sign-ins to this role. +/// are fully operator-defined. People get roles through their groups: a role +/// binding names a built-in group, a Windows account or group, a directory +/// group or an identity-provider claim. is how +/// many bindings grant it. /// public sealed record RoleDto( Guid Id, @@ -12,16 +14,14 @@ public sealed record RoleDto( string? Description, bool IsSystem, IReadOnlyList Permissions, - IReadOnlyList OidcClaimValues, IReadOnlyList DeviceScopeGroupIds, - int UserCount); + int BindingCount); /// POST /api/admin/roles and PUT /api/admin/roles/{id} request body. public sealed record SaveRoleRequest( string Name, string? Description, IReadOnlyList Permissions, - IReadOnlyList? OidcClaimValues = null, IReadOnlyList? DeviceScopeGroupIds = null); /// One grantable permission, grouped for display. @@ -29,30 +29,3 @@ public sealed record PermissionInfoDto(string Key, string Label, string Descript /// GET /api/admin/permissions response item. public sealed record PermissionGroupDto(string Group, IReadOnlyList Permissions); - -/// GET /api/admin/users response item. -public sealed record UserAccountDto( - Guid Id, - string Username, - string? DisplayName, - string AuthProvider, - Guid? RoleId, - string RoleName, - DateTimeOffset CreatedUtc, - DateTimeOffset? LastLoginUtc); - -/// POST /api/admin/users request body (local users only). -public sealed record CreateUserRequest( - string Username, - string Password, - Guid RoleId, - string? DisplayName = null); - -/// -/// PUT /api/admin/users/{id} request body. Null fields are left unchanged; -/// is only honored for local accounts. -/// -public sealed record UpdateUserRequest( - string? DisplayName = null, - Guid? RoleId = null, - string? Password = null); diff --git a/src/Shared.Contracts/Api/AgentUpgradeDtos.cs b/src/Shared.Contracts/Api/AgentUpgradeDtos.cs new file mode 100644 index 0000000..7b4fb24 --- /dev/null +++ b/src/Shared.Contracts/Api/AgentUpgradeDtos.cs @@ -0,0 +1,91 @@ +namespace Shared.Contracts.Api; + +/// One package of an agent version the server holds. +public sealed record AgentPackageDto( + string Version, + string PackageType, + string FileName, + long SizeBytes, + string Sha256, + DateTimeOffset ImportedUtc); + +/// +/// An agent version in the server's catalog, with its packages per platform +/// and how many devices run it. Newest is the version upgrades default to. +/// RemoveBlockedReason is set when it cannot be removed (the newest, or +/// still needed to roll a device back or by an open upgrade). +/// +public sealed record AgentVersionDto( + string Version, + bool Newest, + IReadOnlyList Packages, + int DeviceCount, + DateTimeOffset ImportedUtc, + string? RemoveBlockedReason); + +/// One device's upgrade attempt. +public sealed record AgentUpgradeDto( + Guid Id, + string ClientId, + string? Hostname, + string? FromVersion, + string TargetVersion, + string Source, + string State, + string? Reason, + string? Detail, + IReadOnlyList? LastLog, + int Attempts, + string? RequestedBy, + DateTimeOffset CreatedUtc, + DateTimeOffset? SentUtc, + DateTimeOffset? FinishedUtc); + +/// +/// POST /api/agent-upgrades: upgrade the agents on these devices and groups +/// (nested groups and folders included). Version null = the newest +/// version the server holds for each device's platform. A device already on +/// the target, or with an open upgrade, is left alone. Offline devices are +/// queued and upgrade when they return. +/// +public sealed record StartAgentUpgradeRequest( + IReadOnlyList? ClientIds = null, + IReadOnlyList? GroupIds = null, + string? Version = null); + +/// +/// POST /api/agent-upgrades/rollback: put each device back on the version its +/// last successful upgrade came from. +/// +public sealed record RollBackAgentRequest( + IReadOnlyList? ClientIds = null, + IReadOnlyList? GroupIds = null); + +/// A device an upgrade or rollback request left out, and why (e.g. "already", "no-package", "busy", "no-previous"). +public sealed record AgentUpgradeSkipDto(string ClientId, string? Hostname, string Reason); + +/// What a start or rollback request did: upgrades created, and devices left out. +public sealed record AgentUpgradeBatchDto( + IReadOnlyList Upgrades, + IReadOnlyList Skipped); + +/// +/// Settings › Agent Upgrades (GET/PUT /api/settings/agent-upgrades). +/// With AutomaticUpgrades on, online devices not in an excluded group +/// are kept on the newest version. Automatic upgrades never go to an older +/// version and never retry a version that already failed or rolled back on +/// that device. +/// +/// Upgrades start in paced batches so a large fleet never downloads at once: +/// every 15 seconds the next batch is sent, sized so every queued online device +/// has started within StartWithinMinutes (at least 10 a batch), and each +/// agent waits a random 0–15 seconds before downloading. Only downloads count +/// as load; a device installing has finished its download. +/// +/// +public sealed record AgentUpgradeSettingsDto( + bool AutomaticUpgrades, + int StartWithinMinutes, + int HealthDeadlineMinutes, + IReadOnlyList ExcludedGroupIds, + int KeepVersions); diff --git a/src/Shared.Contracts/Api/ApiRoutes.cs b/src/Shared.Contracts/Api/ApiRoutes.cs index eca15c1..44f0881 100644 --- a/src/Shared.Contracts/Api/ApiRoutes.cs +++ b/src/Shared.Contracts/Api/ApiRoutes.cs @@ -10,15 +10,23 @@ public static class ApiRoutes public const string Health = "/api/health"; public const string Ready = "/api/ready"; - public const string AuthLogin = "/api/auth/login"; - public const string AuthChangePassword = "/api/auth/change-password"; - public const string AuthLogout = "/api/auth/logout"; + // Sign-in (StifleR's model: built-in, local Windows accounts, LDAP, OIDC). + public const string AuthOptions = "/api/auth/options"; + public const string AuthSignIn = "/api/auth/sign-in"; public const string AuthSession = "/api/auth/session"; - public const string AuthConfig = "/api/auth/config"; - public const string AuthSettings = "/api/settings/auth"; - public const string AuthSettingsTest = "/api/settings/auth/test"; - public const string AuthOidcLogin = "/api/auth/oidc/login"; + public const string AuthSignOut = "/api/auth/sign-out"; + public const string AuthPassword = "/api/auth/password"; + public const string AuthOidcSignIn = "/api/auth/oidc/sign-in"; public const string AuthOidcCallback = "/api/auth/oidc/callback"; + public const string AuthStepUp = "/api/auth/step-up"; + public const string AuthStepUpOidc = "/api/auth/step-up/oidc"; + + // Settings › Authentication: one tab per method. + public const string SettingsAuthentication = "/api/settings/authentication"; + public const string SettingsAuthenticationMethod = "/api/settings/authentication/{method}"; + public const string SettingsAuthenticationTest = "/api/settings/authentication/{method}/test"; + public const string SettingsAuthenticationTestResult = "/api/settings/authentication/tests/{method}"; + public const string SettingsLdapBreakerReset = "/api/settings/authentication/ldap/breaker/reset"; public const string Bootstrap = "/api/enrollment/bootstrap"; public const string RefreshCredential = "/api/enrollment/credential"; @@ -28,6 +36,7 @@ public static class ApiRoutes public const string Devices = "/api/devices"; public const string Device = "/api/devices/{clientId}"; public const string DeviceInventory = "/api/devices/{clientId}/inventory"; + public const string DeviceHistory = "/api/devices/{clientId}/history"; public const string DeviceShell = "/api/devices/{clientId}/shell"; public const string DeviceFiles = "/api/devices/{clientId}/files"; @@ -40,12 +49,15 @@ public static class ApiRoutes public const string Groups = "/api/groups"; public const string Group = "/api/groups/{id}"; public const string GroupMembers = "/api/groups/{id}/members"; + public const string GroupMove = "/api/groups/{id}/move"; public const string GroupPreview = "/api/groups/preview"; public const string GroupFields = "/api/groups/fields"; public const string DeviceTags = "/api/devices/{clientId}/tags"; public const string Triggers = "/api/triggers"; public const string Trigger = "/api/triggers/{id}"; + public const string TriggerRun = "/api/triggers/{id}/run"; + public const string TriggerPreview = "/api/triggers/preview"; public const string SecretsProviders = "/api/secrets/providers"; public const string SecretsProvider = "/api/secrets/providers/{id}"; @@ -59,13 +71,34 @@ public static class ApiRoutes public const string AgentPackageStatus = "/api/settings/agent-package"; public const string AgentPackageOffload = "/api/settings/agent-package/offload"; + // Agent upgrades: the version catalog, per-device upgrades, and Settings › Agent Upgrades. + /// GET: every agent version the server holds, newest first. + public const string AgentVersions = "/api/agent-versions"; + /// DELETE: remove a version (refused while it is the newest or still needed). + public const string AgentVersion = "/api/agent-versions/{version}"; + /// GET (?clientId=, ?open=true, ?limit=): upgrade attempts, newest first. POST: start upgrades. + public const string AgentUpgrades = "/api/agent-upgrades"; + /// POST: roll devices back to the version their last upgrade came from. + public const string AgentUpgradesRollback = "/api/agent-upgrades/rollback"; + /// POST: cancel an upgrade that has not been sent yet. + public const string AgentUpgradeCancel = "/api/agent-upgrades/{id}/cancel"; + public const string AgentUpgradeSettings = "/api/settings/agent-upgrades"; + /// GET (anonymous, ranges): one catalog package by SHA-256; what an upgrade command's DownloadUrl points at. + public const string AgentPackageBySha = "/api/agent-packages/{sha256}"; + public const string Jobs = "/api/jobs"; public const string Job = "/api/jobs/{jobId}"; public const string JobOutput = "/api/jobs/{jobId}/output"; + public const string JobOutputDownload = "/api/jobs/{jobId}/output/download"; /// Executions of a script (per-device jobs grouped by run). public const string ScriptExecutions = "/api/scripts/{scriptId}/executions"; + /// Recent executions across scripts (?scriptId, ?limit). + public const string Executions = "/api/executions"; public const string Execution = "/api/executions/{runId}"; + public const string ExecutionOutputDownload = "/api/executions/{runId}/output/download"; + /// POST: a zip with one log per chosen job of the run (all when none are named). + public const string ExecutionOutputArchive = "/api/executions/{runId}/output/archive"; public const string Dashboard = "/api/dashboard"; @@ -82,26 +115,41 @@ public static class ApiRoutes public const string AdminPermissions = "/api/admin/permissions"; public const string AdminUsers = "/api/admin/users"; public const string AdminUser = "/api/admin/users/{id}"; + public const string AdminUserPassword = "/api/admin/users/{id}/password"; + public const string AdminUserAccess = "/api/admin/users/{id}/access"; + public const string AdminLocalGroups = "/api/admin/local-groups"; + public const string AdminLocalGroup = "/api/admin/local-groups/{id}"; + public const string AdminRoleBindings = "/api/admin/role-bindings"; + public const string AdminRoleBinding = "/api/admin/role-bindings/{id}"; /// Builds concrete paths from the route templates. public static class For { public static string Device(string clientId) => $"/api/devices/{Uri.EscapeDataString(clientId)}"; public static string DeviceInventory(string clientId) => $"/api/devices/{Uri.EscapeDataString(clientId)}/inventory"; + public static string DeviceHistory(string clientId) => $"/api/devices/{Uri.EscapeDataString(clientId)}/history"; + public static string AgentVersion(string version) => $"/api/agent-versions/{Uri.EscapeDataString(version)}"; + public static string AgentUpgradeCancel(Guid id) => $"/api/agent-upgrades/{id:D}/cancel"; + public static string AgentPackageBySha(string sha256) => $"/api/agent-packages/{Uri.EscapeDataString(sha256)}"; public static string DeviceShell(string clientId) => $"/api/devices/{Uri.EscapeDataString(clientId)}/shell"; public static string DeviceFiles(string clientId) => $"/api/devices/{Uri.EscapeDataString(clientId)}/files"; public static string Script(Guid id) => $"/api/scripts/{id:D}"; public static string FunctionModule(Guid id) => $"/api/functions/{id:D}"; public static string Group(Guid id) => $"/api/groups/{id:D}"; public static string GroupMembers(Guid id) => $"/api/groups/{id:D}/members"; + public static string GroupMove(Guid id) => $"/api/groups/{id:D}/move"; public static string DeviceTags(string clientId) => $"/api/devices/{Uri.EscapeDataString(clientId)}/tags"; public static string Trigger(Guid id) => $"/api/triggers/{id:D}"; + public static string TriggerRun(Guid id) => $"/api/triggers/{id:D}/run"; public static string SecretsProvider(Guid id) => $"/api/secrets/providers/{id:D}"; public static string SecretsProviderNames(Guid id) => $"/api/secrets/providers/{id:D}/secret-names"; public static string Job(Guid jobId) => $"/api/jobs/{jobId:D}"; public static string JobOutput(Guid jobId) => $"/api/jobs/{jobId:D}/output"; + public static string JobOutputDownload(Guid jobId) => $"/api/jobs/{jobId:D}/output/download"; public static string ScriptExecutions(Guid scriptId) => $"/api/scripts/{scriptId:D}/executions"; public static string Execution(Guid runId) => $"/api/executions/{runId:D}"; + public static string ExecutionOutputDownload(Guid runId) => $"/api/executions/{runId:D}/output/download"; + public static string ExecutionOutputArchive(Guid runId) => $"/api/executions/{runId:D}/output/archive"; public static string AdminBootstrapToken(Guid id) => $"/api/admin/bootstrap-tokens/{id:D}"; public static string AdminRole(Guid id) => $"/api/admin/roles/{id:D}"; public static string AdminUser(Guid id) => $"/api/admin/users/{id:D}"; diff --git a/src/Shared.Contracts/Api/AuthDtos.cs b/src/Shared.Contracts/Api/AuthDtos.cs index 5272c34..5da65dd 100644 --- a/src/Shared.Contracts/Api/AuthDtos.cs +++ b/src/Shared.Contracts/Api/AuthDtos.cs @@ -1,68 +1,5 @@ -using Shared.Contracts.Models; - namespace Shared.Contracts.Api; -/// POST /api/auth/login request body. -public sealed record LoginRequest(string Username, string Password); - -/// -/// POST /api/auth/change-password request body. Pre-session: the current -/// password authenticates the request, so this also completes the forced -/// first-sign-in reset of the defaulted admin account. -/// -public sealed record ChangePasswordRequest(string Username, string CurrentPassword, string NewPassword); - -/// -/// GET /api/auth/config — anonymous. Tells the sign-in page what to render; -/// contains nothing sensitive. -/// -public sealed record AuthConfigDto( - bool OidcAvailable, - bool ShowLocalFields, - bool AutoRedirect, - string? ProviderName); - -/// GET/PUT /api/settings/auth — admin only. The client secret is never returned. -public sealed record AuthSettingsDto( - bool OidcEnabled, - string? Authority, - string? ClientId, - string? ClientSecret, - string? ProviderName, - string Scopes, - string? NameClaim, - string? RoleClaim, - string? AdminRole, - string? OperatorRole, - string? ViewerRole, - UserRole DefaultRole, - bool RequireMappedRole, - string LoginMode, - bool ClientSecretIsSet, - bool ForcedLocalByEnvironment, - string CallbackPath, - string RedirectUri); - -/// POST /api/settings/auth/test — validates the discovery document. -public sealed record AuthTestResultDto(bool Ok, IReadOnlyList Steps); - -/// -/// GET /api/auth/session response body. is the coarse -/// legacy tier derived from the effective permissions; -/// and carry the custom-role detail the UI uses -/// for feature gating. -/// -public sealed record SessionResponse( - bool Authenticated, - string? Username, - string? DisplayName, - UserRole? Role, - string? AuthProvider, - string? RoleName = null, - IReadOnlyList? Permissions = null, - // Credentials were valid but a new password must be set before a session is issued. - bool MustChangePassword = false); - /// /// POST /api/messaging/credential request body. Pass the previously issued /// to refresh a credential while keeping diff --git a/src/Shared.Contracts/Api/ResourceDtos.cs b/src/Shared.Contracts/Api/ResourceDtos.cs index 85fcbc5..4c78074 100644 --- a/src/Shared.Contracts/Api/ResourceDtos.cs +++ b/src/Shared.Contracts/Api/ResourceDtos.cs @@ -17,9 +17,13 @@ public sealed record DeviceDto( DateTimeOffset EnrolledUtc, IReadOnlyList? Tags = null, bool IsOrphaned = false, - string? PublicIp = null); + string? PublicIp = null, + IReadOnlyList? GroupIds = null); -/// Device group resource. +/// +/// Device group resource. MemberCount/OnlineCount include the +/// devices of nested groups; DirectMemberCount is the group's own. +/// public sealed record DeviceGroupDto( Guid Id, string Name, @@ -29,14 +33,21 @@ public sealed record DeviceGroupDto( int MemberCount, DateTimeOffset CreatedUtc, DateTimeOffset UpdatedUtc, - string? UpdatedBy); + string? UpdatedBy, + Guid? ParentId = null, + int DirectMemberCount = 0, + int OnlineCount = 0); -/// POST/PUT /api/groups request body. +/// POST/PUT /api/groups request body. ParentId nests the group (null = top level). public sealed record SaveDeviceGroupRequest( string Name, string? Description, GroupKind Kind, - GroupRuleSet? Rules); + GroupRuleSet? Rules, + Guid? ParentId = null); + +/// POST /api/groups/{id}/move — re-parent a group (null = top level). +public sealed record MoveGroupRequest(Guid? ParentId); /// POST /api/groups/{id}/members request body (static groups). public sealed record UpdateGroupMembersRequest( @@ -69,12 +80,17 @@ public sealed record ScriptTriggerDto( DateTimeOffset? NextRunUtc, DateTimeOffset? LastRunUtc, string? LastResult, - DateTimeOffset CreatedUtc); + DateTimeOffset CreatedUtc, + string? Name = null, + Guid? LastRunId = null, + IReadOnlyDictionary? Arguments = null, + string? CreatedBy = null); /// -/// POST /api/triggers. Target: exactly one of ClientId / GroupId, or neither -/// for all devices. For TriggerType=Scheduled, supply CronExpression (recurring) -/// or RunOnceUtc (one-shot) plus an optional TimeZoneId and Arguments. +/// POST /api/triggers and PUT /api/triggers/{id}. Target: exactly one of +/// ClientId / GroupId, or neither for all devices. For TriggerType=Scheduled, +/// supply CronExpression (recurring) or RunOnceUtc (one-shot) plus an optional +/// TimeZoneId and Arguments. /// public sealed record SaveScriptTriggerRequest( Guid ScriptId, @@ -85,11 +101,35 @@ public sealed record SaveScriptTriggerRequest( string? CronExpression = null, DateTimeOffset? RunOnceUtc = null, string? TimeZoneId = null, - IReadOnlyDictionary? Arguments = null); + IReadOnlyDictionary? Arguments = null, + string? Name = null); + +/// POST /api/triggers/preview — upcoming fire times of a cadence, evaluated server-side. +public sealed record SchedulePreviewRequest(string? CronExpression, string? TimeZoneId, int Count = 5); + +/// Upcoming occurrences (UTC), or the validation error that prevents any. +public sealed record SchedulePreviewDto(IReadOnlyList Occurrences, string? Error); + +/// POST /api/triggers/{id}/run — what a manual firing queued. +public sealed record TriggerRunResultDto(Guid? RunId, int Queued, string Message); /// PATCH /api/triggers/{id} — enable or disable a trigger without deleting it. public sealed record SetTriggerEnabledRequest(bool Enabled); +/// +/// Where every target of a run stands. Targets = jobs + skipped. Pending is +/// queued or sent and not started; Online counts job targets online now. +/// +public sealed record RunCountsDto( + int Targets, + int Pending, + int Running, + int Succeeded, + int Failed, + int Cancelled, + int Skipped, + int Online); + /// One execution (run) of a script — the per-device jobs it created, summarized. public sealed record ExecutionSummaryDto( Guid RunId, @@ -99,7 +139,11 @@ public sealed record ExecutionSummaryDto( int Total, int Succeeded, int Failed, - int Pending); + int Pending, + string? ScriptName = null, + string? Source = null, + string? TargetsLabel = null, + RunCountsDto? Counts = null); /// One device within an execution. public sealed record ExecutionTargetDto( @@ -110,7 +154,12 @@ public sealed record ExecutionTargetDto( int? ExitCode, DateTimeOffset CreatedUtc, DateTimeOffset? StartedUtc, - DateTimeOffset? CompletedUtc); + DateTimeOffset? CompletedUtc, + bool Online = false, + string? Summary = null); + +/// A targeted device that was given no job: orphaned, or offline with Only Devices Online Now. +public sealed record ExecutionSkipDto(string ClientId, string Hostname, string Reason); /// GET /api/executions/{runId} — a run and the targets it ran on. public sealed record ExecutionDetailDto( @@ -119,7 +168,12 @@ public sealed record ExecutionDetailDto( string ScriptName, DateTimeOffset StartedUtc, string? RequestedBy, - IReadOnlyList Targets); + IReadOnlyList Targets, + string? Source = null, + string? TargetsLabel = null, + bool OnlineOnly = false, + IReadOnlyList? Skipped = null, + RunCountsDto? Counts = null); /// Device detail for GET /api/devices/{clientId}. public sealed record DeviceDetailDto( @@ -128,8 +182,19 @@ public sealed record DeviceDetailDto( DateTimeOffset? InventoryUpdatedUtc, IReadOnlyList? Groups = null); -/// A group a device belongs to. -public sealed record DeviceGroupRefDto(Guid Id, string Name, GroupKind Kind); +/// +/// One event in a device's history (GET /api/devices/{clientId}/history): +/// device-enrolled, device-renamed or device-os-changed, +/// with a short detail such as "MINWINPC-ABC → LAB-PC-01". +/// +public sealed record DeviceHistoryEventDto( + long Id, + DateTimeOffset TimestampUtc, + string Action, + string? Detail); + +/// A group a device belongs to; Inherited when only through a nested group. +public sealed record DeviceGroupRefDto(Guid Id, string Name, GroupKind Kind, Guid? ParentId = null, bool Inherited = false); /// Script resource. public sealed record ScriptDto( @@ -223,20 +288,36 @@ public sealed record JobDto( string? RequestedBy, string? OutputSummary); -/// POST /api/jobs request body. maps -/// parameter name → typed JSON value per the script's parameter schema. -/// Targets exactly one of ClientId (single device) or GroupId (fan-out). +/// +/// POST /api/jobs request body. maps parameter +/// name → typed JSON value per the script's parameter schema. Targets are any +/// mix of devices (ClientId/ClientIds) and groups +/// (GroupId/GroupIds), deduplicated into one execution. A lone +/// ClientId answers with the single ; anything else +/// with a . OnlineOnly skips devices that are +/// not online now instead of queueing for their return. +/// public sealed record CreateJobRequest( string? ClientId, Guid ScriptId, IReadOnlyDictionary? Arguments = null, Guid? GroupId = null, - IReadOnlyList? GroupIds = null); + IReadOnlyList? GroupIds = null, + IReadOnlyList? ClientIds = null, + bool OnlineOnly = false); -/// Result of a group fan-out run: one job per eligible member. +/// +/// POST /api/executions/{runId}/output/archive request body: the run's jobs to +/// include (null or empty = every job), with or without line timestamps. +/// +public sealed record OutputArchiveRequest(IReadOnlyList? JobIds = null, bool Timestamps = false); + +/// Result of a fan-out run: one job per eligible target, all sharing RunId. public sealed record GroupRunDto( IReadOnlyList Jobs, - IReadOnlyList SkippedOrphaned); + IReadOnlyList SkippedOrphaned, + Guid? RunId = null, + IReadOnlyList? SkippedOffline = null); /// A labeled count used by the dashboard charts. public sealed record CountPoint(string Label, int Count); @@ -274,11 +355,12 @@ public sealed record JobOutputRecordDto( DateTimeOffset TimestampUtc, string Text); -/// POST /api/devices/{clientId}/shell request body. +/// POST /api/devices/{clientId}/shell request body; Shell is a value (null = automatic). public sealed record CreateShellRequest( string BrowserSessionId, int Cols, - int Rows); + int Rows, + string? Shell = null); /// POST /api/devices/{clientId}/shell response body. public sealed record CreateShellResponse( diff --git a/src/Shared.Contracts/Messages/AgentUpgradePayloads.cs b/src/Shared.Contracts/Messages/AgentUpgradePayloads.cs new file mode 100644 index 0000000..6e398f6 --- /dev/null +++ b/src/Shared.Contracts/Messages/AgentUpgradePayloads.cs @@ -0,0 +1,43 @@ +namespace Shared.Contracts.Messages; + +/// +/// Upgrades (or, with , rolls back) the agent to +/// ; durable command on agent.<clientId>.command.upgrade. +/// The agent downloads (a path starting with "/", +/// resolved against the server URL the agent is configured with, or an absolute +/// presigned object-store URL used as is), checks size and SHA-256, unpacks +/// it into its data folder and hands it to the watchdog, which swaps the files +/// and keeps them only when the new version reports healthy within +/// . The agent waits a random 0 to +/// seconds before downloading, so one +/// batch of devices does not start in the same instant. +/// +public sealed record AgentUpgradeCommandPayload( + Guid UpgradeId, + string Version, + string PackageType, + string DownloadUrl, + string Sha256, + long SizeBytes, + bool Revert, + int HealthDeadlineSeconds, + int StartJitterSeconds = 0); + +/// +/// Progress or outcome of one upgrade, published by the agent on +/// agent.<clientId>.event with message type . +/// is an AgentUpgradeStates value and +/// an AgentUpgradeReasons value. The outcome of +/// a swap is published by whichever version runs afterwards (the new one, or the +/// previous one after a rollback), with up to 40 lines of the watchdog's log. +/// +public sealed record AgentUpgradeEventPayload( + Guid UpgradeId, + string ClientId, + string State, + string? Reason, + string? Detail, + string? FromVersion, + string? ToVersion, + IReadOnlyList? LastLog, + DateTimeOffset TimestampUtc); diff --git a/src/Shared.Contracts/Messages/MessageTypes.cs b/src/Shared.Contracts/Messages/MessageTypes.cs index ad1239a..69bed98 100644 --- a/src/Shared.Contracts/Messages/MessageTypes.cs +++ b/src/Shared.Contracts/Messages/MessageTypes.cs @@ -9,10 +9,13 @@ public static class MessageTypes public const string AgentPresence = "agent.presence"; public const string AgentInventory = "agent.inventory"; public const string AgentEvent = "agent.event"; + /// Upgrade progress or outcome on the agent event subject (). + public const string AgentUpgrade = "agent.upgrade"; public const string CommandInventory = "command.inventory"; public const string CommandScript = "command.script"; public const string CommandFileDownload = "command.file.download"; + public const string CommandAgentUpgrade = "command.agent.upgrade"; public const string CommandShellOpen = "command.shell.open"; public const string CommandShellInput = "command.shell.input"; public const string CommandShellResize = "command.shell.resize"; diff --git a/src/Shared.Contracts/Messages/Payloads.cs b/src/Shared.Contracts/Messages/Payloads.cs index 7d0648c..5c58785 100644 --- a/src/Shared.Contracts/Messages/Payloads.cs +++ b/src/Shared.Contracts/Messages/Payloads.cs @@ -2,7 +2,11 @@ using Shared.Contracts.Models; namespace Shared.Contracts.Messages; -/// Periodic agent heartbeat published on agent.<clientId>.presence. +/// +/// Periodic agent heartbeat published on agent.<clientId>.presence. +/// Runtime is the agent build's runtime identifier (e.g. win-x64), which +/// picks the package it upgrades from; older agents leave it out. +/// public sealed record PresencePayload( string ClientId, string Hostname, @@ -10,7 +14,8 @@ public sealed record PresencePayload( string Status, DateTimeOffset TimestampUtc, long UptimeSeconds, - int ActiveJobs); + int ActiveJobs, + string? Runtime = null); /// Inventory snapshot published on agent.<clientId>.inventory. public sealed record InventoryPayload(InventoryReport Report); @@ -129,11 +134,16 @@ public sealed record JobStatePayload( DateTimeOffset TimestampUtc, string? Message); -/// Opens a remote shell; sent on agent.<clientId>.command.shell.open. +/// +/// Opens a remote shell; sent on agent.<clientId>.command.shell.open. +/// Shell is a value (null = automatic); unix +/// agents, and agents that predate it, ignore it. +/// public sealed record ShellOpenCommandPayload( Guid SessionId, int Cols, - int Rows); + int Rows, + string? Shell = null); /// Terminal input bytes (base64) for an open shell session. public sealed record ShellInputPayload( @@ -157,11 +167,15 @@ public sealed record ShellOutputPayload( long Sequence, string DataBase64); -/// Shell session state on agent.<clientId>.shell.<sessionId>.state. +/// +/// Shell session state on agent.<clientId>.shell.<sessionId>.state. +/// Shell is the value started (Windows agents, on Open). +/// public sealed record ShellStatePayload( Guid SessionId, ShellSessionState State, - string? Message); + string? Message, + string? Shell = null); /// System event: a device enrolled. public sealed record AgentEnrolledEvent( diff --git a/src/Shared.Contracts/Models/AgentUpgrades.cs b/src/Shared.Contracts/Models/AgentUpgrades.cs new file mode 100644 index 0000000..23a358e --- /dev/null +++ b/src/Shared.Contracts/Models/AgentUpgrades.cs @@ -0,0 +1,144 @@ +namespace Shared.Contracts.Models; + +/// +/// States of one device's agent upgrade (one row per attempt, at most one open +/// per device). The server owns queued, sent and cancelled; +/// the agent reports downloading and installing (staged and handed +/// to the watchdog), and the outcome the watchdog left: succeeded, +/// failed or rolled-back. +/// +public static class AgentUpgradeStates +{ + public const string Queued = "queued"; + public const string Sent = "sent"; + public const string Downloading = "downloading"; + public const string Installing = "installing"; + public const string Succeeded = "succeeded"; + public const string Failed = "failed"; + public const string RolledBack = "rolled-back"; + public const string Cancelled = "cancelled"; + + /// Started and not finished: these count against the concurrency limit. + public static readonly IReadOnlySet InFlight = new HashSet(StringComparer.Ordinal) + { Sent, Downloading, Installing }; + + /// Not finished yet (queued included): a device has at most one. + public static readonly IReadOnlySet Open = new HashSet(StringComparer.Ordinal) + { Queued, Sent, Downloading, Installing }; + + public static readonly IReadOnlySet Finished = new HashSet(StringComparer.Ordinal) + { Succeeded, Failed, RolledBack, Cancelled }; +} + +/// Why an upgrade did not succeed (, rolled back or cancelled). +public static class AgentUpgradeReasons +{ + /// The agent already runs the target version (recorded as succeeded). + public const string Already = "already"; + /// The agent is busy with another upgrade. + public const string Busy = "busy"; + /// The agent cannot self-upgrade here (foreground or development run, container, unknown platform). + public const string Unsupported = "unsupported"; + /// The server holds no package of the target version for the device's platform. + public const string NoPackage = "no-package"; + public const string Download = "download"; + /// The downloaded package's size or SHA-256 did not match. + public const string Hash = "hash"; + /// The package could not be unpacked or lacks the agent binary. + public const string Package = "package"; + /// The watchdog is missing or did not pick the hand-over up in time. + public const string Watchdog = "watchdog"; + /// Files could not be swapped (the previous version was put back). + public const string Swap = "swap"; + /// The new version did not report healthy before the deadline (rolled back). + public const string HealthDeadline = "health-deadline"; + /// The new version kept exiting (rolled back). + public const string Crashed = "crashed"; + /// The device stopped reporting within the report deadline. + public const string NoReport = "no-report"; + /// A newer request for the same device replaced this one. + public const string Superseded = "superseded"; + /// Cancelled by an operator before it was sent. + public const string Cancelled = "cancelled"; + /// Queued longer than the server keeps a request waiting (the device did not come online). + public const string Expired = "expired"; +} + +/// Who started an upgrade. +public static class AgentUpgradeSources +{ + /// Upgrade Agent… from the console or API. + public const string Manual = "manual"; + /// Automatic Upgrades keeping devices on the newest version. + public const string Automatic = "automatic"; + /// Roll Back Agent: back to the version the last upgrade came from. + public const string Rollback = "rollback"; +} + +/// +/// Agent package types: the file the server holds for each platform. Windows +/// upgrades always use the portable zip (also for MSI installs: files are +/// swapped in place, the MSI keeps its registration). +/// +public static class AgentPackageTypes +{ + public const string Msi = "msi"; + /// win-x64 portable zip. + public const string WindowsZip = "zip"; + public const string LinuxX64 = "linux-x64"; + public const string LinuxArm64 = "linux-arm64"; + public const string MacX64 = "osx-x64"; + public const string MacArm64 = "osx-arm64"; + + /// The package an agent of this runtime identifier upgrades from, or null when none is built for it. + public static string? ForRuntime(string? runtimeIdentifier) => runtimeIdentifier?.ToLowerInvariant() switch + { + "win-x64" => WindowsZip, + "linux-x64" => LinuxX64, + "linux-arm64" => LinuxArm64, + "osx-x64" => MacX64, + "osx-arm64" => MacArm64, + _ => null, + }; + + /// Types an upgrade can use (everything but the MSI). + public static readonly IReadOnlyList Upgradable = [WindowsZip, LinuxX64, LinuxArm64, MacX64, MacArm64]; +} + +/// +/// The one version comparison used everywhere. Versions are +/// yyyy.MM.dd.HHmm (four numeric parts); anything that does not parse +/// (e.g. a development "0.0.0.0" or a custom label) sorts before every real +/// version, then ordinally. +/// +public static class AgentVersions +{ + public static int Compare(string? left, string? right) + { + var a = Parse(left); + var b = Parse(right); + if (a is not null && b is not null) + { + return a.CompareTo(b); + } + + if (a is not null) + { + return 1; + } + + if (b is not null) + { + return -1; + } + + return string.CompareOrdinal(left, right); + } + + public static bool IsNewer(string? candidate, string? than) => Compare(candidate, than) > 0; + + public static IComparer Comparer { get; } = Comparer.Create(Compare); + + private static Version? Parse(string? value) + => Version.TryParse(value, out var version) && version.Major > 0 ? version : null; +} diff --git a/src/Shared.Contracts/Models/GroupRules.cs b/src/Shared.Contracts/Models/GroupRules.cs index 6903db2..148063a 100644 --- a/src/Shared.Contracts/Models/GroupRules.cs +++ b/src/Shared.Contracts/Models/GroupRules.cs @@ -1,10 +1,15 @@ namespace Shared.Contracts.Models; -/// Static groups hold an explicit member list; dynamic groups evaluate rules. +/// +/// Static groups hold an explicit member list; dynamic groups evaluate rules; +/// folders hold no devices of their own and only organize nested groups. +/// Every kind also includes the devices of the groups nested under it. +/// public enum GroupKind { Static, Dynamic, + Folder, } /// How sibling conditions (or sibling groups) combine. diff --git a/src/Shared.Contracts/Models/ShellKinds.cs b/src/Shared.Contracts/Models/ShellKinds.cs new file mode 100644 index 0000000..66bbc3e --- /dev/null +++ b/src/Shared.Contracts/Models/ShellKinds.cs @@ -0,0 +1,38 @@ +namespace Shared.Contracts.Models; + +/// +/// The shell a remote shell session starts on a Windows device. Unix agents +/// ignore the choice (they start the user's login shell), as do agents that +/// predate it; or no choice picks the first available. +/// +public static class ShellKinds +{ + /// PowerShell 7, then Windows PowerShell, then the agent's built-in PowerShell, then cmd.exe. + public const string Auto = "auto"; + + /// PowerShell 7 (pwsh.exe). + public const string Pwsh = "pwsh"; + + /// Windows PowerShell 5.1 (powershell.exe). + public const string WindowsPowerShell = "powershell"; + + /// Command Prompt (cmd.exe). + public const string Cmd = "cmd"; + + /// The agent's own PowerShell console host (works without any installed PowerShell, e.g. in Windows PE). + public const string BuiltIn = "builtin"; + + public static IReadOnlyList All { get; } = [Auto, Pwsh, WindowsPowerShell, Cmd, BuiltIn]; + + /// The canonical (lowercase) kind, for blank, or null when unknown. + public static string? Normalize(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + { + return Auto; + } + + var trimmed = value.Trim(); + return All.FirstOrDefault(kind => string.Equals(kind, trimmed, StringComparison.OrdinalIgnoreCase)); + } +} diff --git a/src/Shared.Contracts/Models/WatchdogFiles.cs b/src/Shared.Contracts/Models/WatchdogFiles.cs new file mode 100644 index 0000000..07f0248 --- /dev/null +++ b/src/Shared.Contracts/Models/WatchdogFiles.cs @@ -0,0 +1,99 @@ +namespace Shared.Contracts.Models; + +/// +/// The agent and the watchdog meet only in files under +/// <data>/upgrade/ (%ProgramData%\ExecuteR\upgrade, +/// /var/lib/executer/upgrade). Every file is written to a temporary name +/// and renamed over the old one, so a reader never sees half a file. +/// +public static class WatchdogFiles +{ + public const string Folder = "upgrade"; + /// Downloads by SHA-256: downloads/<sha256>.zip. + public const string Downloads = "downloads"; + /// Unpacked packages: staging/<version>-<upgradeId>/. + public const string Staging = "staging"; + /// Written by the agent: a staged version the watchdog should install (). + public const string Handover = "handover.json"; + /// Written by the agent every 5 seconds (). + public const string Health = "health.json"; + /// Written by the watchdog before each step of a swap (). + public const string Journal = "journal.json"; + /// Written by the watchdog when a swap ends; reported and deleted by the agent (). + public const string Outcome = "outcome.json"; + + /// Swap folders inside the install folder, one subfolder per upgrade. + public const string NextFolder = ".next"; + public const string PreviousFolder = ".previous"; + public const string FailedFolder = ".failed"; + + public static readonly TimeSpan BeaconInterval = TimeSpan.FromSeconds(5); + /// A beacon older than this while the agent should run: the watchdog restarts it (at most once per period). + public static readonly TimeSpan BeaconStaleAfter = TimeSpan.FromMinutes(3); + /// A hand-over the watchdog has not picked up by then fails with reason "watchdog". + public static readonly TimeSpan HandoverPickupDeadline = TimeSpan.FromMinutes(10); + /// How long the previous version gets to report healthy after a rollback. + public static readonly TimeSpan RollbackHealthDeadline = TimeSpan.FromMinutes(5); +} + +/// One file of a staged package, relative to the install folder. +public sealed record WatchdogFile(string Path, long Size, string Sha256); + +/// A staged version for the watchdog to install. +public sealed record WatchdogHandover( + Guid UpgradeId, + string Version, + string FromVersion, + string StagingPath, + IReadOnlyList Files, + int HealthDeadlineSeconds, + bool Revert, + DateTimeOffset CreatedUtc); + +/// +/// The agent's heartbeat to the watchdog. Connected means its command +/// consumer is bound (the same moment it publishes "ready"); an upgrade is kept +/// only when the new version reports Connected. +/// +public sealed record WatchdogHealthBeacon( + string Version, + int ProcessId, + bool Connected, + DateTimeOffset AtUtc); + +/// Journal phases, in order; a crash in any phase is finished or undone at the next start. +public static class WatchdogPhases +{ + public const string Stopping = "stopping"; + public const string Swapping = "swapping"; + public const string Verifying = "verifying"; + public const string Committed = "committed"; + public const string RollingBack = "rolling-back"; + public const string RolledBack = "rolled-back"; +} + +/// +/// The watchdog's record of a swap in progress. Previous and +/// Incoming map each relative path to its SHA-256, so recovery can tell +/// which version a file on disk belongs to. +/// +public sealed record WatchdogJournal( + Guid UpgradeId, + string Version, + string FromVersion, + string Phase, + IReadOnlyDictionary Previous, + IReadOnlyDictionary Incoming, + DateTimeOffset StartedUtc, + DateTimeOffset? DeadlineUtc, + int Attempts); + +/// How a swap ended: Result is succeeded, failed or rolled-back (AgentUpgradeStates). +public sealed record WatchdogOutcome( + Guid UpgradeId, + string Result, + string? Reason, + string Version, + string FromVersion, + IReadOnlyList LastLog, + DateTimeOffset FinishedUtc); diff --git a/src/Shared.Contracts/Serialization/WatchdogFileStore.cs b/src/Shared.Contracts/Serialization/WatchdogFileStore.cs new file mode 100644 index 0000000..a4d0708 --- /dev/null +++ b/src/Shared.Contracts/Serialization/WatchdogFileStore.cs @@ -0,0 +1,97 @@ +using System.Text.Json; +using System.Text.Json.Serialization.Metadata; + +namespace Shared.Contracts.Serialization; + +/// +/// Reads and writes the agent/watchdog meeting files the same way on both +/// sides: a write goes to a temporary name beside the file and is renamed over +/// it, so a reader never sees half a file; a read shares every mode, so it +/// holds the other side's rename up no longer than the read itself. +/// +public static class WatchdogFileStore +{ + /// The file's value, or null when it is missing or does not read (never throws for that). + public static T? Read(string path, JsonTypeInfo type) + where T : class + { + try + { + return File.Exists(path) ? JsonSerializer.Deserialize(ReadShared(path), type) : null; + } + catch (Exception exception) when (exception is JsonException or IOException or UnauthorizedAccessException or NotSupportedException) + { + return null; + } + } + + /// The upgradeId of a file that does not read as a whole, when that much does. + public static Guid? ReadUpgradeId(string path) + { + try + { + using var document = JsonDocument.Parse(ReadShared(path)); + return document.RootElement.ValueKind == JsonValueKind.Object + && document.RootElement.TryGetProperty("upgradeId", out var value) + && value.ValueKind == JsonValueKind.String + && Guid.TryParse(value.GetString(), out var id) + ? id + : null; + } + catch (Exception exception) when (exception is JsonException or IOException or UnauthorizedAccessException) + { + return null; + } + } + + public static void Write(string path, T value, JsonTypeInfo type) + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + var temporary = $"{path}.{Guid.NewGuid():N}.tmp"; + File.WriteAllBytes(temporary, JsonSerializer.SerializeToUtf8Bytes(value, type)); + try + { + // Windows refuses a rename over a file someone has open, sharing + // delete or not; the other side's read takes a moment, so wait it out. + for (var attempt = 1; ; attempt++) + { + try + { + File.Move(temporary, path, overwrite: true); + return; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException && attempt < 40) + { + Thread.Sleep(25); + } + } + } + catch + { + TryDelete(temporary); + throw; + } + } + + /// Deletes the file if it is there; true when it is gone afterwards. + public static bool TryDelete(string path) + { + try + { + File.Delete(path); + return true; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return !File.Exists(path); + } + } + + private static byte[] ReadShared(string path) + { + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + using var buffer = new MemoryStream(); + stream.CopyTo(buffer); + return buffer.ToArray(); + } +} diff --git a/src/Shared.Contracts/Serialization/WatchdogJsonContext.cs b/src/Shared.Contracts/Serialization/WatchdogJsonContext.cs new file mode 100644 index 0000000..db264a3 --- /dev/null +++ b/src/Shared.Contracts/Serialization/WatchdogJsonContext.cs @@ -0,0 +1,22 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using Shared.Contracts.Models; + +namespace Shared.Contracts.Serialization; + +/// +/// Source-generated JSON for the files the agent and the watchdog share under +/// <data>/upgrade/ (). Both sides read and +/// write them only through this context: the watchdog is trimmed, so it cannot +/// use the reflection-based , and one context keeps the +/// two sides on the same names (camelCase, as on the wire). +/// +[JsonSourceGenerationOptions( + JsonSerializerDefaults.Web, + WriteIndented = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] +[JsonSerializable(typeof(WatchdogHandover))] +[JsonSerializable(typeof(WatchdogHealthBeacon))] +[JsonSerializable(typeof(WatchdogJournal))] +[JsonSerializable(typeof(WatchdogOutcome))] +public sealed partial class WatchdogJsonContext : JsonSerializerContext; diff --git a/src/Shared.Infrastructure/Constants/Branding.cs b/src/Shared.Infrastructure/Constants/Branding.cs index 96dd825..b72216d 100644 --- a/src/Shared.Infrastructure/Constants/Branding.cs +++ b/src/Shared.Infrastructure/Constants/Branding.cs @@ -21,6 +21,32 @@ public static class Branding public const string AgentExecutableName = "ExecuteR-Agent.exe"; + /// The agent's binary on linux/macOS (lowercase, no extension). + public const string AgentUnixExecutableName = "executer-agent"; + + /// systemd unit / launchd label of the agent on linux/macOS. + public const string AgentSystemdUnit = "executer-agent"; + public const string AgentLaunchdLabel = "info.executer.agent"; + + // The watchdog: a second, small service that keeps the agent running and + // applies upgrades. This file is linked into the watchdog project (which + // references nothing but Shared.Contracts), so it must stay dependency-free. + public const string WatchdogServiceName = "ExecuteRWatchdog"; + public const string WatchdogServiceDisplayName = "ExecuteR Watchdog"; + public const string WatchdogServiceDescription = + "Keeps the ExecuteR Agent running and applies agent upgrades, rolling back a version that does not report healthy."; + + public const string WatchdogExecutableName = "ExecuteR-Watchdog.exe"; + public const string WatchdogUnixExecutableName = "executer-watchdog"; + public const string WatchdogSystemdUnit = "executer-watchdog"; + public const string WatchdogLaunchdLabel = "info.executer.watchdog"; + + /// The agent binary's file name on the running platform. + public static string AgentBinaryName => OperatingSystem.IsWindows() ? AgentExecutableName : AgentUnixExecutableName; + + /// The watchdog binary's file name on the running platform. + public static string WatchdogBinaryName => OperatingSystem.IsWindows() ? WatchdogExecutableName : WatchdogUnixExecutableName; + /// Normal machine configuration key below HKLM. public const string AgentRegistryKey = @"SOFTWARE\" + ProductKey; diff --git a/src/Shared.Infrastructure/Nats/JetStreamDefaults.cs b/src/Shared.Infrastructure/Nats/JetStreamDefaults.cs index 36b580a..2a345ac 100644 --- a/src/Shared.Infrastructure/Nats/JetStreamDefaults.cs +++ b/src/Shared.Infrastructure/Nats/JetStreamDefaults.cs @@ -14,6 +14,7 @@ public static class JetStreamDefaults "agent.*.command.script", "agent.*.command.inventory", "agent.*.command.file", + "agent.*.command.upgrade", ]; public const string JobEventsStreamName = "JOB_EVENTS"; diff --git a/src/Shared.Infrastructure/Nats/NatsSubjects.cs b/src/Shared.Infrastructure/Nats/NatsSubjects.cs index a67981b..cc00979 100644 --- a/src/Shared.Infrastructure/Nats/NatsSubjects.cs +++ b/src/Shared.Infrastructure/Nats/NatsSubjects.cs @@ -17,6 +17,7 @@ public static class NatsSubjects public static string AgentCommandInventory(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.command.inventory"; public static string AgentCommandScript(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.command.script"; public static string AgentCommandFile(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.command.file"; + public static string AgentCommandUpgrade(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.command.upgrade"; public static string AgentCommandShellOpen(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.command.shell.open"; public static string AgentCommandShellInput(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.command.shell.input"; public static string AgentCommandShellResize(string clientId) => $"agent.{SubjectIdentifier.Require(clientId)}.command.shell.resize"; diff --git a/src/WebUI/.gitignore b/src/WebUI/.gitignore index 079b463..48c15a5 100644 --- a/src/WebUI/.gitignore +++ b/src/WebUI/.gitignore @@ -1,23 +1,8 @@ node_modules - -# Output -.output -.vercel -.netlify -.wrangler -/.svelte-kit -/build - -# OS -.DS_Store -Thumbs.db - -# Env +# Vite output: the container image and the combined server binary both ship dist/ +/dist +*.tsbuildinfo +vite.config.mts.timestamp-* .env .env.* !.env.example -!.env.test - -# Vite -vite.config.js.timestamp-* -vite.config.ts.timestamp-* diff --git a/src/WebUI/.prettierrc b/src/WebUI/.prettierrc new file mode 100644 index 0000000..932e3e0 --- /dev/null +++ b/src/WebUI/.prettierrc @@ -0,0 +1,9 @@ +{ + "bracketSpacing": true, + "printWidth": 140, + "singleQuote": true, + "trailingComma": "none", + "tabWidth": 2, + "useTabs": false, + "endOfLine": "auto" +} diff --git a/src/WebUI/README.md b/src/WebUI/README.md deleted file mode 100644 index c665ef0..0000000 --- a/src/WebUI/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# sv - -Everything you need to build a Svelte project, powered by [`sv`](https://github.com/sveltejs/cli). - -## Creating a project - -If you're seeing this, you've probably already done this step. Congrats! - -```sh -# create a new project -npx sv create my-app -``` - -To recreate this project with the same configuration: - -```sh -# recreate this project -npx sv@0.17.0 create --template minimal --types ts --install npm src/WebUI -``` - -## Developing - -Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server: - -```sh -npm run dev - -# or start the server and open the app in a new browser tab -npm run dev -- --open -``` - -## Building - -To create a production version of your app: - -```sh -npm run build -``` - -You can preview the production build with `npm run preview`. - -> To deploy your app, you may need to install an [adapter](https://svelte.dev/docs/kit/adapters) for your target environment. diff --git a/src/WebUI/eslint.config.mjs b/src/WebUI/eslint.config.mjs new file mode 100644 index 0000000..8358075 --- /dev/null +++ b/src/WebUI/eslint.config.mjs @@ -0,0 +1,96 @@ +import { fixupConfigRules, fixupPluginRules } from '@eslint/compat'; +import prettier from 'eslint-plugin-prettier'; +import reactHooks from 'eslint-plugin-react-hooks'; +import typescriptEslint from '@typescript-eslint/eslint-plugin'; +import tsParser from '@typescript-eslint/parser'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import js from '@eslint/js'; +import { FlatCompat } from '@eslint/eslintrc'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const compat = new FlatCompat({ + baseDirectory: __dirname, + recommendedConfig: js.configs.recommended, + allConfig: js.configs.all +}); + +export default [ + ...fixupConfigRules(compat.extends('prettier')), + + { + plugins: { + prettier, + '@typescript-eslint': typescriptEslint, + 'react-hooks': fixupPluginRules(reactHooks) + }, + + languageOptions: { + parser: tsParser, + ecmaVersion: 2020, + sourceType: 'module', + + parserOptions: { + project: './tsconfig.json', + tsconfigRootDir: __dirname, + warnOnUnsupportedTypeScriptVersion: false + } + }, + + settings: { + 'import/resolver': { + node: { + moduleDirectory: ['node_modules', 'src/'] + }, + + typescript: { + alwaysTryTypes: true + } + } + }, + + rules: { + 'react/no-unescaped-entities': 'off', + 'react/jsx-filename-extension': 'off', + 'no-param-reassign': 'off', + 'react/prop-types': 'off', + 'react/require-default-props': 'off', + 'react/no-array-index-key': 'off', + 'react/react-in-jsx-scope': 'off', + 'react/jsx-props-no-spreading': 'off', + 'import/order': 'off', + 'no-console': 'off', + 'no-shadow': 'off', + '@typescript-eslint/naming-convention': 'off', + '@typescript-eslint/no-shadow': 'off', + 'import/no-cycle': 'off', + 'import/no-extraneous-dependencies': 'off', + 'jsx-a11y/label-has-associated-control': 'off', + 'jsx-a11y/no-autofocus': 'off', + 'react-hooks/rules-of-hooks': 'error', // Enforces rules of Hooks + 'react-hooks/exhaustive-deps': 'warn', // Enforces effect dependencies + + 'no-restricted-imports': [ + 'error', + { + patterns: ['@mui/*/*/*', '!@mui/material/test-utils/*'] + } + ], + + '@typescript-eslint/no-unused-vars': [ + 'error', + { + vars: 'all', + args: 'none' + } + ], + + 'prettier/prettier': 'warn' + } + }, + { + ignores: ['node_modules/**'], // Make sure this doesn't match your files. + files: ['src/**/*.{js,jsx,ts,tsx}'] + } +]; \ No newline at end of file diff --git a/src/WebUI/index.html b/src/WebUI/index.html new file mode 100644 index 0000000..d036108 --- /dev/null +++ b/src/WebUI/index.html @@ -0,0 +1,16 @@ + + + + + + + + + ExecuteR Control + + + +
+ + + diff --git a/src/WebUI/package-lock.json b/src/WebUI/package-lock.json index 1962a6f..147825c 100644 --- a/src/WebUI/package-lock.json +++ b/src/WebUI/package-lock.json @@ -1,2156 +1,4090 @@ { - "name": "webui", - "version": "0.0.1", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "webui", - "version": "0.0.1", - "dependencies": { - "@nats-io/nats-core": "^3.4.0", - "@nats-io/nkeys": "^2.0.3", - "@xterm/addon-fit": "^0.11.0", - "@xterm/xterm": "^6.0.0", - "monaco-editor": "^0.56.0" - }, - "devDependencies": { - "@sveltejs/adapter-node": "^5.5.7", - "@sveltejs/adapter-static": "^3.0.10", - "@sveltejs/kit": "^2.63.0", - "@sveltejs/vite-plugin-svelte": "^7.1.2", - "@types/node": "^26.1.2", - "svelte": "^5.56.1", - "svelte-check": "^4.6.0", - "typescript": "^6.0.3", - "vite": "^8.0.16" - } - }, - "node_modules/@jridgewell/gen-mapping": { - "version": "0.3.13", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", - "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.0", - "@jridgewell/trace-mapping": "^0.3.24" - } - }, - "node_modules/@jridgewell/remapping": { - "version": "2.3.5", - "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", - "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/gen-mapping": "^0.3.5", - "@jridgewell/trace-mapping": "^0.3.24" - } - }, - "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", - "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", - "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", - "dev": true, - "license": "MIT" - }, - "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.31", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", - "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/resolve-uri": "^3.1.0", - "@jridgewell/sourcemap-codec": "^1.4.14" - } - }, - "node_modules/@napi-rs/lzma-linux-x64-gnu": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", - "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^22.20 || ^24.12 || >=25" - } - }, - "node_modules/@nats-io/nats-core": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/@nats-io/nats-core/-/nats-core-3.4.0.tgz", - "integrity": "sha512-QMDM86EUNm+wudlKC67HLar/KHHQUvJGLfb4jbahje3pUk3K9afeck9fwsxBZF0eUFox6T/TA6m/t+lQqf+QsQ==", - "license": "Apache-2.0", - "dependencies": { - "@nats-io/nkeys": "2.0.3", - "@nats-io/nuid": "3.0.0" - } - }, - "node_modules/@nats-io/nkeys": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/@nats-io/nkeys/-/nkeys-2.0.3.tgz", - "integrity": "sha512-JVt56GuE6Z89KUkI4TXUbSI9fmIfAmk6PMPknijmuL72GcD+UgIomTcRWiNvvJKxA01sBbmIPStqJs5cMRBC3A==", - "license": "Apache-2.0", - "dependencies": { - "tweetnacl": "^1.0.3" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@nats-io/nuid": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@nats-io/nuid/-/nuid-3.0.0.tgz", - "integrity": "sha512-QbXZDrxmYlrn5AD06gYcUTmEHwxn96HBQMIk7XTjDlEcx6FPzVBBPjp4AMRh1lEv6B4iJ6Xb/Uz61JugPXFRQg==", - "license": "Apache-2.0", - "engines": { - "node": ">= 22.x" - } - }, - "node_modules/@oxc-project/types": { - "version": "0.143.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.143.0.tgz", - "integrity": "sha512-u6JZdLBTLotrNC9Vd6vPssINdzcCzleKAH6EJKImQb7GtYvX5keN2dxkoK44stCc4tffE6QQRtZTXVSzsLUlWA==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/Boshen" - } - }, - "node_modules/@polka/url": { - "version": "1.0.0-next.29", - "resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.29.tgz", - "integrity": "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==", - "dev": true, - "license": "MIT" - }, - "node_modules/@rolldown/binding-android-arm64": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.3.tgz", - "integrity": "sha512-zrJtHDcaZJ1Fp7xf4hNl+7seH9Cn/N5TwLYkhgXREtBwAd/jaqW3uqeHxpDugJLVICWg4eW44kOQEGJ1r6jCGw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.3.tgz", - "integrity": "sha512-ieIiibVCp0tX7TLu2cafoNPv8wJyYi01ekXpbf8q2j7F4rGAhhXb/eQh7ge9DRBY78GwmRQtvjZDux7EDbA8kA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.3.tgz", - "integrity": "sha512-Zh9tCon19eDXJoihx0rqKhMUlMYqzwj3aPsSuHmI4RWZh62dWUL+DJN4C5YQya5TcQBJU/Fe8+rY0jhXTQITqA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.3.tgz", - "integrity": "sha512-nGbJWewA1wrXXZiQhjAT5rhibGfns5ZNkDVqxsO6zJ3f3YvpoDNNmGMSbbhLuXKjNScaBJVOAboztAWVespQMg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.3.tgz", - "integrity": "sha512-QNniJr5Kml0kDEB98jiDOJjXNroxIIi0IXIbdYzY26Xt1pVbeP62+KnoIZLwirOymX/0jDk/2gI/bNUv7A7OIw==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.3.tgz", - "integrity": "sha512-TkqEAcmmvH3I/q4114NB4RVt6241Dao48pF45uLcFGrwAaIn0iITgTAKP/dLjbN0R4buJjGb91+UHSoFmpgIWw==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.3.tgz", - "integrity": "sha512-NHqjnxpsndf4MPymxteFAWHHfkTL8HjWh1KB7z23ofZ6QO2euONuxDXjat69dKZRALnGypg8k8SsK8vZJoXv1Q==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.3.tgz", - "integrity": "sha512-6tbrbwfz5GB9DQ4Jwo6hy9v+vR31xZlvzZ6n5Xut6Hhx5PvrA9q/HsK8KMaYQp063iqZGXwNvZtYNLD7EM/x0w==", - "cpu": [ - "ppc64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.3.tgz", - "integrity": "sha512-oyuXxXmoZHjXC917IAPFAAv4wWAa0cM9afk8nx1+9/jNNOX1uPf8yDA6p7G0RypOfw/X0PQt5IfoquY1um+zSg==", - "cpu": [ - "s390x" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.3.tgz", - "integrity": "sha512-TytMwF2KVGqP2tgd0I1OY0PAv78dZRAYcF5ssDzjM34SUXCED3uXvSd5+lHoC0bTD6eEdFz7LdQNCO1y0oVk9w==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.3.tgz", - "integrity": "sha512-/E9m3qstrJFVPoULV25mVQblSNExY2+kBsYe4sy0Tn0yOOgJ8wZbZt3KnRbF/XeU2Gl1STKUQnDNTqhIE5MD4A==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.3.tgz", - "integrity": "sha512-Kr0OcsoQI816i6HOl3vFHpd1K0eZyh76zgfj4c1nTyaTsd5r2Mj1lwM4R90y/qaCfmTn9eHy0SKwi98eitRxug==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.3.tgz", - "integrity": "sha512-hOtMwTqnME+/gJcH/PCZ0wn0zPUjiWOgkHpxbSJpfGKMezHltx1S7/k1SitzVa7Ww2cqrDDaFbZEhcJZO8o+Jw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.3.tgz", - "integrity": "sha512-ekcqMMkI2PlhYnfzQnB/cEdYUVVJViWvoUyLrbzgDoi3Snfc1mVBwdnc306ufA5ejy8JSPjT2RlW1nQSjW7efg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/pluginutils": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", - "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@rollup/plugin-commonjs": { - "version": "29.0.3", - "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-29.0.3.tgz", - "integrity": "sha512-ZaOxZceP7SOUW7Lqw5IRVweSQYWaeIPnXIGLiB690EBA3FGJTO40EEr2L5yZplJWsgTCogILRSpcAe7+U0Otdg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@rollup/pluginutils": "^5.0.1", - "commondir": "^1.0.1", - "estree-walker": "^2.0.2", - "fdir": "^6.2.0", - "is-reference": "1.2.1", - "magic-string": "^0.30.3", - "picomatch": "^4.0.2" - }, - "engines": { - "node": ">=16.0.0 || 14 >= 14.17" - }, - "peerDependencies": { - "rollup": "^2.68.0||^3.0.0||^4.0.0" - }, - "peerDependenciesMeta": { - "rollup": { - "optional": true - } - } - }, - "node_modules/@rollup/plugin-commonjs/node_modules/is-reference": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-1.2.1.tgz", - "integrity": "sha512-U82MsXXiFIrjCK4otLT+o2NA2Cd2g5MLoOVXUZjIOhLurrRxpEXzI8O0KZHr3IjLvlAH1kTPYSuqer5T9ZVBKQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "*" - } - }, - "node_modules/@rollup/plugin-json": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/@rollup/plugin-json/-/plugin-json-6.1.0.tgz", - "integrity": "sha512-EGI2te5ENk1coGeADSIwZ7G2Q8CJS2sF120T7jLw4xFw9n7wIOXHo+kIYRAoVpJAN+kmqZSoO3Fp4JtoNF4ReA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@rollup/pluginutils": "^5.1.0" - }, - "engines": { - "node": ">=14.0.0" - }, - "peerDependencies": { - "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" - }, - "peerDependenciesMeta": { - "rollup": { - "optional": true - } - } - }, - "node_modules/@rollup/plugin-node-resolve": { - "version": "16.0.3", - "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-16.0.3.tgz", - "integrity": "sha512-lUYM3UBGuM93CnMPG1YocWu7X802BrNF3jW2zny5gQyLQgRFJhV1Sq0Zi74+dh/6NBx1DxFC4b4GXg9wUCG5Qg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@rollup/pluginutils": "^5.0.1", - "@types/resolve": "1.20.2", - "deepmerge": "^4.2.2", - "is-module": "^1.0.0", - "resolve": "^1.22.1" - }, - "engines": { - "node": ">=14.0.0" - }, - "peerDependencies": { - "rollup": "^2.78.0||^3.0.0||^4.0.0" - }, - "peerDependenciesMeta": { - "rollup": { - "optional": true - } - } - }, - "node_modules/@rollup/plugin-replace": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/@rollup/plugin-replace/-/plugin-replace-6.0.3.tgz", - "integrity": "sha512-J4RZarRvQAm5IF0/LwUUg+obsm+xZhYnbMXmXROyoSE1ATJe3oXSb9L5MMppdxP2ylNSjv6zFBwKYjcKMucVfA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@rollup/pluginutils": "^5.0.1", - "magic-string": "^0.30.3" - }, - "engines": { - "node": ">=14.0.0" - }, - "peerDependencies": { - "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" - }, - "peerDependenciesMeta": { - "rollup": { - "optional": true - } - } - }, - "node_modules/@rollup/pluginutils": { - "version": "5.4.0", - "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.4.0.tgz", - "integrity": "sha512-MfPp06CjRLfXQ3wY0R8vJDYBy/MvVcc9OulEfR0B8Iv9ko+GCNaRZ+EpJYFl27LhKsZK0o420sYCRHCjfCgeUg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "^1.0.0", - "estree-walker": "^2.0.2", - "picomatch": "^4.0.2" - }, - "engines": { - "node": ">=14.0.0" - }, - "peerDependencies": { - "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" - }, - "peerDependenciesMeta": { - "rollup": { - "optional": true - } - } - }, - "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.4.tgz", - "integrity": "sha512-RrPokAb7dmbxFoeO3TloqHyOjgye8RkBhSqmp4aJMIex4c9r46ZstPnleDQOq1t46VOVjwIuwNogIqbodV1Vvg==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ] - }, - "node_modules/@rollup/rollup-android-arm64": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.62.4.tgz", - "integrity": "sha512-JKuJc+pnpks2pjy7L/N3v/cAkZxYlnmuZoD840ldbMI5KDbC4iO9NKwPKYdjYFCMAIIlBzYSFHxIJVYzRo2/8A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ] - }, - "node_modules/@rollup/rollup-darwin-arm64": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.62.4.tgz", - "integrity": "sha512-krw5uS2STmvJ02x0uTXHbqQNuz+9eZ1iw+qXk9dmW2gvV4jV7O2hEoOnuhFrpOPiel1mBFtqbxYZZtC46hXLOw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.62.4.tgz", - "integrity": "sha512-wsTxtgApb4PrOsNJIm0FZ1h3WvCC+k9uxLJ4ad75hgoS4NiRes2SoJFlDAyMwiUY8IssDqGcHbXuN0sx1tfF1A==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@rollup/rollup-freebsd-arm64": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.62.4.tgz", - "integrity": "sha512-GUOnQlyZe3yAXhWOtOMsn5Qkrv5E5mZXa0thbARWi5Ei2szlVXJFQhddZ4HbAzh8q92w5twp+CQvs/eFanz9YQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ] - }, - "node_modules/@rollup/rollup-freebsd-x64": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.62.4.tgz", - "integrity": "sha512-/Y7f3QuxjzPKsjA/rfEDa3+0vXqyjmJ50Ln8dPpCmWkKTrUoWHG1cWhTqaAMLob2m2nESWuC7yGrREz019Ztqg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ] - }, - "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.62.4.tgz", - "integrity": "sha512-81wiiX3v7aqy+T+bT61TJ78yJjRquqFFTTbAPt08imfQQzkPIW8t6aJbkTagtCCrXMNc9D66+geqlK7ydLPNqA==", - "cpu": [ - "arm" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-arm-musleabihf": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.62.4.tgz", - "integrity": "sha512-9kmDIvNZqdoHOBZgNtpTBeLWYO/LVipM3H/j62P8848/l/VPEQL6N3uxU9pvP1oZAsXyC2MEnFP3ovRjo7WYNQ==", - "cpu": [ - "arm" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-arm64-gnu": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.62.4.tgz", - "integrity": "sha512-CcnXHWnXg69g+DX5VWL3FHts3qMRN2uVEHX+BZvGLdd07/gXkn3ePjYtO1LDJvxkGKVHMclKBRa1QUTH+6toYQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-arm64-musl": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.62.4.tgz", - "integrity": "sha512-iFOibiHnTRuhrWLlRsOQFdZJJIa7S8OwkneJr4ocALP16u5yk6lWLINFwhHaEqBFMsKDUZofLkGos7+CPzGB3g==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-loong64-gnu": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.62.4.tgz", - "integrity": "sha512-XnWYMI7euHlb5a871xPja+Gm7DRCFU+FGRrtS2sMq9N8FvqtpagUy6gD4YOemC5MRk9xbh8+jYMEJbigFQwsgA==", - "cpu": [ - "loong64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-loong64-musl": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.62.4.tgz", - "integrity": "sha512-qGDAlO0U8xedCcsdRm9oaoQY8DAx/QT7uIxJWhCdx0ceIWX783UC9QSYkdpzAe29wNiVfp24+bZdQmn49o45SQ==", - "cpu": [ - "loong64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-ppc64-gnu": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.62.4.tgz", - "integrity": "sha512-ru4H6ezD7ysA5EiEK6qkkaEb4modH8CTej6kUy/gQi20u3kB3G7Zn8snXXkeJSCOFKG/rbPPtM/+9Wgas1961w==", - "cpu": [ - "ppc64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-ppc64-musl": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.62.4.tgz", - "integrity": "sha512-2W4MO5WQVJnbJaZdvDb9rhBDuFU1nKIepPFpJUBsTh2k1YY2g+ODViaWuyOAjQ5cOP7NvrvLzt3wvHOoiAvc7w==", - "cpu": [ - "ppc64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.62.4.tgz", - "integrity": "sha512-+fxjfuoAmVMCYV5QyjoIpu0cp5DOiOTeqYFk1AVaxGr+/ravWLX89XfQmptsoWcaVy/TGf2hexzbUOrCQIL1CQ==", - "cpu": [ - "riscv64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-riscv64-musl": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.62.4.tgz", - "integrity": "sha512-jTn8JfHGL4djjFxPuM06LmNUJDsst2jeVlsd9OmIH6zc5sC9K6rIuO4YajXatLUpBmBKl6b35ro1QZocLi+tcA==", - "cpu": [ - "riscv64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-s390x-gnu": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.62.4.tgz", - "integrity": "sha512-oCJCJL4pXsoDcP2QZ+JVlPTIRc6266zsIaeJJsWImmF7HO0W8nb6HuSgZlMWxJwaPf8ehbSw8yo0EUw925hKsA==", - "cpu": [ - "s390x" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.62.4.tgz", - "integrity": "sha512-W69hukhZ3KKNRCaMIEzKvcFye42hh0FE1+YoYaf5+Ikacuftoco6yO/xouz0hc5d5W/s3yBro5jRiuEE/Q5vUw==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.62.4.tgz", - "integrity": "sha512-qiXbGG2jkjXhzXpsFZSR2Xpb8DN/UaxYsbb/STbuR/6fpaDgRmmaq1B/LmtF2wQFOFOSsK2jdE0RZ3a0zHn4QA==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-openbsd-x64": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.62.4.tgz", - "integrity": "sha512-nWeM//hxv8mIo6jD7Hu4o48DVmV9pbV6gsKaWU+4NFyqHoPKwrkRiZGLKUhOBk8qNmDmpwFtPKg80Bo/Tn4xiQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ] - }, - "node_modules/@rollup/rollup-openharmony-arm64": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.62.4.tgz", - "integrity": "sha512-s62SQ/vgsRSvMwDkOEfTqfgASF0f26ZNaQuTA6Aok5lrikf89yI2W0gFHvZb2Jpgc6N8JnOKZgCK2iciO3CsxQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ] - }, - "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.62.4.tgz", - "integrity": "sha512-J6wGf8TVGbXJq+HH+ttTvrcfNKPbuZecV6KT1B8I18BC5IURUh5kl4Yl5OEP5eFIUoI5BWxCsyYMhFsDx8kekw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.62.4.tgz", - "integrity": "sha512-zmfrQd/0wu6oJs8Vq8KwY/YtsKSsLtKe/HwAP4Wqy8LhWjeT55fHRAkOhYQ12wI3ayS4Tt12d5CDRD7N96SAYQ==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@rollup/rollup-win32-x64-gnu": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.62.4.tgz", - "integrity": "sha512-qPzHqdj9rfUD+w79dtE07zi/kFwKyCJqplp5K5ygeLTp7jLpAoc16OAH39HSmRC9UpozaecsleI8uAdEj6v2yw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.62.4.tgz", - "integrity": "sha512-zD6NdeWEByGE9QF9vCrlJ5YQB4oq9q91kPZS37Jwj5hOkvR1lTBSpsKhKDw4IJtbQ35LsTS1HD9DZYGKIshU1Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@standard-schema/spec": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", - "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", - "dev": true, - "license": "MIT" - }, - "node_modules/@sveltejs/acorn-typescript": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.12.tgz", - "integrity": "sha512-J1jNYG23QWd67UfrQSFHtjhV37r9mVi0gdc12A3MWPldOjRK35Xk+um+qACPVjgw3AleiqoyEAhok8Wm3q46NA==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "acorn": "^8.9.0" - } - }, - "node_modules/@sveltejs/adapter-node": { - "version": "5.5.7", - "resolved": "https://registry.npmjs.org/@sveltejs/adapter-node/-/adapter-node-5.5.7.tgz", - "integrity": "sha512-uOfc9eVlI3A37RRSaKcgrheBYPrfJwC9VMqDp8x/O6tlKdcLLvHThSWD0KNIbjQ/d+7bwLGx3vx6aowAcRfd2g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@rollup/plugin-commonjs": "^29.0.0", - "@rollup/plugin-json": "^6.1.0", - "@rollup/plugin-node-resolve": "^16.0.0", - "@rollup/plugin-replace": "^6.0.3", - "rollup": "^4.59.0" - }, - "peerDependencies": { - "@sveltejs/kit": "^2.4.0" - } - }, - "node_modules/@sveltejs/adapter-static": { - "version": "3.0.10", - "resolved": "https://registry.npmjs.org/@sveltejs/adapter-static/-/adapter-static-3.0.10.tgz", - "integrity": "sha512-7D9lYFWJmB7zxZyTE/qxjksvMqzMuYrrsyh1f4AlZqeZeACPRySjbC3aFiY55wb1tWUaKOQG9PVbm74JcN2Iew==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "@sveltejs/kit": "^2.0.0" - } - }, - "node_modules/@sveltejs/kit": { - "version": "2.70.2", - "resolved": "https://registry.npmjs.org/@sveltejs/kit/-/kit-2.70.2.tgz", - "integrity": "sha512-RzRoRpuR2KXqc5yMO0akQHDZeT4AslOlznGITURsqHaVbtyYP4Wn3eE3gxj9JcDyNYO0crkxhdwFHc+2vkVm6w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@standard-schema/spec": "^1.0.0", - "@sveltejs/acorn-typescript": "^1.0.9", - "@types/cookie": "^0.6.0", - "acorn": "^8.16.0", - "cookie": "^0.6.0", - "devalue": "^5.8.1", - "esm-env": "^1.2.2", - "kleur": "^4.1.5", - "magic-string": "^0.30.5", - "mrmime": "^2.0.0", - "set-cookie-parser": "^3.0.0", - "sirv": "^3.0.0" - }, - "bin": { - "svelte-kit": "svelte-kit.js" - }, - "engines": { - "node": ">=18.13" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.0.0", - "@sveltejs/vite-plugin-svelte": "^3.0.0 || ^4.0.0-next.1 || ^5.0.0 || ^6.0.0-next.0 || ^7.0.0", - "svelte": "^4.0.0 || ^5.0.0-next.0", - "typescript": "^5.3.3 || ^6.0.0", - "vite": "^5.0.3 || ^6.0.0 || ^7.0.0-beta.0 || ^8.0.0" - }, - "peerDependenciesMeta": { - "@opentelemetry/api": { - "optional": true - }, - "typescript": { - "optional": true - } - } - }, - "node_modules/@sveltejs/load-config": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/@sveltejs/load-config/-/load-config-0.2.1.tgz", - "integrity": "sha512-5m3B2cbqQ4TbwW6Xkh66Ntw6dD7gNc77cCxABTTesWcq9jxIzMgTk97pZx5vEtvQx8iokgi7GIphqZe+PGwcZA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 18.0.0" - } - }, - "node_modules/@sveltejs/vite-plugin-svelte": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@sveltejs/vite-plugin-svelte/-/vite-plugin-svelte-7.2.0.tgz", - "integrity": "sha512-1SpkuMSRLfugrVX+IrKfE1RUegzo8AQzKQ6qQPfVzbcWi5IhuTPaKb5ZrLpucleFznkc4/RTeSPoRnGWFxX+EQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "deepmerge": "^4.3.1", - "magic-string": "^0.30.21", - "obug": "^2.1.0", - "vitefu": "^1.1.2" - }, - "engines": { - "node": "^20.19 || ^22.12 || >=24" - }, - "peerDependencies": { - "svelte": "^5.46.4", - "vite": "^8.0.0-beta.7 || ^8.0.0" - } - }, - "node_modules/@types/cookie": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.6.0.tgz", - "integrity": "sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/estree": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", - "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/node": { - "version": "26.1.2", - "resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.2.tgz", - "integrity": "sha512-Vu4a5UFA9rIIFJ7rB/Vaafh9lrCQszopTCx6KjFboXTGQbPNasehVR5TEiithSDGyd1DEiUByggTZsg8jukeIg==", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": "~8.3.0" - } - }, - "node_modules/@types/resolve": { - "version": "1.20.2", - "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz", - "integrity": "sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/trusted-types": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", - "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", - "devOptional": true, - "license": "MIT" - }, - "node_modules/@xterm/addon-fit": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz", - "integrity": "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==", - "license": "MIT" - }, - "node_modules/@xterm/xterm": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.0.0.tgz", - "integrity": "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==", - "license": "MIT", - "workspaces": [ - "addons/*" - ] - }, - "node_modules/acorn": { - "version": "8.18.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", - "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==", - "dev": true, - "license": "MIT", - "bin": { - "acorn": "bin/acorn" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/aria-query": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.1.tgz", - "integrity": "sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/axobject-query": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz", - "integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/chokidar": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", - "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", - "dev": true, - "license": "MIT", - "dependencies": { - "readdirp": "^4.0.1" - }, - "engines": { - "node": ">= 14.16.0" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/clsx": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", - "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/commondir": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", - "integrity": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==", - "dev": true, - "license": "MIT" - }, - "node_modules/cookie": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz", - "integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/deepmerge": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", - "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/detect-libc": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", - "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=8" - } - }, - "node_modules/devalue": { - "version": "5.9.0", - "resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.0.tgz", - "integrity": "sha512-RWrqdArjvPbsATEhOPUo6Wndc/iWnkWKlhIrdlF3zMMYo/c3CVtoaVAyLtWxz5h8nSlkHzxnzV2uLydPXmtF+A==", - "dev": true, - "license": "MIT" - }, - "node_modules/dompurify": { - "version": "3.4.8", - "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.8.tgz", - "integrity": "sha512-yb1cEmaOum7wFvOCSQxyfgVlv5D47Rc30iZWoMpbDIWTnJ6grDDQyu2KFJzB2k7u0pMuJcQ1zphH//fFnw2tjQ==", - "license": "(MPL-2.0 OR Apache-2.0)", - "optionalDependencies": { - "@types/trusted-types": "^2.0.7" - } - }, - "node_modules/es-errors": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", - "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/esm-env": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.2.2.tgz", - "integrity": "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==", - "dev": true, - "license": "MIT" - }, - "node_modules/esrap": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/esrap/-/esrap-2.3.1.tgz", - "integrity": "sha512-MXjVkrBAjuwIZ8xq9+a1MOOnLIwANZOx/4gtdWHfSJtXOrUh2QQK2I5mMC3urLli559jTlq2j+kSqht80uRgog==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.4.15" - }, - "peerDependencies": { - "@typescript-eslint/types": "^8.2.0" - }, - "peerDependenciesMeta": { - "@typescript-eslint/types": { - "optional": true - } - } - }, - "node_modules/estree-walker": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", - "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", - "dev": true, - "license": "MIT" - }, - "node_modules/fdir": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", - "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12.0.0" - }, - "peerDependencies": { - "picomatch": "^3 || ^4" - }, - "peerDependenciesMeta": { - "picomatch": { - "optional": true - } - } - }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/function-bind": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/hasown": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", - "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", - "dev": true, - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/is-core-module": { - "version": "2.16.2", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.2.tgz", - "integrity": "sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA==", - "dev": true, - "license": "MIT", - "dependencies": { - "hasown": "^2.0.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-module": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz", - "integrity": "sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==", - "dev": true, - "license": "MIT" - }, - "node_modules/is-reference": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.3.tgz", - "integrity": "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "^1.0.6" - } - }, - "node_modules/kleur": { - "version": "4.1.5", - "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", - "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/lightningcss": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", - "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", - "dev": true, - "license": "MPL-2.0", - "dependencies": { - "detect-libc": "^2.0.3" - }, - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - }, - "optionalDependencies": { - "lightningcss-android-arm64": "1.33.0", - "lightningcss-darwin-arm64": "1.33.0", - "lightningcss-darwin-x64": "1.33.0", - "lightningcss-freebsd-x64": "1.33.0", - "lightningcss-linux-arm-gnueabihf": "1.33.0", - "lightningcss-linux-arm64-gnu": "1.33.0", - "lightningcss-linux-arm64-musl": "1.33.0", - "lightningcss-linux-x64-gnu": "1.33.0", - "lightningcss-linux-x64-musl": "1.33.0", - "lightningcss-win32-arm64-msvc": "1.33.0", - "lightningcss-win32-x64-msvc": "1.33.0" - } - }, - "node_modules/lightningcss-android-arm64": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", - "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-darwin-arm64": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", - "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-darwin-x64": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", - "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-freebsd-x64": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", - "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm-gnueabihf": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", - "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm64-gnu": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", - "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm64-musl": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", - "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-x64-gnu": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", - "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-x64-musl": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", - "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-win32-arm64-msvc": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", - "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-win32-x64-msvc": { - "version": "1.33.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", - "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/locate-character": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz", - "integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==", - "dev": true, - "license": "MIT" - }, - "node_modules/magic-string": { - "version": "0.30.21", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", - "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.5" - } - }, - "node_modules/marked": { - "version": "14.0.0", - "resolved": "https://registry.npmjs.org/marked/-/marked-14.0.0.tgz", - "integrity": "sha512-uIj4+faQ+MgHgwUW1l2PsPglZLOLOT1uErt06dAPtx2kjteLAkbsd/0FiYg/MGS+i7ZKLb7w2WClxHkzOOuryQ==", - "license": "MIT", - "bin": { - "marked": "bin/marked.js" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/monaco-editor": { - "version": "0.56.0", - "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.56.0.tgz", - "integrity": "sha512-sXboRm3BeBeLm938eaiyLMe0OxzfXIlZvbv4ir/jVgQy1zDhWjgmny0WoN45fuDKhCCQsYMbBJrv/A6jd8aCUg==", - "license": "MIT", - "dependencies": { - "dompurify": "3.4.8", - "marked": "14.0.0" - } - }, - "node_modules/mri": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", - "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/mrmime": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.1.tgz", - "integrity": "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - } - }, - "node_modules/nanoid": { - "version": "3.3.17", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.17.tgz", - "integrity": "sha512-xQLf0A3HOMlgHq0n247/LRuAOYmB7dXJ/DvAxGvsSBij45XtBSmQycu+F8ODbHwns/XyFZagyL1+J0Offw1E0g==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "bin": { - "nanoid": "bin/nanoid.cjs" - }, - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - } - }, - "node_modules/obug": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.4.tgz", - "integrity": "sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA==", - "dev": true, - "funding": [ - "https://github.com/sponsors/sxzz", - "https://opencollective.com/debug" - ], - "license": "MIT", - "engines": { - "node": ">=12.20.0" - } - }, - "node_modules/path-parse": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", - "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", - "dev": true, - "license": "MIT" - }, - "node_modules/picocolors": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", - "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", - "dev": true, - "license": "ISC" - }, - "node_modules/picomatch": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz", - "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/postcss": { - "version": "8.5.26", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz", - "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "nanoid": "^3.3.17", - "picocolors": "^1.1.1", - "source-map-js": "^1.2.1" - }, - "engines": { - "node": "^10 || ^12 || >=14" - } - }, - "node_modules/readdirp": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", - "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 14.18.0" - }, - "funding": { - "type": "individual", - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/resolve": { - "version": "1.22.12", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.12.tgz", - "integrity": "sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "is-core-module": "^2.16.1", - "path-parse": "^1.0.7", - "supports-preserve-symlinks-flag": "^1.0.0" - }, - "bin": { - "resolve": "bin/resolve" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/rolldown": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.3.tgz", - "integrity": "sha512-rn9wpmxplLf7NLNyCk9FyWh3FM43DbY8jOzCdEPzH7uflhTftRbCEpqi6Ly2osgoU8OwObtmavMbWLaWy4LX7A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@oxc-project/types": "=0.143.0", - "@rolldown/pluginutils": "^1.0.0" - }, - "bin": { - "rolldown": "bin/cli.mjs" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - }, - "optionalDependencies": { - "@rolldown/binding-android-arm64": "1.2.3", - "@rolldown/binding-darwin-arm64": "1.2.3", - "@rolldown/binding-darwin-x64": "1.2.3", - "@rolldown/binding-freebsd-x64": "1.2.3", - "@rolldown/binding-linux-arm-gnueabihf": "1.2.3", - "@rolldown/binding-linux-arm64-gnu": "1.2.3", - "@rolldown/binding-linux-arm64-musl": "1.2.3", - "@rolldown/binding-linux-ppc64-gnu": "1.2.3", - "@rolldown/binding-linux-s390x-gnu": "1.2.3", - "@rolldown/binding-linux-x64-gnu": "1.2.3", - "@rolldown/binding-linux-x64-musl": "1.2.3", - "@rolldown/binding-openharmony-arm64": "1.2.3", - "@rolldown/binding-win32-arm64-msvc": "1.2.3", - "@rolldown/binding-win32-x64-msvc": "1.2.3" - } - }, - "node_modules/rollup": { - "version": "4.62.4", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.4.tgz", - "integrity": "sha512-RXOqwaPsBGjMNMa4sQjDjHieHEZDFoj/Rdr46l2MU5DfEs16wHJPC2RPTPHWhNl+M3aI472LLqFkFKut4SblOg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "1.0.9" - }, - "bin": { - "rollup": "dist/bin/rollup" - }, - "engines": { - "node": ">=18.0.0", - "npm": ">=8.0.0" - }, - "optionalDependencies": { - "@napi-rs/lzma-linux-x64-gnu": "1.5.1", - "@rollup/rollup-android-arm-eabi": "4.62.4", - "@rollup/rollup-android-arm64": "4.62.4", - "@rollup/rollup-darwin-arm64": "4.62.4", - "@rollup/rollup-darwin-x64": "4.62.4", - "@rollup/rollup-freebsd-arm64": "4.62.4", - "@rollup/rollup-freebsd-x64": "4.62.4", - "@rollup/rollup-linux-arm-gnueabihf": "4.62.4", - "@rollup/rollup-linux-arm-musleabihf": "4.62.4", - "@rollup/rollup-linux-arm64-gnu": "4.62.4", - "@rollup/rollup-linux-arm64-musl": "4.62.4", - "@rollup/rollup-linux-loong64-gnu": "4.62.4", - "@rollup/rollup-linux-loong64-musl": "4.62.4", - "@rollup/rollup-linux-ppc64-gnu": "4.62.4", - "@rollup/rollup-linux-ppc64-musl": "4.62.4", - "@rollup/rollup-linux-riscv64-gnu": "4.62.4", - "@rollup/rollup-linux-riscv64-musl": "4.62.4", - "@rollup/rollup-linux-s390x-gnu": "4.62.4", - "@rollup/rollup-linux-x64-gnu": "4.62.4", - "@rollup/rollup-linux-x64-musl": "4.62.4", - "@rollup/rollup-openbsd-x64": "4.62.4", - "@rollup/rollup-openharmony-arm64": "4.62.4", - "@rollup/rollup-win32-arm64-msvc": "4.62.4", - "@rollup/rollup-win32-ia32-msvc": "4.62.4", - "@rollup/rollup-win32-x64-gnu": "4.62.4", - "@rollup/rollup-win32-x64-msvc": "4.62.4", - "fsevents": "~2.3.2" - } - }, - "node_modules/sade": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/sade/-/sade-1.8.1.tgz", - "integrity": "sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==", - "dev": true, - "license": "MIT", - "dependencies": { - "mri": "^1.1.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/set-cookie-parser": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-3.1.2.tgz", - "integrity": "sha512-5/r/lTwbJ3zQ+qwdUFZYeRNqda7P5HD8zQKqlSjdGt1/S0cjLAphHusj4Y58ahDtWn/g32xrIS58/ikOvwl0Lw==", - "dev": true, - "license": "MIT" - }, - "node_modules/sirv": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/sirv/-/sirv-3.0.2.tgz", - "integrity": "sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@polka/url": "^1.0.0-next.24", - "mrmime": "^2.0.0", - "totalist": "^3.0.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/supports-preserve-symlinks-flag": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", - "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/svelte": { - "version": "5.56.8", - "resolved": "https://registry.npmjs.org/svelte/-/svelte-5.56.8.tgz", - "integrity": "sha512-PY8LOw7xP6c8IOiVqdo0sbbZVYhXRSfklOQLAUyGBKqjTX0wx/z4l/9J+PmBpmlLnxzEb1NqltxQ5/wZme/Cmg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/remapping": "^2.3.4", - "@jridgewell/sourcemap-codec": "^1.5.0", - "@sveltejs/acorn-typescript": "^1.0.10", - "@types/estree": "^1.0.5", - "@types/trusted-types": "^2.0.7", - "acorn": "^8.12.1", - "aria-query": "5.3.1", - "axobject-query": "^4.1.0", - "clsx": "^2.1.1", - "devalue": "^5.8.1", - "esm-env": "^1.2.1", - "esrap": "^2.2.12", - "is-reference": "^3.0.3", - "locate-character": "^3.0.0", - "magic-string": "^0.30.11", - "zimmerframe": "^1.1.2" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/svelte-check": { - "version": "4.7.4", - "resolved": "https://registry.npmjs.org/svelte-check/-/svelte-check-4.7.4.tgz", - "integrity": "sha512-IW9ot9YqAoyv8FvyN+eb4ZTe8zgcKZrJLNYU6dzSKkGwEBsSPc4K7lmQ8bKn8W2YMXM6WDfZSSVOaGtekyUfOQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/trace-mapping": "^0.3.25", - "@sveltejs/load-config": "^0.2.1", - "chokidar": "^4.0.1", - "fdir": "^6.2.0", - "picocolors": "^1.0.0", - "sade": "^1.7.4" - }, - "bin": { - "svelte-check": "bin/svelte-check" - }, - "engines": { - "node": ">= 18.0.0" - }, - "peerDependencies": { - "svelte": "^4.0.0 || ^5.0.0-next.0", - "typescript": "^5.0.0 || ^6.0.0" - } - }, - "node_modules/tinyglobby": { - "version": "0.2.17", - "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", - "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", - "dev": true, - "license": "MIT", - "dependencies": { - "fdir": "^6.5.0", - "picomatch": "^4.0.4" - }, - "engines": { - "node": ">=12.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/SuperchupuDev" - } - }, - "node_modules/totalist": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/totalist/-/totalist-3.0.1.tgz", - "integrity": "sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/tweetnacl": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", - "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==", - "license": "Unlicense" - }, - "node_modules/typescript": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", - "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, - "node_modules/undici-types": { - "version": "8.3.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz", - "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/vite": { - "version": "8.2.1", - "resolved": "https://registry.npmjs.org/vite/-/vite-8.2.1.tgz", - "integrity": "sha512-EU/eS7BH3XROHh2YnBefjM6DBKA6ZeMZEYQbj7NLWg5wHYlhB8B/Mayd5XsgWq+NFYccDOTemRpdETWR6Ka/lw==", - "dev": true, - "license": "MIT", - "dependencies": { - "lightningcss": "^1.33.0", - "picomatch": "^4.0.5", - "postcss": "^8.5.25", - "rolldown": "~1.2.1", - "tinyglobby": "^0.2.17" - }, - "bin": { - "vite": "bin/vite.js" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - }, - "funding": { - "url": "https://github.com/vitejs/vite?sponsor=1" - }, - "optionalDependencies": { - "fsevents": "~2.3.3" - }, - "peerDependencies": { - "@types/node": "^20.19.0 || >=22.12.0", - "@vitejs/devtools": "^0.4.0", - "esbuild": "^0.27.0 || ^0.28.0", - "jiti": ">=1.21.0", - "less": "^4.0.0", - "sass": "^1.70.0", - "sass-embedded": "^1.70.0", - "stylus": ">=0.54.8", - "sugarss": "^5.0.0", - "terser": "^5.16.0", - "tsx": "^4.8.1", - "yaml": "^2.4.2" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - }, - "@vitejs/devtools": { - "optional": true - }, - "esbuild": { - "optional": true - }, - "jiti": { - "optional": true - }, - "less": { - "optional": true - }, - "sass": { - "optional": true - }, - "sass-embedded": { - "optional": true - }, - "stylus": { - "optional": true - }, - "sugarss": { - "optional": true - }, - "terser": { - "optional": true - }, - "tsx": { - "optional": true - }, - "yaml": { - "optional": true - } - } - }, - "node_modules/vitefu": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/vitefu/-/vitefu-1.1.3.tgz", - "integrity": "sha512-ub4okH7Z5KLjb6hDyjqrGXqWtWvoYdU3IGm/NorpgHncKoLTCfRIbvlhBm7r0YstIaQRYlp4yEbFqDcKSzXSSg==", - "dev": true, - "license": "MIT", - "workspaces": [ - "tests/deps/*", - "tests/projects/*", - "tests/projects/workspace/packages/*" - ], - "peerDependencies": { - "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" - }, - "peerDependenciesMeta": { - "vite": { - "optional": true - } - } - }, - "node_modules/zimmerframe": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz", - "integrity": "sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ==", - "dev": true, - "license": "MIT" - } - } + "name": "executer-webui", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "executer-webui", + "version": "0.0.0", + "license": "UNLICENSED", + "dependencies": { + "@ant-design/colors": "8.0.1", + "@ant-design/icons": "6.2.3", + "@emotion/react": "11.14.0", + "@emotion/styled": "11.14.1", + "@fontsource/public-sans": "5.2.7", + "@mui/material": "9.0.1", + "@nats-io/nats-core": "3.4.0", + "@nats-io/nkeys": "2.0.3", + "@xterm/addon-fit": "0.11.0", + "@xterm/xterm": "6.0.0", + "lodash-es": "4.18.1", + "monaco-editor": "0.56.0", + "notistack": "3.0.2", + "react": "19.2.6", + "react-dom": "19.2.6", + "react-router-dom": "7.15.0", + "swr": "2.4.1" + }, + "devDependencies": { + "@eslint/compat": "2.1.0", + "@eslint/eslintrc": "3.3.5", + "@eslint/js": "10.0.1", + "@types/lodash-es": "4.17.12", + "@types/node": "25.7.0", + "@types/react": "19.2.14", + "@types/react-dom": "19.2.3", + "@typescript-eslint/eslint-plugin": "8.59.3", + "@typescript-eslint/parser": "8.59.3", + "@vitejs/plugin-react": "6.0.1", + "eslint": "10.3.0", + "eslint-config-prettier": "10.1.8", + "eslint-plugin-prettier": "5.5.5", + "eslint-plugin-react-hooks": "7.1.1", + "prettier": "3.8.3", + "typescript": "6.0.3", + "vite": "8.2.1" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/@ant-design/colors": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@ant-design/colors/-/colors-8.0.1.tgz", + "integrity": "sha512-foPVl0+SWIslGUtD/xBr1p9U4AKzPhNYEseXYRRo5QSzGACYZrQbe11AYJbYfAWnWSpGBx6JjBmSeugUsD9vqQ==", + "license": "MIT", + "dependencies": { + "@ant-design/fast-color": "^3.0.0" + } + }, + "node_modules/@ant-design/fast-color": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@ant-design/fast-color/-/fast-color-3.0.1.tgz", + "integrity": "sha512-esKJegpW4nckh0o6kV3Tkb7NPIZYbPnnFxmQDUmL08ukXZAvV85TZBr70eGuke/CIArLaP6aw8lt9KILjnWuOw==", + "license": "MIT", + "engines": { + "node": ">=8.x" + } + }, + "node_modules/@ant-design/icons": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/@ant-design/icons/-/icons-6.2.3.tgz", + "integrity": "sha512-Pl3aoAtxQeKryYnt6VvDJtOxMOtA8wrRSACe/pTjOAIG3fdHrWm6Ivb4ku9tsFjYroSXBKirvuxG4QkwBXD9gg==", + "license": "MIT", + "dependencies": { + "@ant-design/colors": "^8.0.1", + "@ant-design/icons-svg": "^4.4.2", + "@rc-component/util": "^1.10.1", + "clsx": "^2.1.1" + }, + "engines": { + "node": ">=8" + }, + "peerDependencies": { + "react": ">=16.0.0", + "react-dom": ">=16.0.0" + } + }, + "node_modules/@ant-design/icons-svg": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@ant-design/icons-svg/-/icons-svg-4.6.0.tgz", + "integrity": "sha512-PRomU725ABMf/lnQp5HiB7my1kjEbFY0D10N4lXYxK6TIB1gKjIVD5MRThpDaezLgw1D774J8eOeeDB0M6wHrQ==", + "license": "MIT" + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", + "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.7", + "@babel/helper-compilation-targets": "^7.29.7", + "@babel/helper-module-transforms": "^7.29.7", + "@babel/helpers": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/core/node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@babel/core/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.8.tgz", + "integrity": "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.8", + "@babel/types": "^7.29.8", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz", + "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz", + "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", + "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.10", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.10.tgz", + "integrity": "sha512-EMCx3AGZ3WfAl6ht7AyQoPm2Lh+BGYEMdc4Q6Hf7uSCDOZFuLq44qNwL+iaim8VlyYhRAo4X43+weadK8ZB4Yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.8" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.9", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz", + "integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.8" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.29.10", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.10.tgz", + "integrity": "sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.10", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.10.tgz", + "integrity": "sha512-B3lYAs2nkKskbgQ1nfy8Ma9ao9Q1rntTAQHrzzyDuj+TSO+X3le6PfWwqDvodsb+OumE10eMFfuMCTQSQ5iuIQ==", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.8", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.9", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.8", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz", + "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==", + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@emotion/babel-plugin": { + "version": "11.13.5", + "resolved": "https://registry.npmjs.org/@emotion/babel-plugin/-/babel-plugin-11.13.5.tgz", + "integrity": "sha512-pxHCpT2ex+0q+HH91/zsdHkw/lXd468DIN2zvfvLtPKLLMo6gQj7oLObq8PhkrxOZb/gGCq03S3Z7PDhS8pduQ==", + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.16.7", + "@babel/runtime": "^7.18.3", + "@emotion/hash": "^0.9.2", + "@emotion/memoize": "^0.9.0", + "@emotion/serialize": "^1.3.3", + "babel-plugin-macros": "^3.1.0", + "convert-source-map": "^1.5.0", + "escape-string-regexp": "^4.0.0", + "find-root": "^1.1.0", + "source-map": "^0.5.7", + "stylis": "4.2.0" + } + }, + "node_modules/@emotion/cache": { + "version": "11.14.0", + "resolved": "https://registry.npmjs.org/@emotion/cache/-/cache-11.14.0.tgz", + "integrity": "sha512-L/B1lc/TViYk4DcpGxtAVbx0ZyiKM5ktoIyafGkH6zg/tj+mA+NE//aPYKG0k8kCHSHVJrpLpcAlOBEXQ3SavA==", + "license": "MIT", + "dependencies": { + "@emotion/memoize": "^0.9.0", + "@emotion/sheet": "^1.4.0", + "@emotion/utils": "^1.4.2", + "@emotion/weak-memoize": "^0.4.0", + "stylis": "4.2.0" + } + }, + "node_modules/@emotion/hash": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/@emotion/hash/-/hash-0.9.2.tgz", + "integrity": "sha512-MyqliTZGuOm3+5ZRSaaBGP3USLw6+EGykkwZns2EPC5g8jJ4z9OrdZY9apkl3+UP9+sdz76YYkwCKP5gh8iY3g==", + "license": "MIT" + }, + "node_modules/@emotion/is-prop-valid": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@emotion/is-prop-valid/-/is-prop-valid-1.4.0.tgz", + "integrity": "sha512-QgD4fyscGcbbKwJmqNvUMSE02OsHUa+lAWKdEUIJKgqe5IwRSKd7+KhibEWdaKwgjLj0DRSHA9biAIqGBk05lw==", + "license": "MIT", + "dependencies": { + "@emotion/memoize": "^0.9.0" + } + }, + "node_modules/@emotion/memoize": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/@emotion/memoize/-/memoize-0.9.0.tgz", + "integrity": "sha512-30FAj7/EoJ5mwVPOWhAyCX+FPfMDrVecJAM+Iw9NRoSl4BBAQeqj4cApHHUXOVvIPgLVDsCFoz/hGD+5QQD1GQ==", + "license": "MIT" + }, + "node_modules/@emotion/react": { + "version": "11.14.0", + "resolved": "https://registry.npmjs.org/@emotion/react/-/react-11.14.0.tgz", + "integrity": "sha512-O000MLDBDdk/EohJPFUqvnp4qnHeYkVP5B0xEG0D/L7cOKP9kefu2DXn8dj74cQfsEzUqh+sr1RzFqiL1o+PpA==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.18.3", + "@emotion/babel-plugin": "^11.13.5", + "@emotion/cache": "^11.14.0", + "@emotion/serialize": "^1.3.3", + "@emotion/use-insertion-effect-with-fallbacks": "^1.2.0", + "@emotion/utils": "^1.4.2", + "@emotion/weak-memoize": "^0.4.0", + "hoist-non-react-statics": "^3.3.1" + }, + "peerDependencies": { + "react": ">=16.8.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@emotion/serialize": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@emotion/serialize/-/serialize-1.3.3.tgz", + "integrity": "sha512-EISGqt7sSNWHGI76hC7x1CksiXPahbxEOrC5RjmFRJTqLyEK9/9hZvBbiYn70dw4wuwMKiEMCUlR6ZXTSWQqxA==", + "license": "MIT", + "dependencies": { + "@emotion/hash": "^0.9.2", + "@emotion/memoize": "^0.9.0", + "@emotion/unitless": "^0.10.0", + "@emotion/utils": "^1.4.2", + "csstype": "^3.0.2" + } + }, + "node_modules/@emotion/sheet": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@emotion/sheet/-/sheet-1.4.0.tgz", + "integrity": "sha512-fTBW9/8r2w3dXWYM4HCB1Rdp8NLibOw2+XELH5m5+AkWiL/KqYX6dc0kKYlaYyKjrQ6ds33MCdMPEwgs2z1rqg==", + "license": "MIT" + }, + "node_modules/@emotion/styled": { + "version": "11.14.1", + "resolved": "https://registry.npmjs.org/@emotion/styled/-/styled-11.14.1.tgz", + "integrity": "sha512-qEEJt42DuToa3gurlH4Qqc1kVpNq8wO8cJtDzU46TjlzWjDlsVyevtYCRijVq3SrHsROS+gVQ8Fnea108GnKzw==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.18.3", + "@emotion/babel-plugin": "^11.13.5", + "@emotion/is-prop-valid": "^1.3.0", + "@emotion/serialize": "^1.3.3", + "@emotion/use-insertion-effect-with-fallbacks": "^1.2.0", + "@emotion/utils": "^1.4.2" + }, + "peerDependencies": { + "@emotion/react": "^11.0.0-rc.0", + "react": ">=16.8.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@emotion/unitless": { + "version": "0.10.0", + "resolved": "https://registry.npmjs.org/@emotion/unitless/-/unitless-0.10.0.tgz", + "integrity": "sha512-dFoMUuQA20zvtVTuxZww6OHoJYgrzfKM1t52mVySDJnMSEa08ruEvdYQbhvyu6soU+NeLVd3yKfTfT0NeV6qGg==", + "license": "MIT" + }, + "node_modules/@emotion/use-insertion-effect-with-fallbacks": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@emotion/use-insertion-effect-with-fallbacks/-/use-insertion-effect-with-fallbacks-1.2.0.tgz", + "integrity": "sha512-yJMtVdH59sxi/aVJBpk9FQq+OR8ll5GT8oWd57UpeaKEVGab41JWaCFA7FRLoMLloOZF/c/wsPoe+bfGmRKgDg==", + "license": "MIT", + "peerDependencies": { + "react": ">=16.8.0" + } + }, + "node_modules/@emotion/utils": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/@emotion/utils/-/utils-1.4.2.tgz", + "integrity": "sha512-3vLclRofFziIa3J2wDh9jjbkUz9qk5Vi3IZ/FSTKViB0k+ef0fPV7dYrUIugbgupYDx7v9ud/SjrtEP8Y4xLoA==", + "license": "MIT" + }, + "node_modules/@emotion/weak-memoize": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@emotion/weak-memoize/-/weak-memoize-0.4.0.tgz", + "integrity": "sha512-snKqtPW01tN0ui7yu9rGv69aJXr/a/Ywvl11sUjNtEcRc+ng/mQriFL0wLXMef74iHa/EkftbDzU9F8iFbH+zg==", + "license": "MIT" + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.10.1", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz", + "integrity": "sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.2", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", + "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/compat": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@eslint/compat/-/compat-2.1.0.tgz", + "integrity": "sha512-LgaSCymEpw7tF53xvDw9SNsraPb1IBHxpdABIOM0hW8UAlP8znrjYtuxfR58FSJ3L9BhwD+FaPRFQpZq84Nh6g==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^1.2.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "peerDependencies": { + "eslint": "^8.40 || 9 || 10" + }, + "peerDependenciesMeta": { + "eslint": { + "optional": true + } + } + }, + "node_modules/@eslint/config-array": { + "version": "0.23.5", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.5.tgz", + "integrity": "sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^3.0.5", + "debug": "^4.3.1", + "minimatch": "^10.2.4" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/config-array/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@eslint/config-array/node_modules/brace-expansion": { + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@eslint/config-array/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.5.5.tgz", + "integrity": "sha512-eIJYKTCECbP/nsKaaruF6LW967mtbQbsw4JTtSVkUQc9MneSkbrgPJAbKl9nWr0ZeowV8BfsarBmPpBzGelA2w==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^1.2.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/core": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-1.2.1.tgz", + "integrity": "sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "3.3.5", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.5.tgz", + "integrity": "sha512-4IlJx0X0qftVsN5E+/vGujTRIFtwuLbNsVUe7TO6zYPDR1O6nFwvwhIKEKSrl6dZchmYBITazxKoUYOjdtjlRg==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^6.14.0", + "debug": "^4.3.2", + "espree": "^10.0.1", + "globals": "^14.0.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.1", + "minimatch": "^3.1.5", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/js": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-10.0.1.tgz", + "integrity": "sha512-zeR9k5pd4gxjZ0abRoIaxdc7I3nDktoXZk2qOv9gCNWx3mVwEn32VRhyLaRsDiJjTs0xq/T8mfPtyuXu7GWBcA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "eslint": "^10.0.0" + }, + "peerDependenciesMeta": { + "eslint": { + "optional": true + } + } + }, + "node_modules/@eslint/object-schema": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-3.0.5.tgz", + "integrity": "sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.7.3.tgz", + "integrity": "sha512-IkO+/KEUvwbVpiURZg+P7zF74z5Jxe0UgJxVni+RtoHQ6IZieXaO02kmadomap/q+l6bc/jdPGGqTjhuZnuz1Q==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^1.2.1", + "levn": "^0.4.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@fontsource/public-sans": { + "version": "5.2.7", + "resolved": "https://registry.npmjs.org/@fontsource/public-sans/-/public-sans-5.2.7.tgz", + "integrity": "sha512-pVttDr3HvhVIt2x6sZJfZKksNEpq23C1JCHTQwT9KWJdmFRdNeRM8gQftq8uP72sPW+p3Ku9x8HPk2E392DFvg==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@humanfs/core": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", + "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/types": "^0.15.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.8", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz", + "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.2", + "@humanfs/types": "^0.15.0", + "@humanwhocodes/retry": "^0.4.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/types": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz", + "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@mui/core-downloads-tracker": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/@mui/core-downloads-tracker/-/core-downloads-tracker-9.5.0.tgz", + "integrity": "sha512-PErEpl3Lp+1ZqWYKI7GQU8XSiciAFmLbUAZ7IoaUL598HLy1UAFuEUMEJu8yAS1v8vkXYzWprMVZzky4UwXoOA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mui-org" + } + }, + "node_modules/@mui/material": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/@mui/material/-/material-9.0.1.tgz", + "integrity": "sha512-voyCpeUxcSWLN7KPZuq0pGCIt726T9K6kiVM3XUcywZDAlZSarLHaUxJVQpospbjjOzN53hwyjo8s6KoWl6utw==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.29.2", + "@mui/core-downloads-tracker": "^9.0.1", + "@mui/system": "^9.0.1", + "@mui/types": "^9.0.0", + "@mui/utils": "^9.0.1", + "@popperjs/core": "^2.11.8", + "@types/react-transition-group": "^4.4.12", + "clsx": "^2.1.1", + "csstype": "^3.2.3", + "prop-types": "^15.8.1", + "react-is": "^19.2.4", + "react-transition-group": "^4.4.5" + }, + "engines": { + "node": ">=14.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mui-org" + }, + "peerDependencies": { + "@emotion/react": "^11.5.0", + "@emotion/styled": "^11.3.0", + "@mui/material-pigment-css": "^9.0.1", + "@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0", + "react": "^17.0.0 || ^18.0.0 || ^19.0.0", + "react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@emotion/react": { + "optional": true + }, + "@emotion/styled": { + "optional": true + }, + "@mui/material-pigment-css": { + "optional": true + }, + "@types/react": { + "optional": true + } + } + }, + "node_modules/@mui/private-theming": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/@mui/private-theming/-/private-theming-9.5.0.tgz", + "integrity": "sha512-UHZKySlr4ZJeA5HEhe/Tq1fhsR5573ViKYn7JV80dCVJtgqRQIplRSer1DHPg2Yi22llX7QRhgM0Vtrx4kZHSA==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.29.7 || ^8.0.5", + "@mui/utils": "^9.5.0", + "prop-types": "^15.8.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mui-org" + }, + "peerDependencies": { + "@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0", + "react": "^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@mui/styled-engine": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/@mui/styled-engine/-/styled-engine-9.5.0.tgz", + "integrity": "sha512-IX1ceHnZ0bJgzJRWO/Ayl4ME1rNmpWVYwV28yb089UAMR17rJkV1qfr7ApsWQXXPi1oi+2JapJrWQAiAnTlJHQ==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.29.7 || ^8.0.5", + "@emotion/cache": "^11.14.0", + "@emotion/serialize": "^1.3.3", + "@emotion/sheet": "^1.4.0", + "csstype": "^3.2.3", + "prop-types": "^15.8.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mui-org" + }, + "peerDependencies": { + "@emotion/react": "^11.4.1", + "@emotion/styled": "^11.3.0", + "react": "^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@emotion/react": { + "optional": true + }, + "@emotion/styled": { + "optional": true + } + } + }, + "node_modules/@mui/system": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/@mui/system/-/system-9.5.0.tgz", + "integrity": "sha512-OZuAwvoiaaHpvn0a540VH1DUwwmojJubGfNmO2g+nb2ybNDP4/gF7t7aA6AMduELSuJ5yxwlzyFvUO3CfLv1Yg==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.29.7 || ^8.0.5", + "@mui/private-theming": "^9.5.0", + "@mui/styled-engine": "^9.5.0", + "@mui/types": "^9.5.0", + "@mui/utils": "^9.5.0", + "clsx": "^2.1.1", + "csstype": "^3.2.3", + "prop-types": "^15.8.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mui-org" + }, + "peerDependencies": { + "@emotion/react": "^11.5.0", + "@emotion/styled": "^11.3.0", + "@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0", + "react": "^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@emotion/react": { + "optional": true + }, + "@emotion/styled": { + "optional": true + }, + "@types/react": { + "optional": true + } + } + }, + "node_modules/@mui/types": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/@mui/types/-/types-9.5.0.tgz", + "integrity": "sha512-O0S6xS80qEQqW2CYNrd4GlBEQ1xpMOHZ5b4zO/DaLu6NZmtthM6smEg0Gz/u9gX5vL+8NB3EiBIxmxSCcG590Q==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.29.7 || ^8.0.5" + }, + "peerDependencies": { + "@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@mui/utils": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/@mui/utils/-/utils-9.5.0.tgz", + "integrity": "sha512-8m0LfSgE2pj58znY3kZ+anwRKbnBkcu/7AJPA8L/77wEjN0QnpX4/zRAccyplp1VEUnMsUBADeTRin5Mkf7epA==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.29.7 || ^8.0.5", + "@mui/types": "^9.5.0", + "@types/prop-types": "^15.7.15", + "clsx": "^2.1.1", + "prop-types": "^15.8.1", + "react-is": "^19.3.0" + }, + "engines": { + "node": ">=14.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mui-org" + }, + "peerDependencies": { + "@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0", + "react": "^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@nats-io/nats-core": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/@nats-io/nats-core/-/nats-core-3.4.0.tgz", + "integrity": "sha512-QMDM86EUNm+wudlKC67HLar/KHHQUvJGLfb4jbahje3pUk3K9afeck9fwsxBZF0eUFox6T/TA6m/t+lQqf+QsQ==", + "license": "Apache-2.0", + "dependencies": { + "@nats-io/nkeys": "2.0.3", + "@nats-io/nuid": "3.0.0" + } + }, + "node_modules/@nats-io/nkeys": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@nats-io/nkeys/-/nkeys-2.0.3.tgz", + "integrity": "sha512-JVt56GuE6Z89KUkI4TXUbSI9fmIfAmk6PMPknijmuL72GcD+UgIomTcRWiNvvJKxA01sBbmIPStqJs5cMRBC3A==", + "license": "Apache-2.0", + "dependencies": { + "tweetnacl": "^1.0.3" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@nats-io/nuid": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@nats-io/nuid/-/nuid-3.0.0.tgz", + "integrity": "sha512-QbXZDrxmYlrn5AD06gYcUTmEHwxn96HBQMIk7XTjDlEcx6FPzVBBPjp4AMRh1lEv6B4iJ6Xb/Uz61JugPXFRQg==", + "license": "Apache-2.0", + "engines": { + "node": ">= 22.x" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.155.0.tgz", + "integrity": "sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@pkgr/core": { + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.3.6.tgz", + "integrity": "sha512-SEeaJLb3qBNF/OaXnaR1NmmBbFYk1zC0ZH/52fATcRPLFg/p791YrcyFFy44Bo9sLaGuSuLp5Q6axbb/O+v/RA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/pkgr" + } + }, + "node_modules/@popperjs/core": { + "version": "2.11.8", + "resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz", + "integrity": "sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/popperjs" + } + }, + "node_modules/@rc-component/util": { + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@rc-component/util/-/util-1.14.0.tgz", + "integrity": "sha512-qFpkGBCiyN3NNAU+FOnZdcdz7A/rXCg3JdQk+bujUKAExZgRqzf2yy1f4YN63Lwctic5FcK9rgjQ6aWbykqwEw==", + "license": "MIT", + "dependencies": { + "is-mobile": "^5.0.0", + "react-is": "^19.2.7" + }, + "peerDependencies": { + "react": ">=18.0.0", + "react-dom": ">=18.0.0" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.15.tgz", + "integrity": "sha512-aLcgK9gIJ3YRvrrtfSBbRa27F5WrpiTaPulnFpsHPxpUHgFlSgnU4854MHwoRGEBhfRJDWCS2WQ7lIjskE9Olw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.15.tgz", + "integrity": "sha512-xD7DdZCrbThKuxNg7ooQmvp07ys4J/pnSEMTG3/OdOWl6daC67m/Q4fL78sRHMxTH/N4fGUbYhcPM0MF5WFHkg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.15.tgz", + "integrity": "sha512-m2WuQ6r0B4OTYxyPpNLtXaMRbRDUbG8YQV2Q3KTdSSK8Th6KHCnC8jVCJt8bvYeSB5WivkkNbc85mKadaSdOxA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.15.tgz", + "integrity": "sha512-5RtnsHM36nodM9WbMy+zip0LGS/G+y5wro5RHrpOlr4ac24+1zSi9kiV2MP1myZeZ/ifEHfulQcWjnAXzc2C2A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.15.tgz", + "integrity": "sha512-g3l09pyFqhu+135JKkbkwiKGQmwU5hUMUPJ4VdBADvuqR8d33L6H578rh8m7rtxbdp+VmX/+nzI7nvhSZlzpUQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.15.tgz", + "integrity": "sha512-nIe3VugI97nGQtspPxDqA4sXMUpeiocKIP/CqpY/u/vgbT+alX+cVxu1C/oVBPKg4feNTmYovE91v4DgXvXNwQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.15.tgz", + "integrity": "sha512-iTBjXx+B5QSvgI89lJfmqh4wTh8NabR1YZIIN3hNx4zSG0EVfVqkOvLulNpG4251pbd6/IAmZ/LefVk1Y4rPhw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.15.tgz", + "integrity": "sha512-uN26XOnVR7rqQupG3V9oAG2EGGatWjcJHOeDOHUFCh4TBWmP2tHTFoVN13aYbwfm0aHqJAEmcwhAu6sooIjfqQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.15.tgz", + "integrity": "sha512-9nWkcdd+H+XhaA3fQIwpHnKIrfx/PQ6rO0pivr78Og07tXlUlctBBJoEYLPfhTmCR/QxEVdn6uPjHV5SymPhdw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.15.tgz", + "integrity": "sha512-Ggh0ciFjLwIusLSLz7LZYEaGdxOAUJXI+Qu5JCbhPJJHEt8vP+IjRATTJheiJsdzzTYgUiHUiw3X1Ea3ZpMBdA==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.15.tgz", + "integrity": "sha512-FHg60rS6DBePAYZ9X9F67x+JObFdmgn6tupA1C/a3B+CufFmTD4mX+e8M75tCiAO3foR/6xwVBI0KQiI7sn/rw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.15.tgz", + "integrity": "sha512-/cvV/7v5VGz/moiz0XKRj2dE8DzsKyhIu1KpOvJGPjRywg3yscON889UGvAe8zfiJLHup7VLjBduoGWi3HusWQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.15.tgz", + "integrity": "sha512-MyzC5Hrv/sm+Z7TSGKP/j8001RO2xQm1zOpCNVL4j0cY/VhBZviludA2YFQ7i4lH6ZAXxQm0lcMdBzM+99mE7w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.15.tgz", + "integrity": "sha512-+PgYiS+AH5omy6L45ZLxybasauJaj3M8buoT83D+nzPmCayXlxUV9hydhciCKVyIg0B/v0BtXPDE1uGqNwCPpg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.15.tgz", + "integrity": "sha512-HFZd2QNQYn1JbIi+Hpd7H+r/lkWxcfIu28nirZ6eCn2LafuvmExMlb/P96Sfx5tf7pPArw39IdhmCF8vmV+NhQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-rc.7", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.7.tgz", + "integrity": "sha512-qujRfC8sFVInYSPPMLQByRh7zhwkGFS4+tyMQ83srV1qrxL4g8E2tyxVVyxd0+8QeBM1mIk9KbWxkegRr76XzA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/esrecurse": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz", + "integrity": "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/lodash": { + "version": "4.17.27", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.27.tgz", + "integrity": "sha512-VenMRv/eKNrspX9v3H4dbmjsrnCOYdYBG3kxXKk3dG6X+urBGcj2Prww3xw1U5K4FV/mE4h5GbWd0szEKf+9ew==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/lodash-es": { + "version": "4.17.12", + "resolved": "https://registry.npmjs.org/@types/lodash-es/-/lodash-es-4.17.12.tgz", + "integrity": "sha512-0NgftHUcV4v34VhXm8QBSftKVXtbkBG3ViCjs6+eJ5a6y6Mi/jiFGPc1sC7QK+9BFhWrURE3EOggmWaSxL9OzQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/lodash": "*" + } + }, + "node_modules/@types/node": { + "version": "25.7.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.7.0.tgz", + "integrity": "sha512-z+pdZyxE+RTQE9AcboAZCb4otwcrvgHD+GlBpPgn0emDVt0ohrTMhAwlr2Wd9nZ+nihhYFxO2pThz3C5qSu2Eg==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.21.0" + } + }, + "node_modules/@types/parse-json": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.2.tgz", + "integrity": "sha512-dISoDXWWQwUquiKsyZ4Ng+HX2KsPL7LyHKHQwgGFEA3IaKac4Obd+h2a/a6waisAoepJlBcx9paWqjA8/HVjCw==", + "license": "MIT" + }, + "node_modules/@types/prop-types": { + "version": "15.7.15", + "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz", + "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==", + "license": "MIT" + }, + "node_modules/@types/react": { + "version": "19.2.14", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz", + "integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==", + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.2.3", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz", + "integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.2.0" + } + }, + "node_modules/@types/react-transition-group": { + "version": "4.4.12", + "resolved": "https://registry.npmjs.org/@types/react-transition-group/-/react-transition-group-4.4.12.tgz", + "integrity": "sha512-8TV6R3h2j7a91c+1DXdJi3Syo69zzIZbz7Lg5tORM5LEJG7X/E6a1V3drRyBRZq7/utz7A+c4OgYLiLcYGHG6w==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*" + } + }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "license": "MIT", + "optional": true + }, + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "8.59.3", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.59.3.tgz", + "integrity": "sha512-PwFvSKsXGShKGW6n5bZOhGHEcCZXM8HofLK9fNsEwZXzFRjoY+XT1Vsf1zgyXdwTr0ZYz1/2tkZ0DBTT9jZjhw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.12.2", + "@typescript-eslint/scope-manager": "8.59.3", + "@typescript-eslint/type-utils": "8.59.3", + "@typescript-eslint/utils": "8.59.3", + "@typescript-eslint/visitor-keys": "8.59.3", + "ignore": "^7.0.5", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.59.3", + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": { + "version": "7.0.13", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.13.tgz", + "integrity": "sha512-2E8Q6rh+1RRSq/YdaGsNfXsEZy9FVqv6BSSrkmZJP7BnaoPnRfKL+YaofPvP+5rzdk144qSm6i4+hvPgUcbV4Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "8.59.3", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.59.3.tgz", + "integrity": "sha512-HPwA+hVkfcriajbNvTmZv4VRauibay+cWArYUYq7u7W7PmGShMxbPxLvrwDme55a6d5alG3nrYfhyJ/G28XlLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/scope-manager": "8.59.3", + "@typescript-eslint/types": "8.59.3", + "@typescript-eslint/typescript-estree": "8.59.3", + "@typescript-eslint/visitor-keys": "8.59.3", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/project-service": { + "version": "8.59.3", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.59.3.tgz", + "integrity": "sha512-ECiUWa/KYRGDFUqTNehaRgzDshnJfkTABJxVemHk4ko22gcr0ukloKjWvyQ64g8YCV/UI47kN1dbmjf/GaQYng==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.59.3", + "@typescript-eslint/types": "^8.59.3", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "8.59.3", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.59.3.tgz", + "integrity": "sha512-t2LvZnoEfzKtnPjgeEu41xw5gxq9mQVfYy4OoZ4Vlt0sk3JwxmhCca/AR7DwOiHrjWgjAj6as4AhRLKSDfvZIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.59.3", + "@typescript-eslint/visitor-keys": "8.59.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.59.3", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.59.3.tgz", + "integrity": "sha512-PcIJHjmaREXLgIAIzLnSY9VucEzz8FKXsRgFa1DmdGCK/5tJpW03TKJF01Q6VZd1lLdz2sIKPWaDUZN9dp//dw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "8.59.3", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.59.3.tgz", + "integrity": "sha512-g71d8QD8UaiHGvrJwyIS1hCX5r63w6Jll+4VEYhEAHXTDIqX1JgxhTAbEHtKntL9kuc4jRo7/GWw5xfCepSccQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.59.3", + "@typescript-eslint/typescript-estree": "8.59.3", + "@typescript-eslint/utils": "8.59.3", + "debug": "^4.4.3", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/types": { + "version": "8.59.3", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.59.3.tgz", + "integrity": "sha512-ePFoH0g4ludssdRFqqDxQePCxU4WQyRa9+XVwjm7yLn0FKhMeoetC+qBEEI1Eyb1pGSDveTIT09Bvw2WhlGayg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "8.59.3", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.59.3.tgz", + "integrity": "sha512-CbRjVRAf7Lr9Kr8RopKcbY45p2VfmmHrm0ygOCYFi7oU8q19m0Fs/6iHS7kNOmwpp+ob07ZVcAqlxUod9lYdmg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/project-service": "8.59.3", + "@typescript-eslint/tsconfig-utils": "8.59.3", + "@typescript-eslint/types": "8.59.3", + "@typescript-eslint/visitor-keys": "8.59.3", + "debug": "^4.4.3", + "minimatch": "^10.2.2", + "semver": "^7.7.3", + "tinyglobby": "^0.2.15", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": { + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@typescript-eslint/utils": { + "version": "8.59.3", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.59.3.tgz", + "integrity": "sha512-JAvT14goBzRzzzZyqq3P9BLArIxTtQURUtFgQ/V7FO+eU+Gg6ES+5ymOPP1wRxXcxAYeivCk4uS3jCKWI1K8Zg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.9.1", + "@typescript-eslint/scope-manager": "8.59.3", + "@typescript-eslint/types": "8.59.3", + "@typescript-eslint/typescript-estree": "8.59.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "8.59.3", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.59.3.tgz", + "integrity": "sha512-f1UQF7ggd42YiwI5wGrRaPsa+P0CINBlrkLPmGfpq/u/I/oVtecoEIfFR9ag/oa1sLOsRNZ6xehf6qMZhQGBDg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.59.3", + "eslint-visitor-keys": "^5.0.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", + "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.0.1.tgz", + "integrity": "sha512-l9X/E3cDb+xY3SWzlG1MOGt2usfEHGMNIaegaUGFsLkb3RCn/k8/TOXBcab+OndDI4TBtktT8/9BwwW8Vi9KUQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rolldown/pluginutils": "1.0.0-rc.7" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", + "babel-plugin-react-compiler": "^1.0.0", + "vite": "^8.0.0" + }, + "peerDependenciesMeta": { + "@rolldown/plugin-babel": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + } + } + }, + "node_modules/@xterm/addon-fit": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz", + "integrity": "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==", + "license": "MIT" + }, + "node_modules/@xterm/xterm": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.0.0.tgz", + "integrity": "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==", + "license": "MIT", + "workspaces": [ + "addons/*" + ] + }, + "node_modules/acorn": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/ajv": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", + "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/babel-plugin-macros": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/babel-plugin-macros/-/babel-plugin-macros-3.1.0.tgz", + "integrity": "sha512-Cg7TFGpIr01vOQNODXOOaGz2NpCU5gl8x1qJFbb6hbZxR7XrcE2vtbAsTAbJ7/xwJtUuJEw8K8Zr/AE0LHlesg==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.12.5", + "cosmiconfig": "^7.0.0", + "resolve": "^1.19.0" + }, + "engines": { + "node": ">=10", + "npm": ">=6" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.31", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.31.tgz", + "integrity": "sha512-b0k7wXlWjpuL/Uxb/pYlpjY0ej5BjAmurtPUk3eRGuloI4yjK32m8TiKUQ81l1ptcLjKS/KH2+uqIolZti1x4Q==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/browserslist": { + "version": "4.29.4", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.4.tgz", + "integrity": "sha512-2TcbbiwXEq+N0kD36tykpCfyyQigUXmuwNQbnPp4Xk4PX9JOqVIKjJlIDjpH7uY6tmRGoAd+apeT1p60T8wsdA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.11.29", + "caniuse-lite": "^1.0.30001816", + "electron-to-chromium": "^1.5.459", + "node-releases": "^2.0.59", + "update-browserslist-db": "^1.3.4" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001819", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001819.tgz", + "integrity": "sha512-LFUqIIAwpzsIuevnKnsR9qnStBcgzPShTX61lBwN9uFkkf8o8zLiebEjbW8AYtZiF+1YKDWfdt/pWDtMuG8Xwg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, + "node_modules/convert-source-map": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz", + "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==", + "license": "MIT" + }, + "node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/cosmiconfig": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.1.0.tgz", + "integrity": "sha512-AdmX6xUzdNASswsFtmwSt7Vj8po9IuqXm0UXz7QKPuEUmPB4XyjGfaAr2PSuELMwkRMVH1EpIkX5bTZGRB3eCA==", + "license": "MIT", + "dependencies": { + "@types/parse-json": "^4.0.0", + "import-fresh": "^3.2.1", + "parse-json": "^5.0.0", + "path-type": "^4.0.0", + "yaml": "^1.10.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/cosmiconfig/node_modules/yaml": { + "version": "1.10.3", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.3.tgz", + "integrity": "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==", + "license": "ISC", + "engines": { + "node": ">= 6" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/dom-helpers": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.2.1.tgz", + "integrity": "sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.8.7", + "csstype": "^3.0.2" + } + }, + "node_modules/dompurify": { + "version": "3.4.8", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.8.tgz", + "integrity": "sha512-yb1cEmaOum7wFvOCSQxyfgVlv5D47Rc30iZWoMpbDIWTnJ6grDDQyu2KFJzB2k7u0pMuJcQ1zphH//fFnw2tjQ==", + "license": "(MPL-2.0 OR Apache-2.0)", + "optionalDependencies": { + "@types/trusted-types": "^2.0.7" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.463", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.463.tgz", + "integrity": "sha512-nVWNU6ltFjopvOdD44J4zoBkgO0M+WZiFKKFV7EjebOH9z0KNphk6bCEjplXtJofL21ARIuuwWOCsFkBVklm6w==", + "dev": true, + "license": "ISC" + }, + "node_modules/error-ex": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz", + "integrity": "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==", + "license": "MIT", + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.3.0.tgz", + "integrity": "sha512-XbEXaRva5cF0ZQB8w6MluHA0kZZfV2DuCMJ3ozyEOHLwDpZX2Lmm/7Pp0xdJmI0GL1W05VH5VwIFHEm1Vcw2gw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.8.0", + "@eslint-community/regexpp": "^4.12.2", + "@eslint/config-array": "^0.23.5", + "@eslint/config-helpers": "^0.5.5", + "@eslint/core": "^1.2.1", + "@eslint/plugin-kit": "^0.7.1", + "@humanfs/node": "^0.16.6", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "ajv": "^6.14.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^9.1.2", + "eslint-visitor-keys": "^5.0.1", + "espree": "^11.2.0", + "esquery": "^1.7.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^8.0.0", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "minimatch": "^10.2.4", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + } + }, + "node_modules/eslint-config-prettier": { + "version": "10.1.8", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-10.1.8.tgz", + "integrity": "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==", + "dev": true, + "license": "MIT", + "bin": { + "eslint-config-prettier": "bin/cli.js" + }, + "funding": { + "url": "https://opencollective.com/eslint-config-prettier" + }, + "peerDependencies": { + "eslint": ">=7.0.0" + } + }, + "node_modules/eslint-plugin-prettier": { + "version": "5.5.5", + "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-5.5.5.tgz", + "integrity": "sha512-hscXkbqUZ2sPithAuLm5MXL+Wph+U7wHngPBv9OMWwlP8iaflyxpjTYZkmdgB4/vPIhemRlBEoLrH7UC1n7aUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "prettier-linter-helpers": "^1.0.1", + "synckit": "^0.11.12" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint-plugin-prettier" + }, + "peerDependencies": { + "@types/eslint": ">=8.0.0", + "eslint": ">=8.0.0", + "eslint-config-prettier": ">= 7.0.0 <10.0.0 || >=10.1.0", + "prettier": ">=3.0.0" + }, + "peerDependenciesMeta": { + "@types/eslint": { + "optional": true + }, + "eslint-config-prettier": { + "optional": true + } + } + }, + "node_modules/eslint-plugin-react-hooks": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-7.1.1.tgz", + "integrity": "sha512-f2I7Gw6JbvCexzIInuSbZpfdQ44D7iqdWX01FKLvrPgqxoE7oMj8clOfto8U6vYiz4yd5oKu39rRSVOe1zRu0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.24.4", + "@babel/parser": "^7.24.4", + "hermes-parser": "^0.25.1", + "zod": "^3.25.0 || ^4.0.0", + "zod-validation-error": "^3.5.0 || ^4.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 || ^10.0.0" + } + }, + "node_modules/eslint-scope": { + "version": "9.1.2", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-9.1.2.tgz", + "integrity": "sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "@types/esrecurse": "^4.3.1", + "@types/estree": "^1.0.8", + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/eslint/node_modules/brace-expansion": { + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/eslint/node_modules/eslint-visitor-keys": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", + "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint/node_modules/espree": { + "version": "11.2.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-11.2.0.tgz", + "integrity": "sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.16.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^5.0.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/espree": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", + "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.15.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^4.2.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree/node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esquery": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", + "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-diff": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.3.0.tgz", + "integrity": "sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/file-entry-cache": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^4.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/find-root": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/find-root/-/find-root-1.1.0.tgz", + "integrity": "sha512-NKfW6bec6GfKc0SGx1e07QZY9PE99u0Bft/0rzSD5k3sO/vwkVUpDUKVm5Gpp5Ue3YfShPFTX2070tDs5kB9Ng==", + "license": "MIT" + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat-cache": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.4" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/flatted": { + "version": "3.4.4", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz", + "integrity": "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==", + "dev": true, + "license": "ISC" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/globals": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/goober": { + "version": "2.1.19", + "resolved": "https://registry.npmjs.org/goober/-/goober-2.1.19.tgz", + "integrity": "sha512-U7veizMqxyKlM58+Z5j2ngJBH/r9siDmxpvNxSw0PylF6WQvrASJEZrxh1hidRBJc2jqoBVSyOban5u8m+6Rxg==", + "license": "MIT", + "peerDependencies": { + "csstype": "^3.0.10" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hermes-estree": { + "version": "0.25.1", + "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz", + "integrity": "sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==", + "dev": true, + "license": "MIT" + }, + "node_modules/hermes-parser": { + "version": "0.25.1", + "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.25.1.tgz", + "integrity": "sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hermes-estree": "0.25.1" + } + }, + "node_modules/hoist-non-react-statics": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz", + "integrity": "sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==", + "license": "BSD-3-Clause", + "dependencies": { + "react-is": "^16.7.0" + } + }, + "node_modules/hoist-non-react-statics/node_modules/react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==", + "license": "MIT" + }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", + "license": "MIT" + }, + "node_modules/is-core-module": { + "version": "2.17.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.17.0.tgz", + "integrity": "sha512-J/vG0zBCbIKOQFfufSwyXdMrsohyJIUNkrnmo6WZGzoM7tr/lsbfW5b2BvisL6zsyMzK9UxV9L6c7AoFbyXHOA==", + "license": "MIT", + "dependencies": { + "hasown": "^2.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-mobile": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/is-mobile/-/is-mobile-5.0.0.tgz", + "integrity": "sha512-Tz/yndySvLAEXh+Uk8liFCxOwVH6YutuR74utvOcu7I9Di+DwM0mtdPVZNaVvvBUM2OXxne/NhOs1zAO7riusQ==", + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "license": "MIT" + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash-es": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.18.1.tgz", + "integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==", + "license": "MIT" + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/marked": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/marked/-/marked-14.0.0.tgz", + "integrity": "sha512-uIj4+faQ+MgHgwUW1l2PsPglZLOLOT1uErt06dAPtx2kjteLAkbsd/0FiYg/MGS+i7ZKLb7w2WClxHkzOOuryQ==", + "license": "MIT", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/monaco-editor": { + "version": "0.56.0", + "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.56.0.tgz", + "integrity": "sha512-sXboRm3BeBeLm938eaiyLMe0OxzfXIlZvbv4ir/jVgQy1zDhWjgmny0WoN45fuDKhCCQsYMbBJrv/A6jd8aCUg==", + "license": "MIT", + "dependencies": { + "dompurify": "3.4.8", + "marked": "14.0.0" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, + "node_modules/node-releases": { + "version": "2.0.60", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.60.tgz", + "integrity": "sha512-OmO8+GM1JUZqXET720VrJCwkjUCXmCMQm0Z3UDDRbfNLHS4NEAvY60j5jiFv0tkKw2PNNlqOLhahVmwJIOLDIQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/notistack": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/notistack/-/notistack-3.0.2.tgz", + "integrity": "sha512-0R+/arLYbK5Hh7mEfR2adt0tyXJcCC9KkA2hc56FeWik2QN6Bm/S4uW+BjzDARsJth5u06nTjelSw/VSnB1YEA==", + "license": "MIT", + "dependencies": { + "clsx": "^1.1.0", + "goober": "^2.0.33" + }, + "engines": { + "node": ">=12.0.0", + "npm": ">=6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/notistack" + }, + "peerDependencies": { + "react": "^17.0.0 || ^18.0.0 || ^19.0.0", + "react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/notistack/node_modules/clsx": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-1.2.1.tgz", + "integrity": "sha512-EcR6r5a8bj6pu3ycsa/E/cKVGuTgZJZdsyUYHOksG/UHIiKfjxzRxYJpyVBwYaQeOvghal9fcc4PidlgzugAQg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "license": "MIT" + }, + "node_modules/path-type": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", + "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.31", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.31.tgz", + "integrity": "sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/prettier": { + "version": "3.8.3", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.3.tgz", + "integrity": "sha512-7igPTM53cGHMW8xWuVTydi2KO233VFiTNyF5hLJqpilHfmn8C8gPf+PS7dUT64YcXFbiMGZxS9pCSxL/Dxm/Jw==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/prettier-linter-helpers": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/prettier-linter-helpers/-/prettier-linter-helpers-1.0.1.tgz", + "integrity": "sha512-SxToR7P8Y2lWmv/kTzVLC1t/GDI2WGjMwNhLLE9qtH8Q13C+aEmuRlzDst4Up4s0Wc8sF2M+J57iB3cMLqftfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-diff": "^1.1.2" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/prop-types": { + "version": "15.8.1", + "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", + "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.4.0", + "object-assign": "^4.1.1", + "react-is": "^16.13.1" + } + }, + "node_modules/prop-types/node_modules/react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==", + "license": "MIT" + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/react": { + "version": "19.2.6", + "resolved": "https://registry.npmjs.org/react/-/react-19.2.6.tgz", + "integrity": "sha512-sfWGGfavi0xr8Pg0sVsyHMAOziVYKgPLNrS7ig+ivMNb3wbCBw3KxtflsGBAwD3gYQlE/AEZsTLgToRrSCjb0Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.2.6", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.6.tgz", + "integrity": "sha512-0prMI+hvBbPjsWnxDLxlCGyM8PN6UuWjEUCYmZhO67xIV9Xasa/r/vDnq+Xyq4Lo27g8QSbO5YzARu0D1Sps3g==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.27.0" + }, + "peerDependencies": { + "react": "^19.2.6" + } + }, + "node_modules/react-is": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.3.1.tgz", + "integrity": "sha512-RRieF6IyxQBkcK6pP8xOHprLTPW6QjRkbGdImtqNme+/hYVwCZkLQLdlZGOhUqXwkS9IEynaGvPJtv6XB/cz0Q==", + "license": "MIT" + }, + "node_modules/react-router": { + "version": "7.15.0", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.15.0.tgz", + "integrity": "sha512-HW9vYwuM8f4yx66Izy8xfrzCM+SBJluoZcCbww9A1TySax11S5Vgw6fi3ZjMONw9J4gQwngL7PzkyIpJJpJ7RQ==", + "license": "MIT", + "dependencies": { + "cookie": "^1.0.1", + "set-cookie-parser": "^2.6.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "react": ">=18", + "react-dom": ">=18" + }, + "peerDependenciesMeta": { + "react-dom": { + "optional": true + } + } + }, + "node_modules/react-router-dom": { + "version": "7.15.0", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.15.0.tgz", + "integrity": "sha512-VcrVg64Fo8nwBvDscajG8gRTLIuTC6N50nb22l2HOOV4PTOHgoGp8mUjy9wLiHYoYTSYI36tUnXZgasSRFZorQ==", + "license": "MIT", + "dependencies": { + "react-router": "7.15.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "react": ">=18", + "react-dom": ">=18" + } + }, + "node_modules/react-transition-group": { + "version": "4.4.5", + "resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.5.tgz", + "integrity": "sha512-pZcd1MCJoiKiBR2NRxeCRg13uCXbydPnmB4EOeRrY7480qNWO8IIgQG6zlDkm6uRMsURXPuKq0GWtiM59a5Q6g==", + "license": "BSD-3-Clause", + "dependencies": { + "@babel/runtime": "^7.5.5", + "dom-helpers": "^5.0.1", + "loose-envify": "^1.4.0", + "prop-types": "^15.6.2" + }, + "peerDependencies": { + "react": ">=16.6.0", + "react-dom": ">=16.6.0" + } + }, + "node_modules/resolve": { + "version": "1.22.13", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.13.tgz", + "integrity": "sha512-Dj/cW9zBV2aRj6XzCxuGIs3ESZKv02jixne3q6jFZYZ3/Tg09gHHviSMDL4kObh9pqSahdRHEnDoaP2gn8YLhA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "is-core-module": "^2.17.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/rolldown": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.15.tgz", + "integrity": "sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.155.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.15", + "@rolldown/binding-android-arm64": "1.2.15", + "@rolldown/binding-darwin-arm64": "1.2.15", + "@rolldown/binding-darwin-x64": "1.2.15", + "@rolldown/binding-freebsd-x64": "1.2.15", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.15", + "@rolldown/binding-linux-arm64-gnu": "1.2.15", + "@rolldown/binding-linux-arm64-musl": "1.2.15", + "@rolldown/binding-linux-ppc64-gnu": "1.2.15", + "@rolldown/binding-linux-s390x-gnu": "1.2.15", + "@rolldown/binding-linux-x64-gnu": "1.2.15", + "@rolldown/binding-linux-x64-musl": "1.2.15", + "@rolldown/binding-openharmony-arm64": "1.2.15", + "@rolldown/binding-win32-arm64-msvc": "1.2.15", + "@rolldown/binding-win32-x64-msvc": "1.2.15" + } + }, + "node_modules/rolldown/node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "dev": true, + "license": "MIT" + }, + "node_modules/scheduler": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", + "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/set-cookie-parser": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz", + "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==", + "license": "MIT" + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha512-LbrmJOMUSdEVxIKvdcJzQC+nQhe8FUZQTXQy6+I75skNgn3OoQ0DZA8YnFa7gp8tqtL3KPf1kmo0R5DoApeSGQ==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/stylis": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/stylis/-/stylis-4.2.0.tgz", + "integrity": "sha512-Orov6g6BB1sDfYgzWfTHDOxamtX1bE/zo104Dh9e6fqJ3PooipYyfJ0pUmrZO2wAvO8YbEyeFrkV91XTsGMSrw==", + "license": "MIT" + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/swr": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/swr/-/swr-2.4.1.tgz", + "integrity": "sha512-2CC6CiKQtEwaEeNiqWTAw9PGykW8SR5zZX8MZk6TeAvEAnVS7Visz8WzphqgtQ8v2xz/4Q5K+j+SeMaKXeeQIA==", + "license": "MIT", + "dependencies": { + "dequal": "^2.0.3", + "use-sync-external-store": "^1.6.0" + }, + "peerDependencies": { + "react": "^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/synckit": { + "version": "0.11.13", + "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.11.13.tgz", + "integrity": "sha512-eNRKgb3z66Yp3D2CixVujOUvXLFUTij/zVnV8KRyvFdQwpz7I5DS8UfRkTeLzb64u+dkzDSdelE24izu+zSSUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@pkgr/core": "^0.3.6" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/synckit" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/ts-api-utils": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", + "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + } + }, + "node_modules/tweetnacl": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", + "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==", + "license": "Unlicense" + }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/typescript": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", + "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "7.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.21.0.tgz", + "integrity": "sha512-w9IMgQrz4O0YN1LtB7K5P63vhlIOvC7opSmouCJ+ZywlPAlO9gIkJ+otk6LvGpAs2wg4econaCz3TvQ9xPoyuQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/update-browserslist-db": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", + "integrity": "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/use-sync-external-store": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.7.0.tgz", + "integrity": "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A==", + "license": "MIT", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/vite": { + "version": "8.2.1", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.2.1.tgz", + "integrity": "sha512-EU/eS7BH3XROHh2YnBefjM6DBKA6ZeMZEYQbj7NLWg5wHYlhB8B/Mayd5XsgWq+NFYccDOTemRpdETWR6Ka/lw==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.5", + "postcss": "^8.5.25", + "rolldown": "~1.2.1", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.4.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-validation-error": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/zod-validation-error/-/zod-validation-error-4.0.2.tgz", + "integrity": "sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + } + } + } } diff --git a/src/WebUI/package.json b/src/WebUI/package.json index 57e622f..bd0c7ae 100644 --- a/src/WebUI/package.json +++ b/src/WebUI/package.json @@ -1,32 +1,71 @@ { - "name": "webui", - "private": true, - "version": "0.0.1", - "type": "module", - "scripts": { - "dev": "vite dev", - "build": "vite build", - "preview": "vite preview", - "prepare": "svelte-kit sync || echo ''", - "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", - "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch" - }, - "devDependencies": { - "@sveltejs/adapter-node": "^5.5.7", - "@sveltejs/adapter-static": "^3.0.10", - "@sveltejs/kit": "^2.63.0", - "@sveltejs/vite-plugin-svelte": "^7.1.2", - "@types/node": "^26.1.2", - "svelte": "^5.56.1", - "svelte-check": "^4.6.0", - "typescript": "^6.0.3", - "vite": "^8.0.16" - }, - "dependencies": { - "@nats-io/nats-core": "^3.4.0", - "@nats-io/nkeys": "^2.0.3", - "@xterm/addon-fit": "^0.11.0", - "@xterm/xterm": "^6.0.0", - "monaco-editor": "^0.56.0" - } + "name": "executer-webui", + "version": "0.0.0", + "private": true, + "license": "UNLICENSED", + "type": "module", + "engines": { + "node": ">=22" + }, + "scripts": { + "dev": "vite", + "build": "npm run typecheck && vite build", + "typecheck": "tsc --noEmit && tsc -p tsconfig.node.json --noEmit", + "lint": "eslint \"src/**/*.{ts,tsx}\"", + "lint:fix": "eslint --fix \"src/**/*.{ts,tsx}\"", + "check": "npm run typecheck && npm run lint", + "prettier": "prettier --write \"src/**/*.{ts,tsx}\"", + "preview": "vite preview", + "start": "node server.mjs" + }, + "dependencies": { + "@ant-design/colors": "8.0.1", + "@ant-design/icons": "6.2.3", + "@emotion/react": "11.14.0", + "@emotion/styled": "11.14.1", + "@fontsource/public-sans": "5.2.7", + "@mui/material": "9.0.1", + "@nats-io/nats-core": "3.4.0", + "@nats-io/nkeys": "2.0.3", + "@xterm/addon-fit": "0.11.0", + "@xterm/xterm": "6.0.0", + "lodash-es": "4.18.1", + "monaco-editor": "0.56.0", + "notistack": "3.0.2", + "react": "19.2.6", + "react-dom": "19.2.6", + "react-router-dom": "7.15.0", + "swr": "2.4.1" + }, + "devDependencies": { + "@eslint/compat": "2.1.0", + "@eslint/eslintrc": "3.3.5", + "@eslint/js": "10.0.1", + "@types/lodash-es": "4.17.12", + "@types/node": "25.7.0", + "@types/react": "19.2.14", + "@types/react-dom": "19.2.3", + "@typescript-eslint/eslint-plugin": "8.59.3", + "@typescript-eslint/parser": "8.59.3", + "@vitejs/plugin-react": "6.0.1", + "eslint": "10.3.0", + "eslint-config-prettier": "10.1.8", + "eslint-plugin-prettier": "5.5.5", + "eslint-plugin-react-hooks": "7.1.1", + "prettier": "3.8.3", + "typescript": "6.0.3", + "vite": "8.2.1" + }, + "browserslist": { + "production": [ + ">0.2%", + "not dead", + "not op_mini all" + ], + "development": [ + "last 1 chrome version", + "last 1 firefox version", + "last 1 safari version" + ] + } } diff --git a/src/WebUI/public/favicon.svg b/src/WebUI/public/favicon.svg new file mode 100644 index 0000000..7182e50 --- /dev/null +++ b/src/WebUI/public/favicon.svg @@ -0,0 +1 @@ + diff --git a/src/WebUI/static/robots.txt b/src/WebUI/public/robots.txt similarity index 100% rename from src/WebUI/static/robots.txt rename to src/WebUI/public/robots.txt diff --git a/src/WebUI/server.mjs b/src/WebUI/server.mjs new file mode 100644 index 0000000..de767fd --- /dev/null +++ b/src/WebUI/server.mjs @@ -0,0 +1,106 @@ +// Static server for the webui container: serves the Vite build in dist/ and +// answers unknown paths with index.html so client-side routes deep-link. +// Zero dependencies; /api and /messaging are routed to the backend and NATS +// by the reverse proxy in front of this, never by this process. + +import { createServer } from 'node:http'; +import { createReadStream } from 'node:fs'; +import { stat } from 'node:fs/promises'; +import { extname, join, normalize, resolve, sep } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = resolve(fileURLToPath(new URL('.', import.meta.url)), 'dist'); +const port = Number(process.env.PORT ?? 3000); + +const TYPES = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.svg': 'image/svg+xml', + '.png': 'image/png', + '.ico': 'image/x-icon', + '.woff': 'font/woff', + '.woff2': 'font/woff2', + '.ttf': 'font/ttf', + '.txt': 'text/plain; charset=utf-8', + '.map': 'application/json; charset=utf-8' +}; + +const SECURITY_HEADERS = { + 'X-Content-Type-Options': 'nosniff', + 'Referrer-Policy': 'same-origin', + 'X-Frame-Options': 'DENY' +}; + +async function fileFor(urlPath) { + // Resolve inside dist/ only; anything escaping it is treated as not found. + // A malformed escape ("/%") throws URIError; the handler answers 400. + const candidate = resolve(root, '.' + normalize(decodeURIComponent(urlPath))); + if (candidate !== root && !candidate.startsWith(root + sep)) return null; + try { + const info = await stat(candidate); + if (info.isFile()) return { path: candidate, size: info.size }; + if (info.isDirectory()) return fileFor(join(urlPath, 'index.html')); + } catch { + // Not found: fall through. + } + return null; +} + +const server = createServer((req, res) => { + // Never let one request take the process down (unhandled rejections exit Node). + serve(req, res).catch((error) => { + const status = error instanceof URIError ? 400 : 500; + if (status === 500) console.error(error); + if (!res.headersSent) res.writeHead(status, SECURITY_HEADERS); + res.end(); + }); +}); + +async function serve(req, res) { + if (req.method !== 'GET' && req.method !== 'HEAD') { + res.writeHead(405, { Allow: 'GET, HEAD', ...SECURITY_HEADERS }).end(); + return; + } + + let pathname; + try { + pathname = new URL(req.url ?? '/', 'http://localhost').pathname; + } catch { + res.writeHead(400, SECURITY_HEADERS).end(); + return; + } + + let file = await fileFor(pathname); + const isAsset = pathname.startsWith('/assets/'); + if (!file && !isAsset) { + // Client-side route (e.g. /devices/abc): hand over to the SPA. + file = await fileFor('/index.html'); + } + if (!file) { + res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8', ...SECURITY_HEADERS }).end('Not found'); + return; + } + + res.writeHead(200, { + 'Content-Type': TYPES[extname(file.path)] ?? 'application/octet-stream', + 'Content-Length': file.size, + // Hashed bundles never change; the shell must always be re-checked. + 'Cache-Control': isAsset ? 'public, max-age=31536000, immutable' : 'no-cache', + ...SECURITY_HEADERS + }); + if (req.method === 'HEAD') { + res.end(); + return; + } + createReadStream(file.path) + .on('error', () => res.destroy()) + .pipe(res); +} + +server.listen(port, () => console.log(`ExecuteR console on :${port} (serving ${root})`)); + +for (const signal of ['SIGTERM', 'SIGINT']) { + process.on(signal, () => server.close(() => process.exit(0))); +} diff --git a/src/WebUI/src/App.tsx b/src/WebUI/src/App.tsx new file mode 100644 index 0000000..0a06036 --- /dev/null +++ b/src/WebUI/src/App.tsx @@ -0,0 +1,25 @@ +import { RouterProvider } from 'react-router-dom'; +import { SWRConfig } from 'swr'; + +// project imports +import Notistack from 'components/third-party/Notistack'; +import { SessionProvider } from 'contexts/SessionContext'; +import router from 'routes'; +import ThemeCustomization from 'themes'; + +// ==============================|| APP - THEME, SESSION, ROUTER ||============================== // + +export default function App() { + return ( + + {/* Live NATS events drive most refreshes; focus revalidation covers the rest. */} + + + + + + + + + ); +} diff --git a/src/WebUI/src/api/client.ts b/src/WebUI/src/api/client.ts new file mode 100644 index 0000000..0b9bb70 --- /dev/null +++ b/src/WebUI/src/api/client.ts @@ -0,0 +1,388 @@ +import type { + AgentPackageStatusDto, + AgentUpgradeBatchDto, + AgentUpgradeDto, + AgentUpgradeSettingsDto, + AgentVersionDto, + BootstrapTokenDto, + BrowserCredentialResponse, + CreateShellResponse, + DashboardDto, + DeviceDetailDto, + DeviceDto, + DeviceGroupDto, + ExecutionDetailDto, + ExecutionSummaryDto, + FunctionModuleDto, + GroupFieldDescriptor, + GroupRuleSet, + GroupRunDto, + JobDto, + JobOutputRecordDto, + PermissionGroupDto, + RoleDto, + RollBackAgentBody, + RunScriptBody, + S3SettingsDto, + S3TestResultDto, + SaveGroupBody, + SaveRoleBody, + SaveTriggerBody, + SchedulePreviewDto, + ScriptDto, + ScriptFileBinding, + ScriptParameter, + ScriptTriggerDto, + SecretBinding, + SecretsProviderDto, + SecretsProvidersResponse, + SecretsTestResultDto, + ServerInfoDto, + StartAgentUpgradeBody, + TriggerRunResultDto +} from './types'; + +export interface AgentUpgradeQuery { + clientId?: string; + /** Only upgrades not finished yet (queued, sent, downloading, installing). */ + open?: boolean; + limit?: number; +} + +export interface SaveScriptBody { + name: string; + description?: string; + content: string; + parameters?: ScriptParameter[]; + functionModuleIds?: string[]; + secretBindings?: SecretBinding[]; + secretsVariableName?: string; + engine?: string; + fileBindings?: ScriptFileBinding[]; +} + +export interface SaveSecretsProviderBody { + name: string; + kind: string; + config: Record; +} + +/** The problem+json a refusal carries: `type` is `urn:problem:{id}`; `errors` are field messages by name. */ +export interface ProblemDetails { + type?: string; + title?: string; + detail?: string; + status?: number; + errors?: Record; + retryAfterSeconds?: number; +} + +/** A failed API call: HTTP status, the server's message and, when it sent one, the problem it answered with. */ +export class ApiError extends Error { + constructor( + public status: number, + message: string, + public problem: ProblemDetails = {} + ) { + super(message); + } +} + +/** Whether a failure is the named problem (`step-up-required`, `no-access`, …). */ +export function isProblem(error: unknown, id: string): boolean { + return error instanceof ApiError && error.problem.type === `urn:problem:${id}`; +} + +/** Field messages from a validation problem, by field: `{ baseDn: 'Enter the base DN…' }`. */ +export function fieldErrors(error: unknown): Record { + if (!(error instanceof ApiError) || !error.problem.errors) return {}; + return Object.fromEntries(Object.entries(error.problem.errors).map(([field, messages]) => [field, messages.join(' ')])); +} + +/** The message to show for any thrown value. */ +export function errorMessage(error: unknown, fallback = 'Something went wrong.'): string { + return error instanceof Error && error.message ? error.message : fallback; +} + +function readCookie(name: string): string | undefined { + return document.cookie + .split('; ') + .find((c) => c.startsWith(`${name}=`)) + ?.split('=')[1]; +} + +/** Paths that must not bounce to sign-in on a 401 (they are how sign-in finds out). */ +const SESSION_PROBES = ['/api/auth/session', '/api/auth/sign-in', '/api/auth/options', '/api/auth/password', '/api/auth/step-up']; + +/** The session's CSRF token: the cookie carries the `__Host-` prefix over HTTPS. */ +const csrfToken = () => readCookie('__Host-csrf') ?? readCookie('csrf'); + +export async function request(path: string, init?: RequestInit): Promise { + return (await send(path, init)).value; +} + +/** A settings document with its version: save it back with `ifMatch` so a concurrent edit is refused, not lost. */ +export async function requestVersioned( + path: string, + init: { method?: string; body?: unknown; ifMatch?: string; signal?: AbortSignal } = {} +): Promise<{ value: T; etag: string }> { + const { value, response } = await send(path, { + method: init.method ?? 'GET', + body: init.body === undefined ? undefined : JSON.stringify(init.body), + signal: init.signal, + headers: init.ifMatch ? { 'If-Match': init.ifMatch } : undefined + }); + return { value, etag: response.headers.get('ETag') ?? '' }; +} + +async function send(path: string, init?: RequestInit): Promise<{ value: T; response: Response }> { + const method = (init?.method ?? 'GET').toUpperCase(); + const headers: Record = {}; + if (init?.body) { + headers['Content-Type'] = 'application/json'; + } + // Double-submit CSRF token for state-changing cookie-authenticated calls. + if (!['GET', 'HEAD', 'OPTIONS'].includes(method)) { + const csrf = csrfToken(); + if (csrf) headers['X-CSRF-Token'] = csrf; + } + + const response = await fetch(path, { + credentials: 'same-origin', + ...init, + headers: { ...headers, ...(init?.headers as Record) } + }); + + if (!response.ok) { + // Session expired: bounce to sign-in, then come back here. + if (response.status === 401 && !SESSION_PROBES.some((p) => path.startsWith(p)) && !window.location.pathname.startsWith('/sign-in')) { + const back = encodeURIComponent(window.location.pathname + window.location.search); + window.location.href = `/sign-in?returnUrl=${back}`; + } + + let detail = response.statusText; + let problem: ProblemDetails = {}; + try { + const body = await response.json(); + detail = body?.error ?? body?.detail ?? body?.title ?? detail; + if (body && typeof body === 'object') problem = body as ProblemDetails; + } catch { + // Non-JSON error body. + } + + // A password set for the person comes before anything else. + if ( + response.status === 403 && + problem.type === 'urn:problem:password-change-required' && + !window.location.pathname.startsWith('/sign-in') + ) { + window.location.href = '/sign-in?change=1'; + } + throw new ApiError(response.status, detail, problem); + } + + if (response.status === 204 || response.status === 202) { + return { value: undefined as T, response }; + } + + const text = await response.text(); + return { value: (text ? JSON.parse(text) : undefined) as T, response }; +} + +const json = (method: string, body?: unknown): RequestInit => ({ + method, + body: body === undefined ? undefined : JSON.stringify(body) +}); + +const qs = (params: Record) => { + const search = new URLSearchParams(); + for (const [key, value] of Object.entries(params)) { + if (value !== undefined && value !== '') search.set(key, String(value)); + } + return search.size > 0 ? `?${search}` : ''; +}; + +const enc = encodeURIComponent; + +const upgradeQuery = ({ clientId, open, limit }: AgentUpgradeQuery) => qs({ clientId, open: open ? 'true' : undefined, limit }); + +/** Every REST call the console makes. Reads also have SWR keys (see `keys`). */ +export const api = { + // Devices + devices: () => request('/api/devices'), + device: (clientId: string) => request(`/api/devices/${enc(clientId)}`), + refreshInventory: (clientId: string) => request(`/api/devices/${enc(clientId)}/inventory`, { method: 'POST' }), + openShell: (clientId: string, body: { browserSessionId: string; cols: number; rows: number; shell?: string }) => + request(`/api/devices/${enc(clientId)}/shell`, json('POST', body)), + sendFile: (clientId: string, body: { objectKey: string; destinationPath: string; sha256?: string }) => + request(`/api/devices/${enc(clientId)}/files`, json('POST', body)), + updateDeviceTags: (clientId: string, tags: string[]) => request(`/api/devices/${enc(clientId)}/tags`, json('PUT', { tags })), + + // Agent upgrades: the version catalog, per-device attempts and their settings + agentVersions: () => request('/api/agent-versions'), + /** Refused (409, with the reason) while the version is the newest or still needed. */ + removeAgentVersion: (version: string) => request(`/api/agent-versions/${enc(version)}`, { method: 'DELETE' }), + agentUpgrades: (query: AgentUpgradeQuery = {}) => request(`/api/agent-upgrades${upgradeQuery(query)}`), + startAgentUpgrade: (body: StartAgentUpgradeBody) => request('/api/agent-upgrades', json('POST', body)), + rollBackAgent: (body: RollBackAgentBody) => request('/api/agent-upgrades/rollback', json('POST', body)), + /** Only an upgrade still queued can be cancelled. */ + cancelAgentUpgrade: (id: string) => request(`/api/agent-upgrades/${enc(id)}/cancel`, { method: 'POST' }), + agentUpgradeSettings: () => request('/api/settings/agent-upgrades'), + saveAgentUpgradeSettings: (body: AgentUpgradeSettingsDto) => + request('/api/settings/agent-upgrades', json('PUT', body)), + + // Scripts + scripts: () => request('/api/scripts'), + script: (id: string) => request(`/api/scripts/${id}`), + createScript: (body: SaveScriptBody) => request('/api/scripts', json('POST', body)), + updateScript: (id: string, body: SaveScriptBody) => request(`/api/scripts/${id}`, json('PUT', body)), + deleteScript: (id: string) => request(`/api/scripts/${id}`, { method: 'DELETE' }), + + // Function modules + functions: () => request('/api/functions'), + functionModule: (id: string) => request(`/api/functions/${id}`), + createFunction: (body: { name: string; description?: string; content: string }) => + request('/api/functions', json('POST', body)), + updateFunction: (id: string, body: { name: string; description?: string; content: string }) => + request(`/api/functions/${id}`, json('PUT', body)), + deleteFunction: (id: string) => request(`/api/functions/${id}`, { method: 'DELETE' }), + + // Jobs and executions + dashboard: () => request('/api/dashboard'), + jobs: (params: { clientId?: string; scriptId?: string; limit?: number } = {}) => request(`/api/jobs${qs(params)}`), + job: (jobId: string) => request(`/api/jobs/${jobId}`), + jobOutput: (jobId: string, afterSequence?: number) => request(`/api/jobs/${jobId}/output${qs({ afterSequence })}`), + scriptExecutions: (scriptId: string) => request(`/api/scripts/${scriptId}/executions`), + execution: (runId: string) => request(`/api/executions/${runId}`), + executions: (limit = 50) => request(`/api/executions?limit=${limit}`), + /** Runs a script on any mix of devices and groups as one execution. */ + runScript: (body: RunScriptBody) => request('/api/jobs', json('POST', body)), + + // Groups + groups: () => request('/api/groups'), + group: (id: string) => request(`/api/groups/${id}`), + createGroup: (body: SaveGroupBody) => request('/api/groups', json('POST', body)), + updateGroup: (id: string, body: SaveGroupBody) => request(`/api/groups/${id}`, json('PUT', body)), + moveGroup: (id: string, parentId: string | null) => request(`/api/groups/${id}/move`, json('POST', { parentId })), + deleteGroup: (id: string) => request(`/api/groups/${id}`, { method: 'DELETE' }), + groupMembers: (id: string) => request(`/api/groups/${id}/members`), + updateGroupMembers: (id: string, add: string[], remove: string[]) => + request(`/api/groups/${id}/members`, json('POST', { add, remove })), + previewGroup: (rules: GroupRuleSet) => request('/api/groups/preview', json('POST', { rules })), + groupFields: () => request('/api/groups/fields'), + + // Schedules and event triggers + triggers: () => request('/api/triggers'), + createTrigger: (body: SaveTriggerBody) => request<{ id: string }>('/api/triggers', json('POST', body)), + updateTrigger: (id: string, body: SaveTriggerBody) => request(`/api/triggers/${id}`, json('PUT', body)), + setTriggerEnabled: (id: string, enabled: boolean) => request(`/api/triggers/${id}`, json('PATCH', { enabled })), + deleteTrigger: (id: string) => request(`/api/triggers/${id}`, { method: 'DELETE' }), + runTrigger: (id: string) => request(`/api/triggers/${id}/run`, { method: 'POST' }), + previewSchedule: (cronExpression: string, timeZoneId: string, count = 5) => + request('/api/triggers/preview', json('POST', { cronExpression, timeZoneId, count })), + + // Messaging + messagingCredential: (nkeyPublic: string, browserSessionId?: string) => + request('/api/messaging/credential', json('POST', { nkeyPublic, browserSessionId })), + + // Access control + permissionCatalog: () => request('/api/admin/permissions'), + roles: () => request('/api/admin/roles'), + createRole: (body: SaveRoleBody) => request('/api/admin/roles', json('POST', body)), + updateRole: (id: string, body: SaveRoleBody) => request(`/api/admin/roles/${id}`, json('PUT', body)), + deleteRole: (id: string) => request(`/api/admin/roles/${id}`, { method: 'DELETE' }), + + // Settings: S3 + agent package delivery + s3Settings: () => request('/api/settings/s3'), + saveS3Settings: (body: S3SettingsDto) => request('/api/settings/s3', json('PUT', body)), + testS3Settings: (body: S3SettingsDto) => request('/api/settings/s3/test', json('POST', body)), + agentPackage: (type: 'msi' | 'zip' = 'msi') => request(`/api/settings/agent-package?type=${type}`), + offloadAgentPackage: (type: 'msi' | 'zip' = 'msi') => + request<{ message: string; status: AgentPackageStatusDto }>(`/api/settings/agent-package/offload?type=${type}`, { method: 'POST' }), + + // Secrets providers + secretsProviders: () => request('/api/secrets/providers'), + createSecretsProvider: (body: SaveSecretsProviderBody) => request('/api/secrets/providers', json('POST', body)), + updateSecretsProvider: (id: string, body: SaveSecretsProviderBody) => + request(`/api/secrets/providers/${id}`, json('PUT', body)), + deleteSecretsProvider: (id: string) => request(`/api/secrets/providers/${id}`, { method: 'DELETE' }), + testSecretsProvider: (body: SaveSecretsProviderBody & { id?: string }) => + request('/api/secrets/providers/test', json('POST', body)), + secretNames: (providerId: string, path?: string) => request(`/api/secrets/providers/${providerId}/secret-names${qs({ path })}`), + secretFolders: (providerId: string, path?: string) => request(`/api/secrets/providers/${providerId}/folders${qs({ path })}`), + + // Server info (public base URL for generated commands) + serverInfo: () => request('/api/settings/server'), + + // Enrollment tokens + bootstrapTokens: () => request('/api/admin/bootstrap-tokens'), + createBootstrapToken: (body: { validMinutes?: number; maxUses?: number; note?: string }) => + request('/api/admin/bootstrap-tokens', json('POST', body)), + revokeBootstrapToken: (id: string) => request(`/api/admin/bootstrap-tokens/${id}`, { method: 'DELETE' }) +}; + +/** + * Links that download complete stored output as a .log (the server streams + * every record, tags non-output streams and names the file). Plain GETs on + * the session cookie, so an is enough. + */ +export const downloads = { + jobOutput: (jobId: string, timestamps = false) => `/api/jobs/${jobId}/output/download${timestamps ? '?timestamps=true' : ''}`, + executionOutput: (runId: string, timestamps = false) => `/api/executions/${runId}/output/download${timestamps ? '?timestamps=true' : ''}`, + /** A zip of one .log per chosen job of the run (every job when none are chosen), saved under the server's name. */ + executionLogs: (runId: string, jobIds: string[], timestamps = false) => + saveDownload(`/api/executions/${runId}/output/archive`, { jobIds, timestamps }, `${runId}.zip`) +}; + +/** POSTs (with the CSRF token) and saves the response as a file, named by its Content-Disposition. */ +async function saveDownload(path: string, body: unknown, fallbackName: string): Promise { + const csrf = csrfToken(); + const response = await fetch(path, { + method: 'POST', + credentials: 'same-origin', + headers: { 'Content-Type': 'application/json', ...(csrf ? { 'X-CSRF-Token': csrf } : {}) }, + body: JSON.stringify(body) + }); + if (!response.ok) { + throw new ApiError(response.status, response.status === 404 ? 'Nothing to download.' : response.statusText || 'The download failed.'); + } + + const disposition = response.headers.get('Content-Disposition') ?? ''; + const encoded = /filename\*=UTF-8''([^;]+)/i.exec(disposition)?.[1]; + const plain = /filename="?([^";]+)"?/i.exec(disposition)?.[1]; + const name = encoded ? decodeURIComponent(encoded) : (plain ?? fallbackName); + + const url = URL.createObjectURL(await response.blob()); + const link = Object.assign(document.createElement('a'), { href: url, download: name }); + document.body.appendChild(link); + link.click(); + link.remove(); + setTimeout(() => URL.revokeObjectURL(url), 10_000); +} + +/** + * SWR keys for shared reads, so a write in one place can refresh every view + * of the same data with `mutate(keys.devices)`. + */ +export const keys = { + devices: '/api/devices', + device: (clientId: string) => `/api/devices/${enc(clientId)}`, + deviceHistory: (clientId: string) => `/api/devices/${enc(clientId)}/history`, + agentVersions: '/api/agent-versions', + agentUpgrades: (query: AgentUpgradeQuery = {}) => `/api/agent-upgrades${upgradeQuery(query)}`, + agentUpgradeSettings: '/api/settings/agent-upgrades', + groups: '/api/groups', + groupFields: '/api/groups/fields', + groupMembers: (id: string) => `/api/groups/${id}/members`, + scripts: '/api/scripts', + script: (id: string) => `/api/scripts/${id}`, + functions: '/api/functions', + triggers: '/api/triggers', + dashboard: '/api/dashboard', + jobs: (params: { clientId?: string; scriptId?: string; limit?: number } = {}) => `/api/jobs${qs(params)}`, + scriptExecutions: (scriptId: string) => `/api/scripts/${scriptId}/executions`, + execution: (runId: string) => `/api/executions/${runId}`, + executions: (limit = 50) => `/api/executions?limit=${limit}`, + roles: '/api/admin/roles', + permissionCatalog: '/api/admin/permissions' +}; diff --git a/src/WebUI/src/api/identity.ts b/src/WebUI/src/api/identity.ts new file mode 100644 index 0000000..06f2d7d --- /dev/null +++ b/src/WebUI/src/api/identity.ts @@ -0,0 +1,328 @@ +// Sign-in and access shapes, as the server's /api/auth, /api/settings/authentication and /api/admin routes return them (StifleR's model). + +import { request } from './client'; + +/** `local` is ExecuteR's own accounts (the Built-In tab); `windows` is this server's local Windows accounts, through the same form. */ +export type ProviderId = 'local' | 'windows' | 'ldap' | 'oidc'; +export type PrincipalKind = 'local-group' | 'windows-group' | 'ldap-group' | 'oidc-group'; + +export interface SignInOption { + id: ProviderId; + label: string; + /** `form` takes a user name and password here (LDAP); `redirect` sends the browser to the provider. */ + kind: 'form' | 'redirect'; +} + +export interface SignInOptions { + /** The built-in form is offered. */ + builtIn: boolean; + /** The same form takes this server's local Windows accounts. */ + windowsAccounts: boolean; + providers: SignInOption[]; + /** The provider to go straight to: OIDC in redirect mode, when it is the only way in. */ + redirect: ProviderId | null; +} + +export interface GroupView { + kind: PrincipalKind; + id: string; + name: string | null; +} + +/** One of the server's local groups a Windows account is in, read at its sign-in. */ +export interface WindowsGroupView { + name: string; + sid: string; +} + +export interface RoleGrant { + id: string; + name: string; +} + +export interface Session { + id: string; + userName: string; + displayName: string | null; + provider: ProviderId; + breakGlass: boolean; + passwordChangeRequired: boolean; + groups: GroupView[]; + /** The ExecuteR roles the person's groups are bound to. */ + roles: RoleGrant[]; + permissions: string[]; + expiresUtc: string | null; + absoluteExpiresUtc: string | null; + /** A Windows account's comment, SID and the server's local groups it is in; null and empty for every other account. */ + description: string | null; + sid: string | null; + windowsGroups: WindowsGroupView[]; +} + +export interface AuthenticationMethod { + id: ProviderId; + label: string; + enabled: boolean; + /** This server can offer it (Windows sign-in needs a Windows server). */ + supported: boolean; + /** It has what it needs to sign anyone in. */ + configured: boolean; +} + +export interface AuthenticationView { + methods: AuthenticationMethod[]; + oidcRedirect: boolean; + /** Redirect mode is on and OIDC is the only way in, so sign-in goes straight to it. */ + redirectActive: boolean; + builtInForcedByEnvironment: boolean; + forceBuiltInVariable: string; +} + +export interface BuiltInSettings { + enabled: boolean; + sessionIdleMinutes: number; + sessionMaxHours: number; + forcedByEnvironment: boolean; + forceVariable: string; + breakGlassUserName: string | null; +} + +export interface WindowsSettings { + enabled: boolean; + enabledByDefault: boolean; + supported: boolean; +} + +export type LdapSecurity = 'ldaps' | 'start-tls' | 'kerberos' | 'none'; + +export interface LdapSettings { + enabled: boolean; + label: string; + servers: string[]; + port: number; + security: LdapSecurity; + baseDn: string | null; + bindDn: string | null; + bindPasswordSet: boolean; + userFilter: string; + groupBaseDn: string | null; + groupFilter: string | null; + nestedGroups: boolean; + timeoutSeconds: number; + /** Set up from this server's domain join; an administrator's save makes the settings theirs. */ + automatic: boolean; + breakerFailures: number; + breakerWindowMinutes: number; + /** When the breaker turned automatic LDAP off; null while it has not. */ + breakerTrippedUtc: string | null; + /** This server can use Kerberos (Windows only). */ + kerberosSupported: boolean; +} + +export interface OidcSettings { + enabled: boolean; + /** Straight to the provider when OIDC is the only method on. */ + redirect: boolean; + label: string; + authority: string | null; + clientId: string | null; + clientSecretSet: boolean; + scopes: string[]; + userNameClaim: string; + groupClaims: string[]; + /** Register these with the provider. */ + callbackUrl: string; + postLogoutUrl: string; +} + +export interface SignInTestResult { + passed: boolean; + provider: ProviderId; + userName: string | null; + groups: GroupView[]; + /** The ExecuteR roles the groups found are bound to. */ + roles: string[]; + permissions: string[]; + detail: string | null; +} + +export interface SignInTestView { + provider: ProviderId; + status: 'none' | 'pending' | 'passed' | 'failed'; + detail: string | null; + completedUtc: string | null; + currentSettings: boolean; +} + +export interface StepUpView { + verified: boolean; + validUntilUtc: string | null; + method: 'password' | 'oidc' | 'none'; + unavailable: string | null; +} + +export interface UserView { + id: string; + kind: ProviderId; + userName: string; + displayName: string | null; + email: string | null; + enabled: boolean; + breakGlass: boolean; + passwordChangeRequired: boolean; + createdUtc: string; + lastSignInUtc: string | null; + /** A built-in account's own groups. */ + localGroups: GroupView[]; + /** A Windows account's comment, SID and the server's local groups it is in, read at its latest sign-in. */ + description: string | null; + sid: string | null; + windowsGroups: WindowsGroupView[]; +} + +export interface UserCreated { + user: UserView; + /** The generated one-time password, in this answer only. */ + password: string | null; +} + +export interface PasswordResetResult { + password: string | null; + sessionsEnded: number; +} + +export interface GrantView { + roleId: string; + roleName: string; + bindingId: string; + principalKind: PrincipalKind; + principalId: string; + principalName: string | null; +} + +/** What a person may do and where it came from; for directory people, from their latest sign-in. */ +export interface AccessView { + breakGlass: boolean; + groups: GroupView[]; + grants: GrantView[]; + permissions: string[]; + /** Null: every device. */ + deviceScopeGroupIds: string[] | null; +} + +export interface LocalGroupView { + id: string; + name: string; + description: string | null; + memberCount: number; + members: { id: string; userName: string; displayName: string | null }[]; + createdUtc: string; + /** Role names bound to the group. */ + roles: string[]; +} + +export interface RoleBindingView { + id: string; + roleId: string; + roleName: string; + principalKind: PrincipalKind; + principalId: string; + principalName: string | null; + createdUtc: string; + createdBy: string | null; +} + +export const PRINCIPAL_KIND_LABELS: Record = { + 'local-group': 'Built-In Group', + 'windows-group': 'Windows Group', + 'ldap-group': 'Directory Group', + 'oidc-group': 'OIDC Claim' +}; + +export const PROVIDER_LABELS: Record = { + local: 'Built-In Account', + windows: 'Local Windows Account', + ldap: 'Directory (LDAP)', + oidc: 'OIDC' +}; + +/** Routes, for `requestVersioned`, SWR keys and links. */ +export const IdentityRoutes = { + options: '/api/auth/options', + signIn: '/api/auth/sign-in', + session: '/api/auth/session', + signOut: '/api/auth/sign-out', + password: '/api/auth/password', + oidcSignIn: '/api/auth/oidc/sign-in', + stepUp: '/api/auth/step-up', + stepUpOidc: '/api/auth/step-up/oidc', + authentication: '/api/settings/authentication', + builtIn: '/api/settings/authentication/built-in', + windows: '/api/settings/authentication/windows', + ldap: '/api/settings/authentication/ldap', + oidc: '/api/settings/authentication/oidc', + ldapBreakerReset: '/api/settings/authentication/ldap/breaker/reset', + test: (method: 'windows' | 'ldap' | 'oidc') => `/api/settings/authentication/${method}/test`, + testResult: (method: ProviderId) => `/api/settings/authentication/tests/${method}`, + users: '/api/admin/users', + user: (id: string) => `/api/admin/users/${id}`, + userPassword: (id: string) => `/api/admin/users/${id}/password`, + userAccess: (id: string) => `/api/admin/users/${id}/access`, + localGroups: '/api/admin/local-groups', + localGroup: (id: string) => `/api/admin/local-groups/${id}`, + roleBindings: '/api/admin/role-bindings', + roleBinding: (id: string) => `/api/admin/role-bindings/${id}` +} as const; + +const post = (body?: unknown): RequestInit => ({ method: 'POST', body: body === undefined ? undefined : JSON.stringify(body) }); +const put = (body: unknown): RequestInit => ({ method: 'PUT', body: JSON.stringify(body) }); + +export const identity = { + options: () => request(IdentityRoutes.options), + session: () => request(IdentityRoutes.session), + signIn: (body: { provider: ProviderId | null; userName: string; password: string }) => + request(IdentityRoutes.signIn, post(body)), + /** Ends the session; for an OIDC session, the provider's sign-out page to visit next. */ + signOut: () => request<{ endSessionUrl: string | null }>(IdentityRoutes.signOut, post()), + changePassword: (currentPassword: string, newPassword: string) => + request(IdentityRoutes.password, post({ currentPassword, newPassword })), + + stepUpStatus: () => request(IdentityRoutes.stepUp), + stepUp: (password: string) => request(IdentityRoutes.stepUp, post({ password })), + + authentication: () => request(IdentityRoutes.authentication), + testSignIn: (method: 'windows' | 'ldap', userName: string, password: string) => + request(IdentityRoutes.test(method), post({ userName, password })), + /** Starts a test sign-in through the identity provider: the browser goes to `url` and comes back to the OIDC tab. */ + testOidc: () => request<{ url: string }>(IdentityRoutes.test('oidc'), post()), + testResult: (method: ProviderId) => request(IdentityRoutes.testResult(method)), + + users: (kind?: ProviderId) => request(`${IdentityRoutes.users}${kind ? `?kind=${kind}` : ''}`), + createUser: (body: { + userName: string; + displayName?: string; + email?: string; + password?: string; + generatePassword?: boolean; + localGroupIds?: string[]; + }) => request(IdentityRoutes.users, post(body)), + updateUser: (id: string, body: { displayName?: string; email?: string; enabled?: boolean; localGroupIds?: string[] }) => + request(IdentityRoutes.user(id), put(body)), + resetPassword: (id: string, body: { password?: string; generate?: boolean }) => + request(IdentityRoutes.userPassword(id), post(body)), + deleteUser: (id: string) => request(IdentityRoutes.user(id), { method: 'DELETE' }), + userAccess: (id: string) => request(IdentityRoutes.userAccess(id)), + + localGroups: () => request(IdentityRoutes.localGroups), + createLocalGroup: (body: { name: string; description?: string; memberIds?: string[] }) => + request(IdentityRoutes.localGroups, post(body)), + updateLocalGroup: (id: string, body: { name?: string; description?: string; memberIds?: string[] }) => + request(IdentityRoutes.localGroup(id), put(body)), + deleteLocalGroup: (id: string) => request(IdentityRoutes.localGroup(id), { method: 'DELETE' }), + + roleBindings: (principalKind?: PrincipalKind) => + request(`${IdentityRoutes.roleBindings}${principalKind ? `?principalKind=${principalKind}` : ''}`), + createRoleBinding: (body: { roleId: string; principalKind: PrincipalKind; principalId: string; principalName?: string }) => + request(IdentityRoutes.roleBindings, post(body)), + deleteRoleBinding: (id: string) => request(IdentityRoutes.roleBinding(id), { method: 'DELETE' }) +}; diff --git a/src/WebUI/src/api/menu.ts b/src/WebUI/src/api/menu.ts new file mode 100644 index 0000000..6ad0b96 --- /dev/null +++ b/src/WebUI/src/api/menu.ts @@ -0,0 +1,37 @@ +import useSWR, { mutate } from 'swr'; +import { useMemo } from 'react'; + +// ==============================|| MENU STATE (DRAWER OPEN/CLOSED) ||============================== // + +interface MenuMaster { + isDashboardDrawerOpened: boolean; +} + +const KEY = 'local/menu-master'; +const STORAGE_KEY = 'executer-drawer-open'; + +function initial(): MenuMaster { + try { + const saved = window.localStorage.getItem(STORAGE_KEY); + return { isDashboardDrawerOpened: saved === null ? true : saved === '1' }; + } catch { + return { isDashboardDrawerOpened: true }; + } +} + +export function useGetMenuMaster() { + const { data } = useSWR(KEY, initial, { revalidateIfStale: false, revalidateOnFocus: false, revalidateOnReconnect: false }); + return useMemo(() => ({ menuMaster: data ?? initial() }), [data]); +} + +/** Opens or collapses the drawer; desktop choices are remembered per browser. */ +export function handlerDrawerOpen(isDashboardDrawerOpened: boolean, remember = false) { + if (remember) { + try { + window.localStorage.setItem(STORAGE_KEY, isDashboardDrawerOpened ? '1' : '0'); + } catch { + // Storage unavailable (private window); the choice lasts for the tab. + } + } + void mutate(KEY, (current?: MenuMaster) => ({ ...current, isDashboardDrawerOpened }), false); +} diff --git a/src/WebUI/src/api/types.ts b/src/WebUI/src/api/types.ts new file mode 100644 index 0000000..701dafb --- /dev/null +++ b/src/WebUI/src/api/types.ts @@ -0,0 +1,741 @@ +// DTO mirror of Shared.Contracts (camelCase wire format). + +export type DeviceStatus = 'online' | 'stale' | 'offline'; + +export type JobState = 'queued' | 'dispatched' | 'running' | 'succeeded' | 'failed' | 'cancelled' | 'timedOut'; + +export type OutputStreamKind = 'output' | 'error' | 'warning' | 'verbose' | 'debug' | 'information' | 'progress'; + +export type UserRole = 'admin' | 'operator' | 'viewer'; + +export interface DeviceDto { + clientId: string; + hostname: string; + manufacturer?: string; + model?: string; + osCaption?: string; + osVersion?: string; + agentVersion?: string; + ipAddresses: string[]; + status: DeviceStatus; + lastSeenUtc?: string; + enrolledUtc: string; + tags?: string[]; + /** Public IP the agent was last seen from (trusted headers at enroll/refresh). */ + publicIp?: string; + /** Orphaned devices refuse jobs until they re-enroll. */ + isOrphaned?: boolean; + /** Groups the device is directly in (absent when no groups exist). */ + groupIds?: string[]; +} + +// ── Device grouping ─────────────────────────────────────────────────── + +/** Folders hold no devices of their own; every kind includes its nested groups' devices. */ +export type GroupKind = 'static' | 'dynamic' | 'folder'; +export type RuleCombine = 'and' | 'or'; +export type RuleOperator = + | 'equals' + | 'notEquals' + | 'contains' + | 'notContains' + | 'startsWith' + | 'endsWith' + | 'regex' + | 'in' + | 'notIn' + | 'greaterThan' + | 'greaterOrEqual' + | 'lessThan' + | 'lessOrEqual' + | 'exists' + | 'notExists' + | 'inCidr' + | 'notInCidr'; + +export interface RuleCondition { + field: string; + operator: RuleOperator; + value?: string; + negate?: boolean; +} + +export interface RuleGroup { + combine: RuleCombine; + conditions?: RuleCondition[]; + groups?: RuleGroup[]; + negate?: boolean; +} + +export interface GroupRuleSet { + combine: RuleCombine; + groups?: RuleGroup[]; +} + +export interface GroupFieldDescriptor { + field: string; + displayName: string; + category: string; + numeric: boolean; + multiValue: boolean; +} + +export interface DeviceGroupDto { + id: string; + name: string; + description?: string; + kind: GroupKind; + rules?: GroupRuleSet; + /** Devices in the group including its nested groups. */ + memberCount: number; + createdUtc: string; + updatedUtc: string; + updatedBy?: string; + parentId?: string; + /** The group's own devices (static list or rule matches). */ + directMemberCount: number; + /** Online devices among memberCount. */ + onlineCount: number; +} + +export interface SaveGroupBody { + name: string; + description?: string; + kind: GroupKind; + rules?: GroupRuleSet; + parentId?: string | null; +} + +export interface DeviceGroupRefDto { + id: string; + name: string; + kind: GroupKind; + parentId?: string; + /** In the group only through one of its nested groups. */ + inherited?: boolean; +} + +export interface S3SettingsDto { + enabled: boolean; + endpoint?: string; + region: string; + bucket?: string; + accessKey?: string; + secretKey?: string | null; + forcePathStyle: boolean; + presignExpirySeconds: number; + secretKeyIsSet: boolean; + agentOffloadEnabled: boolean; + lastTestUtc?: string; + fromEnvironment: boolean; +} + +export interface S3TestStepDto { + name: string; + ok: boolean; + detail?: string; +} + +export interface S3TestResultDto { + ok: boolean; + steps: S3TestStepDto[]; + elapsedMs: number; +} + +export interface AgentPackageStatusDto { + available: boolean; + /** image | volume | s3 | none */ + source: string; + fileName?: string; + sizeBytes?: number; + sha256?: string; + builtUtc?: string; + version?: string; + offloadEnabled: boolean; + offloadUploaded: boolean; +} + +// ── Agent upgrades ──────────────────────────────────────────────────── + +/** queued/sent/cancelled are the server's; the agent reports the rest. */ +export type AgentUpgradeState = 'queued' | 'sent' | 'downloading' | 'installing' | 'succeeded' | 'failed' | 'rolled-back' | 'cancelled'; +export type AgentUpgradeSource = 'manual' | 'automatic' | 'rollback'; + +/** One package of a catalog version: msi, zip (win-x64), linux-x64, linux-arm64, osx-x64 or osx-arm64. */ +export interface AgentPackageDto { + version: string; + packageType: string; + fileName: string; + sizeBytes: number; + sha256: string; + importedUtc: string; +} + +export interface AgentVersionDto { + version: string; + /** The version upgrades default to. */ + newest: boolean; + packages: AgentPackageDto[]; + deviceCount: number; + importedUtc: string; + /** Set when it cannot be removed (the newest, or still needed for a rollback or an open upgrade). */ + removeBlockedReason?: string | null; +} + +/** One device's upgrade attempt. */ +export interface AgentUpgradeDto { + id: string; + clientId: string; + hostname?: string | null; + fromVersion?: string | null; + targetVersion: string; + source: AgentUpgradeSource; + state: AgentUpgradeState; + reason?: string | null; + detail?: string | null; + /** The last lines the agent or watchdog logged for it. */ + lastLog?: string[] | null; + attempts: number; + requestedBy?: string | null; + createdUtc: string; + sentUtc?: string | null; + finishedUtc?: string | null; +} + +/** Devices and groups (nested included); no version = the newest for each device's platform. */ +export interface StartAgentUpgradeBody { + clientIds?: string[]; + groupIds?: string[]; + version?: string | null; +} + +export interface RollBackAgentBody { + clientIds?: string[]; + groupIds?: string[]; +} + +/** A device a request left out: already, busy, no-package, unsupported, no-previous, … */ +export interface AgentUpgradeSkipDto { + clientId: string; + hostname?: string | null; + reason: string; +} + +export interface AgentUpgradeBatchDto { + upgrades: AgentUpgradeDto[]; + skipped: AgentUpgradeSkipDto[]; +} + +export interface AgentUpgradeSettingsDto { + automaticUpgrades: boolean; + /** Queued online devices start downloading within this many minutes (1–30), in paced batches. */ + startWithinMinutes: number; + healthDeadlineMinutes: number; + excludedGroupIds: string[]; + keepVersions: number; +} + +export type ScriptTriggerType = 'onRegistration' | 'onAgentReady' | 'scheduled'; + +export interface ScriptTriggerDto { + id: string; + scriptId: string; + scriptName: string; + groupId?: string; + groupName?: string; + clientId?: string; + clientHostname?: string; + triggerType: ScriptTriggerType; + enabled: boolean; + cronExpression?: string; + runOnceUtc?: string; + timeZoneId: string; + nextRunUtc?: string; + lastRunUtc?: string; + lastResult?: string; + createdUtc: string; + name?: string; + /** Execution created by the last firing. */ + lastRunId?: string; + arguments?: Record; + createdBy?: string; +} + +/** POST /api/triggers and PUT /api/triggers/{id}. Target: clientId OR groupId, or neither for all devices. */ +export interface SaveTriggerBody { + scriptId: string; + triggerType: ScriptTriggerType; + name?: string; + clientId?: string; + groupId?: string; + enabled?: boolean; + cronExpression?: string; + runOnceUtc?: string; + timeZoneId?: string; + arguments?: Record; +} + +export interface SchedulePreviewDto { + occurrences: string[]; + error?: string; +} + +export interface TriggerRunResultDto { + runId?: string; + queued: number; + message: string; +} + +export interface InventoryReport { + identity: { + clientId: string; + hostname: string; + manufacturer?: string; + model?: string; + serialNumber?: string; + biosVersion?: string; + baseboardSerial?: string; + domainOrWorkgroup?: string; + partOfDomain: boolean; + systemType?: string; + systemUuid?: string; + baseboardManufacturer?: string; + baseboardProduct?: string; + }; + os: { + caption?: string; + version?: string; + build?: string; + architecture?: string; + installDateUtc?: string; + lastBootUtc?: string; + edition?: string; + releaseVersion?: string; + productType?: string; + }; + cpu: { name?: string; logicalProcessors: number; cores: number }; + memory: { + deviceLocator?: string; + capacityBytes: number; + manufacturer?: string; + speedMhz?: number; + }[]; + totalPhysicalMemoryBytes: number; + disks: { + model?: string; + serialNumber?: string; + sizeBytes: number; + busType?: string; + index?: number; + }[]; + volumes: { + driveLetter: string; + fileSystem?: string; + totalSizeBytes: number; + freeSpaceBytes: number; + diskIndex?: number; + }[]; + network: { + description?: string; + macAddress?: string; + ipv4Addresses: string[]; + ipv6Addresses: string[]; + gateways: string[]; + dnsServers: string[]; + /** OS interface name: "Ethernet0" on Windows, "eth0"/"en0" on unix. */ + interfaceName?: string; + }[]; + collectedUtc: string; +} + +export interface DeviceDetailDto { + device: DeviceDto; + inventory?: InventoryReport; + inventoryUpdatedUtc?: string; + groups?: DeviceGroupRefDto[]; +} + +/** One step in a device's history: enrolled, renamed, OS changed (e.g. Windows PE → its installed OS) or an agent upgrade's outcome. */ +export interface DeviceHistoryEventDto { + id: number; + timestampUtc: string; + /** device-enrolled, device-renamed, device-os-changed, agent-upgraded, agent-rolled-back or agent-upgrade-failed. */ + action: string; + detail?: string; +} + +export type PrimitiveType = 'string' | 'number' | 'boolean'; +export type ScriptParameterType = 'string' | 'number' | 'boolean' | 'array' | 'hashtable'; + +/** + * String values expand on the target device in the background by default + * (%VAR%, $env:VAR, $()); 'literal' passes the value through exactly as typed. + */ +export type ValueExpansion = 'auto' | 'literal'; + +/** + * An S3 object (or prefix) delivered to the device before the script runs. + * The destination expands on the device (%VAR%, $env:VAR, $(…)) and the + * resolved location reaches the script as $Files.Name — a FileInfo, or a + * DirectoryInfo when directory (recursive) is set. + */ +export interface ScriptFileBinding { + name: string; + objectKey: string; + destinationPath: string; + directory?: boolean; + continueOnFailure?: boolean; +} + +export interface ScriptParameter { + name: string; + type: ScriptParameterType; + required?: boolean; + description?: string; + elementType?: PrimitiveType; + defaultValue?: unknown; + expansion?: ValueExpansion; +} + +/** Result of a group fan-out run: one job per eligible member. */ +export interface GroupRunDto { + jobs: JobDto[]; + skippedOrphaned: string[]; + /** Shared by every job of the run; absent when nothing was queued. */ + runId?: string; + skippedOffline?: string[]; +} + +/** POST /api/jobs: any mix of devices and groups, run as one execution. */ +export interface RunScriptBody { + scriptId: string; + clientIds?: string[]; + groupIds?: string[]; + arguments?: Record; + /** Skip devices that are not online now instead of queueing for their return. */ + onlineOnly?: boolean; +} + +export interface CountPoint { + label: string; + count: number; +} + +export interface DayPoint { + date: string; + succeeded: number; + failed: number; + other: number; +} + +export interface DashboardDto { + devicesTotal: number; + devicesOnline: number; + devicesStale: number; + devicesOffline: number; + devicesByPlatform: CountPoint[]; + jobsTotal: number; + jobsSucceeded: number; + jobsFailed: number; + jobsInProgress: number; + successRate: number; + jobsByState: CountPoint[]; + jobsByExitCode: CountPoint[]; + jobsByEngine: CountPoint[]; + topTargets: CountPoint[]; + topScripts: CountPoint[]; + timeline: DayPoint[]; + recentRuns: JobDto[]; +} + +export interface ServerInfoDto { + baseUrl: string; + fromEnvironment: boolean; + /** + * The server is serving its managed self-signed chain directly (no proxy + * in between), so generated commands must skip TLS verification — the + * traffic is still encrypted; the roots just aren't distributed. + */ + selfSignedDirect: boolean; +} + +/** + * Script execution engine. PowerShell = embedded in-process PowerShell 7 + * (all platforms, full typed params/$Secrets/expansion). WindowsPowerShell = + * powershell.exe 5.1 (Windows devices). Bash = bash (unix devices, or + * Windows with Git Bash) — parameters/secrets arrive as environment variables. + */ +export type ScriptEngine = 'PowerShell' | 'WindowsPowerShell' | 'Bash'; + +/** One entry of a script's secrets dictionary, resolved server-side at dispatch. */ +export interface SecretBinding { + /** Key inside the injected dictionary (e.g. $Secrets.ApiKey). */ + name: string; + providerId: string; + secretName: string; + path?: string; +} + +export interface ScriptDto { + id: string; + name: string; + description?: string; + language: string; + content: string; + parameters: ScriptParameter[]; + functionModuleIds: string[]; + createdUtc: string; + updatedUtc: string; + createdBy?: string; + updatedBy?: string; + secretBindings?: SecretBinding[]; + secretsVariableName?: string; + fileBindings?: ScriptFileBinding[]; +} + +// ── Secrets providers ───────────────────────────────────────────────── + +export interface SecretsProviderDto { + id: string; + name: string; + kind: string; + /** Driver-specific non-secret settings. */ + config: Record; + /** Secret config fields that currently hold a value. */ + secretFieldsSet: string[]; + updatedUtc: string; + updatedBy?: string; +} + +export interface SecretsProviderKindDto { + kind: string; + displayName: string; + fields: { name: string; label: string; secret: boolean; placeholder?: string }[]; +} + +export interface SecretsProvidersResponse { + providers: SecretsProviderDto[]; + kinds: SecretsProviderKindDto[]; +} + +export interface SecretsTestResultDto { + ok: boolean; + steps: S3TestStepDto[]; +} + +export interface FunctionModuleDto { + id: string; + name: string; + description?: string; + content: string; + createdUtc: string; + updatedUtc: string; + updatedBy?: string; +} + +export interface JobDto { + jobId: string; + clientId: string; + hostname?: string; + scriptId: string; + scriptName: string; + state: JobState; + createdUtc: string; + startedUtc?: string; + completedUtc?: string; + exitCode?: number; + requestedBy?: string; + outputSummary?: string; +} + +export interface JobOutputRecordDto { + sequence: number; + stream: OutputStreamKind; + timestampUtc: string; + text: string; +} + +/** Where every target of a run stands; targets = jobs + skipped. */ +export interface RunCountsDto { + targets: number; + /** Queued or sent, not started. */ + pending: number; + running: number; + succeeded: number; + failed: number; + cancelled: number; + skipped: number; + /** Job targets online now. */ + online: number; +} + +export type RunSource = 'manual' | 'schedule' | 'trigger'; + +export interface ExecutionSummaryDto { + runId: string; + scriptId: string; + startedUtc: string; + requestedBy?: string; + total: number; + succeeded: number; + failed: number; + pending: number; + scriptName?: string; + source?: RunSource; + targetsLabel?: string; + counts?: RunCountsDto; +} + +export interface ExecutionTargetDto { + jobId: string; + clientId: string; + hostname?: string; + state: JobState; + exitCode?: number; + createdUtc: string; + startedUtc?: string; + completedUtc?: string; + online?: boolean; + /** Failure or completion summary from the agent. */ + summary?: string; +} + +/** A targeted device given no job. */ +export interface ExecutionSkipDto { + clientId: string; + hostname: string; + reason: 'orphaned' | 'offline'; +} + +export interface ExecutionDetailDto { + runId: string; + scriptId: string; + scriptName: string; + startedUtc: string; + requestedBy?: string; + targets: ExecutionTargetDto[]; + source?: RunSource; + targetsLabel?: string; + onlineOnly?: boolean; + skipped?: ExecutionSkipDto[]; + counts?: RunCountsDto; +} + +export interface RoleDto { + id: string; + name: string; + description?: string; + isSystem: boolean; + permissions: string[]; + deviceScopeGroupIds: string[]; + /** How many role bindings grant it. */ + bindingCount: number; +} + +export interface SaveRoleBody { + name: string; + description?: string; + permissions: string[]; + deviceScopeGroupIds?: string[]; +} + +export interface PermissionInfoDto { + key: string; + label: string; + description: string; +} + +export interface PermissionGroupDto { + group: string; + permissions: PermissionInfoDto[]; +} + +export interface BrowserCredentialResponse { + jwt: string; + expiresUtc: string; + browserSessionId: string; + webSocketPath: string; +} + +export interface BootstrapTokenDto { + id: string; + token?: string; + createdUtc: string; + expiresUtc: string; + maxUses: number; + uses: number; + revoked: boolean; + note?: string; + createdBy?: string; +} + +export interface CreateShellResponse { + shellSessionId: string; + clientId: string; + hostname: string; + expiresUtc: string; +} + +// ── Envelope + live payloads ────────────────────────────────────────── + +export interface MessageEnvelope { + messageId: string; + correlationId: string; + causationId?: string; + messageType: string; + schemaVersion: number; + timestampUtc: string; + source: { kind: string; id: string }; + target?: { kind: string; id: string }; + payload: T; +} + +export interface ActivityEventPayload { + kind: string; + text: string; + clientId?: string; + jobId?: string; + timestampUtc: string; +} + +export interface JobOutputPayload { + jobId: string; + clientId: string; + sequence: number; + stream: OutputStreamKind; + timestampUtc: string; + text: string; +} + +export interface JobProgressPayload { + jobId: string; + clientId: string; + activity: string; + statusDescription?: string; + percentComplete?: number; + secondsRemaining?: number; + timestampUtc: string; +} + +export interface JobStatePayload { + jobId: string; + clientId: string; + state: JobState; + exitCode?: number; + timestampUtc: string; + message?: string; +} + +export interface ShellOutputPayload { + sessionId: string; + sequence: number; + dataBase64: string; +} + +export interface ShellStatePayload { + sessionId: string; + state: 'requested' | 'open' | 'closed' | 'failed'; + message?: string; + /** The shell the agent started (a ShellKind; Windows agents, on open). */ + shell?: string; +} diff --git a/src/WebUI/src/app.css b/src/WebUI/src/app.css deleted file mode 100644 index ad0cea6..0000000 --- a/src/WebUI/src/app.css +++ /dev/null @@ -1,343 +0,0 @@ -/* ── Design tokens ─────────────────────────────────────────────────── */ -:root { - --font-sans: - 'Segoe UI Variable', 'Segoe UI', system-ui, -apple-system, 'Inter', Roboto, sans-serif; - --font-mono: 'Cascadia Code', 'Cascadia Mono', Consolas, 'JetBrains Mono', monospace; - - --radius-sm: 6px; - --radius-md: 10px; - --radius-lg: 14px; - - --space-1: 4px; - --space-2: 8px; - --space-3: 12px; - --space-4: 16px; - --space-5: 24px; - --space-6: 32px; - - --bg: #f4f6fa; - --bg-elevated: #ffffff; - --surface: #ffffff; - --surface-muted: #eef1f6; - --border: #dde3ec; - --border-strong: #c3ccd9; - --text: #16202e; - --text-muted: #5b6a7f; - --text-faint: #8b98ab; - - --accent: #2563eb; - --accent-hover: #1d4fd7; - --accent-soft: #dbe7ff; - --accent-contrast: #ffffff; - - --success: #16a34a; - --success-soft: #d7f2e0; - --warning: #d97706; - --warning-soft: #fdeed3; - --danger: #dc2626; - --danger-soft: #fde3e3; - --info: #0891b2; - --info-soft: #d8f1f7; - - --shadow-sm: 0 1px 2px rgb(15 23 42 / 0.06); - --shadow-md: 0 4px 16px rgb(15 23 42 / 0.08); - - color-scheme: light; -} - -@media (prefers-color-scheme: dark) { - :root:not([data-theme='light']) { - --bg: #0d1420; - --bg-elevated: #131c2b; - --surface: #17212f; - --surface-muted: #1d2938; - --border: #263447; - --border-strong: #35465e; - --text: #e6ecf5; - --text-muted: #9aabc2; - --text-faint: #64748c; - - --accent: #4c8dff; - --accent-hover: #6ba1ff; - --accent-soft: #1b2f52; - --accent-contrast: #0b1220; - - --success: #34d27b; - --success-soft: #12331f; - --warning: #f5a623; - --warning-soft: #3a2a10; - --danger: #f26565; - --danger-soft: #3d1717; - --info: #38c3dd; - --info-soft: #10303a; - - --shadow-sm: 0 1px 2px rgb(0 0 0 / 0.4); - --shadow-md: 0 4px 18px rgb(0 0 0 / 0.45); - - color-scheme: dark; - } -} - -:root[data-theme='dark'] { - --bg: #0d1420; - --bg-elevated: #131c2b; - --surface: #17212f; - --surface-muted: #1d2938; - --border: #263447; - --border-strong: #35465e; - --text: #e6ecf5; - --text-muted: #9aabc2; - --text-faint: #64748c; - - --accent: #4c8dff; - --accent-hover: #6ba1ff; - --accent-soft: #1b2f52; - --accent-contrast: #0b1220; - - --success: #34d27b; - --success-soft: #12331f; - --warning: #f5a623; - --warning-soft: #3a2a10; - --danger: #f26565; - --danger-soft: #3d1717; - --info: #38c3dd; - --info-soft: #10303a; - - --shadow-sm: 0 1px 2px rgb(0 0 0 / 0.4); - --shadow-md: 0 4px 18px rgb(0 0 0 / 0.45); - - color-scheme: dark; -} - -/* ── Base ──────────────────────────────────────────────────────────── */ -* { - box-sizing: border-box; -} - -html, -body { - margin: 0; - padding: 0; - height: 100%; -} - -body { - font-family: var(--font-sans); - font-size: 14px; - line-height: 1.5; - background: var(--bg); - color: var(--text); - -webkit-font-smoothing: antialiased; -} - -h1, -h2, -h3 { - margin: 0; - font-weight: 600; - letter-spacing: -0.01em; -} - -h1 { - font-size: 20px; -} - -h2 { - font-size: 16px; -} - -h3 { - font-size: 13px; - text-transform: uppercase; - letter-spacing: 0.06em; - color: var(--text-muted); - font-weight: 600; -} - -a { - color: var(--accent); - text-decoration: none; -} - -a:hover { - text-decoration: underline; -} - -code, -pre { - font-family: var(--font-mono); - font-size: 12.5px; -} - -button { - font-family: inherit; -} - -:focus-visible { - outline: 2px solid var(--accent); - outline-offset: 2px; - border-radius: var(--radius-sm); -} - -/* ── Shared primitives ─────────────────────────────────────────────── */ -.card { - background: var(--surface); - border: 1px solid var(--border); - border-radius: var(--radius-md); - box-shadow: var(--shadow-sm); -} - -.btn { - display: inline-flex; - align-items: center; - gap: var(--space-2); - padding: 7px 14px; - border-radius: var(--radius-sm); - border: 1px solid var(--border-strong); - background: var(--surface); - color: var(--text); - font-size: 13px; - font-weight: 500; - cursor: pointer; - transition: - background 0.12s ease, - border-color 0.12s ease, - opacity 0.12s ease; -} - -.btn:hover:not(:disabled) { - background: var(--surface-muted); -} - -.btn:disabled { - opacity: 0.5; - cursor: not-allowed; -} - -.btn.primary { - background: var(--accent); - border-color: var(--accent); - color: var(--accent-contrast); -} - -.btn.primary:hover:not(:disabled) { - background: var(--accent-hover); -} - -.btn.danger { - color: var(--danger); - border-color: var(--danger); -} - -.input, -.select, -textarea.input { - padding: 7px 10px; - border-radius: var(--radius-sm); - border: 1px solid var(--border-strong); - background: var(--bg-elevated); - color: var(--text); - font-size: 13px; - font-family: inherit; -} - -.input:focus, -.select:focus { - outline: 2px solid var(--accent); - outline-offset: 0; - border-color: transparent; -} - -/* ── Tables ────────────────────────────────────────────────────────── */ -.table-wrap { - overflow: auto; - border-radius: var(--radius-md); -} - -table.data { - width: 100%; - border-collapse: collapse; - font-size: 13px; -} - -table.data thead th { - position: sticky; - top: 0; - z-index: 1; - background: var(--surface-muted); - color: var(--text-muted); - font-weight: 600; - font-size: 12px; - text-transform: uppercase; - letter-spacing: 0.05em; - text-align: left; - padding: 10px 14px; - border-bottom: 1px solid var(--border); - white-space: nowrap; -} - -table.data tbody td { - padding: 10px 14px; - border-bottom: 1px solid var(--border); - vertical-align: middle; -} - -table.data tbody tr { - transition: background 0.1s ease; -} - -table.data tbody tr:hover { - background: var(--surface-muted); -} - -table.data tbody tr.clickable { - cursor: pointer; -} - -/* ── Utility ───────────────────────────────────────────────────────── */ -.muted { - color: var(--text-muted); -} - -.faint { - color: var(--text-faint); -} - -.mono { - font-family: var(--font-mono); -} - -.skeleton { - background: linear-gradient( - 100deg, - var(--surface-muted) 40%, - var(--border) 50%, - var(--surface-muted) 60% - ); - background-size: 200% 100%; - animation: shimmer 1.4s infinite linear; - border-radius: var(--radius-sm); - color: transparent; - user-select: none; -} - -@keyframes shimmer { - to { - background-position: -200% 0; - } -} - -@keyframes pulse-in { - from { - opacity: 0; - transform: translateY(-3px); - } - to { - opacity: 1; - transform: none; - } -} - -.pulse-in { - animation: pulse-in 0.22s ease; -} diff --git a/src/WebUI/src/app.d.ts b/src/WebUI/src/app.d.ts deleted file mode 100644 index 0dea0d9..0000000 --- a/src/WebUI/src/app.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -// See https://svelte.dev/docs/kit/types#app.d.ts -// for information about these interfaces -declare global { - namespace App { - // interface Error {} - // interface Locals {} - // interface PageData {} - // interface PageState {} - // interface Platform {} - } -} - -export {}; diff --git a/src/WebUI/src/app.html b/src/WebUI/src/app.html deleted file mode 100644 index 0d4f5db..0000000 --- a/src/WebUI/src/app.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - %sveltekit.head% - - -
%sveltekit.body%
- - diff --git a/src/WebUI/src/assets/style.css b/src/WebUI/src/assets/style.css new file mode 100644 index 0000000..473a0f4 diff --git a/src/WebUI/src/components/@extended/Avatar.tsx b/src/WebUI/src/components/@extended/Avatar.tsx new file mode 100644 index 0000000..bc86fcd --- /dev/null +++ b/src/WebUI/src/components/@extended/Avatar.tsx @@ -0,0 +1,134 @@ +import { ReactNode } from 'react'; + +// material-ui +import { styled } from '@mui/material/styles'; +import MuiAvatar, { AvatarProps } from '@mui/material/Avatar'; + +// project imports +import getColors from 'utils/getColors'; + +// types +import { AvatarTypeProps, ColorProps, ExtendedStyleProps, SizeProps } from 'types/extended'; + +// ==============================|| AVATAR - COLOR STYLE ||============================== // + +interface AvatarStyleProps extends ExtendedStyleProps { + type?: AvatarTypeProps; +} + +function getColorStyle({ theme, color, type }: AvatarStyleProps) { + const colors = getColors(theme, color); + const { lighter, light, main, contrastText } = colors; + + switch (type) { + case 'filled': + return { + color: contrastText, + background: main + }; + case 'outlined': + return { + color: main, + border: '1px solid', + borderColor: main, + background: 'transparent' + }; + case 'combined': + return { + color: main, + border: '1px solid', + borderColor: light, + background: lighter + }; + default: + return { + color: main, + background: lighter + }; + } +} + +// ==============================|| AVATAR - SIZE STYLE ||============================== // + +function getSizeStyle(size?: SizeProps) { + switch (size) { + case 'badge': + return { + border: '2px solid', + fontSize: '0.675rem', + width: 20, + height: 20 + }; + case 'xs': + return { + fontSize: '0.75rem', + width: 24, + height: 24 + }; + case 'sm': + return { + fontSize: '0.875rem', + width: 32, + height: 32 + }; + case 'lg': + return { + fontSize: '1.2rem', + width: 52, + height: 52 + }; + case 'xl': + return { + fontSize: '1.5rem', + width: 64, + height: 64 + }; + case 'md': + default: + return { + fontSize: '1rem', + width: 40, + height: 40 + }; + } +} + +// ==============================|| STYLED - AVATAR ||============================== // + +interface StyleProps { + color: ColorProps; + type?: AvatarTypeProps; + size?: SizeProps; +} + +const AvatarStyle = styled(MuiAvatar, { shouldForwardProp: (prop) => prop !== 'color' && prop !== 'type' && prop !== 'size' })( + ({ theme, size, color, type }) => ({ + ...getSizeStyle(size), + ...getColorStyle({ theme, color, type }), + variants: [ + { + props: { size: 'badge' }, + style: { + borderColor: theme.vars.palette.background.default + } + } + ] + }) +); + +// ==============================|| EXTENDED - AVATAR ||============================== // + +interface Props extends AvatarProps { + color?: ColorProps; + children?: ReactNode | string; + type?: AvatarTypeProps; + size?: SizeProps; +} + +export default function Avatar({ children, color = 'primary', type, size = 'md', ...others }: Props) { + return ( + + {children} + + ); +} diff --git a/src/WebUI/src/components/@extended/Dot.tsx b/src/WebUI/src/components/@extended/Dot.tsx new file mode 100644 index 0000000..0399376 --- /dev/null +++ b/src/WebUI/src/components/@extended/Dot.tsx @@ -0,0 +1,32 @@ +// material-ui +import { useTheme } from '@mui/material/styles'; +import Box, { BoxProps } from '@mui/material/Box'; + +// project imports +import { ColorProps } from 'types/extended'; +import getColors from 'utils/getColors'; + +interface Props extends BoxProps { + color?: ColorProps; + size?: number; + variant?: string; +} + +export default function Dot({ color, size, variant, sx, ...rest }: Props) { + const theme = useTheme(); + const colors = getColors(theme, color || 'primary'); + const { main } = colors; + + return ( + + ); +} diff --git a/src/WebUI/src/components/@extended/IconButton.tsx b/src/WebUI/src/components/@extended/IconButton.tsx new file mode 100644 index 0000000..0a1ccfb --- /dev/null +++ b/src/WebUI/src/components/@extended/IconButton.tsx @@ -0,0 +1,192 @@ +import { ReactNode } from 'react'; + +// material-ui +import { styled } from '@mui/material/styles'; +import MuiIconButton, { IconButtonProps } from '@mui/material/IconButton'; + +// project imports +import getColors from 'utils/getColors'; +import getShadow from 'utils/getShadow'; +import { withAlpha } from 'utils/colorUtils'; + +// types +import { ButtonVariantProps, ExtendedStyleProps, IconButtonShapeProps } from 'types/extended'; + +// ==============================|| ICON BUTTON - COLOR STYLE ||============================== // + +interface IconButtonStyleProps extends ExtendedStyleProps { + variant?: ButtonVariantProps; +} + +function getColorStyle({ variant, theme, color }: IconButtonStyleProps) { + const colors = getColors(theme, color); + const { lighter, light, dark, main, contrastText } = colors; + + const buttonShadow = `${color}Button`; + const shadows = getShadow(theme, buttonShadow); + + const commonShadow = { + '&::after': { + boxShadow: `0 0 6px 6px ${withAlpha(main, 0.9)}` + }, + '&:active::after': { + boxShadow: `0 0 0 0 ${withAlpha(main, 0.9)}` + }, + '&:focus-visible': { + outline: `2px solid ${dark}`, + outlineOffset: 2 + } + }; + + switch (variant) { + case 'contained': + return { + color: contrastText, + background: main, + '&:hover': { + background: dark + }, + ...commonShadow + }; + case 'light': + return { + color: main, + background: lighter, + '&:hover': { + background: withAlpha(light, 0.5) + }, + ...commonShadow + }; + case 'shadow': + return { + boxShadow: shadows, + color: contrastText, + background: main, + '&:hover': { + boxShadow: 'none', + background: dark + }, + ...commonShadow + }; + case 'outlined': + return { + '&:hover': { + background: 'transparent', + color: dark, + borderColor: dark + }, + ...commonShadow + }; + case 'dashed': + return { + background: lighter, + '&:hover': { + color: dark, + borderColor: dark + }, + ...commonShadow + }; + case 'text': + default: + return { + '&:hover': { + color: dark, + background: color === 'secondary' ? withAlpha(light, 0.1) : lighter + }, + ...commonShadow + }; + } +} + +// ==============================|| STYLED - ICON BUTTON ||============================== // + +interface StyleProps extends Omit { + shape?: IconButtonShapeProps; +} + +const IconButtonStyle = styled(MuiIconButton, { shouldForwardProp: (prop) => prop !== 'variant' && prop !== 'shape' })( + ({ theme, color, variant }) => ({ + position: 'relative', + '::after': { + content: '""', + display: 'block', + position: 'absolute', + left: 0, + top: 0, + width: '100%', + height: '100%', + borderRadius: 4, + opacity: 0, + transition: 'all 0.5s' + }, + + ':active::after': { + position: 'absolute', + borderRadius: 4, + left: 0, + top: 0, + opacity: 1, + transition: '0s' + }, + + ...getColorStyle({ variant, theme, color }), + + variants: [ + { + props: { shape: 'rounded' }, + style: { + borderRadius: '50%', + '::after': { borderRadius: '50%' }, + ':active::after': { borderRadius: '50%' } + } + }, + { + props: { variant: 'outlined' }, + style: { + border: '1px solid', + borderColor: 'inherit' + } + }, + { + props: { variant: 'dashed' }, + style: { + border: '1px dashed', + borderColor: 'inherit' + } + }, + { + props: ({ variant }) => variant !== 'text', + style: { + '&.Mui-disabled': { + background: theme.vars.palette.grey[200], + '&:hover': { + background: theme.vars.palette.grey[200], + color: theme.vars.palette.grey[300], + borderColor: 'inherit' + } + } + } + } + ] + }) +); + +// ==============================|| EXTENDED - ICON BUTTON ||============================== // + +interface Props extends IconButtonProps { + shape?: IconButtonShapeProps; + variant?: ButtonVariantProps; + children: ReactNode; +} + +function IconButton({ variant = 'text', shape = 'square', children, color = 'primary', ref, ...others }: Props) { + return ( + + {children} + + ); +} + +IconButton.displayName = 'IconButton'; + +export default IconButton; diff --git a/src/WebUI/src/components/@extended/Transitions.tsx b/src/WebUI/src/components/@extended/Transitions.tsx new file mode 100644 index 0000000..af7ee38 --- /dev/null +++ b/src/WebUI/src/components/@extended/Transitions.tsx @@ -0,0 +1,113 @@ +import { ReactElement, Ref } from 'react'; + +// material-ui +import Collapse from '@mui/material/Collapse'; +import Fade from '@mui/material/Fade'; +import Grow from '@mui/material/Grow'; +import Slide from '@mui/material/Slide'; +import Zoom, { ZoomProps } from '@mui/material/Zoom'; +import Box from '@mui/material/Box'; + +// ==============================|| TRANSITIONS ||============================== // + +interface Props { + children?: ReactElement; + position?: string; + in?: boolean; + type?: string; + direction?: 'up' | 'right' | 'left' | 'down'; + [others: string]: any; +} + +export default function Transitions({ children, position = 'top-left', type = 'grow', direction = 'up', ref, ...others }: Props) { + let positionSX = { + transformOrigin: '0 0 0' + }; + + switch (position) { + case 'top-right': + positionSX = { + transformOrigin: 'top right' + }; + break; + case 'top': + positionSX = { + transformOrigin: 'top' + }; + break; + case 'bottom-left': + positionSX = { + transformOrigin: 'bottom left' + }; + break; + case 'bottom-right': + positionSX = { + transformOrigin: 'bottom right' + }; + break; + case 'bottom': + positionSX = { + transformOrigin: 'bottom' + }; + break; + case 'top-left': + default: + positionSX = { + transformOrigin: '0 0 0' + }; + break; + } + + return ( + + {type === 'grow' && ( + + {children} + + )} + + {type === 'collapse' && ( + + {children} + + )} + + {type === 'fade' && ( + + {children} + + )} + + {type === 'slide' && ( + + {children} + + )} + + {type === 'zoom' && ( + + {children} + + )} + + ); +} + +export function PopupTransition({ ref, ...props }: ZoomProps & { ref?: Ref }) { + return ; +} diff --git a/src/WebUI/src/components/ActionMenu.tsx b/src/WebUI/src/components/ActionMenu.tsx new file mode 100644 index 0000000..4961ab6 --- /dev/null +++ b/src/WebUI/src/components/ActionMenu.tsx @@ -0,0 +1,96 @@ +import { ReactNode } from 'react'; + +// material-ui +import Divider from '@mui/material/Divider'; +import ListItemIcon from '@mui/material/ListItemIcon'; +import ListItemText from '@mui/material/ListItemText'; +import ListSubheader from '@mui/material/ListSubheader'; +import Menu from '@mui/material/Menu'; +import MenuItem from '@mui/material/MenuItem'; +import Tooltip from '@mui/material/Tooltip'; + +/** + * A menu described as data, so who-may-do-what lives in pure functions and + * one renderer serves row "…" menus, bulk Actions and tree context menus. + */ +export type MenuEntry = + | { + kind: 'item'; + id: string; + label: string; + icon?: ReactNode; + /** Greyed out but still focusable, explaining itself on hover. */ + disabledReason?: string; + destructive?: boolean; + onSelect: () => void; + } + | { kind: 'divider' } + | { kind: 'header'; label: string }; + +interface Props { + entries: MenuEntry[]; + onClose: () => void; + /** Anchor to an element (a "…" button) … */ + anchorEl?: HTMLElement | null; + /** … or to a point (a right-click). */ + anchorPosition?: { top: number; left: number } | null; +} + +// ==============================|| ACTION MENU ||============================== // + +export default function ActionMenu({ entries, onClose, anchorEl, anchorPosition }: Props) { + const open = Boolean(anchorEl || anchorPosition); + + return ( + event.stopPropagation()} + > + {entries.map((entry, index) => { + if (entry.kind === 'divider') return ; + if (entry.kind === 'header') { + return ( + + {entry.label} + + ); + } + + const disabled = Boolean(entry.disabledReason); + const item = ( + { + if (disabled) return; + onClose(); + entry.onSelect(); + }} + sx={{ + color: entry.destructive && !disabled ? 'error.main' : undefined, + ...(disabled && { opacity: 0.5, cursor: 'default', '&:hover': { bgcolor: 'transparent' } }) + }} + > + {entry.icon && {entry.icon}} + {entry.label} + + ); + + return disabled ? ( + + {item} + + ) : ( + item + ); + })} + + ); +} diff --git a/src/WebUI/src/components/CodeEditor.tsx b/src/WebUI/src/components/CodeEditor.tsx new file mode 100644 index 0000000..8c39366 --- /dev/null +++ b/src/WebUI/src/components/CodeEditor.tsx @@ -0,0 +1,441 @@ +import { useEffect, useRef, useState } from 'react'; + +// material-ui +import { useColorScheme } from '@mui/material/styles'; +import Box from '@mui/material/Box'; +import Skeleton from '@mui/material/Skeleton'; +import Stack from '@mui/material/Stack'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; + +// project imports +import IconButton from 'components/@extended/IconButton'; +import { editorSources, loadMonaco, type EditorSource } from 'components/code-editor/monaco'; +import { editorPrefs, setEditorPref, useEditorPrefs, type EditorPrefs } from 'components/code-editor/prefs'; +import StatusBar, { type StatusInfo } from 'components/code-editor/StatusBar'; +import { MONO_FONT_FAMILY } from 'config'; +import { lineChanges } from 'utils/monaco/line-diff'; +import { functionAt, validate, type CompletionContext } from 'utils/monaco/powershell-language'; +import { EDITOR_THEME } from 'utils/monaco/themes'; + +// assets +import CloseOutlined from '@ant-design/icons/CloseOutlined'; + +// types +import type * as Monaco from 'monaco-editor'; + +export type CodeLanguage = 'powershell' | 'shell' | 'plaintext'; + +const LANGUAGE_LABEL: Record = { powershell: 'PowerShell', shell: 'Bash', plaintext: 'Plain Text' }; + +interface Props { + value: string; + onChange?: (value: string) => void; + language: CodeLanguage; + readOnly?: boolean; + /** Editor height including its status bar (CSS length or px); defaults to 480. */ + height?: number | string; + /** Completions, hover cards and context-aware suggestions; on by default. */ + intellisense?: boolean; + /** Script-specific names ($Param, $Secrets.X, $Files.X, attached functions) the editor knows about. */ + completionContext?: CompletionContext; + /** The saved text: change bars in the gutter and Compare with Saved. */ + original?: string; +} + +interface Instance { + monaco: typeof Monaco; + editor: Monaco.editor.IStandaloneCodeEditor; + model: Monaco.editor.ITextModel; +} + +const INITIAL_INFO: StatusInfo = { + line: 1, + column: 1, + selected: 0, + cursors: 1, + tabSize: 4, + insertSpaces: true, + eol: 'LF', + errors: 0, + warnings: 0, + changes: 0 +}; + +const ADDED = '#2ea043'; +const MODIFIED = '#3b82f6'; +const DELETED = '#f85149'; + +/** Options both the editor and the compare view share. */ +function sharedOptions(): Monaco.editor.IEditorOptions { + return { + fontFamily: MONO_FONT_FAMILY, + fontSize: 13, + lineHeight: 20, + padding: { top: 10, bottom: 10 }, + automaticLayout: true, + fixedOverflowWidgets: true, + scrollBeyondLastLine: false, + smoothScrolling: true, + mouseWheelZoom: true, + cursorBlinking: 'smooth', + cursorSmoothCaretAnimation: 'on', + renderLineHighlight: 'all', + renderWhitespace: 'selection', + roundedSelection: true, + bracketPairColorization: { enabled: true }, + guides: { bracketPairs: 'active', indentation: true, highlightActiveIndentation: true }, + showFoldingControls: 'mouseover', + lineNumbersMinChars: 3, + scrollbar: { verticalScrollbarSize: 10, horizontalScrollbarSize: 10, useShadows: false }, + overviewRulerBorder: false, + hover: { delay: 350 } + }; +} + +function viewOptions(prefs: EditorPrefs): Monaco.editor.IEditorOptions { + return { + minimap: { enabled: prefs.minimap, renderCharacters: false, showSlider: 'mouseover' }, + wordWrap: prefs.wordWrap ? 'on' : 'off', + stickyScroll: { enabled: prefs.stickyScroll, maxLineCount: 4 } + }; +} + +// ==============================|| CODE EDITOR (MONACO) ||============================== // + +export default function CodeEditor({ + value, + onChange, + language, + readOnly = false, + height = 480, + intellisense = true, + completionContext, + original +}: Props) { + const { colorScheme } = useColorScheme(); + const prefs = useEditorPrefs(); + const hostRef = useRef(null); + const diffHostRef = useRef(null); + const [instance, setInstance] = useState(null); + const [loadError, setLoadError] = useState(''); + const [info, setInfo] = useState(INITIAL_INFO); + const [focused, setFocused] = useState(false); + const [comparing, setComparing] = useState(false); + + // Latest props for long-lived Monaco callbacks. + const onChangeRef = useRef(onChange); + const sourceRef = useRef({ intellisense, completionContext }); + const originalRef = useRef(original); + const contextRef = useRef(completionContext); + const initialRef = useRef({ value, language, readOnly }); + const toggleCompareRef = useRef<() => void>(() => {}); + /** Recent values this editor reported through onChange (newest last). */ + const emittedRef = useRef([]); + useEffect(() => { + onChangeRef.current = onChange; + sourceRef.current = { intellisense, completionContext }; + originalRef.current = original; + contextRef.current = completionContext; + toggleCompareRef.current = () => { + if (originalRef.current !== undefined) setComparing((on) => !on); + }; + }); + + // Status, change bars and problems are recomputed shortly after edits. + const analysisRef = useRef<() => void>(() => {}); + + useEffect(() => { + let cancelled = false; + const disposables: Monaco.IDisposable[] = []; + let created: Instance | null = null; + let timer: number | undefined; + + loadMonaco() + .then((monaco) => { + if (cancelled || !hostRef.current) return; + const initial = initialRef.current; + const model = monaco.editor.createModel(initial.value, initial.language); + editorSources.set(model.uri.toString(), sourceRef); + const editor = monaco.editor.create(hostRef.current, { + ...sharedOptions(), + ...viewOptions(editorPrefs()), + model, + readOnly: initial.readOnly, + lineDecorationsWidth: 14, + suggest: { showStatusBar: true, preview: true, insertMode: 'replace' }, + quickSuggestions: { other: true, comments: false, strings: false }, + suggestSelection: 'recentlyUsedByPrefix', + tabCompletion: 'on', + linkedEditing: true, + ariaLabel: `${LANGUAGE_LABEL[initial.language]} code editor` + }); + created = { monaco, editor, model }; + + const changesCount = { current: 0 }; + const bars = editor.createDecorationsCollection(); + const { OverviewRulerLane, MinimapPosition } = monaco.editor; + + const paintChanges = () => { + const saved = originalRef.current; + const changes = saved === undefined ? [] : lineChanges(saved, model.getValue()); + changesCount.current = changes.length; + const last = model.getLineCount(); + bars.set( + changes.map((change): Monaco.editor.IModelDeltaDecoration => { + if (change.kind === 'deleted') { + const below = change.line > 1; + const line = Math.min(below ? change.line - 1 : 1, last); + return { + range: new monaco.Range(line, 1, line, 1), + options: { + isWholeLine: true, + linesDecorationsClassName: below ? 'cg-deleted-below' : 'cg-deleted-above', + overviewRuler: { color: DELETED, position: OverviewRulerLane.Left } + } + }; + } + const color = change.kind === 'added' ? ADDED : MODIFIED; + return { + range: new monaco.Range(change.startLine, 1, Math.min(change.endLine, last), 1), + options: { + isWholeLine: true, + linesDecorationsClassName: `cg-${change.kind}`, + overviewRuler: { color, position: OverviewRulerLane.Left }, + minimap: { color, position: MinimapPosition.Gutter } + } + }; + }) + ); + }; + + const refresh = () => { + const selections = editor.getSelections() ?? []; + const primary = editor.getSelection(); + const options = model.getOptions(); + const markers = monaco.editor.getModelMarkers({ resource: model.uri }); + const line = primary?.positionLineNumber ?? 1; + setInfo({ + line, + column: primary?.positionColumn ?? 1, + selected: selections.reduce((n, s) => n + model.getValueLengthInRange(s), 0), + cursors: selections.length, + tabSize: options.tabSize, + insertSpaces: options.insertSpaces, + eol: model.getEOL() === '\r\n' ? 'CRLF' : 'LF', + errors: markers.filter((m) => m.severity === monaco.MarkerSeverity.Error).length, + warnings: markers.filter((m) => m.severity === monaco.MarkerSeverity.Warning).length, + scope: functionAt(monaco, model, line)?.name, + changes: changesCount.current + }); + }; + + const analyseNow = () => { + validate(monaco, model, contextRef.current ?? null); + paintChanges(); + refresh(); + }; + analysisRef.current = () => { + window.clearTimeout(timer); + timer = window.setTimeout(analyseNow, 200); + }; + + disposables.push( + model.onDidChangeContent(() => { + const next = model.getValue(); + emittedRef.current = [...emittedRef.current.slice(-19), next]; + onChangeRef.current?.(next); + analysisRef.current(); + }), + model.onDidChangeOptions(refresh), + editor.onDidChangeCursorSelection(refresh), + editor.onDidFocusEditorWidget(() => setFocused(true)), + editor.onDidBlurEditorWidget(() => setFocused(false)), + monaco.editor.onDidChangeMarkers((uris) => uris.some((uri) => uri.toString() === model.uri.toString()) && refresh()), + editor.addAction({ + id: 'executer.toggleWordWrap', + label: 'View: Toggle Word Wrap', + keybindings: [monaco.KeyMod.Alt | monaco.KeyCode.KeyZ], + run: () => setEditorPref('wordWrap', !editorPrefs().wordWrap) + }), + editor.addAction({ + id: 'executer.toggleMinimap', + label: 'View: Toggle Minimap', + run: () => setEditorPref('minimap', !editorPrefs().minimap) + }), + editor.addAction({ + id: 'executer.toggleStickyScroll', + label: 'View: Toggle Sticky Scroll', + run: () => setEditorPref('stickyScroll', !editorPrefs().stickyScroll) + }), + editor.addAction({ + id: 'executer.compareWithSaved', + label: 'File: Compare with Saved', + keybindings: [monaco.KeyMod.chord(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyK, monaco.KeyCode.KeyD)], + run: () => toggleCompareRef.current() + }) + ); + + analyseNow(); + setInstance(created); + }) + .catch(() => { + if (!cancelled) setLoadError('The code editor could not be loaded.'); + }); + + return () => { + cancelled = true; + window.clearTimeout(timer); + disposables.forEach((d) => d.dispose()); + if (created) { + editorSources.delete(created.model.uri.toString()); + created.editor.dispose(); + created.model.dispose(); + } + }; + }, []); + + // Theme is global to Monaco; follow the resolved MUI color scheme. + useEffect(() => { + instance?.monaco.editor.setTheme(colorScheme === 'dark' ? EDITOR_THEME.dark : EDITOR_THEME.light); + }, [instance, colorScheme]); + + useEffect(() => { + if (instance) instance.monaco.editor.setModelLanguage(instance.model, language); + }, [instance, language]); + + useEffect(() => { + instance?.editor.updateOptions({ readOnly }); + }, [instance, readOnly]); + + useEffect(() => { + instance?.editor.updateOptions(viewOptions(prefs)); + }, [instance, prefs]); + + // Our providers replace word-based suggestions while IntelliSense is on. + useEffect(() => { + instance?.editor.updateOptions({ wordBasedSuggestions: intellisense && language === 'powershell' ? 'off' : 'currentDocument' }); + }, [instance, intellisense, language]); + + // Bindings, the saved text or the language changed: recheck problems and change bars. + useEffect(() => { + if (instance) analysisRef.current(); + }, [instance, completionContext, original, language]); + + // Adopt outside changes (e.g. a different document loaded) without echoing the editor's own edits. + useEffect(() => { + // A render can lag a keystroke behind the model: a value this editor emitted itself is never written back. + if (!instance || emittedRef.current.includes(value) || instance.model.getValue() === value) return; + emittedRef.current = []; + instance.model.setValue(value); + }, [instance, value]); + + // Compare with Saved: a diff editor over the saved text and this same (still editable) model. + useEffect(() => { + if (!instance || !comparing || original === undefined || !diffHostRef.current) return; + const { monaco, model } = instance; + const savedModel = monaco.editor.createModel(original, model.getLanguageId()); + const diff = monaco.editor.createDiffEditor(diffHostRef.current, { + ...sharedOptions(), + readOnly, + originalEditable: false, + renderSideBySide: true, + useInlineViewWhenSpaceIsLimited: true, + renderSideBySideInlineBreakpoint: 760, + ignoreTrimWhitespace: false, + renderMarginRevertIcon: !readOnly, + hideUnchangedRegions: { enabled: true, contextLineCount: 3, minimumLineCount: 3, revealLineCount: 20 }, + minimap: { enabled: false }, + stickyScroll: { enabled: true } + }); + diff.setModel({ original: savedModel, modified: model }); + diff.getModifiedEditor().focus(); + const escape = diff.getModifiedEditor().addAction({ + id: 'executer.closeCompare', + label: 'File: Close Compare with Saved', + keybindings: [monaco.KeyCode.Escape], + precondition: '!suggestWidgetVisible && !findWidgetVisible && !renameInputVisible', + run: () => setComparing(false) + }); + return () => { + escape.dispose(); + diff.dispose(); + savedModel.dispose(); + instance.editor.focus(); + }; + }, [instance, comparing, original, readOnly]); + + const run = (actionId: string) => { + if (!instance) return; + instance.editor.focus(); + void instance.editor.getAction(actionId)?.run(); + }; + + const comparable = original !== undefined; + const showCompare = comparing && comparable; + + return ( + + {showCompare && ( + + + Saved + + + Working Copy + + + setComparing(false)} aria-label="Close Compare"> + + + + + )} + + {!instance && ( + + {loadError || } + + )} + + {showCompare && } + + {instance && ( + instance.model.updateOptions({ insertSpaces, tabSize })} + onConvertIndentation={(toSpaces) => run(toSpaces ? 'editor.action.indentationToSpaces' : 'editor.action.indentationToTabs')} + onEol={(eol) => + instance.model.pushEOL( + eol === 'CRLF' ? instance.monaco.editor.EndOfLineSequence.CRLF : instance.monaco.editor.EndOfLineSequence.LF + ) + } + onTogglePref={(key) => setEditorPref(key, !prefs[key])} + onToggleCompare={() => setComparing((on) => !on)} + /> + )} + + ); +} diff --git a/src/WebUI/src/components/ConfirmDialog.tsx b/src/WebUI/src/components/ConfirmDialog.tsx new file mode 100644 index 0000000..8445040 --- /dev/null +++ b/src/WebUI/src/components/ConfirmDialog.tsx @@ -0,0 +1,94 @@ +import { ReactNode, useState } from 'react'; + +// material-ui +import Alert from '@mui/material/Alert'; +import Button from '@mui/material/Button'; +import Dialog from '@mui/material/Dialog'; +import DialogActions from '@mui/material/DialogActions'; +import DialogContent from '@mui/material/DialogContent'; +import DialogTitle from '@mui/material/DialogTitle'; +import Typography from '@mui/material/Typography'; + +// project imports +import { errorMessage } from 'api/client'; + +interface Props { + open: boolean; + title: string; + /** One line on what happens. */ + message?: ReactNode; + confirmLabel?: string; + destructive?: boolean; + /** Disables Confirm (e.g. while a form inside is invalid). */ + confirmDisabled?: boolean; + maxWidth?: 'xs' | 'sm' | 'md' | 'lg'; + /** Runs on Confirm; the dialog stays open showing the error if it throws. */ + onConfirm: () => Promise | unknown; + onClose: () => void; + children?: ReactNode; +} + +// ==============================|| CONFIRM DIALOG ||============================== // + +export default function ConfirmDialog({ + open, + title, + message, + confirmLabel = 'Confirm', + destructive, + confirmDisabled, + maxWidth = 'xs', + onConfirm, + onClose, + children +}: Props) { + const [busy, setBusy] = useState(false); + const [error, setError] = useState(''); + + const close = () => { + if (busy) return; + setError(''); + onClose(); + }; + + const confirm = async () => { + setBusy(true); + setError(''); + try { + await onConfirm(); + setBusy(false); + onClose(); + } catch (e) { + setBusy(false); + setError(errorMessage(e)); + } + }; + + return ( + + {title} + + {message && ( + + {message} + + )} + {children} + {error && ( + + {error} + + )} + + + {/* Focus starts on Cancel so Enter never confirms by accident. */} + + + + + ); +} diff --git a/src/WebUI/src/components/CopyButton.tsx b/src/WebUI/src/components/CopyButton.tsx new file mode 100644 index 0000000..c32ae1d --- /dev/null +++ b/src/WebUI/src/components/CopyButton.tsx @@ -0,0 +1,36 @@ +import { MouseEvent, useState } from 'react'; + +// material-ui +import Tooltip from '@mui/material/Tooltip'; + +// project imports +import IconButton from 'components/@extended/IconButton'; + +// assets +import CheckOutlined from '@ant-design/icons/CheckOutlined'; +import CopyOutlined from '@ant-design/icons/CopyOutlined'; + +// ==============================|| COPY BUTTON ||============================== // + +export default function CopyButton({ value, label = 'Copy' }: { value: string; label?: string }) { + const [copied, setCopied] = useState(false); + + const copy = async (event: MouseEvent) => { + event.stopPropagation(); + try { + await navigator.clipboard.writeText(value); + setCopied(true); + window.setTimeout(() => setCopied(false), 1500); + } catch { + // Clipboard blocked (insecure context); nothing sensible to do. + } + }; + + return ( + + + {copied ? : } + + + ); +} diff --git a/src/WebUI/src/components/DataTable.tsx b/src/WebUI/src/components/DataTable.tsx new file mode 100644 index 0000000..0c8d897 --- /dev/null +++ b/src/WebUI/src/components/DataTable.tsx @@ -0,0 +1,250 @@ +import { ReactNode, useEffect, useMemo, useState } from 'react'; + +// material-ui +import Alert from '@mui/material/Alert'; +import Box from '@mui/material/Box'; +import Checkbox from '@mui/material/Checkbox'; +import LinearProgress from '@mui/material/LinearProgress'; +import Skeleton from '@mui/material/Skeleton'; +import Table from '@mui/material/Table'; +import TableBody from '@mui/material/TableBody'; +import TableCell from '@mui/material/TableCell'; +import TableContainer from '@mui/material/TableContainer'; +import TableHead from '@mui/material/TableHead'; +import TablePagination from '@mui/material/TablePagination'; +import TableRow from '@mui/material/TableRow'; +import TableSortLabel from '@mui/material/TableSortLabel'; + +// project imports +import HoverHelp from 'components/HoverHelp'; + +export interface Column { + id: string; + header: ReactNode; + cell: (row: T) => ReactNode; + /** Value for sorting; columns without one are not sortable. */ + sortValue?: (row: T) => string | number | boolean | null | undefined; + width?: number | string; + align?: 'left' | 'right' | 'center'; + nowrap?: boolean; + help?: ReactNode; +} + +export interface Selection { + selected: ReadonlySet; + /** Called with the affected row ids and whether they are now chosen. */ + onChange: (ids: string[], on: boolean) => void; + /** Rows that can be chosen (default all); the others show a disabled box and stay out of select-all. */ + selectable?: (row: T) => boolean; +} + +interface Props { + columns: Column[]; + rows: T[] | undefined; + rowId: (row: T) => string; + /** First load (skeleton rows) vs. background refresh (thin bar). */ + loading?: boolean; + refreshing?: boolean; + error?: string; + empty?: ReactNode; + onRowClick?: (row: T) => void; + selection?: Selection; + /** Filters and bulk actions, above the header row. */ + toolbar?: ReactNode; + defaultSort?: { id: string; direction: 'asc' | 'desc' }; + pageSize?: number; + /** Turn off paging for short, bounded lists. */ + paged?: boolean; + dense?: boolean; + /** Accessible name for the row checkboxes ("Choose WS-042"). */ + rowLabel?: (row: T) => string; + /** Marks the row currently open in a side panel. */ + activeRowId?: string; + minWidth?: number; +} + +const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }); + +function compare(a: unknown, b: unknown): number { + if (a == null && b == null) return 0; + if (a == null) return 1; + if (b == null) return -1; + if (typeof a === 'number' && typeof b === 'number') return a - b; + if (typeof a === 'boolean' && typeof b === 'boolean') return Number(a) - Number(b); + return collator.compare(String(a), String(b)); +} + +// ==============================|| DATA TABLE ||============================== // + +export default function DataTable({ + columns, + rows, + rowId, + loading, + refreshing, + error, + empty, + onRowClick, + selection, + toolbar, + defaultSort, + pageSize = 50, + paged = true, + dense = true, + rowLabel, + activeRowId, + minWidth = 720 +}: Props) { + const [sort, setSort] = useState(defaultSort); + const [page, setPage] = useState(0); + const [perPage, setPerPage] = useState(pageSize); + + const sorted = useMemo(() => { + const list = rows ?? []; + const column = sort && columns.find((c) => c.id === sort.id); + if (!column?.sortValue) return list; + const factor = sort!.direction === 'asc' ? 1 : -1; + return [...list].sort((a, b) => factor * compare(column.sortValue!(a), column.sortValue!(b))); + }, [rows, columns, sort]); + + // A filter that shrinks the list must not strand the view on an empty page. + const pageCount = Math.max(1, Math.ceil(sorted.length / perPage)); + useEffect(() => { + if (page > pageCount - 1) setPage(pageCount - 1); + }, [page, pageCount]); + + const visible = paged ? sorted.slice(page * perPage, page * perPage + perPage) : sorted; + + const selectable = selection?.selectable; + const allIds = useMemo(() => (selectable ? sorted.filter(selectable) : sorted).map(rowId), [sorted, rowId, selectable]); + const chosen = selection ? allIds.filter((id) => selection.selected.has(id)).length : 0; + + const toggleSort = (id: string) => { + setSort((current) => { + if (!current || current.id !== id) return { id, direction: 'asc' }; + if (current.direction === 'asc') return { id, direction: 'desc' }; + return defaultSort; // third click returns to the default order + }); + }; + + const colSpan = columns.length + (selection ? 1 : 0); + + return ( + + {toolbar && {toolbar}} + {refreshing && !loading && } + + + + + {selection && ( + + 0 && chosen < allIds.length} + checked={allIds.length > 0 && chosen === allIds.length} + onChange={(e) => selection.onChange(allIds, e.target.checked)} + slotProps={{ input: { 'aria-label': `Choose all ${allIds.length} rows` } }} + /> + + )} + {columns.map((column) => ( + + {column.sortValue ? ( + toggleSort(column.id)} + > + {column.header} + + ) : ( + column.header + )} + {column.help && } + + ))} + + + + {loading && + Array.from({ length: 6 }, (_, i) => ( + + {Array.from({ length: colSpan }, (_, j) => ( + + + + ))} + + ))} + {!loading && error && ( + + + {error} + + + )} + {!loading && !error && sorted.length === 0 && ( + + + {empty} + + + )} + {!loading && + !error && + visible.map((row) => { + const id = rowId(row); + const isChosen = selection?.selected.has(id) ?? false; + return ( + onRowClick(row) : undefined} + sx={{ cursor: onRowClick ? 'pointer' : 'default' }} + > + {selection && ( + e.stopPropagation()}> + selection.onChange([id], e.target.checked)} + slotProps={{ input: { 'aria-label': rowLabel ? `Choose ${rowLabel(row)}` : 'Choose row' } }} + /> + + )} + {columns.map((column) => ( + + {column.cell(row)} + + ))} + + ); + })} + +
+
+ {paged && !loading && sorted.length > perPage && ( + setPage(next)} + rowsPerPage={perPage} + onRowsPerPageChange={(e) => { + setPerPage(parseInt(e.target.value, 10)); + setPage(0); + }} + rowsPerPageOptions={[25, 50, 100, 250]} + /> + )} +
+ ); +} diff --git a/src/WebUI/src/components/DateTime.tsx b/src/WebUI/src/components/DateTime.tsx new file mode 100644 index 0000000..834fa66 --- /dev/null +++ b/src/WebUI/src/components/DateTime.tsx @@ -0,0 +1,43 @@ +// material-ui +import Tooltip from '@mui/material/Tooltip'; +import Typography, { TypographyProps } from '@mui/material/Typography'; + +// project imports +import useNow from 'hooks/useNow'; +import { formatAbsolute, formatRelative } from 'utils/format'; + +interface Props { + value?: string | null; + /** Shown when there is no value. */ + empty?: string; + variant?: TypographyProps['variant']; + color?: TypographyProps['color']; +} + +// ==============================|| DATE TIME (RELATIVE, ABSOLUTE ON HOVER) ||============================== // + +export function RelativeTime({ value, empty = '—', variant = 'body2', color }: Props) { + const now = useNow(); + if (!value) { + return ( + + {empty} + + ); + } + return ( + + + {formatRelative(value, now)} + + + ); +} + +export function AbsoluteTime({ value, empty = '—', variant = 'body2', color }: Props) { + return ( + + {value ? formatAbsolute(value) : empty} + + ); +} diff --git a/src/WebUI/src/components/EmptyState.tsx b/src/WebUI/src/components/EmptyState.tsx new file mode 100644 index 0000000..64094e2 --- /dev/null +++ b/src/WebUI/src/components/EmptyState.tsx @@ -0,0 +1,36 @@ +import { ReactNode } from 'react'; + +// material-ui +import Box from '@mui/material/Box'; +import Stack from '@mui/material/Stack'; +import Typography from '@mui/material/Typography'; + +// assets +import InboxOutlined from '@ant-design/icons/InboxOutlined'; + +interface Props { + title: string; + detail?: ReactNode; + icon?: ReactNode; + action?: ReactNode; + dense?: boolean; +} + +// ==============================|| EMPTY STATE ||============================== // + +export default function EmptyState({ title, detail, icon, action, dense }: Props) { + return ( + + {icon ?? } + + {title} + + {detail && ( + + {detail} + + )} + {action && {action}} + + ); +} diff --git a/src/WebUI/src/components/GatedButton.tsx b/src/WebUI/src/components/GatedButton.tsx new file mode 100644 index 0000000..dbb4aa4 --- /dev/null +++ b/src/WebUI/src/components/GatedButton.tsx @@ -0,0 +1,21 @@ +// material-ui +import Button, { ButtonProps } from '@mui/material/Button'; +import Tooltip from '@mui/material/Tooltip'; + +interface Props extends ButtonProps { + /** Why the button cannot be used; it stays visible, disabled, and explains on hover. */ + gate?: string; +} + +// ==============================|| GATED BUTTON ||============================== // + +export default function GatedButton({ gate, disabled, ...props }: Props) { + if (!gate) return + {error && ( + + {error} + + )} + + + )} + + {p.type === 'hashtable' && ( + + {(draft.hashes[p.name] ?? []).map((row, i) => { + const update = (patch: Partial) => + setHash( + p.name, + (draft.hashes[p.name] ?? []).map((r, idx) => (idx === i ? { ...r, ...patch } : r)) + ); + return ( + + update({ keyType: e.target.value as PrimitiveType })} + disabled={disabled} + sx={{ minWidth: 110 }} + > + {PRIMITIVES.map((t) => ( + + {t} + + ))} + + update({ key })} + /> + update({ valueType: e.target.value as PrimitiveType })} + disabled={disabled} + sx={{ minWidth: 110 }} + > + {PRIMITIVES.map((t) => ( + + {t} + + ))} + + update({ value })} + /> + + setHash( + p.name, + (draft.hashes[p.name] ?? []).filter((_, idx) => idx !== i) + ) + } + > + + + + ); + })} + + + {error && ( + + {error} + + )} + + + )} + + ); + })} + + ); +} diff --git a/src/WebUI/src/components/Properties.tsx b/src/WebUI/src/components/Properties.tsx new file mode 100644 index 0000000..e478fcf --- /dev/null +++ b/src/WebUI/src/components/Properties.tsx @@ -0,0 +1,35 @@ +import { ReactNode } from 'react'; + +// material-ui +import Box from '@mui/material/Box'; +import Typography from '@mui/material/Typography'; + +export interface Property { + label: string; + value: ReactNode; + /** Machine text (ids, versions, serials). */ + mono?: boolean; +} + +// ==============================|| PROPERTIES (LABEL / VALUE LIST) ||============================== // + +export default function Properties({ items, labelWidth = 150 }: { items: Property[]; labelWidth?: number }) { + return ( + + {items.map((item) => ( + + + {item.label} + + + {item.value === undefined || item.value === null || item.value === '' ? '—' : item.value} + + + ))} + + ); +} diff --git a/src/WebUI/src/components/ScrollTop.tsx b/src/WebUI/src/components/ScrollTop.tsx new file mode 100644 index 0000000..49d37f6 --- /dev/null +++ b/src/WebUI/src/components/ScrollTop.tsx @@ -0,0 +1,18 @@ +import { useEffect } from 'react'; +import { useLocation } from 'react-router-dom'; + +// ==============================|| NAVIGATION - SCROLL TO TOP ||============================== // + +export default function ScrollTop() { + const location = useLocation(); + + useEffect(() => { + window.scrollTo({ + top: 0, + left: 0, + behavior: 'smooth' + }); + }, [location.pathname]); + + return null; +} diff --git a/src/WebUI/src/components/Sheet.tsx b/src/WebUI/src/components/Sheet.tsx new file mode 100644 index 0000000..67b6891 --- /dev/null +++ b/src/WebUI/src/components/Sheet.tsx @@ -0,0 +1,65 @@ +import { ReactNode } from 'react'; + +// material-ui +import Box from '@mui/material/Box'; +import Divider from '@mui/material/Divider'; +import Drawer from '@mui/material/Drawer'; +import Stack from '@mui/material/Stack'; +import Typography from '@mui/material/Typography'; + +// project imports +import IconButton from 'components/@extended/IconButton'; + +// assets +import CloseOutlined from '@ant-design/icons/CloseOutlined'; + +interface Props { + open: boolean; + title: ReactNode; + subtitle?: ReactNode; + onClose: () => void; + /** Sticky footer (Save / Cancel). */ + actions?: ReactNode; + /** Panel width on desktop; full width on phones. */ + width?: number | string; + children: ReactNode; +} + +// ==============================|| SHEET (RIGHT-HAND EDITOR PANEL) ||============================== // + +export default function Sheet({ open, title, subtitle, onClose, actions, width = 'min(760px, 66.7vw)', children }: Props) { + return ( + + + + + {title} + + {subtitle && ( + + {subtitle} + + )} + + + + + + + {children} + {actions && ( + <> + + + {actions} + + + )} + + ); +} diff --git a/src/WebUI/src/components/StatusChip.tsx b/src/WebUI/src/components/StatusChip.tsx new file mode 100644 index 0000000..5521512 --- /dev/null +++ b/src/WebUI/src/components/StatusChip.tsx @@ -0,0 +1,66 @@ +// material-ui +import Chip, { ChipProps } from '@mui/material/Chip'; +import Tooltip from '@mui/material/Tooltip'; + +// project imports +import Dot from 'components/@extended/Dot'; +import type { DeviceStatus, JobState } from 'api/types'; + +type Tone = 'success' | 'warning' | 'error' | 'info' | 'primary' | 'secondary'; + +/** One map from status word to tone, so the same word always looks the same. */ +const TONES: Record = { + online: { tone: 'success', label: 'Online' }, + stale: { tone: 'warning', label: 'Stale' }, + offline: { tone: 'secondary', label: 'Offline' }, + orphaned: { tone: 'error', label: 'Orphaned' }, + queued: { tone: 'secondary', label: 'Queued' }, + dispatched: { tone: 'info', label: 'Dispatched' }, + running: { tone: 'primary', label: 'Running' }, + succeeded: { tone: 'success', label: 'Succeeded' }, + failed: { tone: 'error', label: 'Failed' }, + cancelled: { tone: 'secondary', label: 'Cancelled' }, + timedOut: { tone: 'warning', label: 'Timed Out' }, + enabled: { tone: 'success', label: 'Enabled' }, + disabled: { tone: 'secondary', label: 'Disabled' } +}; + +interface Props { + status: string; + /** Overrides the default label for the status word. */ + label?: string; + tooltip?: string; + size?: ChipProps['size']; +} + +// ==============================|| STATUS CHIP ||============================== // + +export default function StatusChip({ status, label, tooltip, size = 'small' }: Props) { + const known = TONES[status] ?? { tone: 'secondary' as Tone, label: status }; + const chip = ( + } + sx={{ fontWeight: 500 }} + /> + ); + return tooltip ? {chip} : chip; +} + +export function DeviceStatusChip({ status, orphaned }: { status: DeviceStatus; orphaned?: boolean }) { + return orphaned ? ( + + ) : ( + + ); +} + +export function JobStateChip({ state, exitCode }: { state: JobState; exitCode?: number | null }) { + return ; +} + +/** Job states that will not change again. */ +export const TERMINAL_JOB_STATES: JobState[] = ['succeeded', 'failed', 'cancelled', 'timedOut']; diff --git a/src/WebUI/src/components/StepUpDialog.tsx b/src/WebUI/src/components/StepUpDialog.tsx new file mode 100644 index 0000000..e39dfb0 --- /dev/null +++ b/src/WebUI/src/components/StepUpDialog.tsx @@ -0,0 +1,133 @@ +import { FormEvent, useEffect, useState } from 'react'; + +// material-ui +import Alert from '@mui/material/Alert'; +import Button from '@mui/material/Button'; +import Dialog from '@mui/material/Dialog'; +import DialogActions from '@mui/material/DialogActions'; +import DialogContent from '@mui/material/DialogContent'; +import DialogTitle from '@mui/material/DialogTitle'; +import TextField from '@mui/material/TextField'; +import Typography from '@mui/material/Typography'; + +// project imports +import HoverHelp from 'components/HoverHelp'; +import { errorMessage, fieldErrors } from 'api/client'; +import { identity, IdentityRoutes } from 'api/identity'; + +/** Where the step-up window lands when it is done; the page closes itself. */ +export const STEP_UP_DONE_PATH = '/step-up/done'; + +const POLL_MS = 1500; +const GIVE_UP_MS = 5 * 60 * 1000; + +const wait = (ms: number) => new Promise((resolve) => window.setTimeout(resolve, ms)); + +/** Opens the provider's confirmation in a small window and waits until the session says it is confirmed. */ +export async function verifyWithProvider(): Promise { + const popup = window.open( + `${IdentityRoutes.stepUpOidc}?returnUrl=${encodeURIComponent(STEP_UP_DONE_PATH)}`, + 'step-up', + 'popup,width=520,height=680' + ); + if (!popup) throw new Error('Allow pop-ups for this console, then try again.'); + const started = Date.now(); + while (Date.now() - started < GIVE_UP_MS) { + await wait(POLL_MS); + if ((await identity.stepUpStatus()).verified) return; + if (popup.closed) { + // One last look: the window closes itself as soon as it is done. + if ((await identity.stepUpStatus()).verified) return; + throw new Error('That did not confirm it. Try again.'); + } + } + throw new Error('That took too long. Try again.'); +} + +// ==============================|| STEP-UP ||============================== // + +/** + * Asks the person to confirm it is them before a sensitive change (switching + * sign-in methods). Built-in, Windows and directory accounts type their + * password; single sign-on sessions confirm with their provider in a small window. + */ +export default function StepUpDialog({ onVerified, onClose }: { onVerified: () => void; onClose: () => void }) { + const [method, setMethod] = useState(null); + const [password, setPassword] = useState(''); + const [error, setError] = useState(); + const [busy, setBusy] = useState(false); + + useEffect(() => { + let live = true; + identity + .stepUpStatus() + .then((status) => live && setMethod(status.method)) + .catch(() => live && setMethod('password')); + return () => { + live = false; + }; + }, []); + + const submit = async (event?: FormEvent) => { + event?.preventDefault(); + setBusy(true); + setError(undefined); + try { + if (method === 'oidc') { + await verifyWithProvider(); + } else { + const status = await identity.stepUp(password); + if (!status.verified) throw new Error(status.unavailable ?? 'That did not confirm it. Try again.'); + } + onVerified(); + } catch (err) { + setError(fieldErrors(err).password ?? errorMessage(err, 'That did not confirm it. Try again.')); + } finally { + setBusy(false); + } + }; + + if (method === null) return null; + + return ( + +
+ + Confirm It Is You + + + + {method === 'oidc' ? ( + Sign in again with your identity provider. + ) : ( + setPassword(e.target.value)} + error={Boolean(error)} + helperText={error} + autoComplete="current-password" + autoFocus + fullWidth + sx={{ mt: 1 }} + /> + )} + {method === 'oidc' && error && ( + + {error} + + )} + + + + + +
+
+ ); +} diff --git a/src/WebUI/src/components/TreeList.tsx b/src/WebUI/src/components/TreeList.tsx new file mode 100644 index 0000000..b09dd03 --- /dev/null +++ b/src/WebUI/src/components/TreeList.tsx @@ -0,0 +1,205 @@ +import { DragEvent, KeyboardEvent, MouseEvent, ReactNode, TouchEvent, useRef, useState } from 'react'; + +// material-ui +import Box from '@mui/material/Box'; +import Collapse from '@mui/material/Collapse'; +import List from '@mui/material/List'; +import ListItemButton from '@mui/material/ListItemButton'; +import Typography from '@mui/material/Typography'; + +// assets +import CaretDownOutlined from '@ant-design/icons/CaretDownOutlined'; +import CaretRightOutlined from '@ant-design/icons/CaretRightOutlined'; + +export interface TreeNode { + id: string; + label: string; + /** Muted figure on the right (e.g. a device count). */ + secondary?: ReactNode; + icon?: ReactNode; + children?: TreeNode[]; +} + +/** Where a context menu opens: at the pointer, or beside the node from the keyboard. */ +export interface TreeMenuAnchor { + top: number; + left: number; +} + +export interface TreeDrag { + canDrag: (node: TreeNode) => boolean; + canDrop: (draggedId: string, target: TreeNode) => boolean; + onDrop: (draggedId: string, target: TreeNode) => void; +} + +interface Props { + nodes: TreeNode[]; + selectedId?: string; + onSelect: (node: TreeNode) => void; + expanded: ReadonlySet; + onToggle: (id: string, open: boolean) => void; + ariaLabel: string; + drag?: TreeDrag; + onContextMenu?: (node: TreeNode, anchor: TreeMenuAnchor) => void; +} + +const LONG_PRESS_MS = 550; +const DRAG_TYPE = 'application/x-executer-tree-node'; + +// ==============================|| TREE LIST ||============================== // + +export default function TreeList({ nodes, selectedId, onSelect, expanded, onToggle, ariaLabel, drag, onContextMenu }: Props) { + const [dragging, setDragging] = useState(null); + const [dropTarget, setDropTarget] = useState(null); + const pressTimer = useRef(undefined); + + const openMenuAt = (node: TreeNode, anchor: TreeMenuAnchor) => onContextMenu?.(node, anchor); + + const render = (node: TreeNode, depth: number): ReactNode => { + const hasChildren = (node.children?.length ?? 0) > 0; + const open = expanded.has(node.id); + const selected = node.id === selectedId; + const canDrag = drag?.canDrag(node) ?? false; + + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === 'ArrowRight' && hasChildren && !open) { + event.preventDefault(); + onToggle(node.id, true); + } else if (event.key === 'ArrowLeft' && hasChildren && open) { + event.preventDefault(); + onToggle(node.id, false); + } else if ((event.key === 'F10' && event.shiftKey) || event.key === 'ContextMenu') { + event.preventDefault(); + const rect = event.currentTarget.getBoundingClientRect(); + openMenuAt(node, { top: rect.top + rect.height / 2, left: rect.left + Math.min(rect.width, 220) }); + } + }; + + const dragHandlers = drag + ? { + draggable: canDrag, + onDragStart: (event: DragEvent) => { + event.dataTransfer.setData(DRAG_TYPE, node.id); + event.dataTransfer.effectAllowed = 'move'; + setDragging(node.id); + }, + onDragEnd: () => { + setDragging(null); + setDropTarget(null); + }, + onDragOver: (event: DragEvent) => { + if (dragging && drag.canDrop(dragging, node)) { + event.preventDefault(); + event.dataTransfer.dropEffect = 'move'; + if (dropTarget !== node.id) setDropTarget(node.id); + } + }, + onDragLeave: () => { + if (dropTarget === node.id) setDropTarget(null); + }, + onDrop: (event: DragEvent) => { + event.preventDefault(); + const draggedId = event.dataTransfer.getData(DRAG_TYPE); + setDragging(null); + setDropTarget(null); + if (draggedId && drag.canDrop(draggedId, node)) drag.onDrop(draggedId, node); + } + } + : {}; + + const touchHandlers = onContextMenu + ? { + onTouchStart: (event: TouchEvent) => { + const touch = event.touches[0]; + pressTimer.current = window.setTimeout(() => openMenuAt(node, { top: touch.clientY, left: touch.clientX }), LONG_PRESS_MS); + }, + onTouchEnd: () => window.clearTimeout(pressTimer.current), + onTouchMove: () => window.clearTimeout(pressTimer.current) + } + : {}; + + return ( + + onSelect(node)} + onKeyDown={onKeyDown} + onContextMenu={ + onContextMenu + ? (event: MouseEvent) => { + event.preventDefault(); + openMenuAt(node, { top: event.clientY, left: event.clientX }); + } + : undefined + } + {...dragHandlers} + {...touchHandlers} + sx={{ + pl: 1 + depth * 2, + pr: 1.5, + py: 0.75, + borderRadius: 1, + mx: 1, + gap: 1, + opacity: dragging === node.id ? 0.5 : 1, + outline: dropTarget === node.id ? '2px dashed' : 'none', + outlineColor: 'primary.main', + outlineOffset: -2 + }} + > + { + if (!hasChildren) return; + event.stopPropagation(); + onToggle(node.id, !open); + }} + sx={{ + width: 14, + display: 'inline-flex', + justifyContent: 'center', + color: 'text.secondary', + fontSize: '0.65rem', + flexShrink: 0 + }} + > + {hasChildren ? open ? : : null} + + {node.icon && ( + {node.icon} + )} + + {node.label} + + {node.secondary != null && ( + + {node.secondary} + + )} + + {hasChildren && ( + + + {node.children!.map((child) => render(child, depth + 1))} + + + )} + + ); + }; + + return ( + + {nodes.map((node) => render(node, 0))} + + ); +} diff --git a/src/WebUI/src/components/charts/BarList.tsx b/src/WebUI/src/components/charts/BarList.tsx new file mode 100644 index 0000000..493c420 --- /dev/null +++ b/src/WebUI/src/components/charts/BarList.tsx @@ -0,0 +1,83 @@ +// material-ui +import Box from '@mui/material/Box'; +import Stack from '@mui/material/Stack'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; + +// project imports +import ChartTooltip from './ChartTooltip'; + +// types +import type { CountPoint } from 'api/types'; + +interface Props { + items: CountPoint[]; + /** One hue for the whole list (a single series). */ + color?: string; + emptyText?: string; + /** Accessible name for the list ("Jobs by script engine"). */ + label: string; + /** Unit for the tooltip ("jobs"). */ + unit?: string; +} + +// ==============================|| CHART - BAR LIST ||============================== // + +/** Horizontal bars for ranked counts: label, proportional bar, value. */ +export default function BarList({ items, color = 'var(--chart-1)', emptyText = 'No data yet.', label, unit = 'jobs' }: Props) { + if (items.length === 0) { + return ( + + {emptyText} + + ); + } + + const max = Math.max(1, ...items.map((i) => i.count)); + const total = items.reduce((sum, i) => sum + i.count, 0); + + return ( + + {items.map((item) => { + const share = total > 0 ? Math.round((item.count / total) * 100) : 0; + return ( + } + > + ({ + display: 'grid', + gridTemplateColumns: 'minmax(0, 9rem) 1fr auto', + alignItems: 'center', + gap: 1.5, + py: 0.5, + px: 0.5, + borderRadius: 1, + outline: 'none', + '& .bar': { transition: 'opacity 0.15s' }, + '&:hover, &:focus-visible': { bgcolor: theme.vars.palette.action.hover }, + '&:hover .bar, &:focus-visible .bar': { opacity: 0.8 } + })} + > + + {item.label} + + + ({ fill: theme.vars.palette.divider })} /> + + + + {item.count.toLocaleString()} + + + + ); + })} + + ); +} diff --git a/src/WebUI/src/components/charts/ChartTooltip.tsx b/src/WebUI/src/components/charts/ChartTooltip.tsx new file mode 100644 index 0000000..2f8fae0 --- /dev/null +++ b/src/WebUI/src/components/charts/ChartTooltip.tsx @@ -0,0 +1,37 @@ +// material-ui +import Box from '@mui/material/Box'; +import Stack from '@mui/material/Stack'; +import Typography from '@mui/material/Typography'; + +export interface TooltipRow { + label: string; + value: number | string; + /** Series color, shown as a short line key. */ + color?: string; +} + +// ==============================|| CHART TOOLTIP CONTENT ||============================== // + +/** Tooltip body for chart marks: a heading, then value-first rows keyed by a short stroke of the series color. */ +export default function ChartTooltip({ heading, rows }: { heading?: string; rows: TooltipRow[] }) { + return ( + + {heading && ( + + {heading} + + )} + {rows.map((row) => ( + + {row.color && } + + {typeof row.value === 'number' ? row.value.toLocaleString() : row.value} + + + {row.label} + + + ))} + + ); +} diff --git a/src/WebUI/src/components/charts/Donut.tsx b/src/WebUI/src/components/charts/Donut.tsx new file mode 100644 index 0000000..26b87b3 --- /dev/null +++ b/src/WebUI/src/components/charts/Donut.tsx @@ -0,0 +1,156 @@ +import { useState } from 'react'; + +// material-ui +import Box from '@mui/material/Box'; +import Stack from '@mui/material/Stack'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; + +// project imports +import ChartTooltip from './ChartTooltip'; + +export interface DonutSegment { + label: string; + value: number; + color: string; +} + +interface Props { + segments: DonutSegment[]; + /** Accessible name for the chart ("Job outcomes"). */ + label: string; + centerValue?: string; + centerLabel?: string; + size?: number; + thickness?: number; + /** Show the legend (label, count, share) beside the ring. */ + legend?: boolean; +} + +/** Surface gap between adjacent arcs, in px along the ring. */ +const GAP = 2; + +const percent = (value: number, total: number) => (total > 0 ? `${Math.round((value / total) * 100)}%` : '0%'); + +// ==============================|| CHART - DONUT ||============================== // + +/** A quiet donut: arcs proportional to value, a centered total, and a legend that highlights its arc. */ +export default function Donut({ segments, label, centerValue, centerLabel, size = 132, thickness = 16, legend = true }: Props) { + const [hovered, setHovered] = useState(null); + + const center = size / 2; + // Leave room for the hovered arc to thicken without clipping. + const radius = (size - thickness) / 2 - 2; + const circumference = 2 * Math.PI * radius; + const total = segments.reduce((sum, s) => sum + s.value, 0); + const visible = segments.filter((s) => s.value > 0); + const gap = visible.length > 1 ? GAP : 0; + + let offset = 0; + const arcs = visible.map((s) => { + const length = (s.value / total) * circumference; + const arc = { ...s, dash: Math.max(length - gap, 0.5), offset }; + offset += length; + return arc; + }); + + const summary = `${label}: ${segments.map((s) => `${s.label} ${s.value}`).join(', ') || 'no data'}`; + + return ( + + + + {summary} + + {arcs.length === 0 && ( + ({ fill: 'none', stroke: theme.vars.palette.divider, strokeWidth: thickness })} + /> + )} + {arcs.map((arc) => ( + + } + > + setHovered(arc.label)} + onMouseLeave={() => setHovered(null)} + style={{ + fill: 'none', + stroke: arc.color, + strokeWidth: hovered === arc.label ? thickness + 4 : thickness, + opacity: hovered && hovered !== arc.label ? 0.55 : 1, + transition: 'stroke-width 0.15s, opacity 0.15s', + cursor: 'default' + }} + /> + + ))} + + + + {centerValue && ( + + {centerValue} + + )} + {centerLabel && ( + + {centerLabel} + + )} + + + + {legend && ( + + {segments.map((s) => ( + setHovered(s.value > 0 ? s.label : null)} + onMouseLeave={() => setHovered(null)} + sx={(theme) => ({ + display: 'grid', + gridTemplateColumns: '10px minmax(0, 1fr) auto auto', + alignItems: 'center', + gap: 1, + px: 0.5, + py: 0.25, + borderRadius: 1, + ...(hovered === s.label && { bgcolor: theme.vars.palette.action.hover }) + })} + > + + + {s.label} + + + {s.value.toLocaleString()} + + + {percent(s.value, total)} + + + ))} + + )} + + ); +} diff --git a/src/WebUI/src/components/charts/TimelineChart.tsx b/src/WebUI/src/components/charts/TimelineChart.tsx new file mode 100644 index 0000000..c8f64e9 --- /dev/null +++ b/src/WebUI/src/components/charts/TimelineChart.tsx @@ -0,0 +1,227 @@ +import { useEffect, useRef, useState } from 'react'; + +// material-ui +import { useTheme } from '@mui/material/styles'; +import Box from '@mui/material/Box'; +import Stack from '@mui/material/Stack'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; + +// project imports +import ChartTooltip from './ChartTooltip'; + +// types +import type { DayPoint } from 'api/types'; + +interface Props { + days: DayPoint[]; + height?: number; + /** Accessible name ("Executions over the last 14 days"). */ + label?: string; + emptyText?: string; +} + +type SeriesKey = 'succeeded' | 'failed' | 'other'; + +const AXIS_HEIGHT = 20; +const TOP_PAD = 14; +/** Surface gap between stacked segments. */ +const GAP = 2; +const RADIUS = 4; + +/** Off-screen but still read by assistive technology. */ +const visuallyHidden = { + position: 'absolute', + width: '1px', + height: '1px', + overflow: 'hidden', + clip: 'rect(0 0 0 0)', + whiteSpace: 'nowrap', + border: 0, + p: 0, + m: '-1px' +} as const; + +/** A rect with only its top corners rounded (the data end; the baseline end stays square). */ +function topRoundedRect(x: number, y: number, w: number, h: number, r: number) { + const radius = Math.min(r, h, w / 2); + return `M${x},${y + h} V${y + radius} Q${x},${y} ${x + radius},${y} H${x + w - radius} Q${x + w},${y} ${x + w},${y + radius} V${y + h} Z`; +} + +/** Tracks an element's content width. */ +function useWidth() { + const ref = useRef(null); + const [width, setWidth] = useState(0); + useEffect(() => { + const element = ref.current; + if (!element) return; + const observer = new ResizeObserver(([entry]) => setWidth(entry.contentRect.width)); + observer.observe(element); + return () => observer.disconnect(); + }, []); + return [ref, width] as const; +} + +// ==============================|| CHART - EXECUTIONS TIMELINE ||============================== // + +/** Stacked columns of executions per day (succeeded / failed / other) with a per-day hover readout. */ +export default function TimelineChart({ + days, + height = 150, + label = 'Executions over the last 14 days', + emptyText = 'No executions in the last 14 days.' +}: Props) { + const theme = useTheme(); + const [ref, width] = useWidth(); + const [hovered, setHovered] = useState(null); + + // Status colors: these segments are outcomes, so they wear the status palette. + const series: { key: SeriesKey; label: string; color: string }[] = [ + { key: 'succeeded', label: 'Succeeded', color: theme.vars.palette.success.main }, + { key: 'failed', label: 'Failed', color: theme.vars.palette.error.main }, + { key: 'other', label: 'Other', color: 'var(--chart-6)' } + ]; + + const sumOf = (d: DayPoint) => d.succeeded + d.failed + d.other; + const max = Math.max(1, ...days.map(sumOf)); + const total = days.reduce((sum, d) => sum + sumOf(d), 0); + + const plotHeight = height - AXIS_HEIGHT - TOP_PAD; + const baseline = TOP_PAD + plotHeight; + const slot = days.length > 0 ? width / days.length : 0; + const barWidth = Math.max(Math.min(slot * 0.62, 28), 2); + const labelStep = Math.max(1, Math.ceil((days.length * 52) / Math.max(width, 1))); + + return ( + + + {total === 0 ? ( + + {emptyText} + + ) : ( + width > 0 && ( + + {`${label}: ${total} in total`} + + {/* recessive grid: top line labelled with the scale maximum, and the baseline */} + + + {max} + + + + {days.map((day, i) => { + const x = i * slot + (slot - barWidth) / 2; + let y = baseline; + const stacked = series.filter((s) => day[s.key] > 0); + const segments = stacked.map((s, index) => { + const h = (day[s.key] / max) * plotHeight; + const top = y - h; + // Every segment above the first gives up GAP px at its bottom. + const drawn = index > 0 ? Math.max(h - GAP, 0.5) : Math.max(h, 1); + y = top; + return { ...s, top, drawn, last: index === stacked.length - 1 }; + }); + + const readout = ( + ({ label: s.label, value: day[s.key], color: s.color })), + { label: 'Total', value: sumOf(day) } + ]} + /> + ); + + return ( + + {segments.map((s) => + s.last ? ( + + ) : ( + + ) + )} + {i % labelStep === 0 && ( + + {day.date} + + )} + {/* the whole column is the hit target */} + + setHovered(i)} + onMouseLeave={() => setHovered(null)} + onFocus={() => setHovered(i)} + onBlur={() => setHovered(null)} + style={{ fill: 'transparent', outline: 'none' }} + /> + + + ); + })} + + ) + )} + + + {total > 0 && ( + <> + + {series.map((s) => ( + + + + {s.label} + + + ))} + + + {/* the same numbers as a table, for screen readers */} + + {label} + + + Day + {series.map((s) => ( + + {s.label} + + ))} + + + + {days.map((day) => ( + + {day.date} + {series.map((s) => ( + {day[s.key]} + ))} + + ))} + + + + )} + + ); +} diff --git a/src/WebUI/src/components/code-editor/StatusBar.tsx b/src/WebUI/src/components/code-editor/StatusBar.tsx new file mode 100644 index 0000000..323a3f5 --- /dev/null +++ b/src/WebUI/src/components/code-editor/StatusBar.tsx @@ -0,0 +1,273 @@ +import { MouseEvent, ReactNode, useState } from 'react'; + +// material-ui +import { alpha } from '@mui/material/styles'; +import ButtonBase from '@mui/material/ButtonBase'; +import Divider from '@mui/material/Divider'; +import ListItemText from '@mui/material/ListItemText'; +import Menu from '@mui/material/Menu'; +import MenuItem from '@mui/material/MenuItem'; +import Stack from '@mui/material/Stack'; +import Tooltip from '@mui/material/Tooltip'; + +// project imports +import type { EditorPrefs } from './prefs'; + +// assets +import CloseCircleOutlined from '@ant-design/icons/CloseCircleOutlined'; +import ColumnWidthOutlined from '@ant-design/icons/ColumnWidthOutlined'; +import DiffOutlined from '@ant-design/icons/DiffOutlined'; +import FunctionOutlined from '@ant-design/icons/FunctionOutlined'; +import LockOutlined from '@ant-design/icons/LockOutlined'; +import PicRightOutlined from '@ant-design/icons/PicRightOutlined'; +import VerticalAlignTopOutlined from '@ant-design/icons/VerticalAlignTopOutlined'; +import WarningOutlined from '@ant-design/icons/WarningOutlined'; + +export interface StatusInfo { + line: number; + column: number; + /** Characters selected across all selections. */ + selected: number; + cursors: number; + tabSize: number; + insertSpaces: boolean; + eol: 'LF' | 'CRLF'; + errors: number; + warnings: number; + /** The function the cursor is in. */ + scope?: string; + /** Changed blocks against the saved text. */ + changes: number; +} + +interface Props { + info: StatusInfo; + languageLabel: string; + readOnly: boolean; + prefs: EditorPrefs; + /** Compare with Saved is available (a saved text exists). */ + canCompare: boolean; + comparing: boolean; + onRun: (actionId: string) => void; + onIndentation: (insertSpaces: boolean, tabSize: number) => void; + onConvertIndentation: (toSpaces: boolean) => void; + onEol: (eol: 'LF' | 'CRLF') => void; + onTogglePref: (key: keyof EditorPrefs) => void; + onToggleCompare: () => void; +} + +function Item({ + title, + onClick, + children, + active +}: { + title: string; + onClick?: (event: MouseEvent) => void; + children: ReactNode; + active?: boolean; +}) { + const content = ( + ({ + height: 1, + px: 0.875, + gap: 0.625, + fontSize: '0.75rem', + lineHeight: 1, + whiteSpace: 'nowrap', + borderRadius: 0.5, + color: active ? 'primary.main' : 'text.secondary', + '&:hover': { bgcolor: 'action.hover', color: active ? 'primary.main' : 'text.primary' }, + '&.Mui-focusVisible': { outline: `1px solid ${theme.palette.primary.main}` }, + '&.Mui-disabled': { color: 'text.secondary' }, + '& .anticon': { fontSize: '0.8rem' } + })} + > + {children} + + ); + return onClick ? ( + + {content} + + ) : ( + content + ); +} + +// ==============================|| CODE EDITOR - STATUS BAR ||============================== // + +/** The strip under the editor, after VS Code's: position, problems, indentation, line endings and view toggles. */ +export default function StatusBar({ + info, + languageLabel, + readOnly, + prefs, + canCompare, + comparing, + onRun, + onIndentation, + onConvertIndentation, + onEol, + onTogglePref, + onToggleCompare +}: Props) { + const [menu, setMenu] = useState<{ anchor: HTMLElement; kind: 'indent' | 'eol' } | null>(null); + const close = () => setMenu(null); + + const position = + info.cursors > 1 + ? `${info.cursors} selections${info.selected ? ` (${info.selected} selected)` : ''}` + : `Ln ${info.line}, Col ${info.column}${info.selected ? ` (${info.selected} selected)` : ''}`; + + return ( + ({ + height: 26, + flex: 'none', + alignItems: 'stretch', + px: 0.5, + py: 0.25, + gap: 0.25, + borderTop: '1px solid', + borderColor: 'divider', + bgcolor: alpha(theme.palette.text.primary, 0.025), + overflowX: 'auto', + scrollbarWidth: 'none', + userSelect: 'none' + })} + > + {info.scope && ( + onRun('editor.action.quickOutline')}> + + {info.scope} + + )} + onRun('editor.action.marker.next')}> + + {info.errors} + + {info.warnings} + + {canCompare && info.changes > 0 && ( + + + {info.changes === 1 ? '1 change' : `${info.changes} changes`} + + )} + + + + {readOnly && ( + + + Read Only + + )} + onRun('editor.action.gotoLine')}> + {position} + + setMenu({ anchor: e.currentTarget, kind: 'indent' })}> + {info.insertSpaces ? `Spaces: ${info.tabSize}` : `Tab Size: ${info.tabSize}`} + + UTF-8 + setMenu({ anchor: e.currentTarget, kind: 'eol' })}> + {info.eol} + + onRun('editor.action.quickCommand')}> + {languageLabel} + + + onTogglePref('wordWrap')} active={prefs.wordWrap}> + + + onTogglePref('stickyScroll')} + active={prefs.stickyScroll} + > + + + onTogglePref('minimap')} active={prefs.minimap}> + + + {canCompare && ( + + + + )} + + + {menu?.kind === 'indent' && [ + ...[2, 4, 8].map((size) => ( + { + onIndentation(true, size); + close(); + }} + > + Indent Using Spaces: {size} + + )), + { + onIndentation(false, info.tabSize); + close(); + }} + > + Indent Using Tabs + , + , + { + onConvertIndentation(true); + close(); + }} + > + Convert Indentation to Spaces + , + { + onConvertIndentation(false); + close(); + }} + > + Convert Indentation to Tabs + + ]} + {menu?.kind === 'eol' && + (['LF', 'CRLF'] as const).map((eol) => ( + { + onEol(eol); + close(); + }} + > + {eol} + + ))} + + + ); +} diff --git a/src/WebUI/src/components/code-editor/monaco.ts b/src/WebUI/src/components/code-editor/monaco.ts new file mode 100644 index 0000000..b0c6a9c --- /dev/null +++ b/src/WebUI/src/components/code-editor/monaco.ts @@ -0,0 +1,51 @@ +import { registerScriptLanguages, type CompletionContext } from 'utils/monaco/powershell-language'; +import { defineEditorThemes } from 'utils/monaco/themes'; + +// assets +import EditorWorker from 'monaco-editor/editor/editor.worker.js?worker'; + +// types +import type * as Monaco from 'monaco-editor'; + +export interface EditorSource { + intellisense: boolean; + completionContext?: CompletionContext; +} + +/** Each mounted editor's completion settings, by model URI (one set of providers serves them all). */ +export const editorSources = new Map(); + +/** Gutter change bars (against the saved text), drawn like VS Code's. */ +const EDITOR_CSS = ` + .monaco-editor .cg-added, .monaco-editor .cg-modified { margin-left: 5px; } + .monaco-editor .cg-added { border-left: 3px solid #2ea043; } + .monaco-editor .cg-modified { border-left: 3px solid #3b82f6; } + .monaco-editor .cg-deleted-below::after, .monaco-editor .cg-deleted-above::after { + content: ''; position: absolute; left: 5px; border-style: solid; border-width: 4px 0 4px 6px; + border-color: transparent transparent transparent #f85149; } + .monaco-editor .cg-deleted-below::after { bottom: -4px; } + .monaco-editor .cg-deleted-above::after { top: -4px; } +`; + +let monacoLoading: Promise | null = null; + +/** + * Loads Monaco once (lazily, so pages without an editor never pay for it), + * defines the console's themes and registers the script language features. + */ +export function loadMonaco(): Promise { + monacoLoading ??= import('monaco-editor').then((monaco) => { + self.MonacoEnvironment = { getWorker: () => new EditorWorker() }; + defineEditorThemes(monaco); + registerScriptLanguages(monaco, (model) => { + const source = editorSources.get(model.uri.toString())?.current; + return source?.intellisense ? (source.completionContext ?? {}) : null; + }); + const style = document.createElement('style'); + style.dataset.owner = 'code-editor'; + style.textContent = EDITOR_CSS; + document.head.append(style); + return monaco; + }); + return monacoLoading; +} diff --git a/src/WebUI/src/components/code-editor/prefs.ts b/src/WebUI/src/components/code-editor/prefs.ts new file mode 100644 index 0000000..6d2a34b --- /dev/null +++ b/src/WebUI/src/components/code-editor/prefs.ts @@ -0,0 +1,47 @@ +import { useSyncExternalStore } from 'react'; + +/** View preferences shared by every code editor and remembered per browser. */ +export interface EditorPrefs { + minimap: boolean; + wordWrap: boolean; + stickyScroll: boolean; +} + +const KEY = 'editor-prefs'; +const DEFAULTS: EditorPrefs = { minimap: false, wordWrap: false, stickyScroll: true }; + +function read(): EditorPrefs { + try { + return { ...DEFAULTS, ...JSON.parse(localStorage.getItem(KEY) ?? '{}') }; + } catch { + return DEFAULTS; + } +} + +let prefs = read(); +const listeners = new Set<() => void>(); + +export function setEditorPref(key: K, value: EditorPrefs[K]) { + prefs = { ...prefs, [key]: value }; + try { + localStorage.setItem(KEY, JSON.stringify(prefs)); + } catch { + // Private windows: the preference lasts for this page only. + } + listeners.forEach((listener) => listener()); +} + +export function useEditorPrefs(): EditorPrefs { + return useSyncExternalStore( + (listener) => { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + () => prefs + ); +} + +/** For Monaco actions, which run outside React. */ +export const editorPrefs = () => prefs; diff --git a/src/WebUI/src/components/logo/LogoIcon.tsx b/src/WebUI/src/components/logo/LogoIcon.tsx new file mode 100644 index 0000000..2edb56f --- /dev/null +++ b/src/WebUI/src/components/logo/LogoIcon.tsx @@ -0,0 +1,18 @@ +// ==============================|| LOGO ICON ||============================== // + +/** The ExecuteR mark: a cyan X over a bar on a dark tile (assets/icon-source.png). */ +export default function LogoIcon({ size = 32 }: { size?: number }) { + return ( + + + + + + + + + + + + ); +} diff --git a/src/WebUI/src/components/logo/LogoMain.tsx b/src/WebUI/src/components/logo/LogoMain.tsx new file mode 100644 index 0000000..ce5e967 --- /dev/null +++ b/src/WebUI/src/components/logo/LogoMain.tsx @@ -0,0 +1,19 @@ +// material-ui +import Stack from '@mui/material/Stack'; +import Typography from '@mui/material/Typography'; + +// project imports +import LogoIcon from './LogoIcon'; + +// ==============================|| LOGO - ICON + WORDMARK ||============================== // + +export default function LogoMain() { + return ( + + + + ExecuteR + + + ); +} diff --git a/src/WebUI/src/components/logo/index.tsx b/src/WebUI/src/components/logo/index.tsx new file mode 100644 index 0000000..5821239 --- /dev/null +++ b/src/WebUI/src/components/logo/index.tsx @@ -0,0 +1,26 @@ +import { Link } from 'react-router-dom'; + +// material-ui +import { SxProps } from '@mui/material/styles'; +import ButtonBase from '@mui/material/ButtonBase'; + +// project imports +import LogoMain from './LogoMain'; +import LogoIcon from './LogoIcon'; +import { APP_DEFAULT_PATH } from 'config'; + +// ==============================|| MAIN LOGO ||============================== // + +interface Props { + isIcon?: boolean; + sx?: SxProps; + to?: string; +} + +export default function LogoSection({ isIcon, sx, to }: Props) { + return ( + + {isIcon ? : } + + ); +} diff --git a/src/WebUI/src/components/third-party/Notistack.tsx b/src/WebUI/src/components/third-party/Notistack.tsx new file mode 100644 index 0000000..1c17fce --- /dev/null +++ b/src/WebUI/src/components/third-party/Notistack.tsx @@ -0,0 +1,42 @@ +import { ReactNode } from 'react'; + +// material-ui +import { styled } from '@mui/material/styles'; + +// third-party +import { SnackbarProvider } from 'notistack'; + +// assets +import CheckCircleOutlined from '@ant-design/icons/CheckCircleOutlined'; +import CloseCircleOutlined from '@ant-design/icons/CloseCircleOutlined'; +import InfoCircleOutlined from '@ant-design/icons/InfoCircleOutlined'; +import WarningOutlined from '@ant-design/icons/WarningOutlined'; + +const StyledSnackbarProvider = styled(SnackbarProvider)(({ theme }) => ({ + '&.notistack-MuiContent-default': { background: theme.vars.palette.primary.main }, + '&.notistack-MuiContent-error': { background: theme.vars.palette.error.main }, + '&.notistack-MuiContent-success': { background: theme.vars.palette.success.main }, + '&.notistack-MuiContent-info': { background: theme.vars.palette.info.main }, + '&.notistack-MuiContent-warning': { background: theme.vars.palette.warning.main } +})); + +const iconSX = { marginRight: 8, fontSize: '1.15rem' }; + +// ===========================|| SNACKBAR - NOTISTACK ||=========================== // + +export default function Notistack({ children }: { children: ReactNode }) { + return ( + , + error: , + warning: , + info: + }} + > + {children} + + ); +} diff --git a/src/WebUI/src/config.ts b/src/WebUI/src/config.ts new file mode 100644 index 0000000..9593d19 --- /dev/null +++ b/src/WebUI/src/config.ts @@ -0,0 +1,27 @@ +// ==============================|| APP CONSTANTS ||============================== // + +export const APP_DEFAULT_PATH = '/'; +export const DRAWER_WIDTH = 260; +export const MINI_DRAWER_WIDTH = 64; +export const CSS_VAR_PREFIX = ''; + +/** Body and UI typeface (self-hosted via @fontsource/public-sans). */ +export const FONT_FAMILY = `'Public Sans', sans-serif`; +/** Scripts, output, ids and other machine text. */ +export const MONO_FONT_FAMILY = `'Cascadia Code', 'Cascadia Mono', Consolas, 'SFMono-Regular', Menlo, monospace`; + +/** Injected by Vite (PUBLIC_BUILD_VERSION at build time). */ +export const BUILD_VERSION: string = __BUILD_VERSION__; + +export enum ThemeMode { + LIGHT = 'light', + DARK = 'dark', + SYSTEM = 'system' +} + +export const DEFAULT_THEME_MODE: ThemeMode = ThemeMode.SYSTEM; + +export enum NavActionType { + FUNCTION = 'function', + LINK = 'link' +} diff --git a/src/WebUI/src/contexts/AutomationContext.tsx b/src/WebUI/src/contexts/AutomationContext.tsx new file mode 100644 index 0000000..3eb66e8 --- /dev/null +++ b/src/WebUI/src/contexts/AutomationContext.tsx @@ -0,0 +1,46 @@ +import { createContext, ReactNode, useCallback, useMemo, useState } from 'react'; + +// project imports +import RunScriptDialog from 'sections/runs/RunScriptDialog'; +import ScheduleEditor, { SchedulePreset } from 'sections/schedules/ScheduleEditor'; +import type { RunTarget } from 'sections/runs/TargetPicker'; +import type { ScriptTriggerDto } from 'api/types'; + +export interface RunRequest { + scriptId?: string; + targets?: RunTarget[]; +} + +export interface AutomationContextValue { + /** Opens Run Script, optionally with the script and/or targets chosen. */ + openRun: (request?: RunRequest) => void; + /** Opens the schedule editor for a new schedule (preset) or an existing one. */ + openSchedule: (request?: { trigger?: ScriptTriggerDto; preset?: SchedulePreset }) => void; +} + +export const AutomationContext = createContext(undefined); + +// ==============================|| AUTOMATION PROVIDER (RUN NOW + SCHEDULE) ||============================== // + +/** Mounts Run Script and the schedule editor once, so any page or menu can open them. */ +export function AutomationProvider({ children }: { children: ReactNode }) { + const [run, setRun] = useState(null); + const [schedule, setSchedule] = useState<{ trigger?: ScriptTriggerDto; preset?: SchedulePreset } | null>(null); + + const openRun = useCallback((request: RunRequest = {}) => setRun(request), []); + const openSchedule = useCallback((request: { trigger?: ScriptTriggerDto; preset?: SchedulePreset } = {}) => setSchedule(request), []); + const value = useMemo(() => ({ openRun, openSchedule }), [openRun, openSchedule]); + + return ( + + {children} + setRun(null)} scriptId={run?.scriptId} targets={run?.targets} /> + setSchedule(null)} + trigger={schedule?.trigger ?? null} + preset={schedule?.preset} + /> + + ); +} diff --git a/src/WebUI/src/contexts/SessionContext.tsx b/src/WebUI/src/contexts/SessionContext.tsx new file mode 100644 index 0000000..ea93c82 --- /dev/null +++ b/src/WebUI/src/contexts/SessionContext.tsx @@ -0,0 +1,69 @@ +import { createContext, ReactNode, useCallback, useEffect, useMemo, useState } from 'react'; + +// project imports +import { identity } from 'api/identity'; +import { nats } from 'messaging/nats'; +import { markSignedOut } from 'utils/signIn'; +import type { Session } from 'api/identity'; + +export interface SessionContextValue { + /** Undefined until the first session check completes; null when signed out. */ + session: Session | null | undefined; + /** True when the session's roles grant the permission. */ + can: (permission: string) => boolean; + /** Re-reads the session (after sign-in or a password change). */ + refresh: () => Promise; + /** Adopts a session returned by sign-in without another round trip. */ + adopt: (session: Session) => void; + signOut: () => Promise; +} + +export const SessionContext = createContext(undefined); + +// ==============================|| SESSION PROVIDER ||============================== // + +/** Who is signed in, read once for the shell; every page asks `can(permission)` rather than reading roles. */ +export function SessionProvider({ children }: { children: ReactNode }) { + const [session, setSession] = useState(undefined); + + const refresh = useCallback(async () => { + try { + const current = await identity.session(); + setSession(current); + return current; + } catch { + // 401 or unreachable: either way there is no usable session. + setSession(null); + return null; + } + }, []); + + useEffect(() => { + void refresh(); + }, [refresh]); + + // Live updates follow the session: connect once signed in (and past a forced password change), drop on sign-out. + const live = Boolean(session && !session.passwordChangeRequired); + useEffect(() => { + if (live) void nats.start().catch(() => undefined); + }, [live]); + + const signOut = useCallback(async () => { + await nats.stop(); + let endSessionUrl: string | null = null; + try { + endSessionUrl = (await identity.signOut()).endSessionUrl; + } finally { + // The identity provider's own sign-out, when there is one, returns to the sign-in page; redirect mode waits there for the person. + markSignedOut(); + setSession(null); + window.location.assign(endSessionUrl ?? '/sign-in'); + } + }, []); + + const can = useCallback((permission: string) => Boolean(session?.permissions.includes(permission)), [session]); + + const value = useMemo(() => ({ session, can, refresh, adopt: setSession, signOut }), [session, can, refresh, signOut]); + + return {children}; +} diff --git a/src/WebUI/src/hooks/useApi.ts b/src/WebUI/src/hooks/useApi.ts new file mode 100644 index 0000000..86ddc57 --- /dev/null +++ b/src/WebUI/src/hooks/useApi.ts @@ -0,0 +1,13 @@ +import useSWR, { SWRConfiguration } from 'swr'; + +// project imports +import { request } from 'api/client'; + +/** + * Cached GET of an API path (null skips). Every view reading the same path + * shares one request and one cache entry; `mutate(path)` refreshes them all. + */ +export default function useApi(path: string | null, options?: SWRConfiguration) { + const { data, error, isLoading, isValidating, mutate } = useSWR(path, (key: string) => request(key), options); + return { data, error: error as Error | undefined, loading: isLoading, validating: isValidating, mutate }; +} diff --git a/src/WebUI/src/hooks/useAutomation.ts b/src/WebUI/src/hooks/useAutomation.ts new file mode 100644 index 0000000..9120309 --- /dev/null +++ b/src/WebUI/src/hooks/useAutomation.ts @@ -0,0 +1,11 @@ +import { useContext } from 'react'; + +// project imports +import { AutomationContext } from 'contexts/AutomationContext'; + +/** `openRun` (Run Script) and `openSchedule` (schedule editor) from anywhere in the console. */ +export default function useAutomation() { + const context = useContext(AutomationContext); + if (!context) throw new Error('useAutomation must be used inside AutomationProvider'); + return context; +} diff --git a/src/WebUI/src/hooks/useLiveRefresh.ts b/src/WebUI/src/hooks/useLiveRefresh.ts new file mode 100644 index 0000000..2f9713f --- /dev/null +++ b/src/WebUI/src/hooks/useLiveRefresh.ts @@ -0,0 +1,30 @@ +import { useEffect, useRef } from 'react'; + +// project imports +import { nats } from 'messaging/nats'; +import type { ActivityEventPayload } from 'api/types'; + +/** + * Calls `refresh` when live activity arrives (optionally only for matching + * events), coalescing bursts — a group run emits one event per device — into + * at most one refresh per `debounceMs`. + */ +export default function useLiveRefresh(refresh: () => unknown, filter?: (event: ActivityEventPayload) => boolean, debounceMs = 750) { + const refreshRef = useRef(refresh); + const filterRef = useRef(filter); + refreshRef.current = refresh; + filterRef.current = filter; + + useEffect(() => { + let timer: number | undefined; + const off = nats.onActivity((event) => { + if (filterRef.current && !filterRef.current(event)) return; + window.clearTimeout(timer); + timer = window.setTimeout(() => void refreshRef.current(), debounceMs); + }); + return () => { + window.clearTimeout(timer); + off(); + }; + }, [debounceMs]); +} diff --git a/src/WebUI/src/hooks/useNow.ts b/src/WebUI/src/hooks/useNow.ts new file mode 100644 index 0000000..b48b8d6 --- /dev/null +++ b/src/WebUI/src/hooks/useNow.ts @@ -0,0 +1,11 @@ +import { useEffect, useState } from 'react'; + +/** The current time, re-read every `intervalMs` so relative times stay fresh. */ +export default function useNow(intervalMs = 30_000): number { + const [now, setNow] = useState(() => Date.now()); + useEffect(() => { + const timer = window.setInterval(() => setNow(Date.now()), intervalMs); + return () => window.clearInterval(timer); + }, [intervalMs]); + return now; +} diff --git a/src/WebUI/src/hooks/useSession.ts b/src/WebUI/src/hooks/useSession.ts new file mode 100644 index 0000000..2870512 --- /dev/null +++ b/src/WebUI/src/hooks/useSession.ts @@ -0,0 +1,16 @@ +import { useContext } from 'react'; + +// project imports +import { SessionContext } from 'contexts/SessionContext'; + +export default function useSession() { + const context = useContext(SessionContext); + if (!context) throw new Error('useSession must be used inside SessionProvider'); + return context; +} + +/** Reason text for a control the session cannot use, or undefined when allowed. */ +export function useGate(permission: string, label?: string): string | undefined { + const { can } = useSession(); + return can(permission) ? undefined : `Needs the ${label ?? permission} permission.`; +} diff --git a/src/WebUI/src/index.tsx b/src/WebUI/src/index.tsx new file mode 100644 index 0000000..015feda --- /dev/null +++ b/src/WebUI/src/index.tsx @@ -0,0 +1,16 @@ +import { createRoot } from 'react-dom/client'; + +// fonts (self-hosted; no third-party requests) +import '@fontsource/public-sans/400.css'; +import '@fontsource/public-sans/500.css'; +import '@fontsource/public-sans/600.css'; +import '@fontsource/public-sans/700.css'; + +import 'assets/style.css'; + +// project imports +import App from './App'; + +// ==============================|| MAIN - REACT DOM RENDER ||============================== // + +createRoot(document.getElementById('root')!).render(); diff --git a/src/WebUI/src/layout/Dashboard/Drawer/DrawerContent/Navigation/NavGroup.tsx b/src/WebUI/src/layout/Dashboard/Drawer/DrawerContent/Navigation/NavGroup.tsx new file mode 100644 index 0000000..40a263e --- /dev/null +++ b/src/WebUI/src/layout/Dashboard/Drawer/DrawerContent/Navigation/NavGroup.tsx @@ -0,0 +1,43 @@ +// material-ui +import List from '@mui/material/List'; +import Typography from '@mui/material/Typography'; +import Box from '@mui/material/Box'; + +// project imports +import NavItem from './NavItem'; +import { useGetMenuMaster } from 'api/menu'; + +// types +import { NavGroupType } from 'types/menu'; + +// ==============================|| NAVIGATION - GROUP ||============================== // + +export default function NavGroup({ item }: { item: NavGroupType }) { + const { menuMaster } = useGetMenuMaster(); + const drawerOpen = menuMaster.isDashboardDrawerOpened; + + return ( + + + {item.title} + +
+ ) : ( + + ) + } + > + {item.children.map((child) => ( + + ))} + + ); +} diff --git a/src/WebUI/src/layout/Dashboard/Drawer/DrawerContent/Navigation/NavItem.tsx b/src/WebUI/src/layout/Dashboard/Drawer/DrawerContent/Navigation/NavItem.tsx new file mode 100644 index 0000000..9cc1ad4 --- /dev/null +++ b/src/WebUI/src/layout/Dashboard/Drawer/DrawerContent/Navigation/NavItem.tsx @@ -0,0 +1,84 @@ +import { Link, matchPath, useLocation } from 'react-router-dom'; + +// material-ui +import useMediaQuery from '@mui/material/useMediaQuery'; +import ListItemButton from '@mui/material/ListItemButton'; +import ListItemIcon from '@mui/material/ListItemIcon'; +import ListItemText from '@mui/material/ListItemText'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; + +// project imports +import { handlerDrawerOpen, useGetMenuMaster } from 'api/menu'; +import useSession from 'hooks/useSession'; + +// types +import { NavItemType } from 'types/menu'; + +// ==============================|| NAVIGATION - LIST ITEM ||============================== // + +export default function NavItem({ item }: { item: NavItemType }) { + const { menuMaster } = useGetMenuMaster(); + const drawerOpen = menuMaster.isDashboardDrawerOpened; + const downLG = useMediaQuery((theme) => theme.breakpoints.down('lg')); + const { pathname } = useLocation(); + const { can } = useSession(); + + const gate = item.permission && !can(item.permission) ? `Needs the ${item.permissionLabel ?? item.permission} permission.` : undefined; + const isSelected = !!matchPath({ path: item.url, end: Boolean(item.exact) }, pathname); + const Icon = item.icon; + + const button = ( + { + if (gate) { + event.preventDefault(); + return; + } + if (downLG) handlerDrawerOpen(false); + }} + sx={{ + mx: drawerOpen ? 1.5 : 1, + my: 0.25, + borderRadius: 1.5, + py: 1, + px: drawerOpen ? 1.5 : 1.25, + justifyContent: drawerOpen ? 'flex-start' : 'center', + ...(gate && { opacity: 0.5, cursor: 'default', '&:hover': { bgcolor: 'transparent' } }), + // Both schemes: dark ramps run darkest-first, so "lighter" is the subtle + // tint there too and "main" stays readable on it. + '&.Mui-selected': { + bgcolor: 'primary.lighter', + color: 'primary.main', + '&:hover': { bgcolor: 'primary.lighter' } + } + }} + > + + + + {drawerOpen && ( + + {item.title} + + } + /> + )} + + ); + + const hint = gate ?? (drawerOpen ? undefined : item.title); + return hint ? ( + + {button} + + ) : ( + button + ); +} diff --git a/src/WebUI/src/layout/Dashboard/Drawer/DrawerContent/Navigation/index.tsx b/src/WebUI/src/layout/Dashboard/Drawer/DrawerContent/Navigation/index.tsx new file mode 100644 index 0000000..414975c --- /dev/null +++ b/src/WebUI/src/layout/Dashboard/Drawer/DrawerContent/Navigation/index.tsx @@ -0,0 +1,18 @@ +// material-ui +import Box from '@mui/material/Box'; + +// project imports +import NavGroup from './NavGroup'; +import menuItems from 'menu-items'; + +// ==============================|| DRAWER CONTENT - NAVIGATION ||============================== // + +export default function Navigation() { + return ( + + {menuItems.map((group) => ( + + ))} + + ); +} diff --git a/src/WebUI/src/layout/Dashboard/Drawer/DrawerContent/index.tsx b/src/WebUI/src/layout/Dashboard/Drawer/DrawerContent/index.tsx new file mode 100644 index 0000000..bd95a36 --- /dev/null +++ b/src/WebUI/src/layout/Dashboard/Drawer/DrawerContent/index.tsx @@ -0,0 +1,28 @@ +// material-ui +import Box from '@mui/material/Box'; +import Typography from '@mui/material/Typography'; + +// project imports +import Navigation from './Navigation'; +import { useGetMenuMaster } from 'api/menu'; +import { BUILD_VERSION } from 'config'; + +// ==============================|| DRAWER CONTENT ||============================== // + +export default function DrawerContent() { + const { menuMaster } = useGetMenuMaster(); + const drawerOpen = menuMaster.isDashboardDrawerOpened; + + return ( + + + + + {drawerOpen && ( + + v{BUILD_VERSION} + + )} + + ); +} diff --git a/src/WebUI/src/layout/Dashboard/Drawer/DrawerHeader/DrawerHeaderStyled.ts b/src/WebUI/src/layout/Dashboard/Drawer/DrawerHeader/DrawerHeaderStyled.ts new file mode 100644 index 0000000..7a1fc6a --- /dev/null +++ b/src/WebUI/src/layout/Dashboard/Drawer/DrawerHeader/DrawerHeaderStyled.ts @@ -0,0 +1,21 @@ +// material-ui +import { styled } from '@mui/material/styles'; +import Box from '@mui/material/Box'; + +// ==============================|| DRAWER HEADER - STYLED ||============================== // + +const DrawerHeaderStyled = styled(Box, { shouldForwardProp: (prop) => prop !== 'open' })<{ open: boolean }>(({ theme }) => ({ + ...theme.mixins.toolbar, + display: 'flex', + alignItems: 'center', + justifyContent: 'center', + paddingLeft: theme.spacing(0), + variants: [ + { + props: ({ open }) => open, + style: { justifyContent: 'flex-start', paddingLeft: theme.spacing(3) } + } + ] +})); + +export default DrawerHeaderStyled; diff --git a/src/WebUI/src/layout/Dashboard/Drawer/DrawerHeader/index.tsx b/src/WebUI/src/layout/Dashboard/Drawer/DrawerHeader/index.tsx new file mode 100644 index 0000000..74fb7ba --- /dev/null +++ b/src/WebUI/src/layout/Dashboard/Drawer/DrawerHeader/index.tsx @@ -0,0 +1,13 @@ +// project imports +import DrawerHeaderStyled from './DrawerHeaderStyled'; +import Logo from 'components/logo'; + +// ==============================|| DRAWER HEADER ||============================== // + +export default function DrawerHeader({ open }: { open: boolean }) { + return ( + + + + ); +} diff --git a/src/WebUI/src/layout/Dashboard/Drawer/MiniDrawerStyled.ts b/src/WebUI/src/layout/Dashboard/Drawer/MiniDrawerStyled.ts new file mode 100644 index 0000000..7c53b1f --- /dev/null +++ b/src/WebUI/src/layout/Dashboard/Drawer/MiniDrawerStyled.ts @@ -0,0 +1,56 @@ +// material-ui +import { styled, Theme, CSSObject } from '@mui/material/styles'; +import Drawer from '@mui/material/Drawer'; + +// project imports +import { DRAWER_WIDTH } from 'config'; + +const openedMixin = (theme: Theme) => + ({ + width: DRAWER_WIDTH, + borderRight: '1px solid', + borderRightColor: theme.vars.palette.divider, + + transition: theme.transitions.create('width', { + easing: theme.transitions.easing.sharp, + duration: theme.transitions.duration.enteringScreen + }), + + overflowX: 'hidden', + boxShadow: 'none', + ...theme.applyStyles('dark', { boxShadow: theme.vars.customShadows.z1 }) + }) as CSSObject; + +const closedMixin = (theme: Theme) => + ({ + transition: theme.transitions.create('width', { + easing: theme.transitions.easing.sharp, + duration: theme.transitions.duration.leavingScreen + }), + + overflowX: 'hidden', + width: theme.spacing(7.5), + borderRight: 'none', + boxShadow: theme.vars.customShadows.z1 + }) as CSSObject; + +// ==============================|| DRAWER - MINI STYLED ||============================== // + +const MiniDrawerStyled = styled(Drawer, { shouldForwardProp: (prop) => prop !== 'open' })(({ theme }) => ({ + width: DRAWER_WIDTH, + flexShrink: 0, + whiteSpace: 'nowrap', + boxSizing: 'border-box', + variants: [ + { + props: ({ open }) => open, + style: { ...openedMixin(theme), '& .MuiDrawer-paper': openedMixin(theme) } + }, + { + props: ({ open }) => !open, + style: { ...closedMixin(theme), '& .MuiDrawer-paper': closedMixin(theme) } + } + ] +})); + +export default MiniDrawerStyled; diff --git a/src/WebUI/src/layout/Dashboard/Drawer/index.tsx b/src/WebUI/src/layout/Dashboard/Drawer/index.tsx new file mode 100644 index 0000000..7cfc664 --- /dev/null +++ b/src/WebUI/src/layout/Dashboard/Drawer/index.tsx @@ -0,0 +1,68 @@ +import { useMemo } from 'react'; + +// material-ui +import { Theme } from '@mui/material/styles'; +import useMediaQuery from '@mui/material/useMediaQuery'; +import Drawer from '@mui/material/Drawer'; +import Box from '@mui/material/Box'; + +// project imports +import DrawerHeader from './DrawerHeader'; +import DrawerContent from './DrawerContent'; +import MiniDrawerStyled from './MiniDrawerStyled'; + +import { DRAWER_WIDTH } from 'config'; +import { handlerDrawerOpen, useGetMenuMaster } from 'api/menu'; + +interface Props { + window?: () => Window; +} + +// ==============================|| MAIN LAYOUT - DRAWER ||============================== // + +export default function MainDrawer({ window }: Props) { + const { menuMaster } = useGetMenuMaster(); + const drawerOpen = menuMaster.isDashboardDrawerOpened; + const downLG = useMediaQuery((theme: Theme) => theme.breakpoints.down('lg')); + + // responsive drawer container + const container = window !== undefined ? () => window().document.body : undefined; + + // header content + const drawerContent = useMemo(() => , []); + const drawerHeader = useMemo(() => , [drawerOpen]); + + return ( + + {!downLG ? ( + + {drawerHeader} + {drawerContent} + + ) : ( + handlerDrawerOpen(!drawerOpen)} + ModalProps={{ keepMounted: true }} + sx={{ display: { xs: drawerOpen ? 'block' : 'none', lg: 'none' } }} + slotProps={{ + paper: { + sx: { + boxSizing: 'border-box', + width: DRAWER_WIDTH, + borderRight: '1px solid', + borderRightColor: 'divider', + boxShadow: 'inherit' + } + } + }} + > + {drawerHeader} + {drawerContent} + + )} + + ); +} diff --git a/src/WebUI/src/layout/Dashboard/Header/AppBarStyled.tsx b/src/WebUI/src/layout/Dashboard/Header/AppBarStyled.tsx new file mode 100644 index 0000000..e414c2d --- /dev/null +++ b/src/WebUI/src/layout/Dashboard/Header/AppBarStyled.tsx @@ -0,0 +1,41 @@ +// material-ui +import { styled } from '@mui/material/styles'; +import AppBar, { AppBarProps as MuiAppBarProps } from '@mui/material/AppBar'; + +// project imports +import { DRAWER_WIDTH } from 'config'; + +// ==============================|| HEADER - APP BAR STYLED ||============================== // + +interface Props extends MuiAppBarProps { + open?: boolean; +} + +const AppBarStyled = styled(AppBar, { shouldForwardProp: (prop) => prop !== 'open' })(({ theme }) => ({ + zIndex: theme.zIndex.drawer + 1, + transition: theme.transitions.create(['width', 'margin'], { + easing: theme.transitions.easing.sharp, + duration: theme.transitions.duration.leavingScreen + }), + variants: [ + { + props: ({ open }) => !open, + style: { + width: `calc(100% - ${theme.spacing(7.5)})` + } + }, + { + props: ({ open }) => open, + style: { + marginLeft: DRAWER_WIDTH, + width: `calc(100% - ${DRAWER_WIDTH}px)`, + transition: theme.transitions.create(['width', 'margin'], { + easing: theme.transitions.easing.sharp, + duration: theme.transitions.duration.enteringScreen + }) + } + } + ] +})); + +export default AppBarStyled; diff --git a/src/WebUI/src/layout/Dashboard/Header/HeaderContent/index.tsx b/src/WebUI/src/layout/Dashboard/Header/HeaderContent/index.tsx new file mode 100644 index 0000000..412d031 --- /dev/null +++ b/src/WebUI/src/layout/Dashboard/Header/HeaderContent/index.tsx @@ -0,0 +1,189 @@ +import { useState } from 'react'; + +// material-ui +import { useColorScheme } from '@mui/material/styles'; +import Box from '@mui/material/Box'; +import ButtonBase from '@mui/material/ButtonBase'; +import Chip from '@mui/material/Chip'; +import Dialog from '@mui/material/Dialog'; +import DialogContent from '@mui/material/DialogContent'; +import DialogTitle from '@mui/material/DialogTitle'; +import Divider from '@mui/material/Divider'; +import ListItemIcon from '@mui/material/ListItemIcon'; +import ListItemText from '@mui/material/ListItemText'; +import Menu from '@mui/material/Menu'; +import MenuItem from '@mui/material/MenuItem'; +import Stack from '@mui/material/Stack'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; + +// project imports +import Avatar from 'components/@extended/Avatar'; +import Dot from 'components/@extended/Dot'; +import IconButton from 'components/@extended/IconButton'; +import Properties from 'components/Properties'; +import useSession from 'hooks/useSession'; +import { PROVIDER_LABELS } from 'api/identity'; +import { useLiveState } from 'messaging/nats'; + +// assets +import BulbOutlined from '@ant-design/icons/BulbOutlined'; +import IdcardOutlined from '@ant-design/icons/IdcardOutlined'; +import LogoutOutlined from '@ant-design/icons/LogoutOutlined'; +import MoonOutlined from '@ant-design/icons/MoonOutlined'; +import SunOutlined from '@ant-design/icons/SunOutlined'; + +// ==============================|| HEADER - LIVE CONNECTION ||============================== // + +function ConnectionIndicator() { + const state = useLiveState(); + const tone = state === 'connected' ? 'success' : state === 'connecting' ? 'warning' : 'secondary'; + const label = state === 'connected' ? 'Live' : state === 'connecting' ? 'Connecting' : 'Offline'; + const help = + state === 'connected' + ? 'Device activity and job output arrive as they happen.' + : 'The live connection is down; pages still work and refresh on demand.'; + return ( + + } /> + + ); +} + +// ==============================|| HEADER - THEME MODE ||============================== // + +const MODES = [ + { mode: 'system', label: 'Match System', icon: BulbOutlined }, + { mode: 'light', label: 'Light', icon: SunOutlined }, + { mode: 'dark', label: 'Dark', icon: MoonOutlined } +] as const; + +function ThemeModeToggle() { + const { mode, setMode } = useColorScheme(); + const current = MODES.find((m) => m.mode === mode) ?? MODES[0]; + const next = MODES[(MODES.indexOf(current) + 1) % MODES.length]; + const Icon = current.icon; + return ( + + setMode(next.mode)} aria-label="Change appearance"> + + + + ); +} + +// ==============================|| HEADER - USER MENU ||============================== // + +function UserMenu() { + const { session, signOut } = useSession(); + const [anchor, setAnchor] = useState(null); + const [details, setDetails] = useState(false); + const name = session?.displayName || session?.userName || 'Signed in'; + const windows = session?.provider === 'windows'; + const roles = session?.breakGlass ? 'Break-Glass' : (session?.roles.map((r) => r.name).join(', ') ?? ''); + const initials = name + .replace(/^.*\\/, '') + .split(/[\s._@-]+/) + .filter(Boolean) + .slice(0, 2) + .map((part) => part[0]!.toUpperCase()) + .join(''); + + return ( + <> + setAnchor(e.currentTarget)} + aria-label="Account" + sx={{ borderRadius: 1, px: 0.75, py: 0.5, '&:hover': { bgcolor: 'secondary.lighter' } }} + > + + + {initials || '?'} + + + + {name} + + + {roles} + + + + + setAnchor(null)} + anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }} + transformOrigin={{ vertical: 'top', horizontal: 'right' }} + slotProps={{ paper: { sx: { minWidth: 220 } } }} + > + + {name} + + {session?.userName} + {session ? ` · ${PROVIDER_LABELS[session.provider] ?? session.provider}` : ''} + + {session?.breakGlass && ( + + )} + + + {windows && ( + { + setAnchor(null); + setDetails(true); + }} + > + + + + Account Details + + )} + { + setAnchor(null); + void signOut(); + }} + > + + + + Sign Out + + + {windows && session && ( + setDetails(false)} maxWidth="sm" fullWidth> + {name} + + g.name).join(', ') || '—' } + ]} + /> + + + )} + + ); +} + +// ==============================|| HEADER - CONTENT ||============================== // + +export default function HeaderContent() { + return ( + <> + + + + + + + + ); +} diff --git a/src/WebUI/src/layout/Dashboard/Header/index.tsx b/src/WebUI/src/layout/Dashboard/Header/index.tsx new file mode 100644 index 0000000..fbbe74d --- /dev/null +++ b/src/WebUI/src/layout/Dashboard/Header/index.tsx @@ -0,0 +1,64 @@ +// material-ui +import useMediaQuery from '@mui/material/useMediaQuery'; +import AppBar, { AppBarProps } from '@mui/material/AppBar'; +import Toolbar from '@mui/material/Toolbar'; + +// project imports +import AppBarStyled from './AppBarStyled'; +import HeaderContent from './HeaderContent'; +import IconButton from 'components/@extended/IconButton'; +import { handlerDrawerOpen, useGetMenuMaster } from 'api/menu'; +import { DRAWER_WIDTH, MINI_DRAWER_WIDTH } from 'config'; + +// assets +import MenuFoldOutlined from '@ant-design/icons/MenuFoldOutlined'; +import MenuUnfoldOutlined from '@ant-design/icons/MenuUnfoldOutlined'; + +// ==============================|| MAIN LAYOUT - HEADER ||============================== // + +export default function Header() { + const downLG = useMediaQuery((theme) => theme.breakpoints.down('lg')); + const { menuMaster } = useGetMenuMaster(); + const drawerOpen = menuMaster.isDashboardDrawerOpened; + + const toolbar = ( + + handlerDrawerOpen(!drawerOpen, !downLG)} + edge="start" + color="secondary" + variant="light" + sx={(theme) => ({ + color: 'text.primary', + bgcolor: drawerOpen ? 'transparent' : 'grey.100', + ...theme.applyStyles('dark', { bgcolor: drawerOpen ? 'transparent' : 'background.default' }), + ml: { xs: 0, lg: -2 } + })} + > + {!drawerOpen ? : } + + + + ); + + const appBar: AppBarProps = { + position: 'fixed', + color: 'inherit', + elevation: 0, + sx: { + borderBottom: '1px solid', + borderBottomColor: 'divider', + zIndex: 1200, + width: { xs: '100%', lg: drawerOpen ? `calc(100% - ${DRAWER_WIDTH}px)` : `calc(100% - ${MINI_DRAWER_WIDTH}px)` } + } + }; + + return !downLG ? ( + + {toolbar} + + ) : ( + {toolbar} + ); +} diff --git a/src/WebUI/src/layout/Dashboard/index.tsx b/src/WebUI/src/layout/Dashboard/index.tsx new file mode 100644 index 0000000..02b72e9 --- /dev/null +++ b/src/WebUI/src/layout/Dashboard/index.tsx @@ -0,0 +1,46 @@ +import { useEffect } from 'react'; +import { Outlet } from 'react-router-dom'; + +// material-ui +import { Theme } from '@mui/material/styles'; +import useMediaQuery from '@mui/material/useMediaQuery'; +import Box from '@mui/material/Box'; +import Stack from '@mui/material/Stack'; +import Toolbar from '@mui/material/Toolbar'; + +// project imports +import Drawer from './Drawer'; +import Header from './Header'; +import RequireAuth from 'utils/route-guard/RequireAuth'; +import { AutomationProvider } from 'contexts/AutomationContext'; +import ShellWindows from 'sections/shell/ShellWindows'; +import { handlerDrawerOpen } from 'api/menu'; + +// ==============================|| MAIN LAYOUT ||============================== // + +export default function DashboardLayout() { + const downLG = useMediaQuery((theme: Theme) => theme.breakpoints.down('lg')); + + // Below lg the drawer is a temporary overlay: start it closed. + useEffect(() => { + if (downLG) handlerDrawerOpen(false); + }, [downLG]); + + return ( + + + +
+ + + + + + + + + + + + ); +} diff --git a/src/WebUI/src/lib/api/client.ts b/src/WebUI/src/lib/api/client.ts deleted file mode 100644 index 3fdb44e..0000000 --- a/src/WebUI/src/lib/api/client.ts +++ /dev/null @@ -1,347 +0,0 @@ -import type { - BootstrapTokenDto, - BrowserCredentialResponse, - CreateShellResponse, - DeviceDetailDto, - DeviceDto, - DeviceGroupDto, - FunctionModuleDto, - GroupFieldDescriptor, - GroupKind, - GroupRuleSet, - GroupRunDto, - JobDto, - DashboardDto, - JobOutputRecordDto, - ExecutionSummaryDto, - ExecutionDetailDto, - AgentPackageStatusDto, - AuthConfigDto, - AuthSettingsDto, - AuthTestResultDto, - PermissionGroupDto, - RoleDto, - SaveRoleBody, - UserAccountDto, - S3SettingsDto, - S3TestResultDto, - ScriptDto, - ServerInfoDto, - ScriptParameter, - ScriptFileBinding, - ScriptTriggerDto, - ScriptTriggerType, - SecretBinding, - SecretsProviderDto, - SecretsProvidersResponse, - SecretsTestResultDto, - SessionResponse -} from './types'; - -interface SaveScriptBody { - name: string; - description?: string; - content: string; - parameters?: ScriptParameter[]; - functionModuleIds?: string[]; - secretBindings?: SecretBinding[]; - secretsVariableName?: string; - engine?: string; - fileBindings?: ScriptFileBinding[]; -} - -interface SaveSecretsProviderBody { - name: string; - kind: string; - config: Record; -} - -interface SaveGroupBody { - name: string; - description?: string; - kind: GroupKind; - rules?: GroupRuleSet; -} - -export class ApiError extends Error { - constructor( - public status: number, - message: string - ) { - super(message); - } -} - -function readCookie(name: string): string | undefined { - if (typeof document === 'undefined') return undefined; - return document.cookie - .split('; ') - .find((c) => c.startsWith(`${name}=`)) - ?.split('=')[1]; -} - -async function request(path: string, init?: RequestInit): Promise { - const method = (init?.method ?? 'GET').toUpperCase(); - const headers: Record = {}; - if (init?.body) { - headers['Content-Type'] = 'application/json'; - } - // Double-submit CSRF token for state-changing cookie-authenticated calls. - if (!['GET', 'HEAD', 'OPTIONS'].includes(method)) { - const csrf = readCookie('csrf_token'); - if (csrf) headers['X-CSRF-Token'] = csrf; - } - - const response = await fetch(path, { - credentials: 'same-origin', - ...init, - headers: { ...headers, ...(init?.headers as Record) } - }); - - if (!response.ok) { - // Session expired: bounce to login (except while checking the session). - if ( - response.status === 401 && - typeof window !== 'undefined' && - !path.endsWith('/api/auth/session') && - !window.location.pathname.startsWith('/login') - ) { - window.location.href = '/login'; - } - - let detail = response.statusText; - try { - const body = await response.json(); - detail = body?.error ?? body?.title ?? detail; - } catch { - // Non-JSON error body. - } - throw new ApiError(response.status, detail); - } - - if (response.status === 204) { - return undefined as T; - } - - return (await response.json()) as T; -} - -export const api = { - // Auth - session: () => request('/api/auth/session'), - login: (username: string, password: string) => - request('/api/auth/login', { - method: 'POST', - body: JSON.stringify({ username, password }) - }), - changePassword: (username: string, currentPassword: string, newPassword: string) => - request('/api/auth/change-password', { - method: 'POST', - body: JSON.stringify({ username, currentPassword, newPassword }) - }), - logout: () => request('/api/auth/logout', { method: 'POST' }), - - // Devices - devices: () => request('/api/devices'), - device: (clientId: string) => request(`/api/devices/${clientId}`), - refreshInventory: (clientId: string) => - request(`/api/devices/${clientId}/inventory`, { method: 'POST' }), - openShell: ( - clientId: string, - body: { browserSessionId: string; cols: number; rows: number } - ) => - request(`/api/devices/${clientId}/shell`, { - method: 'POST', - body: JSON.stringify(body) - }), - sendFile: ( - clientId: string, - body: { objectKey: string; destinationPath: string; sha256?: string } - ) => - request(`/api/devices/${clientId}/files`, { - method: 'POST', - body: JSON.stringify(body) - }), - - // Scripts - scripts: () => request('/api/scripts'), - script: (id: string) => request(`/api/scripts/${id}`), - createScript: (body: SaveScriptBody) => - request('/api/scripts', { method: 'POST', body: JSON.stringify(body) }), - updateScript: (id: string, body: SaveScriptBody) => - request(`/api/scripts/${id}`, { method: 'PUT', body: JSON.stringify(body) }), - deleteScript: (id: string) => request(`/api/scripts/${id}`, { method: 'DELETE' }), - - // Function modules - functions: () => request('/api/functions'), - functionModule: (id: string) => request(`/api/functions/${id}`), - createFunction: (body: { name: string; description?: string; content: string }) => - request('/api/functions', { method: 'POST', body: JSON.stringify(body) }), - updateFunction: (id: string, body: { name: string; description?: string; content: string }) => - request(`/api/functions/${id}`, { method: 'PUT', body: JSON.stringify(body) }), - deleteFunction: (id: string) => request(`/api/functions/${id}`, { method: 'DELETE' }), - - // Jobs - dashboard: () => request('/api/dashboard'), - - jobs: (clientId?: string, limit?: number, scriptId?: string) => { - const params = new URLSearchParams(); - if (clientId) params.set('clientId', clientId); - if (limit) params.set('limit', String(limit)); - if (scriptId) params.set('scriptId', scriptId); - const qs = params.size > 0 ? `?${params}` : ''; - return request(`/api/jobs${qs}`); - }, - job: (jobId: string) => request(`/api/jobs/${jobId}`), - jobOutput: (jobId: string, afterSequence?: number) => - request( - `/api/jobs/${jobId}/output${afterSequence ? `?afterSequence=${afterSequence}` : ''}` - ), - scriptExecutions: (scriptId: string) => - request(`/api/scripts/${scriptId}/executions`), - execution: (runId: string) => request(`/api/executions/${runId}`), - createJob: (clientId: string, scriptId: string, args?: Record) => - request('/api/jobs', { - method: 'POST', - body: JSON.stringify({ clientId, scriptId, arguments: args }) - }), - createGroupJob: (groupId: string, scriptId: string, args?: Record) => - request('/api/jobs', { - method: 'POST', - body: JSON.stringify({ groupId, scriptId, arguments: args }) - }), - createGroupsJob: (groupIds: string[], scriptId: string, args?: Record) => - request('/api/jobs', { - method: 'POST', - body: JSON.stringify({ groupIds, scriptId, arguments: args }) - }), - - - // Groups - groups: () => request('/api/groups'), - group: (id: string) => request(`/api/groups/${id}`), - createGroup: (body: SaveGroupBody) => - request('/api/groups', { method: 'POST', body: JSON.stringify(body) }), - updateGroup: (id: string, body: SaveGroupBody) => - request(`/api/groups/${id}`, { method: 'PUT', body: JSON.stringify(body) }), - deleteGroup: (id: string) => request(`/api/groups/${id}`, { method: 'DELETE' }), - groupMembers: (id: string) => request(`/api/groups/${id}/members`), - updateGroupMembers: (id: string, add: string[], remove: string[]) => - request(`/api/groups/${id}/members`, { - method: 'POST', - body: JSON.stringify({ add, remove }) - }), - previewGroup: (rules: GroupRuleSet) => - request('/api/groups/preview', { - method: 'POST', - body: JSON.stringify({ rules }) - }), - groupFields: () => request('/api/groups/fields'), - updateDeviceTags: (clientId: string, tags: string[]) => - request(`/api/devices/${clientId}/tags`, { - method: 'PUT', - body: JSON.stringify({ tags }) - }), - - // Script triggers - triggers: () => request('/api/triggers'), - createTrigger: (body: { - scriptId: string; - triggerType: ScriptTriggerType; - clientId?: string; - groupId?: string; - enabled?: boolean; - cronExpression?: string; - runOnceUtc?: string; - timeZoneId?: string; - arguments?: Record; - }) => request<{ id: string }>('/api/triggers', { method: 'POST', body: JSON.stringify(body) }), - setTriggerEnabled: (id: string, enabled: boolean) => - request(`/api/triggers/${id}`, { method: 'PATCH', body: JSON.stringify({ enabled }) }), - deleteTrigger: (id: string) => request(`/api/triggers/${id}`, { method: 'DELETE' }), - - // Messaging - messagingCredential: (nkeyPublic: string, browserSessionId?: string) => - request('/api/messaging/credential', { - method: 'POST', - body: JSON.stringify({ nkeyPublic, browserSessionId }) - }), - - // Access control - permissionCatalog: () => request('/api/admin/permissions'), - roles: () => request('/api/admin/roles'), - createRole: (body: SaveRoleBody) => - request('/api/admin/roles', { method: 'POST', body: JSON.stringify(body) }), - updateRole: (id: string, body: SaveRoleBody) => - request(`/api/admin/roles/${id}`, { method: 'PUT', body: JSON.stringify(body) }), - deleteRole: (id: string) => request(`/api/admin/roles/${id}`, { method: 'DELETE' }), - users: () => request('/api/admin/users'), - createUser: (body: { username: string; password: string; roleId: string; displayName?: string }) => - request('/api/admin/users', { method: 'POST', body: JSON.stringify(body) }), - updateUser: (id: string, body: { displayName?: string; roleId?: string; password?: string }) => - request(`/api/admin/users/${id}`, { method: 'PUT', body: JSON.stringify(body) }), - deleteUser: (id: string) => request(`/api/admin/users/${id}`, { method: 'DELETE' }), - - // Settings: authentication - authConfig: () => request('/api/auth/config'), - authSettings: () => request('/api/settings/auth'), - saveAuthSettings: (body: AuthSettingsDto) => - request('/api/settings/auth', { method: 'PUT', body: JSON.stringify(body) }), - testAuthSettings: (body: AuthSettingsDto) => - request('/api/settings/auth/test', { method: 'POST', body: JSON.stringify(body) }), - - // Settings: S3 + agent package delivery - s3Settings: () => request('/api/settings/s3'), - saveS3Settings: (body: S3SettingsDto) => - request('/api/settings/s3', { method: 'PUT', body: JSON.stringify(body) }), - testS3Settings: (body: S3SettingsDto) => - request('/api/settings/s3/test', { method: 'POST', body: JSON.stringify(body) }), - agentPackage: (type: 'msi' | 'zip' = 'msi') => - request(`/api/settings/agent-package?type=${type}`), - offloadAgentPackage: (type: 'msi' | 'zip' = 'msi') => - request<{ message: string; status: AgentPackageStatusDto }>( - `/api/settings/agent-package/offload?type=${type}`, - { method: 'POST' } - ), - - // Secrets providers - secretsProviders: () => request('/api/secrets/providers'), - createSecretsProvider: (body: SaveSecretsProviderBody) => - request('/api/secrets/providers', { - method: 'POST', - body: JSON.stringify(body) - }), - updateSecretsProvider: (id: string, body: SaveSecretsProviderBody) => - request(`/api/secrets/providers/${id}`, { - method: 'PUT', - body: JSON.stringify(body) - }), - deleteSecretsProvider: (id: string) => - request(`/api/secrets/providers/${id}`, { method: 'DELETE' }), - testSecretsProvider: (body: SaveSecretsProviderBody & { id?: string }) => - request('/api/secrets/providers/test', { - method: 'POST', - body: JSON.stringify(body) - }), - secretNames: (providerId: string, path?: string) => - request( - `/api/secrets/providers/${providerId}/secret-names${path ? `?path=${encodeURIComponent(path)}` : ''}` - ), - secretFolders: (providerId: string, path?: string) => - request( - `/api/secrets/providers/${providerId}/folders${path ? `?path=${encodeURIComponent(path)}` : ''}` - ), - - // Server info (public base URL for generated commands) - serverInfo: () => request('/api/settings/server'), - - // Admin - bootstrapTokens: () => request('/api/admin/bootstrap-tokens'), - createBootstrapToken: (body: { validMinutes?: number; maxUses?: number; note?: string }) => - request('/api/admin/bootstrap-tokens', { - method: 'POST', - body: JSON.stringify(body) - }), - revokeBootstrapToken: (id: string) => - request(`/api/admin/bootstrap-tokens/${id}`, { method: 'DELETE' }) -}; diff --git a/src/WebUI/src/lib/api/types.ts b/src/WebUI/src/lib/api/types.ts deleted file mode 100644 index b4a0e2b..0000000 --- a/src/WebUI/src/lib/api/types.ts +++ /dev/null @@ -1,626 +0,0 @@ -// DTO mirror of Shared.Contracts (camelCase wire format). - -export type DeviceStatus = 'online' | 'stale' | 'offline'; - -export type JobState = - | 'queued' - | 'dispatched' - | 'running' - | 'succeeded' - | 'failed' - | 'cancelled' - | 'timedOut'; - -export type OutputStreamKind = - | 'output' - | 'error' - | 'warning' - | 'verbose' - | 'debug' - | 'information' - | 'progress'; - -export type UserRole = 'admin' | 'operator' | 'viewer'; - -export interface DeviceDto { - clientId: string; - hostname: string; - manufacturer?: string; - model?: string; - osCaption?: string; - osVersion?: string; - agentVersion?: string; - ipAddresses: string[]; - status: DeviceStatus; - lastSeenUtc?: string; - enrolledUtc: string; - tags?: string[]; - /** Public IP the agent was last seen from (trusted headers at enroll/refresh). */ - publicIp?: string; -} - -// ── Device grouping ─────────────────────────────────────────────────── - -export type GroupKind = 'static' | 'dynamic'; -export type RuleCombine = 'and' | 'or'; -export type RuleOperator = - | 'equals' - | 'notEquals' - | 'contains' - | 'notContains' - | 'startsWith' - | 'endsWith' - | 'regex' - | 'in' - | 'notIn' - | 'greaterThan' - | 'greaterOrEqual' - | 'lessThan' - | 'lessOrEqual' - | 'exists' - | 'notExists' - | 'inCidr' - | 'notInCidr'; - -export interface RuleCondition { - field: string; - operator: RuleOperator; - value?: string; - negate?: boolean; -} - -export interface RuleGroup { - combine: RuleCombine; - conditions?: RuleCondition[]; - groups?: RuleGroup[]; - negate?: boolean; -} - -export interface GroupRuleSet { - combine: RuleCombine; - groups?: RuleGroup[]; -} - -export interface GroupFieldDescriptor { - field: string; - displayName: string; - category: string; - numeric: boolean; - multiValue: boolean; -} - -export interface DeviceGroupDto { - id: string; - name: string; - description?: string; - kind: GroupKind; - rules?: GroupRuleSet; - memberCount: number; - createdUtc: string; - updatedUtc: string; - updatedBy?: string; -} - -export interface DeviceGroupRefDto { - id: string; - name: string; - kind: GroupKind; -} - -export interface AuthConfigDto { - oidcAvailable: boolean; - showLocalFields: boolean; - autoRedirect: boolean; - providerName?: string; -} - -export type LoginMode = 'LocalOnly' | 'Both' | 'OidcOnly' | 'OidcAutoRedirect'; - -export interface AuthSettingsDto { - oidcEnabled: boolean; - authority?: string; - clientId?: string; - clientSecret?: string | null; - /** Friendly IdP name shown on the sign-in button (e.g. "Authentik", "Entra ID"). */ - providerName?: string; - scopes: string; - nameClaim?: string; - roleClaim?: string; - adminRole?: string; - operatorRole?: string; - viewerRole?: string; - defaultRole: UserRole; - requireMappedRole: boolean; - loginMode: LoginMode; - clientSecretIsSet: boolean; - forcedLocalByEnvironment: boolean; - callbackPath: string; - redirectUri: string; -} - -export interface AuthTestResultDto { - ok: boolean; - steps: S3TestStepDto[]; -} - -export interface S3SettingsDto { - enabled: boolean; - endpoint?: string; - region: string; - bucket?: string; - accessKey?: string; - secretKey?: string | null; - forcePathStyle: boolean; - presignExpirySeconds: number; - secretKeyIsSet: boolean; - agentOffloadEnabled: boolean; - lastTestUtc?: string; - fromEnvironment: boolean; -} - -export interface S3TestStepDto { - name: string; - ok: boolean; - detail?: string; -} - -export interface S3TestResultDto { - ok: boolean; - steps: S3TestStepDto[]; - elapsedMs: number; -} - -export interface AgentPackageStatusDto { - available: boolean; - /** image | volume | s3 | none */ - source: string; - fileName?: string; - sizeBytes?: number; - sha256?: string; - builtUtc?: string; - version?: string; - offloadEnabled: boolean; - offloadUploaded: boolean; -} - -export type ScriptTriggerType = 'onRegistration' | 'onAgentReady' | 'scheduled'; - -export interface ScriptTriggerDto { - id: string; - scriptId: string; - scriptName: string; - groupId?: string; - groupName?: string; - clientId?: string; - clientHostname?: string; - triggerType: ScriptTriggerType; - enabled: boolean; - cronExpression?: string; - runOnceUtc?: string; - timeZoneId: string; - nextRunUtc?: string; - lastRunUtc?: string; - lastResult?: string; - createdUtc: string; -} - -export interface InventoryReport { - identity: { - clientId: string; - hostname: string; - manufacturer?: string; - model?: string; - serialNumber?: string; - biosVersion?: string; - baseboardSerial?: string; - domainOrWorkgroup?: string; - partOfDomain: boolean; - systemType?: string; - systemUuid?: string; - baseboardManufacturer?: string; - baseboardProduct?: string; - }; - os: { - caption?: string; - version?: string; - build?: string; - architecture?: string; - installDateUtc?: string; - lastBootUtc?: string; - edition?: string; - releaseVersion?: string; - productType?: string; - }; - cpu: { name?: string; logicalProcessors: number; cores: number }; - memory: { - deviceLocator?: string; - capacityBytes: number; - manufacturer?: string; - speedMhz?: number; - }[]; - totalPhysicalMemoryBytes: number; - disks: { - model?: string; - serialNumber?: string; - sizeBytes: number; - busType?: string; - index?: number; - }[]; - volumes: { - driveLetter: string; - fileSystem?: string; - totalSizeBytes: number; - freeSpaceBytes: number; - diskIndex?: number; - }[]; - network: { - description?: string; - macAddress?: string; - ipv4Addresses: string[]; - ipv6Addresses: string[]; - gateways: string[]; - dnsServers: string[]; - /** OS interface name: "Ethernet0" on Windows, "eth0"/"en0" on unix. */ - interfaceName?: string; - }[]; - collectedUtc: string; -} - -export interface DeviceDetailDto { - device: DeviceDto; - inventory?: InventoryReport; - inventoryUpdatedUtc?: string; - groups?: DeviceGroupRefDto[]; -} - -export type PrimitiveType = 'string' | 'number' | 'boolean'; -export type ScriptParameterType = 'string' | 'number' | 'boolean' | 'array' | 'hashtable'; - -/** - * String values expand on the target device in the background by default - * (%VAR%, $env:VAR, $()); 'literal' passes the value through exactly as typed. - */ -export type ValueExpansion = 'auto' | 'literal'; - -/** - * An S3 object (or prefix) delivered to the device before the script runs. - * The destination expands on the device (%VAR%, $env:VAR, $(…)) and the - * resolved location reaches the script as $Files.Name — a FileInfo, or a - * DirectoryInfo when directory (recursive) is set. - */ -export interface ScriptFileBinding { - name: string; - objectKey: string; - destinationPath: string; - directory?: boolean; - continueOnFailure?: boolean; -} - -export interface ScriptParameter { - name: string; - type: ScriptParameterType; - required?: boolean; - description?: string; - elementType?: PrimitiveType; - defaultValue?: unknown; - expansion?: ValueExpansion; -} - -/** Result of a group fan-out run: one job per eligible member. */ -export interface GroupRunDto { - jobs: JobDto[]; - skippedOrphaned: string[]; -} - -export interface CountPoint { - label: string; - count: number; -} - -export interface DayPoint { - date: string; - succeeded: number; - failed: number; - other: number; -} - -export interface DashboardDto { - devicesTotal: number; - devicesOnline: number; - devicesStale: number; - devicesOffline: number; - devicesByPlatform: CountPoint[]; - jobsTotal: number; - jobsSucceeded: number; - jobsFailed: number; - jobsInProgress: number; - successRate: number; - jobsByState: CountPoint[]; - jobsByExitCode: CountPoint[]; - jobsByEngine: CountPoint[]; - topTargets: CountPoint[]; - topScripts: CountPoint[]; - timeline: DayPoint[]; - recentRuns: JobDto[]; -} - -export interface ServerInfoDto { - baseUrl: string; - fromEnvironment: boolean; - /** - * The server is serving its managed self-signed chain directly (no proxy - * in between), so generated commands must skip TLS verification — the - * traffic is still encrypted; the roots just aren't distributed. - */ - selfSignedDirect: boolean; -} - -/** - * Script execution engine. PowerShell = embedded in-process PowerShell 7 - * (all platforms, full typed params/$Secrets/expansion). WindowsPowerShell = - * powershell.exe 5.1 (Windows devices). Bash = bash (unix devices, or - * Windows with Git Bash) — parameters/secrets arrive as environment variables. - */ -export type ScriptEngine = 'PowerShell' | 'WindowsPowerShell' | 'Bash'; - -/** One entry of a script's secrets dictionary, resolved server-side at dispatch. */ -export interface SecretBinding { - /** Key inside the injected dictionary (e.g. $Secrets.ApiKey). */ - name: string; - providerId: string; - secretName: string; - path?: string; -} - -export interface ScriptDto { - id: string; - name: string; - description?: string; - language: string; - content: string; - parameters: ScriptParameter[]; - functionModuleIds: string[]; - createdUtc: string; - updatedUtc: string; - createdBy?: string; - updatedBy?: string; - secretBindings?: SecretBinding[]; - secretsVariableName?: string; - fileBindings?: ScriptFileBinding[]; -} - -// ── Secrets providers ───────────────────────────────────────────────── - -export interface SecretsProviderDto { - id: string; - name: string; - kind: string; - /** Driver-specific non-secret settings. */ - config: Record; - /** Secret config fields that currently hold a value. */ - secretFieldsSet: string[]; - updatedUtc: string; - updatedBy?: string; -} - -export interface SecretsProviderKindDto { - kind: string; - displayName: string; - fields: { name: string; label: string; secret: boolean; placeholder?: string }[]; -} - -export interface SecretsProvidersResponse { - providers: SecretsProviderDto[]; - kinds: SecretsProviderKindDto[]; -} - -export interface SecretsTestResultDto { - ok: boolean; - steps: S3TestStepDto[]; -} - -export interface FunctionModuleDto { - id: string; - name: string; - description?: string; - content: string; - createdUtc: string; - updatedUtc: string; - updatedBy?: string; -} - -export interface JobDto { - jobId: string; - clientId: string; - hostname?: string; - scriptId: string; - scriptName: string; - state: JobState; - createdUtc: string; - startedUtc?: string; - completedUtc?: string; - exitCode?: number; - requestedBy?: string; - outputSummary?: string; -} - -export interface JobOutputRecordDto { - sequence: number; - stream: OutputStreamKind; - timestampUtc: string; - text: string; -} - -export interface ExecutionSummaryDto { - runId: string; - scriptId: string; - startedUtc: string; - requestedBy?: string; - total: number; - succeeded: number; - failed: number; - pending: number; -} - -export interface ExecutionTargetDto { - jobId: string; - clientId: string; - hostname?: string; - state: JobState; - exitCode?: number; - createdUtc: string; - startedUtc?: string; - completedUtc?: string; -} - -export interface ExecutionDetailDto { - runId: string; - scriptId: string; - scriptName: string; - startedUtc: string; - requestedBy?: string; - targets: ExecutionTargetDto[]; -} - -export interface SessionResponse { - authenticated: boolean; - username?: string; - displayName?: string; - role?: UserRole; - authProvider?: string; - /** Assigned role name (custom or system). */ - roleName?: string; - /** Effective permission keys; '*' grants everything. */ - permissions?: string[]; - /** Credentials were valid but a new password must be set before a session is issued. */ - mustChangePassword?: boolean; -} - -export interface RoleDto { - id: string; - name: string; - description?: string; - isSystem: boolean; - permissions: string[]; - oidcClaimValues: string[]; - deviceScopeGroupIds: string[]; - userCount: number; -} - -export interface SaveRoleBody { - name: string; - description?: string; - permissions: string[]; - oidcClaimValues?: string[]; - deviceScopeGroupIds?: string[]; -} - -export interface PermissionInfoDto { - key: string; - label: string; - description: string; -} - -export interface PermissionGroupDto { - group: string; - permissions: PermissionInfoDto[]; -} - -export interface UserAccountDto { - id: string; - username: string; - displayName?: string; - authProvider: string; - roleId?: string; - roleName: string; - createdUtc: string; - lastLoginUtc?: string; -} - -export interface BrowserCredentialResponse { - jwt: string; - expiresUtc: string; - browserSessionId: string; - webSocketPath: string; -} - -export interface BootstrapTokenDto { - id: string; - token?: string; - createdUtc: string; - expiresUtc: string; - maxUses: number; - uses: number; - revoked: boolean; - note?: string; - createdBy?: string; -} - -export interface CreateShellResponse { - shellSessionId: string; - clientId: string; - hostname: string; - expiresUtc: string; -} - -// ── Envelope + live payloads ────────────────────────────────────────── - -export interface MessageEnvelope { - messageId: string; - correlationId: string; - causationId?: string; - messageType: string; - schemaVersion: number; - timestampUtc: string; - source: { kind: string; id: string }; - target?: { kind: string; id: string }; - payload: T; -} - -export interface ActivityEventPayload { - kind: string; - text: string; - clientId?: string; - jobId?: string; - timestampUtc: string; -} - -export interface JobOutputPayload { - jobId: string; - clientId: string; - sequence: number; - stream: OutputStreamKind; - timestampUtc: string; - text: string; -} - -export interface JobProgressPayload { - jobId: string; - clientId: string; - activity: string; - statusDescription?: string; - percentComplete?: number; - secondsRemaining?: number; - timestampUtc: string; -} - -export interface JobStatePayload { - jobId: string; - clientId: string; - state: JobState; - exitCode?: number; - timestampUtc: string; - message?: string; -} - -export interface ShellOutputPayload { - sessionId: string; - sequence: number; - dataBase64: string; -} - -export interface ShellStatePayload { - sessionId: string; - state: 'requested' | 'open' | 'closed' | 'failed'; - message?: string; -} diff --git a/src/WebUI/src/lib/assets/favicon.svg b/src/WebUI/src/lib/assets/favicon.svg deleted file mode 100644 index f6d91de..0000000 --- a/src/WebUI/src/lib/assets/favicon.svg +++ /dev/null @@ -1 +0,0 @@ -svelte-logo \ No newline at end of file diff --git a/src/WebUI/src/lib/auth/session.ts b/src/WebUI/src/lib/auth/session.ts deleted file mode 100644 index 36264ca..0000000 --- a/src/WebUI/src/lib/auth/session.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { writable } from 'svelte/store'; -import { goto } from '$app/navigation'; -import { api, ApiError } from '$lib/api/client'; -import type { SessionResponse } from '$lib/api/types'; -import { nats } from '$lib/messaging/nats'; - -export interface SessionState extends SessionResponse { - loaded: boolean; -} - -/** - * True when the session grants the permission. Sessions predating the - * permissions field (or not yet loaded) show everything; the API still - * enforces, so this only affects navigation visibility. - */ -export function hasPermission(state: SessionState, permission: string): boolean { - if (!state.loaded || !state.permissions) return true; - return state.permissions.includes('*') || state.permissions.includes(permission); -} - -function createSessionStore() { - const { subscribe, set } = writable({ authenticated: false, loaded: false }); - - return { - subscribe, - - /** Loads the current session; redirects to /login when unauthenticated. */ - async initialize(): Promise { - try { - const current = await api.session(); - set({ ...current, loaded: true }); - if (!current.authenticated) { - await goto('/login'); - return false; - } - return true; - } catch (error) { - set({ authenticated: false, loaded: true }); - if (error instanceof ApiError && error.status === 401) { - await goto('/login'); - } - return false; - } - }, - - async login(username: string, password: string): Promise { - const result = await api.login(username, password); - set({ ...result, loaded: true }); - return result; - }, - - async logout(): Promise { - await nats.stop(); - try { - await api.logout(); - } finally { - set({ authenticated: false, loaded: true }); - await goto('/login'); - } - } - }; -} - -export const session = createSessionStore(); diff --git a/src/WebUI/src/lib/components/AddDeviceModal.svelte b/src/WebUI/src/lib/components/AddDeviceModal.svelte deleted file mode 100644 index 600d018..0000000 --- a/src/WebUI/src/lib/components/AddDeviceModal.svelte +++ /dev/null @@ -1,371 +0,0 @@ - - - { - if (e.key === 'Escape') close(); - }} -/> - - - - diff --git a/src/WebUI/src/lib/components/AuthSettings.svelte b/src/WebUI/src/lib/components/AuthSettings.svelte deleted file mode 100644 index 8301f94..0000000 --- a/src/WebUI/src/lib/components/AuthSettings.svelte +++ /dev/null @@ -1,379 +0,0 @@ - - -
-

Authentication

- - {#if settings?.forcedLocalByEnvironment} - - {/if} - - {#if !settings} -
loading…
- {:else} -
- Sign-in page -
- {#each modes as mode (mode.value)} - - {/each} -
- {#if ssoModeChosen && !settings.oidcEnabled} -

Enable and configure OIDC below, or saving will be rejected.

- {/if} -
- - - -
- - - - - - - -
- -
- Redirect URI to register at your provider: - {settings.redirectUri} - -
-

- This path is fixed. It must match the provider registration exactly, and letting it drift is - a common cause of sign-in failures with no clear error. -

- -

Group to role mapping

-

- Values from the group/role claim above. The first match wins, checked Admin → Operator → - Viewer. -

-
- - - - -
- - -
- - - {#if statusText}{statusText}{/if} -
- - {#if test} -
    - {#each test.steps as step (step.name)} -
  • - {step.ok ? '✔' : '✕'} - {step.name} - {step.detail ?? ''} -
  • - {/each} -
- {/if} - - - {/if} -
- - diff --git a/src/WebUI/src/lib/components/ConnectionIndicator.svelte b/src/WebUI/src/lib/components/ConnectionIndicator.svelte deleted file mode 100644 index 130335a..0000000 --- a/src/WebUI/src/lib/components/ConnectionIndicator.svelte +++ /dev/null @@ -1,56 +0,0 @@ - - - - - {labels[$live]} - - - diff --git a/src/WebUI/src/lib/components/CopyChip.svelte b/src/WebUI/src/lib/components/CopyChip.svelte deleted file mode 100644 index 4287b7f..0000000 --- a/src/WebUI/src/lib/components/CopyChip.svelte +++ /dev/null @@ -1,86 +0,0 @@ - - - - - diff --git a/src/WebUI/src/lib/components/EmptyState.svelte b/src/WebUI/src/lib/components/EmptyState.svelte deleted file mode 100644 index 1068862..0000000 --- a/src/WebUI/src/lib/components/EmptyState.svelte +++ /dev/null @@ -1,51 +0,0 @@ - - -
- -
{title}
- {#if detail} -
{detail}
- {/if} - {#if children} -
{@render children()}
- {/if} -
- - diff --git a/src/WebUI/src/lib/components/FileBindingsEditor.svelte b/src/WebUI/src/lib/components/FileBindingsEditor.svelte deleted file mode 100644 index 1f9fb73..0000000 --- a/src/WebUI/src/lib/components/FileBindingsEditor.svelte +++ /dev/null @@ -1,109 +0,0 @@ - - -

- Downloaded to the device before the script runs. Destinations expand on the device - (%TEMP%, $env:ProgramData, $(…)) and each entry reaches - the script as $Files.Name — a FileInfo, or a DirectoryInfo when the S3 key is a - prefix delivered recursively. Requires S3 (Settings → File delivery). -

- -{#each bindings as binding, i (i)} -
- - - - - - -
- {#if binding.directory && looksLikeFile(binding.destinationPath)} -

- A directory delivery unpacks into the destination — give a directory, not a file path. -

- {/if} -{/each} - - - - diff --git a/src/WebUI/src/lib/components/JobStateBadge.svelte b/src/WebUI/src/lib/components/JobStateBadge.svelte deleted file mode 100644 index 56060c0..0000000 --- a/src/WebUI/src/lib/components/JobStateBadge.svelte +++ /dev/null @@ -1,68 +0,0 @@ - - -{entry.label} - - diff --git a/src/WebUI/src/lib/components/OsIcon.svelte b/src/WebUI/src/lib/components/OsIcon.svelte deleted file mode 100644 index aa1e1d2..0000000 --- a/src/WebUI/src/lib/components/OsIcon.svelte +++ /dev/null @@ -1,100 +0,0 @@ - - - - - - {#if platform === 'windows'} - - {:else if platform === 'macos'} - - {:else if platform === 'linux'} - - - {:else} - - {/if} - - - diff --git a/src/WebUI/src/lib/components/ParameterInputs.svelte b/src/WebUI/src/lib/components/ParameterInputs.svelte deleted file mode 100644 index 1548082..0000000 --- a/src/WebUI/src/lib/components/ParameterInputs.svelte +++ /dev/null @@ -1,268 +0,0 @@ - - -{#if parameters.length > 0} -
- {#each parameters as p (p.name)} -
- - {#if p.description}
{p.description}
{/if} - - {#if p.type === 'boolean'} - - {:else if p.type === 'number'} - - {:else if p.type === 'string'} - - {:else if p.type === 'array'} -
- {#each arrays[p.name] ?? [] as _, i (i)} -
- {#if p.elementType === 'boolean'} - - {:else} - - {/if} - -
- {/each} - -
- {:else if p.type === 'hashtable'} -
- {#each hashes[p.name] ?? [] as _, i (i)} -
- - {#if hashes[p.name][i].keyType === 'boolean'} - - {:else} - - {/if} - = - - {#if hashes[p.name][i].valueType === 'boolean'} - - {:else} - - {/if} - -
- {/each} - -
- {/if} -
- {/each} -
-{/if} - - diff --git a/src/WebUI/src/lib/components/ParameterSchemaEditor.svelte b/src/WebUI/src/lib/components/ParameterSchemaEditor.svelte deleted file mode 100644 index c71869e..0000000 --- a/src/WebUI/src/lib/components/ParameterSchemaEditor.svelte +++ /dev/null @@ -1,170 +0,0 @@ - - -
- {#if parameters.length === 0} -

No parameters yet. Each parameter becomes a typed input when the script runs.

- {:else} -
- Name - Type - Items - Description - - Literal - - Req. - -
- {#each parameters as param, i (i)} -
- - - -
- {#if param.type === 'array'} - - {:else if param.type === 'hashtable'} - - typed per entry - - {:else} - — - {/if} -
- - - {#if canExpand(param)} - - {:else} - — - {/if} - - -
- {/each} - {/if} - -
- -
-
- - diff --git a/src/WebUI/src/lib/components/RelativeTime.svelte b/src/WebUI/src/lib/components/RelativeTime.svelte deleted file mode 100644 index 70b243b..0000000 --- a/src/WebUI/src/lib/components/RelativeTime.svelte +++ /dev/null @@ -1,27 +0,0 @@ - - -{text} diff --git a/src/WebUI/src/lib/components/RuleBuilder.svelte b/src/WebUI/src/lib/components/RuleBuilder.svelte deleted file mode 100644 index f9e0741..0000000 --- a/src/WebUI/src/lib/components/RuleBuilder.svelte +++ /dev/null @@ -1,229 +0,0 @@ - - -
-
- Match - -
- -
- - {#if (rules.groups ?? []).length === 0} -

- No condition groups yet. A dynamic group with no rules matches no devices. -

- {:else} - {#each rules.groups ?? [] as group, gi (gi)} -
-
- Group {gi + 1} - - -
- - -
- - {#each group.conditions ?? [] as condition, ci (ci)} -
- - - - - {#if needsValue(condition.operator)} - - {:else} - - {/if} - - - -
- {/each} - - {#if (group.conditions ?? []).length === 0} -

No conditions — this group matches nothing.

- {/if} -
- {/each} - {/if} -
- - diff --git a/src/WebUI/src/lib/components/S3Settings.svelte b/src/WebUI/src/lib/components/S3Settings.svelte deleted file mode 100644 index b36c03c..0000000 --- a/src/WebUI/src/lib/components/S3Settings.svelte +++ /dev/null @@ -1,347 +0,0 @@ - - -
-

Object storage (S3)

-

- Used for pushing files to devices and, optionally, for serving the agent installer. Any - S3-compatible store works — AWS S3, MinIO, Backblaze B2. - {#if settings?.fromEnvironment} -
Environment variables provide the current defaults; saving here overrides them. - {/if} -

- - {#if !settings} -
loading…
- {:else} -
- - - - - - - - -
- -
- - - {#if statusText}{statusText}{/if} - {#if settings.lastTestUtc} - Last successful test {new Date(settings.lastTestUtc).toLocaleString()} - {/if} -
- - {#if test} -
    - {#each test.steps as step (step.name)} -
  • - {step.ok ? '✔' : '✕'} - {step.name} - {step.detail ?? ''} -
  • - {/each} -
- {/if} - {/if} -
- -
-

Agent installer delivery

-

- CI bakes the built installer into the backend image, so the URL install command works without - seeding anything. With S3 configured you can optionally offload it, and installs are redirected - to a presigned URL instead of streaming through the control plane. -

- - {#if !agent} -
loading…
- {:else} -
-
Status
-
- {#if agent.available} - Available - {:else} - Missing - {/if} - {sourceLabel[agent.source] ?? agent.source} -
-
File
-
{agent.fileName ?? '—'}{sizeMb ? ` · ${sizeMb} MB` : ''}
-
Version
-
{agent.version ?? '—'}
-
SHA-256
-
{agent.sha256 ?? '—'}
-
- - {#if !agent.available} -

- No installer present. It ships in images built by CI; for a local build run - scripts/Package-Agent.ps1 and mount the output at /data/agent. -

- {/if} - -
- - - {#if agent.offloadUploaded}Uploaded{/if} -
-

- Enabling the toggle takes effect after Save. Uploads are skipped when the same build is - already in the bucket. -

- {/if} -
- - diff --git a/src/WebUI/src/lib/components/ScheduleCadenceEditor.svelte b/src/WebUI/src/lib/components/ScheduleCadenceEditor.svelte deleted file mode 100644 index 5ad4ec2..0000000 --- a/src/WebUI/src/lib/components/ScheduleCadenceEditor.svelte +++ /dev/null @@ -1,287 +0,0 @@ - - - - -
- - - {#if freq === 'minutes' || freq === 'hours'} - - {:else if freq === 'daily' || freq === 'weekly' || freq === 'monthly'} - - {#if freq === 'weekly'} -
- {#each allDays as day (day)} - - {/each} -
- {:else if freq === 'monthly'} - - {/if} - {:else if freq === 'once'} - - {:else if freq === 'cron'} - - {/if} - - {#if freq !== 'once'} - - {/if} - -
- {description} -
-
- - diff --git a/src/WebUI/src/lib/components/SecretBindingsEditor.svelte b/src/WebUI/src/lib/components/SecretBindingsEditor.svelte deleted file mode 100644 index 849dd7f..0000000 --- a/src/WebUI/src/lib/components/SecretBindingsEditor.svelte +++ /dev/null @@ -1,310 +0,0 @@ - - -
- {#if providers.length === 0} -

- No secrets providers configured. Add one under Settings → Secrets providers first. -

- {:else} -
- -

- The server fetches each value at run time and injects them, in order, as a - case-insensitive dictionary: use ${effectiveVar}.{bindings[0]?.name || 'SecretName'} - anywhere in the script. Devices never contact the vault. -

-
- - {#if bindings.length > 0} -
- Key (${effectiveVar}.…) - Provider - Path - Secret - -
- {#each bindings as binding, i (i)} - {@const path = effectivePath(binding)} - {@const key = cacheKey(binding.providerId, path)} - {@const root = defaultPath(binding.providerId)} - {@const parent = parentOf(path, root)} - {@const listed = names[key]} - {@const failed = key in loadErrors} -
- - - - - - - {#if manual[i] || failed || (listed && listed.length === 0)} - - {#if listed && listed.length > 0} - - {/if} - {:else} - - - {/if} - - - -
- {#if failed} -

- Listing failed ({loadErrors[key]}) — type the path and secret name manually. -

- {/if} - {/each} - {/if} - -
- -
- {/if} -
- - diff --git a/src/WebUI/src/lib/components/SecretsProviders.svelte b/src/WebUI/src/lib/components/SecretsProviders.svelte deleted file mode 100644 index 997aeef..0000000 --- a/src/WebUI/src/lib/components/SecretsProviders.svelte +++ /dev/null @@ -1,364 +0,0 @@ - - -
-
-

Secrets providers

- {#if !formOpen} - - {/if} -
-

- External vaults scripts can pull secrets from. The server fetches values at dispatch time and - injects them as a dictionary variable (default $Secrets) — devices and browsers - never talk to the vault, and connection details are encrypted at rest. -

- - {#if providers.length === 0 && !formOpen} -

No providers configured.

- {:else if providers.length > 0} -
- - - - - - - - - - - - {#each providers as provider (provider.id)} - - - - - - - - {#if rowTests[provider.id]} - {@const rowTest = rowTests[provider.id]} - - - - {/if} - {/each} - -
NameKindCredentialsUpdated
{provider.name} - {kinds.find((k) => k.kind === provider.kind)?.displayName ?? provider.kind} - - {#if provider.secretFieldsSet.length > 0} - stored - {:else} - missing - {/if} - {new Date(provider.updatedUtc).toLocaleString()} - - - -
-
    - {#each rowTest?.steps ?? [] as step (step.name)} -
  • - {step.ok ? '✔' : '✕'} - {step.name} - {step.detail ?? ''} -
  • - {/each} -
-
-
- {/if} - - {#if formOpen} -
-

{editing ? `Edit “${editing.name}”` : 'New provider'}

-
- - - {#each kindDef?.fields ?? [] as field (field.name)} - - {/each} -
- -
- - - - {#if statusText}{statusText}{/if} -
- - {#if test} -
    - {#each test.steps as step (step.name)} -
  • - {step.ok ? '✔' : '✕'} - {step.name} - {step.detail ?? ''} -
  • - {/each} -
- {/if} -
- {/if} -
- - diff --git a/src/WebUI/src/lib/components/StatusBadge.svelte b/src/WebUI/src/lib/components/StatusBadge.svelte deleted file mode 100644 index 7c18a5e..0000000 --- a/src/WebUI/src/lib/components/StatusBadge.svelte +++ /dev/null @@ -1,64 +0,0 @@ - - - - - {labels[status]} - - - diff --git a/src/WebUI/src/lib/components/TriggersCard.svelte b/src/WebUI/src/lib/components/TriggersCard.svelte deleted file mode 100644 index e394dfd..0000000 --- a/src/WebUI/src/lib/components/TriggersCard.svelte +++ /dev/null @@ -1,261 +0,0 @@ - - -
-

Triggers

-

- Run this script automatically — on registration, when the agent becomes ready, or on a schedule - — against a chosen target. Add as many as you like: the same script can run at different times on - different targets. -

- -
- - - {#if when === 'scheduled'} -
- Schedule - -
- {/if} - - - - -
- - {#if errorText}

{errorText}

{/if} - - {#if mine.length === 0} -

No triggers yet.

- {:else} -
    - {#each mine as trigger (trigger.id)} -
  • -
    - {whenLabel(trigger)} - → {targetLabel(trigger)} - {#if !trigger.enabled} - Disabled - {:else if trigger.triggerType === 'scheduled' && trigger.nextRunUtc} - · next {new Date(trigger.nextRunUtc).toLocaleString()} - {/if} - {#if trigger.lastResult}· {trigger.lastResult}{/if} -
    -
    - - -
    -
  • - {/each} -
- {/if} -
- - diff --git a/src/WebUI/src/lib/components/charts/BarList.svelte b/src/WebUI/src/lib/components/charts/BarList.svelte deleted file mode 100644 index 7f03876..0000000 --- a/src/WebUI/src/lib/components/charts/BarList.svelte +++ /dev/null @@ -1,82 +0,0 @@ - - -{#if items.length === 0} -

{emptyText}

-{:else} -
    - {#each items as item (item.label)} -
  • - {item.label} - - - - {item.count} -
  • - {/each} -
-{/if} - - diff --git a/src/WebUI/src/lib/components/charts/Donut.svelte b/src/WebUI/src/lib/components/charts/Donut.svelte deleted file mode 100644 index 92ac445..0000000 --- a/src/WebUI/src/lib/components/charts/Donut.svelte +++ /dev/null @@ -1,101 +0,0 @@ - - -
- - - - {#each arcs as arc (arc.label)} - - {/each} - - -
-
{centerValue}
-
{centerLabel}
-
-
- - diff --git a/src/WebUI/src/lib/components/charts/TimelineChart.svelte b/src/WebUI/src/lib/components/charts/TimelineChart.svelte deleted file mode 100644 index d473433..0000000 --- a/src/WebUI/src/lib/components/charts/TimelineChart.svelte +++ /dev/null @@ -1,93 +0,0 @@ - - -{#if total === 0} -

No executions in the last 14 days.

-{:else} - -
- {days[0]?.date} - {days[days.length - 1]?.date} -
-{/if} - - diff --git a/src/WebUI/src/lib/editor/powershell-completions.ts b/src/WebUI/src/lib/editor/powershell-completions.ts deleted file mode 100644 index 5880a42..0000000 --- a/src/WebUI/src/lib/editor/powershell-completions.ts +++ /dev/null @@ -1,274 +0,0 @@ -/** - * Lightweight PowerShell IntelliSense for the Monaco editor: a curated set of - * common cmdlets, language keywords, automatic variables and snippets, plus - * dynamic entries for the script's own parameters and secret bindings. No - * language server involved — fast, offline and optional. - */ - -/* eslint-disable @typescript-eslint/no-explicit-any */ - -const CMDLETS = [ - 'Get-ChildItem', - 'Get-Content', - 'Set-Content', - 'Add-Content', - 'Get-Item', - 'Get-ItemProperty', - 'Set-ItemProperty', - 'New-Item', - 'New-ItemProperty', - 'Remove-Item', - 'Copy-Item', - 'Move-Item', - 'Rename-Item', - 'Test-Path', - 'Join-Path', - 'Split-Path', - 'Resolve-Path', - 'Get-Location', - 'Set-Location', - 'Get-Process', - 'Stop-Process', - 'Start-Process', - 'Wait-Process', - 'Get-Service', - 'Start-Service', - 'Stop-Service', - 'Restart-Service', - 'Set-Service', - 'Get-CimInstance', - 'Invoke-CimMethod', - 'Get-Date', - 'Start-Sleep', - 'Write-Output', - 'Write-Host', - 'Write-Error', - 'Write-Warning', - 'Write-Verbose', - 'Write-Debug', - 'Write-Progress', - 'Read-Host', - 'Out-String', - 'Out-Null', - 'Out-File', - 'ForEach-Object', - 'Where-Object', - 'Select-Object', - 'Sort-Object', - 'Group-Object', - 'Measure-Object', - 'Compare-Object', - 'Select-String', - 'ConvertTo-Json', - 'ConvertFrom-Json', - 'ConvertTo-Csv', - 'ConvertFrom-Csv', - 'Export-Csv', - 'Import-Csv', - 'Invoke-RestMethod', - 'Invoke-WebRequest', - 'Invoke-Expression', - 'Invoke-Command', - 'Test-Connection', - 'Test-NetConnection', - 'Resolve-DnsName', - 'Get-NetIPAddress', - 'Get-NetAdapter', - 'Compress-Archive', - 'Expand-Archive', - 'Get-FileHash', - 'New-Guid', - 'Get-Random', - 'Get-WinEvent', - 'Get-EventLog', - 'Get-HotFix', - 'Get-ComputerInfo', - 'Restart-Computer', - 'Stop-Computer', - 'Get-LocalUser', - 'Get-LocalGroup', - 'Add-LocalGroupMember', - 'Get-ScheduledTask', - 'Register-ScheduledTask', - 'Unregister-ScheduledTask', - 'Get-Module', - 'Import-Module', - 'Install-PSResource', - 'Find-PSResource', - 'Start-ThreadJob', - 'Get-Job', - 'Receive-Job', - 'Wait-Job', - 'Remove-Job', - 'Get-Variable', - 'Set-Variable', - 'Get-Command', - 'Get-Member', - 'Get-Help', - 'Get-Error', - 'New-Object', - 'Add-Type', - 'Get-Acl', - 'Set-Acl', - 'ConvertTo-SecureString', - 'ConvertFrom-SecureString' -]; - -const KEYWORDS = [ - 'if', - 'elseif', - 'else', - 'switch', - 'foreach', - 'for', - 'while', - 'do', - 'until', - 'break', - 'continue', - 'return', - 'function', - 'param', - 'begin', - 'process', - 'end', - 'try', - 'catch', - 'finally', - 'throw', - 'trap', - 'class', - 'enum', - 'using', - 'in', - 'exit' -]; - -const AUTOMATIC_VARIABLES = [ - '$_', - '$PSItem', - '$args', - '$error', - '$LASTEXITCODE', - '$PSVersionTable', - '$PSScriptRoot', - '$env:COMPUTERNAME', - '$env:USERNAME', - '$env:TEMP', - '$env:ProgramFiles', - '$true', - '$false', - '$null', - '$ErrorActionPreference', - '$ProgressPreference' -]; - -const SNIPPETS: { label: string; detail: string; insert: string }[] = [ - { - label: 'param block', - detail: 'Script parameter declaration', - insert: 'param(\n [string]$${1:Name}${2:,\n [int]$${3:Count} = ${4:1}}\n)\n' - }, - { - label: 'try / catch', - detail: 'Error handling block', - insert: 'try {\n ${1}\n}\ncatch {\n Write-Error "${2:Operation failed}: $_"\n}\n' - }, - { - label: 'foreach loop', - detail: 'Iterate a collection', - insert: 'foreach ($${1:item} in $${2:collection}) {\n ${3}\n}\n' - }, - { - label: 'progress loop', - detail: 'Loop reporting Write-Progress', - insert: - '1..${1:10} | ForEach-Object {\n Write-Progress -Activity \'${2:Working}\' -Status "Step $_ of ${1:10}" -PercentComplete ($_ * ${3:10})\n ${4}\n}\n' - } -]; - -export interface CompletionContext { - /** Names of the script's declared parameters. */ - parameterNames: () => string[]; - /** Names bound in the secrets dictionary. */ - secretNames: () => string[]; - /** The secrets variable name (default "Secrets"). */ - secretsVariable: () => string; - /** Names bound in the $Files dictionary, with directory flags. */ - fileBindings?: () => { name: string; directory: boolean }[]; -} - -/** Registers the provider for the given language; returns its disposable. */ -export function registerPowerShellCompletions( - monaco: any, - language: string, - context: CompletionContext -): { dispose(): void } { - return monaco.languages.registerCompletionItemProvider(language, { - triggerCharacters: ['-', '$', '.'], - provideCompletionItems(model: any, position: any) { - const word = model.getWordUntilPosition(position); - const range = { - startLineNumber: position.lineNumber, - endLineNumber: position.lineNumber, - startColumn: word.startColumn, - endColumn: word.endColumn - }; - const kinds = monaco.languages.CompletionItemKind; - - const suggestions: any[] = [ - ...CMDLETS.map((c) => ({ - label: c, - kind: kinds.Function, - insertText: c, - range - })), - ...KEYWORDS.map((k) => ({ - label: k, - kind: kinds.Keyword, - insertText: k, - range - })), - ...AUTOMATIC_VARIABLES.map((v) => ({ - label: v, - kind: kinds.Variable, - insertText: v, - range - })), - ...SNIPPETS.map((s) => ({ - label: s.label, - kind: kinds.Snippet, - detail: s.detail, - insertText: s.insert, - insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet, - range - })), - ...context.parameterNames().map((p) => ({ - label: `$${p}`, - kind: kinds.Variable, - detail: 'Script parameter', - insertText: `$${p}`, - range - })), - ...context.secretNames().map((s) => ({ - label: `$${context.secretsVariable()}.${s}`, - kind: kinds.Variable, - detail: 'Secret binding', - insertText: `$${context.secretsVariable()}.${s}`, - range - })), - ...(context.fileBindings?.() ?? []).map((f) => ({ - label: `$Files.${f.name}`, - kind: kinds.File, - detail: f.directory - ? 'Delivered directory (DirectoryInfo)' - : 'Delivered file (FileInfo)', - insertText: `$Files.${f.name}`, - range - })) - ]; - - return { suggestions }; - } - }); -} diff --git a/src/WebUI/src/lib/index.ts b/src/WebUI/src/lib/index.ts deleted file mode 100644 index 8ca99b4..0000000 --- a/src/WebUI/src/lib/index.ts +++ /dev/null @@ -1 +0,0 @@ -// place files you want to import through the `$lib` alias in this folder. diff --git a/src/WebUI/src/lib/messaging/nats.ts b/src/WebUI/src/lib/messaging/nats.ts deleted file mode 100644 index 8d4e68f..0000000 --- a/src/WebUI/src/lib/messaging/nats.ts +++ /dev/null @@ -1,209 +0,0 @@ -// Browser-side NATS-over-WebSocket connection. -// -// The NKey pair is generated in browser memory (the seed never leaves this -// tab). The backend issues a short-lived JWT restricted to this session's -// browser..> subjects; we refresh it before expiry while the -// backend auth session remains valid. - -import { writable, type Readable } from 'svelte/store'; -import { wsconnect, jwtAuthenticator, type NatsConnection, type Subscription } from '@nats-io/nats-core'; -import { createUser, type KeyPair } from '@nats-io/nkeys'; -import { api } from '$lib/api/client'; -import type { - ActivityEventPayload, - JobOutputPayload, - JobProgressPayload, - JobStatePayload, - MessageEnvelope, - ShellOutputPayload, - ShellStatePayload -} from '$lib/api/types'; - -export type LiveState = 'disconnected' | 'connecting' | 'connected'; - -export type JobEvent = - | { type: 'job.output'; payload: JobOutputPayload } - | { type: 'job.progress'; payload: JobProgressPayload } - | { type: 'job.state'; payload: JobStatePayload }; - -export type ShellEvent = - | { type: 'shell.output'; payload: ShellOutputPayload } - | { type: 'shell.state'; payload: ShellStatePayload }; - -type ActivityHandler = (event: ActivityEventPayload) => void; -type JobHandler = (jobId: string, event: JobEvent) => void; -type ShellHandler = (shellId: string, event: ShellEvent) => void; - -const liveState = writable('disconnected'); -export const live: Readable = liveState; - -class NatsService { - private connection: NatsConnection | null = null; - private keyPair: KeyPair | null = null; - private jwt = ''; - private sessionId = ''; - private refreshTimer: ReturnType | null = null; - private subscription: Subscription | null = null; - private starting: Promise | null = null; - - private activityHandlers = new Set(); - private jobHandlers = new Set(); - private shellHandlers = new Set(); - - get browserSessionId(): string { - return this.sessionId; - } - - onActivity(handler: ActivityHandler): () => void { - this.activityHandlers.add(handler); - return () => this.activityHandlers.delete(handler); - } - - onJobEvent(handler: JobHandler): () => void { - this.jobHandlers.add(handler); - return () => this.jobHandlers.delete(handler); - } - - onShellEvent(handler: ShellHandler): () => void { - this.shellHandlers.add(handler); - return () => this.shellHandlers.delete(handler); - } - - /** Publishes raw bytes to a subject inside this session's namespace. */ - publish(subject: string, data: Uint8Array): void { - this.connection?.publish(subject, data); - } - - shellInputSubject(shellId: string): string { - return `browser.${this.sessionId}.shell.${shellId}.input`; - } - - async start(): Promise { - this.starting ??= this.startCore().catch((error) => { - this.starting = null; - liveState.set('disconnected'); - throw error; - }); - return this.starting; - } - - private async startCore(): Promise { - liveState.set('connecting'); - - this.keyPair ??= createUser(); - const credential = await api.messagingCredential( - this.keyPair.getPublicKey(), - this.sessionId || undefined - ); - this.jwt = credential.jwt; - this.sessionId = credential.browserSessionId; - this.scheduleRefresh(credential.expiresUtc); - - const scheme = location.protocol === 'https:' ? 'wss' : 'ws'; - const url = `${scheme}://${location.host}${credential.webSocketPath}`; - - this.connection = await wsconnect({ - servers: [url], - name: `browser-${this.sessionId}`, - authenticator: jwtAuthenticator(() => this.jwt, this.keyPair.getSeed()), - maxReconnectAttempts: -1, - waitOnFirstConnect: true - }); - - liveState.set('connected'); - this.monitorStatus(); - this.subscribeSession(); - } - - private monitorStatus(): void { - if (!this.connection) return; - void (async () => { - for await (const status of this.connection!.status()) { - if (status.type === 'disconnect') { - liveState.set('connecting'); - } else if (status.type === 'reconnect') { - liveState.set('connected'); - } - } - })(); - } - - private subscribeSession(): void { - if (!this.connection) return; - this.subscription?.unsubscribe(); - this.subscription = this.connection.subscribe(`browser.${this.sessionId}.>`); - - void (async () => { - for await (const message of this.subscription!) { - try { - this.dispatch(message.subject, message.json()); - } catch { - // Ignore malformed payloads. - } - } - })(); - } - - private dispatch(subject: string, envelope: MessageEnvelope): void { - // browser..event | browser..job. | browser..shell. - const parts = subject.split('.'); - const kind = parts[2]; - - if (kind === 'event') { - const payload = envelope.payload as ActivityEventPayload; - for (const handler of this.activityHandlers) handler(payload); - return; - } - - if (kind === 'job' && parts.length >= 4) { - const jobId = parts[3]; - const event = { type: envelope.messageType, payload: envelope.payload } as JobEvent; - for (const handler of this.jobHandlers) handler(jobId, event); - return; - } - - if (kind === 'shell' && parts.length >= 4) { - const shellId = parts[3]; - const event = { type: envelope.messageType, payload: envelope.payload } as ShellEvent; - for (const handler of this.shellHandlers) handler(shellId, event); - } - } - - private scheduleRefresh(expiresUtc: string): void { - if (this.refreshTimer) clearTimeout(this.refreshTimer); - const msUntilRefresh = Math.max(new Date(expiresUtc).getTime() - Date.now() - 60_000, 15_000); - this.refreshTimer = setTimeout(() => void this.refreshCredential(), msUntilRefresh); - } - - private async refreshCredential(): Promise { - try { - if (!this.keyPair) return; - const credential = await api.messagingCredential(this.keyPair.getPublicKey(), this.sessionId); - this.jwt = credential.jwt; - if (credential.browserSessionId !== this.sessionId) { - // Session expired server-side; rebind subscriptions to the new one. - this.sessionId = credential.browserSessionId; - this.subscribeSession(); - } - this.scheduleRefresh(credential.expiresUtc); - } catch { - // Auth session likely gone; retry shortly (page will redirect on 401). - this.refreshTimer = setTimeout(() => void this.refreshCredential(), 30_000); - } - } - - async stop(): Promise { - if (this.refreshTimer) clearTimeout(this.refreshTimer); - this.refreshTimer = null; - this.subscription?.unsubscribe(); - this.subscription = null; - this.starting = null; - if (this.connection) { - await this.connection.close().catch(() => undefined); - this.connection = null; - } - liveState.set('disconnected'); - } -} - -export const nats = new NatsService(); diff --git a/src/WebUI/src/lib/schedule/cron-describe.ts b/src/WebUI/src/lib/schedule/cron-describe.ts deleted file mode 100644 index acf201b..0000000 --- a/src/WebUI/src/lib/schedule/cron-describe.ts +++ /dev/null @@ -1,99 +0,0 @@ -// Best-effort plain-English description of a 5-field cron expression. -// Covers everything the schedule builder generates plus common hand-written -// shapes; anything else returns null and the UI falls back to the raw cron -// (the server-computed next-run preview stays the ground truth either way). - -const dayNames: Record = { - '0': 'Sun', - '1': 'Mon', - '2': 'Tue', - '3': 'Wed', - '4': 'Thu', - '5': 'Fri', - '6': 'Sat', - '7': 'Sun', - SUN: 'Sun', - MON: 'Mon', - TUE: 'Tue', - WED: 'Wed', - THU: 'Thu', - FRI: 'Fri', - SAT: 'Sat' -}; - -function time(minute: string, hour: string): string | null { - const m = Number(minute); - const h = Number(hour); - if (!Number.isInteger(m) || !Number.isInteger(h) || m < 0 || m > 59 || h < 0 || h > 23) { - return null; - } - return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`; -} - -function days(field: string): string | null { - const parts = field.split(',').map((d) => dayNames[d.trim().toUpperCase()]); - return parts.every(Boolean) ? parts.join(', ') : null; -} - -export function describeCron(expression: string): string | null { - const fields = expression.trim().split(/\s+/); - if (fields.length !== 5) return null; - const [minute, hour, dayOfMonth, month, dayOfWeek] = fields; - - if (month !== '*') return null; - - // */N * * * * — every N minutes - let match = /^\*\/(\d+)$/.exec(minute); - if (match && hour === '*' && dayOfMonth === '*' && dayOfWeek === '*') { - return match[1] === '1' ? 'Every minute' : `Every ${match[1]} minutes`; - } - - // M */N * * * — every N hours at minute M - match = /^\*\/(\d+)$/.exec(hour); - if (match && dayOfMonth === '*' && dayOfWeek === '*' && /^\d+$/.test(minute)) { - const at = minute === '0' ? '' : ` at :${minute.padStart(2, '0')}`; - return match[1] === '1' ? `Hourly${at}` : `Every ${match[1]} hours${at}`; - } - - // M * * * * — hourly at minute M - if (/^\d+$/.test(minute) && hour === '*' && dayOfMonth === '*' && dayOfWeek === '*') { - return minute === '0' ? 'Hourly' : `Hourly at :${minute.padStart(2, '0')}`; - } - - const at = time(minute, hour); - if (!at) return null; - - // M H * * * — daily - if (dayOfMonth === '*' && dayOfWeek === '*') { - return `Daily at ${at}`; - } - - // M H * * DAYS — weekly - if (dayOfMonth === '*' && dayOfWeek !== '*') { - const named = days(dayOfWeek); - return named ? `Weekly on ${named} at ${at}` : null; - } - - // M H D * * — monthly - if (dayOfWeek === '*' && /^\d+$/.test(dayOfMonth)) { - return `Monthly on day ${dayOfMonth} at ${at}`; - } - - return null; -} - -/** One-line cadence for a stored schedule or assignment (falls back to the raw cron). */ -export function scheduleCadence(schedule: { - cronExpression?: string; - runOnceUtc?: string; - timeZoneId: string; -}): string { - if (schedule.runOnceUtc) { - return `Once at ${new Date(schedule.runOnceUtc).toLocaleString()}`; - } - if (schedule.cronExpression) { - const text = describeCron(schedule.cronExpression) ?? schedule.cronExpression; - return schedule.timeZoneId === 'UTC' ? text : `${text} (${schedule.timeZoneId})`; - } - return '—'; -} diff --git a/src/WebUI/src/lib/theme/theme.ts b/src/WebUI/src/lib/theme/theme.ts deleted file mode 100644 index edfbc04..0000000 --- a/src/WebUI/src/lib/theme/theme.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { writable } from 'svelte/store'; -import { browser } from '$app/environment'; - -export type ThemePreference = 'system' | 'light' | 'dark'; - -function initial(): ThemePreference { - if (!browser) return 'system'; - const stored = localStorage.getItem('theme'); - return stored === 'light' || stored === 'dark' ? stored : 'system'; -} - -export const theme = writable(initial()); - -export function setTheme(preference: ThemePreference): void { - theme.set(preference); - if (!browser) return; - - if (preference === 'system') { - localStorage.removeItem('theme'); - document.documentElement.removeAttribute('data-theme'); - } else { - localStorage.setItem('theme', preference); - document.documentElement.setAttribute('data-theme', preference); - } -} diff --git a/src/WebUI/src/menu-items/index.ts b/src/WebUI/src/menu-items/index.ts new file mode 100644 index 0000000..fc298d6 --- /dev/null +++ b/src/WebUI/src/menu-items/index.ts @@ -0,0 +1,89 @@ +// assets +import ApartmentOutlined from '@ant-design/icons/ApartmentOutlined'; +import CalendarOutlined from '@ant-design/icons/CalendarOutlined'; +import CodeOutlined from '@ant-design/icons/CodeOutlined'; +import DashboardOutlined from '@ant-design/icons/DashboardOutlined'; +import DesktopOutlined from '@ant-design/icons/DesktopOutlined'; +import FunctionOutlined from '@ant-design/icons/FunctionOutlined'; +import HistoryOutlined from '@ant-design/icons/HistoryOutlined'; +import SafetyCertificateOutlined from '@ant-design/icons/SafetyCertificateOutlined'; +import SettingOutlined from '@ant-design/icons/SettingOutlined'; + +// types +import { NavGroupType, NavItemType } from 'types/menu'; + +// ==============================|| MENU ITEMS ||============================== // + +const menuItems: NavGroupType[] = [ + { + id: 'overview', + title: 'Overview', + children: [{ id: 'dashboard', title: 'Dashboard', url: '/', icon: DashboardOutlined, exact: true }] + }, + { + id: 'fleet', + title: 'Fleet', + children: [ + { + id: 'devices', + title: 'Devices', + url: '/devices', + icon: DesktopOutlined, + permission: 'devices.view', + permissionLabel: 'View Devices' + }, + { id: 'groups', title: 'Groups', url: '/groups', icon: ApartmentOutlined, permission: 'groups.view', permissionLabel: 'View Groups' } + ] + }, + { + id: 'automation', + title: 'Automation', + children: [ + { id: 'scripts', title: 'Scripts', url: '/scripts', icon: CodeOutlined, permission: 'scripts.view', permissionLabel: 'View Scripts' }, + { + id: 'functions', + title: 'Functions', + url: '/functions', + icon: FunctionOutlined, + permission: 'functions.view', + permissionLabel: 'View Functions' + }, + { + id: 'schedules', + title: 'Schedules', + url: '/schedules', + icon: CalendarOutlined, + permission: 'automation.view', + permissionLabel: 'View Automation' + }, + { id: 'jobs', title: 'Jobs', url: '/jobs', icon: HistoryOutlined, permission: 'jobs.view', permissionLabel: 'View Jobs' } + ] + }, + { + id: 'administration', + title: 'Administration', + children: [ + { + id: 'access', + title: 'Access', + url: '/access', + icon: SafetyCertificateOutlined, + permission: 'access.manage', + permissionLabel: 'Manage Access' + }, + { + id: 'settings', + title: 'Settings', + url: '/settings', + icon: SettingOutlined, + permission: 'settings.manage', + permissionLabel: 'Manage Settings' + } + ] + } +]; + +export default menuItems; + +/** Every navigable item, for titles and breadcrumbs. */ +export const allMenuItems: NavItemType[] = menuItems.flatMap((group) => group.children); diff --git a/src/WebUI/src/messaging/nats.ts b/src/WebUI/src/messaging/nats.ts new file mode 100644 index 0000000..f774887 --- /dev/null +++ b/src/WebUI/src/messaging/nats.ts @@ -0,0 +1,224 @@ +// Browser-side NATS-over-WebSocket connection. +// +// The NKey pair is generated in browser memory (the seed never leaves this +// tab). The backend issues a short-lived JWT restricted to this session's +// browser..> subjects; we refresh it before expiry while the +// backend auth session remains valid. + +import { useSyncExternalStore } from 'react'; +import { wsconnect, jwtAuthenticator, type NatsConnection, type Subscription } from '@nats-io/nats-core'; +import { createUser, type KeyPair } from '@nats-io/nkeys'; +import { api } from 'api/client'; +import type { + ActivityEventPayload, + JobOutputPayload, + JobProgressPayload, + JobStatePayload, + MessageEnvelope, + ShellOutputPayload, + ShellStatePayload +} from 'api/types'; + +export type LiveState = 'disconnected' | 'connecting' | 'connected'; + +export type JobEvent = + | { type: 'job.output'; payload: JobOutputPayload } + | { type: 'job.progress'; payload: JobProgressPayload } + | { type: 'job.state'; payload: JobStatePayload }; + +export type ShellEvent = { type: 'shell.output'; payload: ShellOutputPayload } | { type: 'shell.state'; payload: ShellStatePayload }; + +type ActivityHandler = (event: ActivityEventPayload) => void; +type JobHandler = (jobId: string, event: JobEvent) => void; +type ShellHandler = (shellId: string, event: ShellEvent) => void; + +/** Connection state with change listeners (read in React via useLiveState). */ +const liveState = (() => { + let value: LiveState = 'disconnected'; + const listeners = new Set<() => void>(); + return { + get: () => value, + set(next: LiveState) { + if (next === value) return; + value = next; + for (const listener of listeners) listener(); + }, + subscribe(listener: () => void) { + listeners.add(listener); + return () => void listeners.delete(listener); + } + }; +})(); + +/** The live (NATS WebSocket) connection state, re-rendering on change. */ +export function useLiveState(): LiveState { + return useSyncExternalStore(liveState.subscribe, liveState.get); +} + +class NatsService { + private connection: NatsConnection | null = null; + private keyPair: KeyPair | null = null; + private jwt = ''; + private sessionId = ''; + private refreshTimer: ReturnType | null = null; + private subscription: Subscription | null = null; + private starting: Promise | null = null; + + private activityHandlers = new Set(); + private jobHandlers = new Set(); + private shellHandlers = new Set(); + + get browserSessionId(): string { + return this.sessionId; + } + + onActivity(handler: ActivityHandler): () => void { + this.activityHandlers.add(handler); + return () => this.activityHandlers.delete(handler); + } + + onJobEvent(handler: JobHandler): () => void { + this.jobHandlers.add(handler); + return () => this.jobHandlers.delete(handler); + } + + onShellEvent(handler: ShellHandler): () => void { + this.shellHandlers.add(handler); + return () => this.shellHandlers.delete(handler); + } + + /** Publishes raw bytes to a subject inside this session's namespace. */ + publish(subject: string, data: Uint8Array): void { + this.connection?.publish(subject, data); + } + + shellInputSubject(shellId: string): string { + return `browser.${this.sessionId}.shell.${shellId}.input`; + } + + async start(): Promise { + this.starting ??= this.startCore().catch((error) => { + this.starting = null; + liveState.set('disconnected'); + throw error; + }); + return this.starting; + } + + private async startCore(): Promise { + liveState.set('connecting'); + + this.keyPair ??= createUser(); + const credential = await api.messagingCredential(this.keyPair.getPublicKey(), this.sessionId || undefined); + this.jwt = credential.jwt; + this.sessionId = credential.browserSessionId; + this.scheduleRefresh(credential.expiresUtc); + + const scheme = location.protocol === 'https:' ? 'wss' : 'ws'; + const url = `${scheme}://${location.host}${credential.webSocketPath}`; + + this.connection = await wsconnect({ + servers: [url], + name: `browser-${this.sessionId}`, + authenticator: jwtAuthenticator(() => this.jwt, this.keyPair.getSeed()), + maxReconnectAttempts: -1, + waitOnFirstConnect: true + }); + + liveState.set('connected'); + this.monitorStatus(); + this.subscribeSession(); + } + + private monitorStatus(): void { + if (!this.connection) return; + void (async () => { + for await (const status of this.connection!.status()) { + if (status.type === 'disconnect') { + liveState.set('connecting'); + } else if (status.type === 'reconnect') { + liveState.set('connected'); + } + } + })(); + } + + private subscribeSession(): void { + if (!this.connection) return; + this.subscription?.unsubscribe(); + this.subscription = this.connection.subscribe(`browser.${this.sessionId}.>`); + + void (async () => { + for await (const message of this.subscription!) { + try { + this.dispatch(message.subject, message.json()); + } catch { + // Ignore malformed payloads. + } + } + })(); + } + + private dispatch(subject: string, envelope: MessageEnvelope): void { + // browser..event | browser..job. | browser..shell. + const parts = subject.split('.'); + const kind = parts[2]; + + if (kind === 'event') { + const payload = envelope.payload as ActivityEventPayload; + for (const handler of this.activityHandlers) handler(payload); + return; + } + + if (kind === 'job' && parts.length >= 4) { + const jobId = parts[3]; + const event = { type: envelope.messageType, payload: envelope.payload } as JobEvent; + for (const handler of this.jobHandlers) handler(jobId, event); + return; + } + + if (kind === 'shell' && parts.length >= 4) { + const shellId = parts[3]; + const event = { type: envelope.messageType, payload: envelope.payload } as ShellEvent; + for (const handler of this.shellHandlers) handler(shellId, event); + } + } + + private scheduleRefresh(expiresUtc: string): void { + if (this.refreshTimer) clearTimeout(this.refreshTimer); + const msUntilRefresh = Math.max(new Date(expiresUtc).getTime() - Date.now() - 60_000, 15_000); + this.refreshTimer = setTimeout(() => void this.refreshCredential(), msUntilRefresh); + } + + private async refreshCredential(): Promise { + try { + if (!this.keyPair) return; + const credential = await api.messagingCredential(this.keyPair.getPublicKey(), this.sessionId); + this.jwt = credential.jwt; + if (credential.browserSessionId !== this.sessionId) { + // Session expired server-side; rebind subscriptions to the new one. + this.sessionId = credential.browserSessionId; + this.subscribeSession(); + } + this.scheduleRefresh(credential.expiresUtc); + } catch { + // Auth session likely gone; retry shortly (page will redirect on 401). + this.refreshTimer = setTimeout(() => void this.refreshCredential(), 30_000); + } + } + + async stop(): Promise { + if (this.refreshTimer) clearTimeout(this.refreshTimer); + this.refreshTimer = null; + this.subscription?.unsubscribe(); + this.subscription = null; + this.starting = null; + if (this.connection) { + await this.connection.close().catch(() => undefined); + this.connection = null; + } + liveState.set('disconnected'); + } +} + +export const nats = new NatsService(); diff --git a/src/WebUI/src/pages/access/index.tsx b/src/WebUI/src/pages/access/index.tsx new file mode 100644 index 0000000..96e8094 --- /dev/null +++ b/src/WebUI/src/pages/access/index.tsx @@ -0,0 +1,97 @@ +import { useSearchParams } from 'react-router-dom'; + +// material-ui +import Chip from '@mui/material/Chip'; +import Stack from '@mui/material/Stack'; +import Tab from '@mui/material/Tab'; +import Tabs from '@mui/material/Tabs'; + +// project imports +import PageHeader from 'components/PageHeader'; +import PeopleTab from 'sections/access/PeopleTab'; +import RolesTab from 'sections/access/RolesTab'; +import { useManageGate } from 'sections/settings/authentication/MethodControls'; +import { errorMessage, keys } from 'api/client'; +import { IdentityRoutes } from 'api/identity'; +import useApi from 'hooks/useApi'; + +// assets +import SafetyOutlined from '@ant-design/icons/SafetyOutlined'; +import TeamOutlined from '@ant-design/icons/TeamOutlined'; + +// types +import type { UserView } from 'api/identity'; +import type { DeviceGroupDto, PermissionGroupDto, RoleDto } from 'api/types'; + +type AccessTab = 'people' | 'roles'; + +function TabLabel({ label, count }: { label: string; count?: number }) { + return ( + + {label} + {count !== undefined && } + + ); +} + +// ==============================|| ACCESS CONTROL ||============================== // + +export default function AccessPage() { + const [params, setParams] = useSearchParams(); + const tab: AccessTab = params.get('tab') === 'roles' ? 'roles' : 'people'; + const gate = useManageGate(); + + const users = useApi(IdentityRoutes.users); + const roles = useApi(keys.roles); + const catalog = useApi(keys.permissionCatalog); + const groups = useApi(keys.groups); + + const setTab = (next: AccessTab) => + setParams( + (current) => { + const updated = new URLSearchParams(current); + updated.set('tab', next); + return updated; + }, + { replace: true } + ); + + return ( + + + + setTab(value)} sx={{ borderBottom: 1, borderColor: 'divider' }}> + } iconPosition="start" label={} /> + } iconPosition="start" label={} /> + + + {tab === 'people' ? ( + + ) : ( + + )} + + ); +} diff --git a/src/WebUI/src/pages/auth/sign-in.tsx b/src/WebUI/src/pages/auth/sign-in.tsx new file mode 100644 index 0000000..9a5c806 --- /dev/null +++ b/src/WebUI/src/pages/auth/sign-in.tsx @@ -0,0 +1,286 @@ +import { FormEvent, useEffect, useRef, useState } from 'react'; +import { useNavigate, useSearchParams } from 'react-router-dom'; + +// material-ui +import Alert from '@mui/material/Alert'; +import Button from '@mui/material/Button'; +import CircularProgress from '@mui/material/CircularProgress'; +import Divider from '@mui/material/Divider'; +import Skeleton from '@mui/material/Skeleton'; +import Stack from '@mui/material/Stack'; +import TextField from '@mui/material/TextField'; +import ToggleButton from '@mui/material/ToggleButton'; +import ToggleButtonGroup from '@mui/material/ToggleButtonGroup'; +import Typography from '@mui/material/Typography'; + +// project imports +import AuthWrapper from 'sections/auth/AuthWrapper'; +import { ApiError, errorMessage } from 'api/client'; +import { identity, IdentityRoutes } from 'api/identity'; +import useApi from 'hooks/useApi'; +import useSession from 'hooks/useSession'; +import { passwordChoices, safeReturnUrl, signInPlan, takeSignedOut } from 'utils/signIn'; +import type { ProviderId, Session, SignInOptions } from 'api/identity'; + +// assets +import SafetyOutlined from '@ant-design/icons/SafetyOutlined'; + +/** Why a provider sent the browser back here, in one line. */ +const RETURN_ERRORS: Record = { + 'oidc-off': 'Single sign-on is not turned on.', + 'oidc-unavailable': 'The identity provider could not be reached just now.', + 'oidc-failed': 'The identity provider did not complete the sign-in.', + 'no-access': 'You signed in, but none of your groups has access here. Ask an administrator.' +}; + +/** The identity provider's sign-in route, the only kind that leaves this page. */ +const providerUrl = (returnUrl: string) => `${IdentityRoutes.oidcSignIn}?returnUrl=${encodeURIComponent(returnUrl)}`; + +function Failure({ error }: { error: unknown }) { + return {errorMessage(error, 'The sign-in did not complete; try again.')}; +} + +// ==============================|| SIGN-IN FORM ||============================== // + +function PasswordForm({ options, onSignedIn }: { options: SignInOptions; onSignedIn: (session: Session) => void }) { + const choices = passwordChoices(options); + const directory = options.providers.find((p) => p.kind === 'form'); + const [provider, setProvider] = useState(choices[0]?.id ?? 'local'); + const [userName, setUserName] = useState(''); + const [password, setPassword] = useState(''); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + if (choices.length === 0) return null; + + const submit = async (event: FormEvent) => { + event.preventDefault(); + setBusy(true); + setError(null); + try { + onSignedIn(await identity.signIn({ provider, userName, password })); + } catch (err) { + setError(err); + setPassword(''); + } finally { + setBusy(false); + } + }; + + return ( + + {choices.length > 1 && ( + value && setProvider(value)} + aria-label="Account type" + > + {choices.map((c) => ( + + {c.label} + + ))} + + )} + setUserName(e.target.value)} + autoComplete="username" + autoFocus + fullWidth + /> + setPassword(e.target.value)} + autoComplete="current-password" + fullWidth + /> + {error !== null && } + + + ); +} + +// ==============================|| PASSWORD CHANGE ||============================== // + +function PasswordChange({ onDone }: { onDone: () => void }) { + const [current, setCurrent] = useState(''); + const [next, setNext] = useState(''); + const [confirm, setConfirm] = useState(''); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const mismatch = confirm.length > 0 && confirm !== next; + + const submit = async (event: FormEvent) => { + event.preventDefault(); + setBusy(true); + setError(null); + try { + await identity.changePassword(current, next); + onDone(); + } catch (err) { + if (err instanceof ApiError && err.status === 401) { + window.location.assign('/sign-in'); + return; + } + setError(err); + } finally { + setBusy(false); + } + }; + + return ( + + setCurrent(e.target.value)} + autoComplete="current-password" + autoFocus + fullWidth + /> + setNext(e.target.value)} + autoComplete="new-password" + helperText="At least 12 characters, without your user name." + fullWidth + /> + setConfirm(e.target.value)} + autoComplete="new-password" + error={mismatch} + helperText={mismatch ? 'The passwords do not match.' : ' '} + fullWidth + /> + {error !== null && } + + + ); +} + +// ==============================|| SIGN IN ||============================== // + +export default function SignInPage() { + const [params] = useSearchParams(); + const navigate = useNavigate(); + const { adopt, refresh } = useSession(); + const returnUrl = safeReturnUrl(params.get('returnUrl')); + const returnError = params.get('error'); + const [changing, setChanging] = useState(params.get('change') === '1'); + const [signedOut] = useState(takeSignedOut); + const { data: options, error, mutate } = useApi(IdentityRoutes.options); + + // Redirect mode: straight to the provider, once, unless it just sent the browser back with an error or the person just signed out. + const plan = signInPlan(options, { error: returnError, signedOut, changingPassword: changing }); + const target = plan.redirectTo ? options?.providers.find((p) => p.id === plan.redirectTo) : undefined; + const redirected = useRef(false); + useEffect(() => { + if (target && !redirected.current) { + redirected.current = true; + window.location.assign(providerUrl(returnUrl)); + } + }, [target, returnUrl]); + + const enter = () => navigate(returnUrl, { replace: true }); + const finish = (session: Session) => { + adopt(session); + if (session.passwordChangeRequired) setChanging(true); + else enter(); + }; + const redirects = options?.providers.filter((p) => p.kind === 'redirect') ?? []; + const hasForm = passwordChoices(options).length > 0; + + return ( + + + + {changing ? 'Choose a New Password' : 'Sign In'} + {changing && ( + + Your password was set for you; choose your own to continue. + + )} + + {changing ? ( + void refresh().then(enter)} /> + ) : !options && !error ? ( + + + + + + ) : error ? ( + + + + + ) : target ? ( + + + Going to {target.label}… + + ) : options ? ( + + {returnError && {RETURN_ERRORS[returnError] ?? 'The sign-in did not complete; try again.'}} + {plan.heldBack && signedOut && !returnError && ( + + You signed out. + + )} + {redirects.map((p) => ( + + ))} + {redirects.length > 0 && hasForm && ( + + + or + + + )} + {hasForm && } + + ) : null} + + + ); +} diff --git a/src/WebUI/src/pages/auth/step-up-done.tsx b/src/WebUI/src/pages/auth/step-up-done.tsx new file mode 100644 index 0000000..90a9bfe --- /dev/null +++ b/src/WebUI/src/pages/auth/step-up-done.tsx @@ -0,0 +1,20 @@ +import { useEffect } from 'react'; + +// material-ui +import Stack from '@mui/material/Stack'; +import Typography from '@mui/material/Typography'; + +// ==============================|| STEP-UP DONE ||============================== // + +/** Where the identity provider's step-up window lands: the console that opened it polls the session, so this only closes itself. */ +export default function StepUpDone() { + useEffect(() => { + window.setTimeout(() => window.close(), 300); + }, []); + + return ( + + Confirmed + + ); +} diff --git a/src/WebUI/src/pages/dashboard/index.tsx b/src/WebUI/src/pages/dashboard/index.tsx new file mode 100644 index 0000000..cea0f9f --- /dev/null +++ b/src/WebUI/src/pages/dashboard/index.tsx @@ -0,0 +1,248 @@ +import { ReactNode } from 'react'; + +// material-ui +import { useTheme } from '@mui/material/styles'; +import Alert from '@mui/material/Alert'; +import Grid from '@mui/material/Grid'; +import Skeleton from '@mui/material/Skeleton'; +import Stack from '@mui/material/Stack'; + +// project imports +import BarList from 'components/charts/BarList'; +import Donut, { DonutSegment } from 'components/charts/Donut'; +import TimelineChart from 'components/charts/TimelineChart'; +import HoverHelp from 'components/HoverHelp'; +import KpiCard from 'components/KpiCard'; +import MainCard from 'components/MainCard'; +import PageHeader from 'components/PageHeader'; +import useApi from 'hooks/useApi'; +import useLiveRefresh from 'hooks/useLiveRefresh'; +import { useGate } from 'hooks/useSession'; +import ActivityFeed from 'sections/dashboard/ActivityFeed'; +import LiveDeployment from 'sections/dashboard/LiveDeployment'; +import RecentRuns from 'sections/dashboard/RecentRuns'; +import { errorMessage, keys } from 'api/client'; +import type { CountPoint, DashboardDto } from 'api/types'; + +// assets +import CheckCircleOutlined from '@ant-design/icons/CheckCircleOutlined'; +import CloseCircleOutlined from '@ant-design/icons/CloseCircleOutlined'; +import DesktopOutlined from '@ant-design/icons/DesktopOutlined'; +import HistoryOutlined from '@ant-design/icons/HistoryOutlined'; +import SyncOutlined from '@ant-design/icons/SyncOutlined'; + +/** A slow poll keeps the aggregates current even without a live connection. */ +const POLL_MS = 15_000; + +/** Fleet platforms in a fixed categorical order, so a platform keeps its color as the mix changes. */ +const PLATFORMS: Record = { + windows: { label: 'Windows', color: 'var(--chart-1)' }, + linux: { label: 'Linux', color: 'var(--chart-2)' }, + macos: { label: 'macOS', color: 'var(--chart-3)' }, + unknown: { label: 'Unknown', color: 'var(--chart-6)' } +}; + +function ChartCard({ title, children }: { title: string; children: ReactNode }) { + return ( + + {children} + + ); +} + +// ==============================|| DASHBOARD ||============================== // + +export default function Dashboard() { + const theme = useTheme(); + // The dashboard aggregates fleet data, so the API asks for View Devices. + const gate = useGate('devices.view', 'View Devices'); + const { data, error, loading, mutate } = useApi(gate ? null : keys.dashboard, { refreshInterval: POLL_MS }); + + // Presence flaps are frequent and only move the device counts; the poll covers them. + useLiveRefresh( + () => mutate(), + (event) => event.kind !== 'device-presence' + ); + + /** Job states (the API sends JobState names, "TimedOut") wear the same tones as their status chips. */ + const jobStates: Record = { + queued: { label: 'Queued', color: theme.vars.palette.secondary.main }, + dispatched: { label: 'Dispatched', color: theme.vars.palette.info.main }, + running: { label: 'Running', color: theme.vars.palette.primary.main }, + succeeded: { label: 'Succeeded', color: theme.vars.palette.success.main }, + failed: { label: 'Failed', color: theme.vars.palette.error.main }, + cancelled: { label: 'Cancelled', color: theme.vars.palette.secondary.light }, + timedout: { label: 'Timed Out', color: theme.vars.palette.warning.main } + }; + + const toSegments = (points: CountPoint[], known: Record, fallback: string[]) => { + let next = 0; + return points.map((p) => { + const entry = known[p.label.toLowerCase()]; + return { + label: entry?.label ?? p.label, + value: p.count, + color: entry?.color ?? fallback[next++ % fallback.length] + }; + }); + }; + + const stateSegments = toSegments(data?.jobsByState ?? [], jobStates, ['var(--chart-4)', 'var(--chart-5)']); + const platformSegments = toSegments(data?.devicesByPlatform ?? [], PLATFORMS, ['var(--chart-4)', 'var(--chart-5)']); + + const pending = !data; + const header = ; + + if (gate) { + return ( + + {header} + + {gate} + + + + ); + } + + return ( + + {header} + + {error && !data && {errorMessage(error, 'The dashboard could not be loaded.')}} + + void mutate()} /> + + + + } + tone="primary" + to="/devices" + loading={pending} + /> + + + } + tone="info" + to="/jobs" + loading={pending} + /> + + + } + tone="success" + to="/jobs" + loading={pending} + /> + + + 0} />} + tone="warning" + to="/jobs" + loading={pending} + /> + + + } + tone={data && data.jobsFailed > 0 ? 'error' : 'secondary'} + to="/jobs?state=failed" + loading={pending} + /> + + + + {pending ? ( + loading && ( + + {Array.from({ length: 4 }, (_, i) => ( + + + + ))} + + ) + ) : ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + )} + + ); +} diff --git a/src/WebUI/src/pages/devices/detail.tsx b/src/WebUI/src/pages/devices/detail.tsx new file mode 100644 index 0000000..300bf05 --- /dev/null +++ b/src/WebUI/src/pages/devices/detail.tsx @@ -0,0 +1,246 @@ +import { useMemo, useState } from 'react'; +import { Link as RouterLink, useNavigate, useParams, useSearchParams } from 'react-router-dom'; + +// material-ui +import Alert from '@mui/material/Alert'; +import Button from '@mui/material/Button'; +import Skeleton from '@mui/material/Skeleton'; +import Stack from '@mui/material/Stack'; +import Tab from '@mui/material/Tab'; +import Tabs from '@mui/material/Tabs'; +import Typography from '@mui/material/Typography'; + +// project imports +import ActionMenu from 'components/ActionMenu'; +import EmptyState from 'components/EmptyState'; +import GatedButton from 'components/GatedButton'; +import HoverHelp from 'components/HoverHelp'; +import IconButton from 'components/@extended/IconButton'; +import MainCard from 'components/MainCard'; +import OsIcon, { isWinPe, WinPeChip } from 'components/OsIcon'; +import PageHeader from 'components/PageHeader'; +import { DeviceStatusChip } from 'components/StatusChip'; +import DeviceHardware from 'sections/devices/DeviceHardware'; +import DeviceHistory from 'sections/devices/DeviceHistory'; +import DeviceJobs from 'sections/devices/DeviceJobs'; +import DeviceNetwork from 'sections/devices/DeviceNetwork'; +import DeviceOverview from 'sections/devices/DeviceOverview'; +import DeviceUpgrades from 'sections/devices/DeviceUpgrades'; +import SendFileCard from 'sections/devices/SendFileCard'; +import useDeviceActions from 'sections/devices/useDeviceActions'; +import ScheduleTable from 'sections/schedules/ScheduleTable'; +import useApi from 'hooks/useApi'; +import useAutomation from 'hooks/useAutomation'; +import useLiveRefresh from 'hooks/useLiveRefresh'; +import useSession from 'hooks/useSession'; +import { ApiError, keys } from 'api/client'; +import type { DeviceDetailDto, ScriptTriggerDto } from 'api/types'; + +// assets +import CalendarOutlined from '@ant-design/icons/CalendarOutlined'; +import CodeOutlined from '@ant-design/icons/CodeOutlined'; +import MoreOutlined from '@ant-design/icons/MoreOutlined'; +import PlayCircleOutlined from '@ant-design/icons/PlayCircleOutlined'; + +const TABS = [ + { id: 'overview', label: 'Overview' }, + { id: 'hardware', label: 'Hardware' }, + { id: 'network', label: 'Network' }, + { id: 'jobs', label: 'Execution History' }, + { id: 'history', label: 'Device History' }, + { id: 'upgrades', label: 'Agent Upgrades' }, + { id: 'schedules', label: 'Schedules' }, + { id: 'files', label: 'Files' } +] as const; + +type TabId = (typeof TABS)[number]['id']; + +// ==============================|| DEVICE DETAIL ||============================== // + +export default function DeviceDetailPage() { + const { clientId = '' } = useParams(); + const navigate = useNavigate(); + const [params, setParams] = useSearchParams(); + const { can } = useSession(); + const { openRun, openSchedule } = useAutomation(); + const [menuAnchor, setMenuAnchor] = useState(null); + + const { data: detail, error, mutate } = useApi(keys.device(clientId)); + const { data: triggers, loading: triggersLoading } = useApi(can('automation.view') ? keys.triggers : null); + useLiveRefresh( + () => mutate(), + (event) => event.clientId === clientId + ); + const actions = useDeviceActions({ onDone: () => void mutate() }); + + const tab = (TABS.find((t) => t.id === params.get('tab'))?.id ?? 'overview') as TabId; + const device = detail?.device; + + // Schedules reach a device directly, through any group it is in (including + // through nesting: detail.groups lists those ancestors too) or as "All Devices". + const reaching = useMemo(() => { + const groupIds = new Set((detail?.groups ?? []).map((g) => g.id)); + return (triggers ?? []).filter((t) => t.clientId === clientId || (t.groupId && groupIds.has(t.groupId)) || (!t.clientId && !t.groupId)); + }, [triggers, detail, clientId]); + + if (error) { + return ( + + + Back to Devices + + } + /> + + ); + } + + if (!device) { + return ( + + + + + ); + } + + const online = device.status === 'online' && !device.isOrphaned; + const runGate = !can('jobs.run') + ? 'Needs the Run Jobs permission.' + : device.isOrphaned + ? 'Orphaned devices refuse jobs until they re-enroll.' + : undefined; + const shellGate = !can('shell.use') ? 'Needs the Remote Shell permission.' : !online ? 'The device is not online.' : undefined; + + return ( + + + + {device.hostname} + + } + adornment={ + + + {isWinPe(device.osCaption) && } + + } + description={[device.manufacturer, device.model, device.osCaption].filter(Boolean).join(' · ') || undefined} + primaryAction={ + } + gate={runGate} + onClick={() => openRun({ targets: [{ kind: 'device', id: device.clientId }] })} + > + Run Script + + } + secondaryActions={ + <> + } + gate={can('automation.manage') ? undefined : 'Needs the Manage Automation permission.'} + onClick={() => openSchedule({ preset: { target: { kind: 'device', id: device.clientId } } })} + > + Schedule + + } + gate={shellGate} + onClick={() => navigate(`/devices/${encodeURIComponent(device.clientId)}/shell`)} + > + Open Shell + + setMenuAnchor(e.currentTarget)}> + + + + } + /> + + {device.isOrphaned && ( + + Orphaned; refuses jobs until it re-enrolls. + + + )} + + setParams(value === 'overview' ? {} : { tab: value }, { replace: true })} + variant="scrollable" + scrollButtons="auto" + sx={{ borderBottom: 1, borderColor: 'divider' }} + > + {TABS.map((t) => ( + 0 ? ( + + {t.label}{' '} + + ({reaching.length}) + + + ) : ( + t.label + ) + } + /> + ))} + + + {tab === 'overview' && void mutate()} />} + {tab === 'hardware' && } + {tab === 'network' && } + {tab === 'jobs' && } + {tab === 'history' && } + {tab === 'upgrades' && } + {tab === 'schedules' && ( + + Schedules Reaching This Device + + + } + secondary={ + openSchedule({ preset: { target: { kind: 'device', id: device.clientId } } })} + > + New Schedule + + } + > + {can('automation.view') ? ( + + ) : ( + + )} + + )} + {tab === 'files' && } + + {menuAnchor && setMenuAnchor(null)} entries={actions.menuFor([device])} />} + {actions.elements} + + ); +} diff --git a/src/WebUI/src/pages/devices/index.tsx b/src/WebUI/src/pages/devices/index.tsx new file mode 100644 index 0000000..2641ec9 --- /dev/null +++ b/src/WebUI/src/pages/devices/index.tsx @@ -0,0 +1,583 @@ +import { MouseEvent, useMemo, useState } from 'react'; +import { Link as RouterLink, useNavigate, useSearchParams } from 'react-router-dom'; + +// material-ui +import Box from '@mui/material/Box'; +import Button from '@mui/material/Button'; +import Chip from '@mui/material/Chip'; +import FormControlLabel from '@mui/material/FormControlLabel'; +import Grid from '@mui/material/Grid'; +import InputAdornment from '@mui/material/InputAdornment'; +import Link from '@mui/material/Link'; +import MenuItem from '@mui/material/MenuItem'; +import Stack from '@mui/material/Stack'; +import Switch from '@mui/material/Switch'; +import TextField from '@mui/material/TextField'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; + +// project imports +import ActionMenu, { MenuEntry } from 'components/ActionMenu'; +import DataTable, { Column } from 'components/DataTable'; +import { RelativeTime } from 'components/DateTime'; +import EmptyState from 'components/EmptyState'; +import GatedButton from 'components/GatedButton'; +import HoverHelp from 'components/HoverHelp'; +import IconButton from 'components/@extended/IconButton'; +import MainCard from 'components/MainCard'; +import OsIcon, { isWinPe, platformOf, WinPeChip } from 'components/OsIcon'; +import PageHeader from 'components/PageHeader'; +import { DeviceStatusChip } from 'components/StatusChip'; +import AddDeviceDialog from 'sections/devices/AddDeviceDialog'; +import useDeviceActions from 'sections/devices/useDeviceActions'; +import GroupTreePanel, { ALL_NODE, UNGROUPED_NODE } from 'sections/groups/GroupTreePanel'; +import useGroupActions from 'sections/groups/useGroupActions'; +import { isUpgradeActivity, newestFor, versionSortKey } from 'sections/upgrades/agentVersions'; +import { AgentVersion } from 'sections/upgrades/UpgradeChips'; +import useApi from 'hooks/useApi'; +import useAutomation from 'hooks/useAutomation'; +import useLiveRefresh from 'hooks/useLiveRefresh'; +import useSession, { useGate } from 'hooks/useSession'; +import { keys } from 'api/client'; +import { plural } from 'utils/format'; +import { ancestors, devicesInGroup, ungroupedDevices } from 'utils/groupTree'; +import type { AgentUpgradeDto, AgentVersionDto, DeviceDto, DeviceGroupDto } from 'api/types'; + +// assets +import CalendarOutlined from '@ant-design/icons/CalendarOutlined'; +import DownOutlined from '@ant-design/icons/DownOutlined'; +import MoreOutlined from '@ant-design/icons/MoreOutlined'; +import PlayCircleOutlined from '@ant-design/icons/PlayCircleOutlined'; +import PlusOutlined from '@ant-design/icons/PlusOutlined'; +import SearchOutlined from '@ant-design/icons/SearchOutlined'; + +type StatusFilter = 'all' | 'online' | 'stale' | 'offline' | 'orphaned'; + +const KIND_LABEL = { static: 'Static Group', dynamic: 'Dynamic Group', folder: 'Folder' } as const; + +function matches(device: DeviceDto, query: string): boolean { + return [ + device.hostname, + device.clientId, + device.manufacturer, + device.model, + device.osCaption, + device.publicIp, + ...device.ipAddresses, + ...(device.tags ?? []) + ].some((v) => v?.toLowerCase().includes(query)); +} + +// ==============================|| DEVICES ||============================== // + +export default function DevicesPage() { + const navigate = useNavigate(); + const [params, setParams] = useSearchParams(); + const { can } = useSession(); + const { openRun, openSchedule } = useAutomation(); + const addDeviceGate = useGate('settings.manage', 'Manage Settings'); + const newGroupGate = useGate('groups.manage', 'Manage Groups'); + + const { + data: devices, + error, + loading, + validating, + mutate: refreshDevices + } = useApi(keys.devices, { refreshInterval: 60_000 }); + const { data: groups, mutate: refreshGroups } = useApi(can('groups.view') ? keys.groups : null); + const { data: versions } = useApi(keys.agentVersions); + // One read of every open upgrade for the page, by device. + const { data: openUpgrades, mutate: refreshUpgrades } = useApi(keys.agentUpgrades({ open: true }), { + refreshInterval: 60_000 + }); + const openByDevice = useMemo(() => new Map((openUpgrades ?? []).map((u) => [u.clientId, u])), [openUpgrades]); + // Presence and inventory changes arrive as activity carrying a client id. + useLiveRefresh( + () => Promise.all([refreshDevices(), refreshGroups()]), + (event) => Boolean(event.clientId) + ); + useLiveRefresh(() => refreshUpgrades(), isUpgradeActivity); + + const selectedId = params.get('group') ?? ALL_NODE; + const search = params.get('q') ?? ''; + const status = (params.get('status') as StatusFilter) || 'all'; + const platform = params.get('platform') ?? 'all'; + const nested = params.get('nested') !== '0'; + + const setParam = (key: string, value: string | null) => + setParams( + (current) => { + const next = new URLSearchParams(current); + if (value === null || value === '' || value === 'all') next.delete(key); + else next.set(key, value); + return next; + }, + { replace: true } + ); + + const [chosen, setChosen] = useState>(new Set()); + const [menu, setMenu] = useState<{ anchor: HTMLElement; devices: DeviceDto[] } | null>(null); + const [groupMenu, setGroupMenu] = useState(null); + const [addOpen, setAddOpen] = useState(false); + + const selectedGroup = groups?.find((g) => g.id === selectedId) ?? null; + const groupActions = useGroupActions({ onDeleted: () => setParam('group', null) }); + const deviceActions = useDeviceActions({ + staticGroup: selectedGroup?.kind === 'static' ? selectedGroup : null, + onDone: () => setChosen(new Set()) + }); + + const inScope = useMemo(() => { + const list = devices ?? []; + if (selectedId === ALL_NODE) return list; + if (selectedId === UNGROUPED_NODE) return ungroupedDevices(list); + return devicesInGroup(list, groups ?? [], selectedId, nested); + }, [devices, groups, selectedId, nested]); + + const rows = useMemo(() => { + const query = search.trim().toLowerCase(); + return inScope.filter((d) => { + if (query && !matches(d, query)) return false; + if (status === 'orphaned' ? !d.isOrphaned : status !== 'all' && (d.status !== status || d.isOrphaned)) return false; + if (platform !== 'all' && platformOf(d.osCaption) !== platform) return false; + return true; + }); + }, [inScope, search, status, platform]); + + const chosenRows = rows.filter((d) => chosen.has(d.clientId)); + const groupName = (id: string) => groups?.find((g) => g.id === id)?.name ?? '…'; + + const title = + selectedId === ALL_NODE ? 'All Devices' : selectedId === UNGROUPED_NODE ? 'Ungrouped Devices' : (selectedGroup?.name ?? 'Group'); + const trail = selectedGroup ? [...ancestors(groups ?? [], selectedGroup.id).reverse(), selectedGroup] : []; + const online = inScope.filter((d) => d.status === 'online').length; + + const columns: Column[] = [ + { + id: 'hostname', + header: 'Name', + sortValue: (d) => d.hostname, + cell: (d) => ( + + + + e.stopPropagation()} + > + {d.hostname} + + + {d.clientId} + + + + ) + }, + { + id: 'status', + header: 'Status', + sortValue: (d) => (d.isOrphaned ? 'z' : d.status), + cell: (d) => + }, + { + id: 'os', + header: 'Operating System', + sortValue: (d) => d.osCaption, + cell: (d) => ( + + {isWinPe(d.osCaption) ? ( + + ) : ( + + {d.osCaption ?? '—'} + + )} + {d.osVersion && ( + + {d.osVersion} + + )} + + ) + }, + { + id: 'address', + header: 'Address', + sortValue: (d) => d.ipAddresses[0], + cell: (d) => + d.ipAddresses.length === 0 ? ( + '—' + ) : ( + + + {d.ipAddresses[0]} + {d.ipAddresses.length > 1 && ( + + {' '} + +{d.ipAddresses.length - 1} + + )} + + + ) + }, + ...(groups && groups.length > 0 + ? [ + { + id: 'groups', + header: 'Groups', + help: 'Groups the device is directly in. Parent groups include it too.', + sortValue: (d: DeviceDto) => d.groupIds?.length ?? 0, + cell: (d: DeviceDto) => { + const ids = d.groupIds ?? []; + return ids.length === 0 ? ( + + — + + ) : ( + + {ids.slice(0, 1).map((id) => ( + { + e.stopPropagation(); + setParam('group', id); + }} + /> + ))} + {ids.length > 1 && ( + + + + )} + + ); + } + } satisfies Column + ] + : []), + { + id: 'tags', + header: 'Tags', + sortValue: (d) => d.tags?.join(','), + cell: (d) => + (d.tags?.length ?? 0) === 0 ? ( + + — + + ) : ( + + {d.tags!.slice(0, 3).map((t) => ( + + ))} + {d.tags!.length > 3 && } + + ) + }, + { + id: 'agent', + header: 'Agent', + nowrap: true, + sortValue: (d) => versionSortKey(d.agentVersion), + cell: (d) => + }, + { + id: 'lastSeen', + header: 'Last Seen', + nowrap: true, + sortValue: (d) => d.lastSeenUtc, + cell: (d) => + }, + { + id: 'actions', + header: '', + width: 56, + align: 'right', + cell: (d) => ( + ) => { + e.stopPropagation(); + setMenu({ anchor: e.currentTarget, devices: [d] }); + }} + > + + + ) + } + ]; + + const toolbar = ( + + {chosenRows.length > 0 && ( + + + {plural(chosenRows.length, 'device')} chosen + + } + gate={can('jobs.run') ? undefined : 'Needs the Run Jobs permission.'} + onClick={() => openRun({ targets: chosenRows.filter((d) => !d.isOrphaned).map((d) => ({ kind: 'device', id: d.clientId })) })} + > + Run Script + + + + + )} + + setParam('q', e.target.value)} + sx={{ minWidth: 280, flex: 1 }} + slotProps={{ + input: { + startAdornment: ( + + + + ) + } + }} + /> + setParam('status', e.target.value)} + sx={{ minWidth: 140 }} + > + Any + Online + Stale + Offline + Orphaned + + setParam('platform', e.target.value)} + sx={{ minWidth: 140 }} + > + Any + Windows + Linux + macOS + + {selectedGroup && ( + setParam('nested', e.target.checked ? null : '0')} />} + label={ + + Include Nested Groups + + + } + sx={{ ml: 0, whiteSpace: 'nowrap' }} + /> + )} + + + ); + + const groupMenuEntries: MenuEntry[] = selectedGroup ? groupActions.menuFor(selectedGroup) : []; + + return ( + + d.status === 'online').length} online.` + : undefined + } + primaryAction={ + } gate={addDeviceGate} onClick={() => setAddOpen(true)}> + Add Device + + } + /> + + + {can('groups.view') && ( + + { + setChosen(new Set()); + setParam('group', id === ALL_NODE ? null : id); + }} + menuFor={groupActions.menuFor} + canMove={groupActions.canMove} + onMove={groupActions.requestMove} + draggable={can('groups.manage')} + onNewGroup={() => groupActions.openEditor({ preset: { parentId: selectedGroup?.id ?? null } })} + newGroupGate={newGroupGate} + /> + + )} + + + + {trail.length > 1 && ( + + {trail.slice(0, -1).map((g) => ( + setParam('group', g.id)}> + {g.name} › + + ))} + + )} + + + {title} + + {selectedGroup && } + + + {plural(inScope.length, 'device')}, {online} online + {selectedGroup?.description ? ` · ${selectedGroup.description}` : ''} + + + } + secondary={ + selectedGroup && ( + + } + gate={ + !can('jobs.run') + ? 'Needs the Run Jobs permission.' + : inScope.length === 0 + ? 'No devices in this group yet.' + : undefined + } + onClick={() => openRun({ targets: [{ kind: 'group', id: selectedGroup.id }] })} + > + Run on Group + + } + gate={can('automation.manage') ? undefined : 'Needs the Manage Automation permission.'} + onClick={() => openSchedule({ preset: { target: { kind: 'group', id: selectedGroup.id } } })} + > + Schedule + + setGroupMenu(e.currentTarget)} + > + + + + ) + } + > + d.clientId} + loading={loading} + refreshing={validating && !loading} + error={error?.message} + toolbar={toolbar} + defaultSort={{ id: 'hostname', direction: 'asc' }} + rowLabel={(d) => d.hostname} + onRowClick={(d) => navigate(`/devices/${encodeURIComponent(d.clientId)}`)} + minWidth={1100} + selection={{ + selected: chosen, + onChange: (ids, on) => + setChosen((current) => { + const next = new Set(current); + for (const id of ids) { + if (on) next.add(id); + else next.delete(id); + } + return next; + }) + }} + empty={ + (devices?.length ?? 0) === 0 ? ( + setAddOpen(true)}> + Add Device + + } + /> + ) : inScope.length === 0 ? ( + + ) : ( + + ) + } + /> + + + + + {menu && setMenu(null)} entries={deviceActions.menuFor(menu.devices)} />} + {groupMenu && setGroupMenu(null)} entries={groupMenuEntries} />} + {deviceActions.elements} + {groupActions.elements} + + setAddOpen(false)} /> + + + ); +} diff --git a/src/WebUI/src/pages/devices/shell.tsx b/src/WebUI/src/pages/devices/shell.tsx new file mode 100644 index 0000000..654c678 --- /dev/null +++ b/src/WebUI/src/pages/devices/shell.tsx @@ -0,0 +1,217 @@ +import { useEffect } from 'react'; +import { useParams } from 'react-router-dom'; + +// material-ui +import Alert from '@mui/material/Alert'; +import Box from '@mui/material/Box'; +import Button from '@mui/material/Button'; +import MenuItem from '@mui/material/MenuItem'; +import Stack from '@mui/material/Stack'; +import TextField from '@mui/material/TextField'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; + +// third-party +import { enqueueSnackbar } from 'notistack'; + +// project imports +import GatedButton from 'components/GatedButton'; +import HoverHelp from 'components/HoverHelp'; +import MainCard from 'components/MainCard'; +import { platformOf } from 'components/OsIcon'; +import PageHeader from 'components/PageHeader'; +import StatusChip from 'components/StatusChip'; +import useApi from 'hooks/useApi'; +import useSession, { useGate } from 'hooks/useSession'; +import useRemoteShell, { SHELL_KINDS, shellLabel, ShellKind, ShellState, TERMINAL_THEME } from 'sections/shell/useRemoteShell'; +import { keys } from 'api/client'; +import type { DeviceDetailDto } from 'api/types'; + +// assets +import '@xterm/xterm/css/xterm.css'; +import ExportOutlined from '@ant-design/icons/ExportOutlined'; +import ImportOutlined from '@ant-design/icons/ImportOutlined'; +import PoweroffOutlined from '@ant-design/icons/PoweroffOutlined'; +import ReloadOutlined from '@ant-design/icons/ReloadOutlined'; + +/** Session state → status word (for the chip's tone) and label. */ +const STATUS: Record = { + connecting: { status: 'queued', label: 'Connecting' }, + opening: { status: 'dispatched', label: 'Opening Shell' }, + open: { status: 'online', label: 'Connected' }, + noResponse: { status: 'stale', label: 'No Response' }, + closed: { status: 'offline', label: 'Closed' }, + failed: { status: 'failed', label: 'Failed' }, + disconnected: { status: 'offline', label: 'Disconnected' } +}; + +/** States with a session that can still be closed from here. */ +const ACTIVE: ShellState[] = ['connecting', 'opening', 'open', 'noResponse']; + +/** Which shell a Windows device starts; picking one opens a new session with it. */ +function ShellPicker({ value, started, onChange }: { value: ShellKind; started?: string; onChange: (kind: ShellKind) => void }) { + return ( + onChange(e.target.value as ShellKind)} + sx={{ minWidth: 200 }} + slotProps={{ + select: { + // Automatic shows what it picked once the session is open. + renderValue: (kind) => { + const label = shellLabel(kind as string); + return kind === 'auto' && started && shellLabel(started) ? `${label} · ${shellLabel(started)}` : label; + } + } + }} + > + {SHELL_KINDS.map(({ kind, label, hint }) => ( + + + {label} + + + ))} + + ); +} + +function ShellView({ clientId }: { clientId: string }) { + const { can } = useSession(); + const gate = useGate('shell.use', 'Remote Shell'); + const allowed = !gate; + const { data: detail } = useApi(can('devices.view') ? keys.device(clientId) : null); + const { + hostRef, + state, + message, + hostname, + poppedOut, + shell, + startedShell, + controller, + close, + reconnect, + popOut, + focusWindow, + chooseShell + } = useRemoteShell(clientId, allowed); + // The shell choice applies to Windows devices only (unix agents start the login shell). + const windows = platformOf(detail?.device.osCaption) === 'windows'; + + const knownHostname = detail?.device.hostname; + useEffect(() => { + if (knownHostname) controller?.knownHostname(knownHostname); + }, [controller, knownHostname]); + + const name = hostname || knownHostname || clientId.slice(0, 12); + const active = ACTIVE.includes(state); + const status = STATUS[state]; + + const openWindow = () => { + if (!popOut()) { + enqueueSnackbar('The browser blocked the new window. Allow pop-ups for this site and try again.', { variant: 'warning' }); + } + }; + // Bringing it back from this page never needs to navigate. + const bringBack = () => controller?.dock(() => {}); + + return ( + + {`${shellLabel(startedShell) ?? 'Shell'} · ${name} · ExecuteR`} + } + secondaryActions={ + allowed && ( + <> + {windows && controller && } + {poppedOut ? ( + + ) : ( + + )} + + ) + } + primaryAction={ + active ? ( + + ) : ( + } onClick={reconnect} gate={gate}> + Reconnect + + ) + } + /> + + {gate ? ( + + {gate} + + + ) : ( + <> + {(state === 'failed' || state === 'noResponse') && message && ( + {message} + )} + + + {/* xterm sizes itself to this element (the padding lives on the parent so fitting stays exact). + It stays mounted while popped out so closing the window can dock the terminal straight back. */} + + {poppedOut && ( + + + + This Shell Is In Its Own Window + + + + + + + + )} + + + + )} + + ); +} + +// ==============================|| DEVICE - REMOTE SHELL ||============================== // + +export default function DeviceShell() { + const { clientId = '' } = useParams(); + // A new device means a new terminal and session. + return ; +} diff --git a/src/WebUI/src/pages/functions/index.tsx b/src/WebUI/src/pages/functions/index.tsx new file mode 100644 index 0000000..2d2dd5f --- /dev/null +++ b/src/WebUI/src/pages/functions/index.tsx @@ -0,0 +1,199 @@ +import { useMemo, useState } from 'react'; +import { useSearchParams } from 'react-router-dom'; + +// material-ui +import Alert from '@mui/material/Alert'; +import Box from '@mui/material/Box'; +import Grid from '@mui/material/Grid'; +import InputAdornment from '@mui/material/InputAdornment'; +import List from '@mui/material/List'; +import ListItemButton from '@mui/material/ListItemButton'; +import ListItemText from '@mui/material/ListItemText'; +import Skeleton from '@mui/material/Skeleton'; +import Stack from '@mui/material/Stack'; +import TextField from '@mui/material/TextField'; + +// project imports +import ConfirmDialog from 'components/ConfirmDialog'; +import { RelativeTime } from 'components/DateTime'; +import EmptyState from 'components/EmptyState'; +import GatedButton from 'components/GatedButton'; +import HoverHelp from 'components/HoverHelp'; +import MainCard from 'components/MainCard'; +import PageHeader from 'components/PageHeader'; +import FunctionEditor from 'sections/functions/FunctionEditor'; +import { errorMessage, keys } from 'api/client'; +import useApi from 'hooks/useApi'; +import { useGate } from 'hooks/useSession'; +import { plural } from 'utils/format'; + +// assets +import FunctionOutlined from '@ant-design/icons/FunctionOutlined'; +import PlusOutlined from '@ant-design/icons/PlusOutlined'; +import SearchOutlined from '@ant-design/icons/SearchOutlined'; + +// types +import type { FunctionModuleDto } from 'api/types'; + +const NEW = 'new'; + +// ==============================|| FUNCTIONS ||============================== // + +export default function FunctionsPage() { + const [params, setParams] = useSearchParams(); + const selectedId = params.get('id'); + const gate = useGate('functions.manage', 'Manage Functions'); + const { data: modules, error, loading } = useApi(keys.functions); + + const [search, setSearch] = useState(''); + const [dirty, setDirty] = useState(false); + // A switch waiting on "discard unsaved changes?" (undefined: none pending). + const [pending, setPending] = useState(undefined); + + const sorted = useMemo(() => [...(modules ?? [])].sort((a, b) => a.name.localeCompare(b.name)), [modules]); + const visible = useMemo(() => { + const needle = search.trim().toLowerCase(); + return needle ? sorted.filter((m) => m.name.toLowerCase().includes(needle) || m.description?.toLowerCase().includes(needle)) : sorted; + }, [sorted, search]); + + const selected = selectedId && selectedId !== NEW ? modules?.find((m) => m.id === selectedId) : undefined; + + const go = (id: string | null) => + setParams((current) => { + const next = new URLSearchParams(current); + if (id) next.set('id', id); + else next.delete('id'); + return next; + }); + + /** Switches module, asking first when the open one has unsaved edits. */ + const select = (id: string | null) => { + if (id === selectedId) return; + if (dirty) setPending(id); + else go(id); + }; + + let editor; + if (selectedId === NEW) { + editor = ( + m.name)} + gate={gate} + onSelect={go} + onDirtyChange={setDirty} + /> + ); + } else if (selected) { + editor = ( + m.name)} + gate={gate} + onSelect={go} + onDirtyChange={setDirty} + /> + ); + } else if (selectedId && loading) { + editor = ( + + + + ); + } else { + editor = ( + + } + title={selectedId ? 'Function Not Found' : 'No Function Selected'} + detail={selectedId ? 'It may have been deleted.' : 'Pick one or create one.'} + /> + + ); + } + + return ( + + + Reusable PowerShell functions. + + + } + primaryAction={ + } onClick={() => select(NEW)}> + New Function + + } + /> + + + + + + setSearch(e.target.value)} + slotProps={{ + input: { + startAdornment: ( + + + + ) + } + }} + /> + + {error && ( + + {errorMessage(error, 'Could not load functions.')} + + )} + {loading ? ( + + {Array.from({ length: 4 }, (_, i) => ( + + ))} + + ) : !error && sorted.length === 0 ? ( + + ) : !error && visible.length === 0 ? ( + + ) : ( + + {visible.map((m) => ( + select(m.id)} sx={{ borderRadius: 1 }}> + } + slotProps={{ primary: { noWrap: true, sx: { fontWeight: 600 } }, secondary: { component: 'div' } }} + /> + + ))} + + )} + + + {editor} + + + go(pending ?? null)} + onClose={() => setPending(undefined)} + /> + + ); +} diff --git a/src/WebUI/src/pages/groups/index.tsx b/src/WebUI/src/pages/groups/index.tsx new file mode 100644 index 0000000..11ca6d5 --- /dev/null +++ b/src/WebUI/src/pages/groups/index.tsx @@ -0,0 +1,421 @@ +import { MouseEvent, useMemo, useState } from 'react'; +import { Link as RouterLink, useSearchParams } from 'react-router-dom'; + +// material-ui +import Button from '@mui/material/Button'; +import Chip from '@mui/material/Chip'; +import Grid from '@mui/material/Grid'; +import Link from '@mui/material/Link'; +import Stack from '@mui/material/Stack'; +import Typography from '@mui/material/Typography'; + +// project imports +import ActionMenu from 'components/ActionMenu'; +import DataTable, { Column } from 'components/DataTable'; +import { RelativeTime } from 'components/DateTime'; +import EmptyState from 'components/EmptyState'; +import GatedButton from 'components/GatedButton'; +import HoverHelp from 'components/HoverHelp'; +import IconButton from 'components/@extended/IconButton'; +import MainCard from 'components/MainCard'; +import PageHeader from 'components/PageHeader'; +import Properties from 'components/Properties'; +import GroupTreePanel, { ALL_NODE } from 'sections/groups/GroupTreePanel'; +import useGroupActions from 'sections/groups/useGroupActions'; +import ScheduleTable from 'sections/schedules/ScheduleTable'; +import useApi from 'hooks/useApi'; +import useAutomation from 'hooks/useAutomation'; +import useLiveRefresh from 'hooks/useLiveRefresh'; +import useSession, { useGate } from 'hooks/useSession'; +import { keys } from 'api/client'; +import { plural } from 'utils/format'; +import { devicesInGroup, groupPath } from 'utils/groupTree'; +import type { DeviceDto, DeviceGroupDto, GroupFieldDescriptor, GroupRuleSet, RuleCondition, ScriptTriggerDto } from 'api/types'; + +// assets +import ApartmentOutlined from '@ant-design/icons/ApartmentOutlined'; +import CalendarOutlined from '@ant-design/icons/CalendarOutlined'; +import EditOutlined from '@ant-design/icons/EditOutlined'; +import MoreOutlined from '@ant-design/icons/MoreOutlined'; +import PlayCircleOutlined from '@ant-design/icons/PlayCircleOutlined'; +import PlusOutlined from '@ant-design/icons/PlusOutlined'; + +const KIND_LABEL = { static: 'Static', dynamic: 'Dynamic', folder: 'Folder' } as const; + +const OPERATOR_TEXT: Record = { + equals: 'is', + notEquals: 'is not', + contains: 'contains', + notContains: 'does not contain', + startsWith: 'starts with', + endsWith: 'ends with', + regex: 'matches', + in: 'is one of', + notIn: 'is none of', + greaterThan: '>', + greaterOrEqual: '≥', + lessThan: '<', + lessOrEqual: '≤', + exists: 'has a value', + notExists: 'has no value', + inCidr: 'is in', + notInCidr: 'is not in' +}; + +/** Rules in plain words, one line per block ("Tags is web AND OS name contains Server"). */ +function describeRules(rules: GroupRuleSet | undefined, fields: GroupFieldDescriptor[]): string[] { + const label = (c: RuleCondition) => fields.find((f) => f.field === c.field)?.displayName ?? c.field; + return (rules?.groups ?? []).map((block) => { + const parts = (block.conditions ?? []).map( + (c) => `${c.negate ? 'NOT ' : ''}${label(c)} ${OPERATOR_TEXT[c.operator] ?? c.operator}${c.value ? ` “${c.value}”` : ''}` + ); + const text = parts.length > 0 ? parts.join(block.combine === 'and' ? ' AND ' : ' OR ') : '(no conditions)'; + return block.negate ? `NOT (${text})` : text; + }); +} + +// ==============================|| GROUPS ||============================== // + +export default function GroupsPage() { + const [params, setParams] = useSearchParams(); + const { can } = useSession(); + const { openRun, openSchedule } = useAutomation(); + const manageGate = useGate('groups.manage', 'Manage Groups'); + const [menuAnchor, setMenuAnchor] = useState(null); + + const { data: groups, error, loading, mutate: refreshGroups } = useApi(keys.groups); + const { data: devices, mutate: refreshDevices } = useApi(keys.devices); + const { data: fields } = useApi(keys.groupFields); + const { data: triggers, loading: triggersLoading } = useApi(can('automation.view') ? keys.triggers : null); + useLiveRefresh( + () => Promise.all([refreshGroups(), refreshDevices()]), + (event) => Boolean(event.clientId) + ); + + const selectedId = params.get('group') ?? ALL_NODE; + const select = (id: string) => setParams(id === ALL_NODE ? {} : { group: id }, { replace: true }); + const group = groups?.find((g) => g.id === selectedId) ?? null; + const actions = useGroupActions({ onDeleted: () => select(ALL_NODE), onSaved: (saved) => select(saved.id) }); + + const scheduleCount = (id: string) => (triggers ?? []).filter((t) => t.groupId === id).length; + + const overviewColumns: Column[] = [ + { + id: 'name', + header: 'Group', + sortValue: (g) => groupPath(groups ?? [], g.id), + cell: (g) => ( + + {g.name} + {g.parentId && ( + + {groupPath(groups ?? [], g.parentId)} + + )} + + ) + }, + { + id: 'kind', + header: 'Kind', + sortValue: (g) => g.kind, + cell: (g) => + }, + { + id: 'members', + header: 'Devices', + align: 'right', + help: 'Including nested groups; the group’s own count in brackets.', + sortValue: (g) => g.memberCount, + cell: (g) => ( + + {g.memberCount} + {g.kind !== 'folder' && g.directMemberCount !== g.memberCount && ( + + {' '} + ({g.directMemberCount}) + + )} + + ) + }, + { id: 'online', header: 'Online', align: 'right', sortValue: (g) => g.onlineCount, cell: (g) => g.onlineCount }, + ...(can('automation.view') + ? [ + { + id: 'schedules', + header: 'Schedules', + align: 'right', + sortValue: (g: DeviceGroupDto) => scheduleCount(g.id), + cell: (g: DeviceGroupDto) => scheduleCount(g.id) || '—' + } satisfies Column + ] + : []), + { id: 'updated', header: 'Updated', nowrap: true, sortValue: (g) => g.updatedUtc, cell: (g) => } + ]; + + const children = useMemo(() => (groups ?? []).filter((g) => g.parentId === selectedId), [groups, selectedId]); + const members = group && devices ? devicesInGroup(devices, groups ?? [], group.id) : []; + + return ( + + + Folders, static groups and dynamic groups. + + + } + primaryAction={ + } + gate={manageGate} + onClick={() => actions.openEditor({ preset: { parentId: group?.id ?? null } })} + > + New Group + + } + /> + + + + + + + + {!group ? ( + + All Groups + + + } + content={false} + > + g.id} + loading={loading} + error={error?.message} + defaultSort={{ id: 'name', direction: 'asc' }} + onRowClick={(g) => select(g.id)} + empty={ + } + title="No Groups Yet" + detail="Run and schedule scripts on many devices." + action={ + actions.openEditor()}> + New Group + + } + /> + } + /> + + ) : ( + + + {group.name} + + + } + subheader={group.parentId ? groupPath(groups ?? [], group.parentId) : 'Top level'} + secondary={ + + } + gate={ + !can('jobs.run') + ? 'Needs the Run Jobs permission.' + : group.memberCount === 0 + ? 'No devices in this group yet.' + : undefined + } + onClick={() => openRun({ targets: [{ kind: 'group', id: group.id }] })} + > + Run Script + + } + gate={manageGate} + onClick={() => actions.openEditor({ group })} + > + Edit + + ) => setMenuAnchor(e.currentTarget)} + > + + + + } + > + + + + {plural(group.memberCount, 'device')}, {group.onlineCount} online + + ) + }, + ...(group.kind !== 'folder' && group.directMemberCount !== group.memberCount + ? [{ label: 'Its Own', value: `${plural(group.directMemberCount, 'device')} (the rest via nested groups)` }] + : []), + { label: 'Nested Groups', value: children.length > 0 ? children.length : 'None' }, + { + label: 'Updated', + value: ( + + {} + {group.updatedBy ? ` by ${group.updatedBy}` : ''} + + ) + } + ]} + /> + + + {group.kind === 'dynamic' && ( + + Rules + {describeRules(group.rules, fields ?? []).map((line, i, all) => ( + + + {line} + + {i < all.length - 1 && ( + + {group.rules?.combine === 'or' ? 'OR' : 'AND'} + + )} + + ))} + {(group.rules?.groups ?? []).length === 0 && ( + + No rules; matches no devices. + + )} + + )} + {group.kind === 'static' && ( + + Listed Devices + + {members + .filter((d) => d.groupIds?.includes(group.id)) + .slice(0, 24) + .map((d) => ( + + ))} + {group.directMemberCount > 24 && } + {group.directMemberCount === 0 && ( + + None listed. + + + )} + + + )} + {group.kind === 'folder' && ( + + No devices of its own. + + + )} + + + + + {children.length > 0 && ( + + c.id !== 'updated')} + rows={children} + rowId={(g) => g.id} + paged={false} + defaultSort={{ id: 'name', direction: 'asc' }} + onRowClick={(g) => select(g.id)} + /> + + )} + + {can('automation.view') && ( + + Schedules + + + } + content={false} + secondary={ + } + gate={can('automation.manage') ? undefined : 'Needs the Manage Automation permission.'} + onClick={() => openSchedule({ preset: { target: { kind: 'group', id: group.id } } })} + > + New Schedule + + } + > + t.groupId === group.id)} + loading={triggersLoading} + hideTarget + empty={} + /> + + )} + + + )} + + + + {menuAnchor && group && setMenuAnchor(null)} entries={actions.menuFor(group)} />} + {actions.elements} + + ); +} diff --git a/src/WebUI/src/pages/jobs/index.tsx b/src/WebUI/src/pages/jobs/index.tsx new file mode 100644 index 0000000..f1f1239 --- /dev/null +++ b/src/WebUI/src/pages/jobs/index.tsx @@ -0,0 +1,296 @@ +import { MouseEvent, useCallback, useEffect, useMemo, useState } from 'react'; +import { Link as RouterLink, Navigate, useSearchParams } from 'react-router-dom'; + +// material-ui +import Button from '@mui/material/Button'; +import Chip from '@mui/material/Chip'; +import InputAdornment from '@mui/material/InputAdornment'; +import Link from '@mui/material/Link'; +import MenuItem from '@mui/material/MenuItem'; +import Stack from '@mui/material/Stack'; +import Tab from '@mui/material/Tab'; +import Tabs from '@mui/material/Tabs'; +import TextField from '@mui/material/TextField'; +import Typography from '@mui/material/Typography'; + +// project imports +import DataTable, { Column } from 'components/DataTable'; +import { RelativeTime } from 'components/DateTime'; +import EmptyState from 'components/EmptyState'; +import HoverHelp from 'components/HoverHelp'; +import MainCard from 'components/MainCard'; +import PageHeader from 'components/PageHeader'; +import { JobStateChip } from 'components/StatusChip'; +import JobOutputDrawer from 'sections/jobs/JobOutputDrawer'; +import RecentRuns from 'sections/runs/RecentRuns'; +import { errorMessage, keys } from 'api/client'; +import useApi from 'hooks/useApi'; +import useLiveRefresh from 'hooks/useLiveRefresh'; +import { nats } from 'messaging/nats'; +import { formatDuration } from 'utils/format'; + +// assets +import SearchOutlined from '@ant-design/icons/SearchOutlined'; + +// types +import type { JobDto, JobState } from 'api/types'; + +const STATES: { value: JobState; label: string }[] = [ + { value: 'queued', label: 'Queued' }, + { value: 'dispatched', label: 'Dispatched' }, + { value: 'running', label: 'Running' }, + { value: 'succeeded', label: 'Succeeded' }, + { value: 'failed', label: 'Failed' }, + { value: 'cancelled', label: 'Cancelled' }, + { value: 'timedOut', label: 'Timed Out' } +]; + +const LIMITS = [100, 250, 500]; + +const durationMs = (job: JobDto) => + job.startedUtc && job.completedUtc ? new Date(job.completedUtc).getTime() - new Date(job.startedUtc).getTime() : null; + +const stop = (event: MouseEvent) => event.stopPropagation(); + +type View = 'runs' | 'jobs'; + +// ==============================|| JOBS ||============================== // + +export default function JobsPage() { + const [params, setParams] = useSearchParams(); + const clientId = params.get('clientId') ?? undefined; + const scriptId = params.get('scriptId') ?? undefined; + const runId = params.get('runId') ?? undefined; + // Case-insensitive so links like ?state=failed (the dashboard's Failed tile) keep working. + const stateParam = params.get('state')?.toLowerCase() ?? ''; + const stateFilter = STATES.find((s) => s.value.toLowerCase() === stateParam)?.value ?? ''; + const openJobId = params.get('job'); + // Job filters (from the dashboard, a device or a script) open the job history; otherwise runs. + const view: View = (params.get('view') as View | null) ?? (clientId || scriptId || stateParam || openJobId ? 'jobs' : 'runs'); + + const [limit, setLimit] = useState(100); + const [search, setSearch] = useState(''); + + const history = useApi(view === 'jobs' && !runId ? keys.jobs({ clientId, scriptId, limit }) : null); + const { mutate: mutateHistory } = history; + const refresh = useCallback(() => mutateHistory(), [mutateHistory]); + useLiveRefresh(refresh, (event) => Boolean(event.jobId)); + + // Job state changes arrive on the job channel too; coalesce bursts from group runs. + useEffect(() => { + if (view !== 'jobs') return; + let timer: number | undefined; + const off = nats.onJobEvent((_, event) => { + if (event.type !== 'job.state') return; + window.clearTimeout(timer); + timer = window.setTimeout(() => void refresh(), 500); + }); + return () => { + window.clearTimeout(timer); + off(); + }; + }, [refresh, view]); + + const rows = useMemo(() => { + const needle = search.trim().toLowerCase(); + return history.data?.filter( + (job) => + (!stateFilter || job.state === stateFilter) && + (!needle || [job.scriptName, job.hostname, job.clientId, job.requestedBy, job.jobId].some((v) => v?.toLowerCase().includes(needle))) + ); + }, [history.data, stateFilter, search]); + + const setParam = (name: string, value: string | null, replace = true) => + setParams( + (current) => { + const next = new URLSearchParams(current); + if (value) next.set(name, value); + else next.delete(name); + return next; + }, + { replace } + ); + + const clearFilters = () => { + setSearch(''); + setParams((current) => { + const next = new URLSearchParams({ view: 'jobs' }); + const job = current.get('job'); + if (job) next.set('job', job); + return next; + }); + }; + + // Older links to one run's jobs now open the run itself. + if (runId) return ; + + // Names for the filter chips, taken from the rows themselves. + const deviceName = clientId && (history.data?.find((j) => j.clientId === clientId)?.hostname ?? clientId); + const scriptName = scriptId && (history.data?.find((j) => j.scriptId === scriptId)?.scriptName ?? 'Script'); + const filtered = Boolean(stateFilter || clientId || scriptId || search.trim()); + + const columns: Column[] = [ + { + id: 'state', + header: 'State', + cell: (job) => , + sortValue: (job) => job.state, + width: 130 + }, + { + id: 'script', + header: 'Script', + cell: (job) => ( + + {job.scriptName} + + ), + sortValue: (job) => job.scriptName + }, + { + id: 'device', + header: 'Device', + cell: (job) => ( + + {job.hostname ?? job.clientId.slice(0, 10)} + + ), + sortValue: (job) => job.hostname ?? job.clientId + }, + { + id: 'requestedBy', + header: 'Requested By', + cell: (job) => ( + + {job.requestedBy ?? '—'} + + ), + sortValue: (job) => job.requestedBy + }, + { + id: 'created', + header: 'Created', + cell: (job) => , + sortValue: (job) => job.createdUtc, + nowrap: true + }, + { + id: 'duration', + header: 'Duration', + cell: (job) => formatDuration(job.startedUtc, job.completedUtc), + sortValue: durationMs, + nowrap: true + }, + { + id: 'exitCode', + header: 'Exit Code', + cell: (job) => {job.exitCode ?? '—'}, + sortValue: (job) => job.exitCode, + align: 'right', + width: 100 + } + ]; + + const toolbar = ( + + setSearch(e.target.value)} + sx={{ width: { xs: '100%', sm: 260 } }} + slotProps={{ + input: { + startAdornment: ( + + + + ) + } + }} + /> + setParam('state', e.target.value || null)} + sx={{ minWidth: 160 }} + > + All States + {STATES.map((s) => ( + + {s.label} + + ))} + + setLimit(Number(e.target.value))} sx={{ minWidth: 130 }}> + {LIMITS.map((n) => ( + + Latest {n} + + ))} + + {deviceName && setParam('clientId', null)} />} + {scriptName && setParam('scriptId', null)} />} + {filtered && ( + + )} + + ); + + return ( + + + + + setParams({ view: next })} sx={{ px: 2, borderBottom: 1, borderColor: 'divider' }}> + + + Jobs + + + } + /> + + {view === 'runs' ? ( + + ) : ( + job.jobId} + loading={history.loading} + refreshing={history.validating} + error={history.error ? errorMessage(history.error, 'Could not load jobs.') : undefined} + toolbar={toolbar} + defaultSort={{ id: 'created', direction: 'desc' }} + onRowClick={(job) => setParam('job', job.jobId, false)} + activeRowId={openJobId ?? undefined} + empty={ + filtered && (history.data?.length ?? 0) > 0 ? ( + + Clear Filters + + } + /> + ) : ( + + ) + } + /> + )} + + + setParam('job', null)} /> + + ); +} diff --git a/src/WebUI/src/pages/maintenance/404.tsx b/src/WebUI/src/pages/maintenance/404.tsx new file mode 100644 index 0000000..cd37d37 --- /dev/null +++ b/src/WebUI/src/pages/maintenance/404.tsx @@ -0,0 +1,30 @@ +import { Link } from 'react-router-dom'; + +// material-ui +import Button from '@mui/material/Button'; + +// project imports +import EmptyState from 'components/EmptyState'; +import MainCard from 'components/MainCard'; + +// assets +import CompassOutlined from '@ant-design/icons/CompassOutlined'; + +// ==============================|| NOT FOUND ||============================== // + +export default function NotFound() { + return ( + + } + title="Page Not Found" + detail="No page at this address." + action={ + + } + /> + + ); +} diff --git a/src/WebUI/src/pages/runs/detail.tsx b/src/WebUI/src/pages/runs/detail.tsx new file mode 100644 index 0000000..6877a99 --- /dev/null +++ b/src/WebUI/src/pages/runs/detail.tsx @@ -0,0 +1,122 @@ +import { useParams, useSearchParams } from 'react-router-dom'; + +// material-ui +import Alert from '@mui/material/Alert'; +import Button from '@mui/material/Button'; +import Stack from '@mui/material/Stack'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; + +// project imports +import { RelativeTime } from 'components/DateTime'; +import GatedButton from 'components/GatedButton'; +import MainCard from 'components/MainCard'; +import PageHeader from 'components/PageHeader'; +import StatusChip from 'components/StatusChip'; +import JobOutputDrawer from 'sections/jobs/JobOutputDrawer'; +import RunProgress, { RUN_SOURCE_LABEL, runCounts, runFinished, useRun } from 'sections/runs/RunProgress'; +import { downloads, errorMessage } from 'api/client'; +import useAutomation from 'hooks/useAutomation'; +import { useGate } from 'hooks/useSession'; + +// assets +import DownloadOutlined from '@ant-design/icons/DownloadOutlined'; +import PlayCircleOutlined from '@ant-design/icons/PlayCircleOutlined'; + +// types +import type { ExecutionDetailDto } from 'api/types'; + +/** Running / Complete / Complete With Failures, for the header. */ +function RunStatus({ run }: { run: ExecutionDetailDto }) { + const counts = runCounts(run); + if (!runFinished(counts)) return ; + return counts.failed > 0 ? ( + + ) : ( + + ); +} + +// ==============================|| RUN ||============================== // + +export default function RunPage() { + const { runId = '' } = useParams(); + const [params, setParams] = useSearchParams(); + const openJobId = params.get('job'); + const runGate = useGate('jobs.run', 'Run Jobs'); + const { openRun } = useAutomation(); + const execution = useRun(runId); + const run = execution.data; + + const setJob = (jobId: string | null) => + setParams( + (current) => { + const next = new URLSearchParams(current); + if (jobId) next.set('job', jobId); + else next.delete('job'); + return next; + }, + { replace: !jobId } + ); + + // The same script on the same devices (skipped ones included: they may be back). + const runAgain = () => + run && + openRun({ + scriptId: run.scriptId, + targets: [...run.targets.map((t) => t.clientId), ...(run.skipped ?? []).map((s) => s.clientId)].map((id) => ({ + kind: 'device' as const, + id + })) + }); + + return ( + + {`${run?.scriptName ?? 'Run'} · Runs · ExecuteR`} + } + description={ + run && ( + + Started + {run.requestedBy ? ` by ${run.requestedBy}` : ''} + {run.source ? ` · ${RUN_SOURCE_LABEL[run.source] ?? run.source}` : ''} + {run.targetsLabel ? ` · ${run.targetsLabel}` : ''} + {run.onlineOnly ? ' · Online Only' : ''} + + ) + } + secondaryActions={ + + + + } + primaryAction={ + } gate={runGate} disabled={!run} onClick={runAgain}> + Run Again + + } + /> + + {execution.error && !run ? ( + {errorMessage(execution.error, 'Could not load the run.')} + ) : ( + + + + )} + + setJob(null)} /> + + ); +} diff --git a/src/WebUI/src/pages/schedules/index.tsx b/src/WebUI/src/pages/schedules/index.tsx new file mode 100644 index 0000000..6506564 --- /dev/null +++ b/src/WebUI/src/pages/schedules/index.tsx @@ -0,0 +1,122 @@ +import { useMemo } from 'react'; +import { useSearchParams } from 'react-router-dom'; + +// material-ui +import InputAdornment from '@mui/material/InputAdornment'; +import Stack from '@mui/material/Stack'; +import TextField from '@mui/material/TextField'; +import ToggleButton from '@mui/material/ToggleButton'; +import ToggleButtonGroup from '@mui/material/ToggleButtonGroup'; + +// project imports +import GatedButton from 'components/GatedButton'; +import MainCard from 'components/MainCard'; +import PageHeader from 'components/PageHeader'; +import ScheduleTable, { targetText, whenText } from 'sections/schedules/ScheduleTable'; +import useApi from 'hooks/useApi'; +import useAutomation from 'hooks/useAutomation'; +import useLiveRefresh from 'hooks/useLiveRefresh'; +import { useGate } from 'hooks/useSession'; +import { keys } from 'api/client'; +import type { ScriptTriggerDto } from 'api/types'; + +// assets +import PlusOutlined from '@ant-design/icons/PlusOutlined'; +import SearchOutlined from '@ant-design/icons/SearchOutlined'; + +type Kind = 'all' | 'scheduled' | 'events' | 'paused'; + +// ==============================|| SCHEDULES ||============================== // + +export default function SchedulesPage() { + const [params, setParams] = useSearchParams(); + const { openSchedule } = useAutomation(); + const manageGate = useGate('automation.manage', 'Manage Automation'); + const { data, error, loading, mutate } = useApi(keys.triggers, { refreshInterval: 60_000 }); + // Firings show up as job activity; refresh so Last Run/Next Run stay current. + useLiveRefresh( + () => mutate(), + (event) => event.kind === 'job-created' + ); + + const kind = (params.get('kind') as Kind) || 'all'; + const search = params.get('q') ?? ''; + const setParam = (key: string, value: string) => + setParams( + (current) => { + const next = new URLSearchParams(current); + if (value && value !== 'all') next.set(key, value); + else next.delete(key); + return next; + }, + { replace: true } + ); + + const rows = useMemo(() => { + const query = search.trim().toLowerCase(); + return (data ?? []).filter((t) => { + if (kind === 'scheduled' && t.triggerType !== 'scheduled') return false; + if (kind === 'events' && t.triggerType === 'scheduled') return false; + if (kind === 'paused' && t.enabled) return false; + if (!query) return true; + return [t.name, t.scriptName, whenText(t), targetText(t)].some((v) => v?.toLowerCase().includes(query)); + }); + }, [data, kind, search]); + + const counts = useMemo( + () => ({ + all: data?.length ?? 0, + scheduled: data?.filter((t) => t.triggerType === 'scheduled').length ?? 0, + events: data?.filter((t) => t.triggerType !== 'scheduled').length ?? 0, + paused: data?.filter((t) => !t.enabled).length ?? 0 + }), + [data] + ); + + return ( + + } gate={manageGate} onClick={() => openSchedule()}> + New Schedule + + } + /> + + + setParam('q', e.target.value)} + sx={{ minWidth: 300 }} + slotProps={{ + input: { + startAdornment: ( + + + + ) + } + }} + /> + value && setParam('kind', value)}> + All ({counts.all}) + On a Schedule ({counts.scheduled}) + On Events ({counts.events}) + Paused ({counts.paused}) + + + } + /> + + + ); +} diff --git a/src/WebUI/src/pages/scripts/editor.tsx b/src/WebUI/src/pages/scripts/editor.tsx new file mode 100644 index 0000000..2f8b7be --- /dev/null +++ b/src/WebUI/src/pages/scripts/editor.tsx @@ -0,0 +1,721 @@ +import { MouseEvent, ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { BlockerFunction, Link as RouterLink, useBlocker, useNavigate, useParams, useSearchParams } from 'react-router-dom'; + +// material-ui +import Alert from '@mui/material/Alert'; +import Box from '@mui/material/Box'; +import Button from '@mui/material/Button'; +import Chip from '@mui/material/Chip'; +import FormControlLabel from '@mui/material/FormControlLabel'; +import Grid from '@mui/material/Grid'; +import MenuItem from '@mui/material/MenuItem'; +import Skeleton from '@mui/material/Skeleton'; +import Stack from '@mui/material/Stack'; +import Switch from '@mui/material/Switch'; +import Tab from '@mui/material/Tab'; +import Tabs from '@mui/material/Tabs'; +import TextField from '@mui/material/TextField'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; + +// third-party +import { enqueueSnackbar } from 'notistack'; +import { mutate } from 'swr'; + +// project imports +import IconButton from 'components/@extended/IconButton'; +import ActionMenu from 'components/ActionMenu'; +import CodeEditor from 'components/CodeEditor'; +import ConfirmDialog from 'components/ConfirmDialog'; +import { RelativeTime } from 'components/DateTime'; +import EmptyState from 'components/EmptyState'; +import GatedButton from 'components/GatedButton'; +import HoverHelp from 'components/HoverHelp'; +import MainCard from 'components/MainCard'; +import PageHeader from 'components/PageHeader'; +import ExecutionsPanel from 'sections/scripts/ExecutionsPanel'; +import FileBindingsEditor from 'sections/scripts/FileBindingsEditor'; +import FunctionModulesPicker from 'sections/scripts/FunctionModulesPicker'; +import ParameterSchemaEditor from 'sections/scripts/ParameterSchemaEditor'; +import SecretBindingsEditor from 'sections/scripts/SecretBindingsEditor'; +import { scriptMenu, useScriptGates } from 'sections/scripts/scriptMenu'; +import { + ENGINES, + NEW_SCRIPT_DRAFT, + draftFromScript, + duplicateBody, + editorLanguage, + engineInfo, + firstProblem, + normalizeDraft, + PARAMETER_NAME_REQUIRED, + saveBody, + validateDraft +} from 'sections/scripts/scriptModel'; +import ScheduleTable from 'sections/schedules/ScheduleTable'; +import { ApiError, api, errorMessage, keys } from 'api/client'; +import useApi from 'hooks/useApi'; +import useAutomation from 'hooks/useAutomation'; +import useLiveRefresh from 'hooks/useLiveRefresh'; + +// assets +import CalendarOutlined from '@ant-design/icons/CalendarOutlined'; +import FullscreenExitOutlined from '@ant-design/icons/FullscreenExitOutlined'; +import FullscreenOutlined from '@ant-design/icons/FullscreenOutlined'; +import MoreOutlined from '@ant-design/icons/MoreOutlined'; +import PlayCircleOutlined from '@ant-design/icons/PlayCircleOutlined'; +import PlusOutlined from '@ant-design/icons/PlusOutlined'; +import SaveOutlined from '@ant-design/icons/SaveOutlined'; + +// types +import type { FunctionModuleDto, ScriptDto, ScriptTriggerDto } from 'api/types'; +import type { CompletionContext } from 'utils/monaco/powershell-language'; +import type { EditorTab, ScriptDraft, ScriptEngine } from 'sections/scripts/scriptModel'; + +const TABS: EditorTab[] = ['code', 'parameters', 'functions', 'secrets', 'files', 'executions', 'schedules']; +const INTELLISENSE_KEY = 'editor-intellisense'; + +function readIntellisense(): boolean { + try { + return localStorage.getItem(INTELLISENSE_KEY) !== '0'; + } catch { + return true; + } +} + +/** Tab label with a count, red when something in the tab needs fixing. */ +function TabLabel({ label, count, problem }: { label: string; count?: number; problem?: boolean }) { + return ( + + {label} + {(Boolean(count) || problem) && ( + + )} + + ); +} + +function TabBody({ children }: { children: ReactNode }) { + return {children}; +} + +// ==============================|| SCRIPT EDITOR ||============================== // + +/** Route `/scripts/:id` (`new` for a new script). Each script gets a fresh editor. */ +export default function ScriptEditorPage() { + const { id = 'new' } = useParams(); + return ; +} + +function ScriptEditor({ id }: { id: string }) { + const isNew = id === 'new'; + const navigate = useNavigate(); + const [params, setParams] = useSearchParams(); + const gates = useScriptGates(); + const readOnly = Boolean(gates.manage); + const { openRun, openSchedule } = useAutomation(); + + const { data: script, error: loadError } = useApi(isNew ? null : keys.script(id), { revalidateOnFocus: false }); + const triggers = useApi(isNew ? null : keys.triggers); + const { mutate: mutateTriggers } = triggers; + useLiveRefresh( + () => mutateTriggers(), + (event) => event.kind === 'job-created' + ); + const scriptTriggers = useMemo(() => triggers.data?.filter((t) => t.scriptId === id), [triggers.data, id]); + + // The draft is seeded once from the loaded script; background revalidation never clobbers edits. + const [draft, setDraft] = useState(isNew ? NEW_SCRIPT_DRAFT : null); + const [baseline, setBaseline] = useState(() => (isNew ? JSON.stringify(NEW_SCRIPT_DRAFT) : '')); + if (draft === null && script) { + const loaded = draftFromScript(script); + setDraft(loaded); + setBaseline(JSON.stringify(loaded)); + } + const dirty = useMemo(() => draft !== null && JSON.stringify(draft) !== baseline, [draft, baseline]); + const problems = useMemo(() => (draft ? validateDraft(draft) : null), [draft]); + // Empty names on fresh rows are only flagged once a save has been tried. + const [attempted, setAttempted] = useState(false); + const shown = useMemo( + () => + problems && !attempted + ? { ...problems, name: undefined, parameters: problems.parameters.map((p) => (p === PARAMETER_NAME_REQUIRED ? undefined : p)) } + : problems, + [problems, attempted] + ); + + const [saving, setSaving] = useState(false); + const [saveError, setSaveError] = useState(''); + const [menuAnchor, setMenuAnchor] = useState(null); + const [deleting, setDeleting] = useState(false); + const [fullscreen, setFullscreen] = useState(false); + const [intellisense, setIntellisense] = useState(readIntellisense); + + const requestedTab = params.get('tab') as EditorTab | null; + const tab: EditorTab = + requestedTab && TABS.includes(requestedTab) && !(isNew && ['executions', 'schedules'].includes(requestedTab)) ? requestedTab : 'code'; + const setTab = (next: EditorTab) => + setParams( + (current) => { + const search = new URLSearchParams(current); + if (next === 'code') search.delete('tab'); + else search.set('tab', next); + search.delete('run'); + return search; + }, + { replace: true } + ); + + const edit = (patch: Partial) => setDraft((current) => (current ? { ...current, ...patch } : current)); + + // ── Leaving with unsaved changes ────────────────────────────────────── + const dirtyRef = useRef(dirty); + // Set before navigating away on purpose (after a save, duplicate or delete). + const leavingRef = useRef(false); + const proceedingRef = useRef(false); + useEffect(() => { + dirtyRef.current = dirty; + }, [dirty]); + const blocker = useBlocker( + useCallback( + ({ currentLocation, nextLocation }) => dirtyRef.current && !leavingRef.current && currentLocation.pathname !== nextLocation.pathname, + [] + ) + ); + useEffect(() => { + if (!dirty) return; + const warn = (event: BeforeUnloadEvent) => event.preventDefault(); + window.addEventListener('beforeunload', warn); + return () => window.removeEventListener('beforeunload', warn); + }, [dirty]); + + /** Keeps only the tab when moving to another script. */ + const tabSearch = tab === 'code' ? '' : `?tab=${tab}`; + + // ── Save, duplicate, delete ────────────────────────────────────────── + /** Saves when needed; resolves to the script id, or null when it could not be saved. */ + const save = async (): Promise => { + if (!draft || !problems || saving) return null; + if (!isNew && !dirty) return id; + if (readOnly) return null; + const problem = firstProblem(problems); + if (problem) { + setAttempted(true); + setSaveError(problem.message); + if (problem.tab !== 'code') setTab(problem.tab); + return null; + } + + setSaving(true); + setSaveError(''); + try { + if (isNew) { + const created = await api.createScript(saveBody(draft)); + await mutate(keys.script(created.id), created, { revalidate: false }); + await mutate(keys.scripts); + leavingRef.current = true; + enqueueSnackbar('Script created.', { variant: 'success' }); + navigate(`/scripts/${created.id}${tabSearch}`, { replace: true }); + return created.id; + } + await api.updateScript(id, saveBody(draft)); + // Show what was stored (incomplete rows dropped) unless editing continued meanwhile. + const stored = normalizeDraft(draft); + setDraft((current) => (current === draft ? stored : current)); + setBaseline(JSON.stringify(stored)); + void mutate(keys.script(id)); + await mutate(keys.scripts); + enqueueSnackbar('Saved.', { variant: 'success' }); + return id; + } catch (e) { + setSaveError(errorMessage(e, 'Save failed.')); + return null; + } finally { + setSaving(false); + } + }; + + // Ctrl+S / Cmd+S saves (also from inside the code editor). + const saveRef = useRef(save); + useEffect(() => { + saveRef.current = save; + }); + useEffect(() => { + const onKey = (event: KeyboardEvent) => { + if ((event.ctrlKey || event.metaKey) && !event.altKey && event.key.toLowerCase() === 's') { + event.preventDefault(); + void saveRef.current(); + } + }; + window.addEventListener('keydown', onKey, true); + return () => window.removeEventListener('keydown', onKey, true); + }, []); + + useEffect(() => { + if (!fullscreen) return; + const onKey = (event: KeyboardEvent) => event.key === 'Escape' && setFullscreen(false); + window.addEventListener('keydown', onKey); + return () => window.removeEventListener('keydown', onKey); + }, [fullscreen]); + + /** Runs and schedules use the stored script, so unsaved edits are saved first. */ + const runNow = async () => { + const savedId = await save(); + if (savedId) openRun({ scriptId: savedId }); + }; + const schedule = async () => { + const savedId = await save(); + if (savedId) openSchedule({ preset: { scriptId: savedId } }); + }; + + /** Copies the editor state (unsaved edits included) and switches to the copy. */ + const duplicate = async () => { + if (!draft || !problems) return; + const problem = firstProblem(problems); + if (problem) { + setSaveError(problem.message); + return; + } + try { + const created = await api.createScript(duplicateBody(draft)); + await mutate(keys.script(created.id), created, { revalidate: false }); + await mutate(keys.scripts); + leavingRef.current = true; + navigate(`/scripts/${created.id}${tabSearch}`); + enqueueSnackbar('Duplicated — you are editing the copy.', { variant: 'success' }); + } catch (e) { + setSaveError(errorMessage(e, 'Duplicate failed.')); + } + }; + + // ── Code editor ─────────────────────────────────────────────────────── + // Keyed on the bindings (not the whole draft) so typing code keeps the same context. + const functionModules = useApi(draft?.functionModuleIds.length ? keys.functions : null).data; + const parameters = draft?.parameters; + const secretBindings = draft?.secretBindings; + const secretsVariableName = draft?.secretsVariableName; + const fileBindings = draft?.fileBindings; + const functionModuleIds = draft?.functionModuleIds; + const completionContext = useMemo( + () => + parameters && secretBindings && fileBindings + ? { + parameterNames: parameters.map((p) => p.name).filter(Boolean), + secretNames: secretBindings.map((b) => b.name).filter(Boolean), + secretsVariable: secretsVariableName?.trim() || 'Secrets', + fileBindings: fileBindings.filter((b) => b.name.trim()).map((b) => ({ name: b.name, directory: b.directory ?? false })), + functionModules: functionModules + ?.filter((m) => functionModuleIds?.includes(m.id)) + .map((m) => ({ name: m.name, content: m.content })) + } + : undefined, + [parameters, secretBindings, secretsVariableName, fileBindings, functionModules, functionModuleIds] + ); + // The saved code, for change bars and Compare with Saved. + const savedContent = useMemo(() => (baseline ? (JSON.parse(baseline) as ScriptDraft).content : undefined), [baseline]); + + const toggleIntellisense = () => + setIntellisense((on) => { + try { + localStorage.setItem(INTELLISENSE_KEY, on ? '0' : '1'); + } catch { + // Storage unavailable; the choice lasts for this page only. + } + return !on; + }); + + // ── Render ──────────────────────────────────────────────────────────── + const notFound = loadError instanceof ApiError && loadError.status === 404; + const title = draft?.name.trim() || (isNew ? 'New Script' : (script?.name ?? 'Script')); + const runGate = gates.run ?? (isNew ? gates.manage : undefined); + const scheduleGate = gates.automate ?? (isNew ? gates.manage : undefined); + + if (loadError && !script) { + return ( + + + + {notFound ? ( + + Back to Scripts + + } + /> + ) : ( + {errorMessage(loadError, 'The script could not be loaded.')} + )} + + + ); + } + + return ( + + } + description={ + isNew ? ( + 'Write the code, then add its inputs.' + ) : script ? ( + <> + Updated + {script.updatedBy && ` by ${script.updatedBy}`} + + ) : undefined + } + secondaryActions={ + <> + } + gate={runGate} + disabled={!draft || saving} + onClick={() => void runNow()} + > + Run… + + } + gate={scheduleGate} + disabled={!draft || saving} + onClick={() => void schedule()} + > + Schedule… + + {!isNew && ( + ) => setMenuAnchor(e.currentTarget)} + sx={{ width: 36, height: 36 }} + > + + + )} + + } + primaryAction={ + + + } + gate={gates.manage} + disabled={!draft || saving || (!isNew && !dirty)} + onClick={() => void save()} + > + {saving ? 'Saving…' : 'Save'} + + + + } + /> + + {saveError && ( + setSaveError('')}> + {saveError} + + )} + + {!draft || !shown ? ( + <> + + + + ) : ( + <> + + + + edit({ name: e.target.value })} + error={Boolean(shown.name)} + helperText={shown.name} + disabled={readOnly} + autoFocus={isNew} + /> + + + edit({ description: e.target.value })} + disabled={readOnly} + /> + + + + Script Engine + + + } + value={draft.engine} + onChange={(e) => edit({ engine: e.target.value as ScriptEngine })} + disabled={readOnly} + > + {ENGINES.map((engine) => ( + + {engine.label} + + ))} + + + + + + + setTab(next)} + variant="scrollable" + scrollButtons="auto" + sx={{ px: 1, borderBottom: '1px solid', borderColor: 'divider' }} + > + + } + /> + } /> + + } + /> + } /> + + } disabled={isNew} /> + + + {tab === 'code' && ( + theme.zIndex.modal, + bgcolor: 'background.paper', + p: 2, + display: 'flex', + flexDirection: 'column', + gap: 1.5 + } + : { p: { xs: 2, md: 2.5 }, display: 'flex', flexDirection: 'column', gap: 1.5 } + } + > + + + {fullscreen ? `${title} · ` : ''} + {draft.engine === 'Bash' ? 'bash' : 'powershell'} + + + + } + label={IntelliSense} + sx={{ mr: 0 }} + /> + + + + + {fullscreen && ( + } + gate={gates.manage} + disabled={saving || (!isNew && !dirty)} + onClick={() => void save()} + > + Save + + )} + + + + edit({ content })} + language={editorLanguage(draft.engine)} + readOnly={readOnly} + height={fullscreen ? '100%' : 'max(380px, 56vh)'} + intellisense={intellisense && draft.engine !== 'Bash'} + completionContext={completionContext} + original={savedContent} + /> + + + )} + + {tab === 'parameters' && ( + + + {draft.engine === 'Bash' && Bash receives these as environment variables.} + edit({ parameters })} + problems={shown.parameters} + readOnly={readOnly} + /> + + + )} + + {tab === 'functions' && ( + + edit({ functionModuleIds })} + readOnly={readOnly} + /> + + )} + + {tab === 'secrets' && ( + + + {draft.engine === 'Bash' && Bash receives these as environment variables.} + edit({ secretBindings })} + variableName={draft.secretsVariableName} + onVariableNameChange={(secretsVariableName) => edit({ secretsVariableName })} + problems={shown.secrets} + variableProblem={shown.secretsVariable} + readOnly={readOnly} + /> + + + )} + + {tab === 'files' && ( + + edit({ fileBindings })} + problems={shown.files} + readOnly={readOnly} + /> + + )} + + {tab === 'executions' && !isNew && } + + {tab === 'schedules' && !isNew && ( + + + Schedules and event triggers. + + } + gate={gates.automate} + disabled={saving} + onClick={() => void schedule()} + > + New Schedule + + + } + empty={ + } title="No Schedules" detail="Run it on a cadence or on device events." /> + } + /> + )} + + + )} + + setMenuAnchor(null)} + entries={scriptMenu(gates, { + run: () => void runNow(), + schedule: () => void schedule(), + duplicate: () => void duplicate(), + remove: () => setDeleting(true) + }).filter((entry) => entry.kind === 'item' && ['duplicate', 'delete'].includes(entry.id))} + /> + + setDeleting(false)} + onConfirm={async () => { + await api.deleteScript(id); + await mutate(keys.scripts); + leavingRef.current = true; + enqueueSnackbar('Script deleted.', { variant: 'success' }); + navigate('/scripts'); + }} + /> + + { + proceedingRef.current = true; + blocker.proceed?.(); + }} + onClose={() => { + // After Discard the blocker has already moved on; only Cancel resets it. + if (!proceedingRef.current) blocker.reset?.(); + proceedingRef.current = false; + }} + /> + + ); +} diff --git a/src/WebUI/src/pages/scripts/index.tsx b/src/WebUI/src/pages/scripts/index.tsx new file mode 100644 index 0000000..e82775b --- /dev/null +++ b/src/WebUI/src/pages/scripts/index.tsx @@ -0,0 +1,236 @@ +import { MouseEvent, useMemo, useState } from 'react'; +import { useNavigate, useSearchParams } from 'react-router-dom'; + +// material-ui +import Chip from '@mui/material/Chip'; +import InputAdornment from '@mui/material/InputAdornment'; +import Stack from '@mui/material/Stack'; +import TextField from '@mui/material/TextField'; +import Typography from '@mui/material/Typography'; + +// third-party +import { enqueueSnackbar } from 'notistack'; +import { mutate } from 'swr'; + +// project imports +import IconButton from 'components/@extended/IconButton'; +import ActionMenu from 'components/ActionMenu'; +import ConfirmDialog from 'components/ConfirmDialog'; +import DataTable, { Column } from 'components/DataTable'; +import { RelativeTime } from 'components/DateTime'; +import EmptyState from 'components/EmptyState'; +import GatedButton from 'components/GatedButton'; +import MainCard from 'components/MainCard'; +import PageHeader from 'components/PageHeader'; +import { duplicateBody, engineInfo, engineOf } from 'sections/scripts/scriptModel'; +import { scriptMenu, useScriptGates } from 'sections/scripts/scriptMenu'; +import { api, errorMessage, keys } from 'api/client'; +import useApi from 'hooks/useApi'; +import useAutomation from 'hooks/useAutomation'; + +// assets +import CodeOutlined from '@ant-design/icons/CodeOutlined'; +import MoreOutlined from '@ant-design/icons/MoreOutlined'; +import PlusOutlined from '@ant-design/icons/PlusOutlined'; +import SearchOutlined from '@ant-design/icons/SearchOutlined'; + +// types +import type { ScriptDto } from 'api/types'; + +const scriptId = (script: ScriptDto) => script.id; + +// ==============================|| SCRIPTS ||============================== // + +export default function ScriptsPage() { + const navigate = useNavigate(); + const [params, setParams] = useSearchParams(); + const { openRun, openSchedule } = useAutomation(); + const gates = useScriptGates(); + const { data, error, loading, validating } = useApi(keys.scripts); + const [menu, setMenu] = useState<{ anchor: HTMLElement; script: ScriptDto } | null>(null); + const [deleting, setDeleting] = useState(null); + + const search = params.get('q') ?? ''; + const setSearch = (value: string) => + setParams( + (current) => { + const next = new URLSearchParams(current); + if (value) next.set('q', value); + else next.delete('q'); + return next; + }, + { replace: true } + ); + + const rows = useMemo(() => { + const query = search.trim().toLowerCase(); + if (!query) return data; + return data?.filter((s) => + [s.name, s.description, engineInfo(engineOf(s.language)).label].some((v) => v?.toLowerCase().includes(query)) + ); + }, [data, search]); + + const duplicate = async (script: ScriptDto) => { + try { + const created = await api.createScript(duplicateBody(script)); + await mutate(keys.scripts); + enqueueSnackbar(`Duplicated as “${created.name}”.`, { variant: 'success' }); + } catch (e) { + enqueueSnackbar(errorMessage(e, 'Duplicate failed.'), { variant: 'error' }); + } + }; + + const columns: Column[] = [ + { + id: 'name', + header: 'Name', + sortValue: (s) => s.name, + cell: (s) => ( + + + {s.name} + + {s.description && ( + + {s.description} + + )} + + ) + }, + { + id: 'engine', + header: 'Engine', + width: 140, + sortValue: (s) => engineInfo(engineOf(s.language)).label, + cell: (s) => { + const engine = engineInfo(engineOf(s.language)); + return ; + } + }, + { + id: 'parameters', + header: 'Parameters', + align: 'right', + width: 120, + sortValue: (s) => s.parameters?.length ?? 0, + cell: (s) => ( + + {s.parameters?.length || '—'} + + ) + }, + { + id: 'updated', + header: 'Updated', + nowrap: true, + width: 200, + sortValue: (s) => s.updatedUtc, + cell: (s) => ( + + + {s.updatedBy && ( + + by {s.updatedBy} + + )} + + ) + }, + { + id: 'actions', + header: '', + width: 56, + align: 'right', + cell: (s) => ( + ) => { + e.stopPropagation(); + setMenu({ anchor: e.currentTarget, script: s }); + }} + > + + + ) + } + ]; + + const newScript = ( + } gate={gates.manage} onClick={() => navigate('/scripts/new')}> + New Script + + ); + + return ( + + + + navigate(`/scripts/${s.id}`)} + defaultSort={{ id: 'name', direction: 'asc' }} + toolbar={ + setSearch(e.target.value)} + sx={{ minWidth: 300 }} + slotProps={{ + input: { + startAdornment: ( + + + + ) + } + }} + /> + } + empty={ + search ? ( + + ) : ( + } title="No Scripts Yet" detail="Create one to run on your devices." action={newScript} /> + ) + } + /> + + + {menu && ( + setMenu(null)} + entries={scriptMenu(gates, { + open: () => navigate(`/scripts/${menu.script.id}`), + run: () => openRun({ scriptId: menu.script.id }), + schedule: () => openSchedule({ preset: { scriptId: menu.script.id } }), + duplicate: () => void duplicate(menu.script), + remove: () => setDeleting(menu.script) + })} + /> + )} + setDeleting(null)} + onConfirm={async () => { + await api.deleteScript(deleting!.id); + await mutate(keys.scripts); + enqueueSnackbar('Script deleted.', { variant: 'success' }); + }} + /> + + ); +} diff --git a/src/WebUI/src/pages/settings/index.tsx b/src/WebUI/src/pages/settings/index.tsx new file mode 100644 index 0000000..8c67c87 --- /dev/null +++ b/src/WebUI/src/pages/settings/index.tsx @@ -0,0 +1,101 @@ +import { ComponentType, ReactElement, useState } from 'react'; +import { useNavigate, useParams, useSearchParams } from 'react-router-dom'; + +// material-ui +import Box from '@mui/material/Box'; +import Stack from '@mui/material/Stack'; +import Tab from '@mui/material/Tab'; +import Tabs from '@mui/material/Tabs'; + +// project imports +import PageHeader from 'components/PageHeader'; +import useSession from 'hooks/useSession'; +import AgentUpgradeSettings from 'sections/settings/AgentUpgradeSettings'; +import AppearanceSettings from 'sections/settings/AppearanceSettings'; +import AuthenticationSettings from 'sections/settings/AuthenticationSettings'; +import EnrollmentTokens from 'sections/settings/EnrollmentTokens'; +import SecretsProviders from 'sections/settings/SecretsProviders'; +import StorageSettings from 'sections/settings/StorageSettings'; + +// assets +import BgColorsOutlined from '@ant-design/icons/BgColorsOutlined'; +import CloudServerOutlined from '@ant-design/icons/CloudServerOutlined'; +import CloudSyncOutlined from '@ant-design/icons/CloudSyncOutlined'; +import KeyOutlined from '@ant-design/icons/KeyOutlined'; +import LockOutlined from '@ant-design/icons/LockOutlined'; +import SafetyCertificateOutlined from '@ant-design/icons/SafetyCertificateOutlined'; + +const TABS: { id: string; label: string; icon: ReactElement; Section: ComponentType; permission?: string }[] = [ + { id: 'authentication', label: 'Authentication', icon: , Section: AuthenticationSettings, permission: 'access.manage' }, + { id: 'enrollment', label: 'Enrollment Tokens', icon: , Section: EnrollmentTokens, permission: 'settings.manage' }, + { id: 'secrets', label: 'Secrets Providers', icon: , Section: SecretsProviders, permission: 'secrets.use' }, + { + id: 'storage', + label: 'Storage & Agent Package', + icon: , + Section: StorageSettings, + permission: 'settings.manage' + }, + { + id: 'agent-upgrades', + label: 'Agent Upgrades', + icon: , + Section: AgentUpgradeSettings, + permission: 'settings.manage' + }, + { id: 'appearance', label: 'Appearance', icon: , Section: AppearanceSettings } +]; + +// ==============================|| SETTINGS ||============================== // + +export default function SettingsPage() { + const [params, setParams] = useSearchParams(); + const navigate = useNavigate(); + const { can } = useSession(); + // /settings/authentication/{method} is the Authentication tab on one of its sign-in methods. + const { method } = useParams(); + const tabs = TABS.filter((tab) => !tab.permission || can(tab.permission)); + const current = tabs.find((tab) => tab.id === (method ? 'authentication' : params.get('tab'))) ?? tabs[0]; + + // Sections stay mounted once visited, so unsaved edits survive a tab switch. + const [visited, setVisited] = useState([current.id]); + if (!visited.includes(current.id)) setVisited([...visited, current.id]); + + const select = (id: string) => + method || id === 'authentication' + ? navigate(id === 'authentication' ? '/settings/authentication/built-in' : `/settings?tab=${id}`, { replace: true }) + : setParams( + (prev) => { + const next = new URLSearchParams(prev); + next.set('tab', id); + return next; + }, + { replace: true } + ); + + return ( + + + + select(id)} + variant="scrollable" + scrollButtons="auto" + aria-label="Settings sections" + > + {tabs.map((tab) => ( + + ))} + + + {tabs + .filter((tab) => visited.includes(tab.id)) + .map(({ id, label, Section }) => ( +
+ + ))} + + ); +} diff --git a/src/WebUI/src/routes/+layout.svelte b/src/WebUI/src/routes/+layout.svelte deleted file mode 100644 index af95152..0000000 --- a/src/WebUI/src/routes/+layout.svelte +++ /dev/null @@ -1,262 +0,0 @@ - - - - - ExecuteR Control - - -{#if isLoginPage} - {@render children()} -{:else} -
- - -
-
-

ExecuteR Control

-
- - - {#if $session.authenticated} - {$session.displayName ?? $session.username} - - {/if} -
-
-
- {@render children()} -
-
-
-{/if} - - diff --git a/src/WebUI/src/routes/+layout.ts b/src/WebUI/src/routes/+layout.ts deleted file mode 100644 index 42ac1a4..0000000 --- a/src/WebUI/src/routes/+layout.ts +++ /dev/null @@ -1,5 +0,0 @@ -// The app is fully client-driven (cookie auth + fetch + NATS WebSocket), so -// SSR adds nothing and disabling it lets the same codebase build both the -// node deployment and the static SPA embedded in the combined server binary. -export const ssr = false; -export const prerender = false; diff --git a/src/WebUI/src/routes/+page.svelte b/src/WebUI/src/routes/+page.svelte deleted file mode 100644 index 1ae7801..0000000 --- a/src/WebUI/src/routes/+page.svelte +++ /dev/null @@ -1,525 +0,0 @@ - - -{#if data === null} -
- {#each Array(4) as _, i (i)}
loading…
{/each} -
-{:else} - {#if liveActive} -
-
- - Deploying - {liveFinished} of {liveTotal} endpoints finished - -
-
-
-
-
- {/if} - -
- - - - -
- -
-
-

Job outcomes

-
- -
    - {#each data.jobsByState as s (s.label)} -
  • - - {s.label} - {s.count} -
  • - {/each} -
-
-
- -
-

Executions · 14 days

- -
- Succeeded - Failed - Other -
-
- -
-

Script engine

- -
- -
-

Exit codes

- -
- -
-

Top targets

- -
- -
-

Most-run scripts

- -
- -
-

Fleet platforms

-
- -
    - {#each data.devicesByPlatform as p (p.label)} -
  • - - {p.label} - {p.count} -
  • - {/each} -
-
-
- -
-

Latest executions

- {#if data.recentRuns.length === 0} - - {:else} -
    - {#each data.recentRuns as run (run.jobId)} -
  • - -
  • - {/each} -
- {/if} -
- -
-

Activity

- {#if activity.length === 0} - - {:else} -
    - {#each activity as a, i (a.timestampUtc + '-' + i)} -
  • - -
  • - {/each} -
- {/if} -
-
-{/if} - - diff --git a/src/WebUI/src/routes/access/+page.svelte b/src/WebUI/src/routes/access/+page.svelte deleted file mode 100644 index 80b386e..0000000 --- a/src/WebUI/src/routes/access/+page.svelte +++ /dev/null @@ -1,613 +0,0 @@ - - -
-
-

Access control

-

- Who can do what, over which devices. Roles bundle permissions (optionally limited to device - groups) and apply to local users and OIDC sign-ins alike — list a role's IdP claim values to - map identity-provider groups onto it. -

-
-
- -{#if errorText}

{errorText}

{/if} - -
-
-

Users

- {#if !userFormOpen} - - {/if} -
- - {#if userFormOpen} -
-

{editingUser ? `Edit “${editingUser.username}”` : 'New local user'}

-
- {#if !editingUser} - - {/if} - - - {#if !editingUser || editingUser.authProvider === 'local'} - - {/if} -
-
- - -
-
- {/if} - -
- {#if users === null} -
loading…
- {:else if users.length === 0} - - {:else} - - - - - - - - - - - - - {#each users as user (user.id)} - - - - - - - - - {/each} - -
UsernameDisplay nameProviderRoleLast sign-in
{user.username}{user.displayName ?? '—'}{user.authProvider}{user.roleName} - {#if user.lastLoginUtc} - - {:else} - never - {/if} - - - -
- {/if} -
-
- -
-
-

Roles

- {#if !roleFormOpen} - - {/if} -
- - {#if roleFormOpen} -
-

{editingRole ? `Edit “${editingRole.name}”` : 'New role'}

-
- - - -
- -
- Permissions -
- {#each catalog as group (group.group)} -
- {group.group} - {#each group.permissions as perm (perm.key)} - - {/each} -
- {/each} -
-
- -
- Device scope -

- Leave empty for all devices; otherwise members only see and target devices in the - selected groups. -

- {#if groups.length === 0} -

No device groups exist yet.

- {:else} -
- {#each groups as group (group.id)} - - {/each} -
- {/if} -
- -
- - -
-
- {/if} - -
- {#if roles === null} -
loading…
- {:else} - - - - - - - - - - - - - - {#each roles as role (role.id)} - - - - - - - - - - {/each} - -
NameDescriptionPermissionsDevice scopeOIDC claimsUsers
- {role.name} - {#if role.isSystem}system{/if} - {role.description ?? '—'} - {role.permissions.includes('*') - ? 'Everything' - : `${role.permissions.length} granted`} - {scopeSummary(role)} - {role.oidcClaimValues.length > 0 ? role.oidcClaimValues.join(', ') : '—'} - {role.userCount} - - {#if !role.isSystem} - - - {/if} -
- {/if} -
-
- - diff --git a/src/WebUI/src/routes/devices/+page.svelte b/src/WebUI/src/routes/devices/+page.svelte deleted file mode 100644 index 4a10161..0000000 --- a/src/WebUI/src/routes/devices/+page.svelte +++ /dev/null @@ -1,204 +0,0 @@ - - -
-

Devices

-
- - - {#if canAddDevice} - - {/if} -
-
- -{#if showAddDevice} - (showAddDevice = false)} /> -{/if} - -
- {#if devices === null} -
- {#each Array(4) as _, i (i)} -
loading device row…
- {/each} -
- {:else if filtered.length === 0} - - {:else} - - - - - - - - - - - - - - {#each filtered as device (device.clientId)} - goto(`/devices/${device.clientId}`)} - onkeydown={(e) => e.key === 'Enter' && goto(`/devices/${device.clientId}`)} - tabindex="0" - > - - - - - - - - - {/each} - -
StatusManufacturer / ModelAgentIP
- - - {device.hostname} - - - {[device.manufacturer, device.model].filter(Boolean).join(' · ') || '—'} - {device.osCaption ?? '—'}{device.agentVersion ?? '—'}{device.ipAddresses[0] ?? '—'}
- {/if} -
- - diff --git a/src/WebUI/src/routes/devices/[clientId]/+page.svelte b/src/WebUI/src/routes/devices/[clientId]/+page.svelte deleted file mode 100644 index ed37ccb..0000000 --- a/src/WebUI/src/routes/devices/[clientId]/+page.svelte +++ /dev/null @@ -1,859 +0,0 @@ - - -{#if error} - - Back to devices - -{:else if !device} -
loading device…
-{:else} -
-
-
Devices / {device.hostname}
-
- -

{device.hostname}

- -
-
- {[device.manufacturer, device.model].filter(Boolean).join(' · ')} -
-
- Client ID: - -
-
-
- - -
-
- - - - {#if tab === 'overview'} -
-
-

Identity

-
-
Hostname
-
{device.hostname}
-
Make / model
-
- {[inventory?.identity.manufacturer, inventory?.identity.model] - .filter(Boolean) - .join(' · ') || '—'} -
-
Serial number
-
{inventory?.identity.serialNumber ?? '—'}
-
System UUID
-
{inventory?.identity.systemUuid ?? '—'}
-
Domain / workgroup
-
{inventory?.identity.domainOrWorkgroup ?? '—'}
-
System type
-
{inventory?.identity.systemType ?? '—'}
-
-
-
-

Operating system

-
-
OS
-
{inventory?.os.caption ?? device.osCaption ?? '—'}
-
Edition
-
{inventory?.os.edition ?? '—'}
-
Product type
-
{inventory?.os.productType ?? '—'}
-
Release
-
{inventory?.os.releaseVersion ?? '—'}
-
Version
-
{inventory?.os.version ?? '—'}
-
Architecture
-
{inventory?.os.architecture ?? '—'}
-
Installed
-
{inventory?.os.installDateUtc ? new Date(inventory.os.installDateUtc).toLocaleDateString() : '—'}
-
Last boot
-
{inventory?.os.lastBootUtc ? new Date(inventory.os.lastBootUtc).toLocaleString() : '—'}
-
-
-
-

Agent

-
-
Version
-
{device.agentVersion ?? '—'}
-
Enrolled
-
{new Date(device.enrolledUtc).toLocaleString()}
-
-
-
-

Tags

-
- {#each device.tags ?? [] as tag (tag)} - - {tag} - - - {/each} - {#if (device.tags ?? []).length === 0} - No tags - {/if} -
-
- e.key === 'Enter' && addTag()} - /> - -
-
- -
-

Groups

-
- {#each detail?.groups ?? [] as g (g.id)} - {g.name} · {g.kind} - {/each} - {#if (detail?.groups ?? []).length === 0} - Not in any group - {/if} -
-
- -
-

Connectivity

-
-
Last seen
-
-
IP addresses
-
{device.ipAddresses.join(', ') || '—'}
-
Public IP
-
- {#if !device.publicIp} - — - {:else if showPublicIp} - - - - - {:else} - - •••.•••.•••.••• - - - {/if} -
-
Inventory updated
-
-
-
-
- {:else if tab === 'hardware'} - {#if !inventory} - - {:else} -
-
-

Processor

-
-
Name
-
{inventory.cpu.name ?? '—'}
-
Cores / logical
-
{inventory.cpu.cores} cores, {inventory.cpu.logicalProcessors} logical
-
-
-
-

Memory

-
-
Total
-
{formatBytes(inventory.totalPhysicalMemoryBytes)}
-
- {#each inventory.memory as dimm, i (i)} -
- {dimm.deviceLocator ?? `DIMM ${i + 1}`}: {formatBytes(dimm.capacityBytes)} - {dimm.speedMhz ? ` @ ${dimm.speedMhz} MHz` : ''} - {dimm.manufacturer ? ` (${dimm.manufacturer})` : ''} -
- {/each} -
-
-

Firmware & board

-
-
BIOS version
-
{inventory.identity.biosVersion ?? '—'}
-
Motherboard
-
- {[inventory.identity.baseboardManufacturer, inventory.identity.baseboardProduct] - .filter(Boolean) - .join(' · ') || '—'} -
-
Baseboard serial
-
{inventory.identity.baseboardSerial ?? '—'}
-
-
-
-

Storage

- {#each sortedDisks as { disk, diskIndex } (diskIndex)} - {@const diskVolumes = inventory.volumes.filter((v) => v.diskIndex === diskIndex)} -
-
- - 🖴 - {disk.model ?? `Disk ${diskIndex}`} - - - Disk {diskIndex} · {disk.busType ?? '?'} · {formatBytes(disk.sizeBytes)} - - {#if disk.serialNumber} - - {/if} -
- {#if diskVolumes.length === 0} -

No mapped volumes.

- {:else} -
- {#each diskVolumes as vol (vol.driveLetter)} - {@const used = vol.totalSizeBytes - vol.freeSpaceBytes} - {@const pct = vol.totalSizeBytes > 0 ? Math.round((used / vol.totalSizeBytes) * 100) : 0} -
-
- {vol.driveLetter} - {vol.fileSystem ?? '—'} - - {formatBytes(vol.freeSpaceBytes)} free of {formatBytes(vol.totalSizeBytes)} - -
-
-
= 85} style="width: {pct}%">
-
-
- {/each} -
- {/if} -
- {/each} - {#if unmappedVolumes.length > 0} -
-
- Volumes without a disk mapping -
-
- {#each unmappedVolumes as vol (vol.driveLetter)} - {@const used = vol.totalSizeBytes - vol.freeSpaceBytes} - {@const pct = vol.totalSizeBytes > 0 ? Math.round((used / vol.totalSizeBytes) * 100) : 0} -
-
- {vol.driveLetter} - {vol.fileSystem ?? '—'} - - {formatBytes(vol.freeSpaceBytes)} free of {formatBytes(vol.totalSizeBytes)} - -
-
-
= 85} style="width: {pct}%">
-
-
- {/each} -
-
- {/if} -
-
- {/if} - {:else if tab === 'network'} - {#if !inventory || inventory.network.length === 0} - - {:else} -
- {#each inventory.network as adapter, i (i)} -
-

- {adapter.interfaceName ?? adapter.description ?? `Adapter ${i + 1}`} - {#if adapter.interfaceName && adapter.description && adapter.interfaceName !== adapter.description} - · {adapter.description} - {/if} -

-
- {#each [{ label: 'Interface', values: adapter.interfaceName ? [adapter.interfaceName] : [] }, { label: 'MAC', values: adapter.macAddress ? [adapter.macAddress] : [] }, { label: 'IPv4', values: adapter.ipv4Addresses }, { label: 'IPv6', values: adapter.ipv6Addresses }, { label: 'Gateways', values: adapter.gateways }, { label: 'DNS', values: adapter.dnsServers }] as row (row.label)} -
- {row.label} -
- {#if row.values.length === 0} - — - {:else} - {#each row.values as value (value)} - - {/each} - {/if} -
-
- {/each} -
-
- {/each} -
- {/if} - {:else if tab === 'jobs'} -
- {#if jobs.length === 0} - - {:else} - {#each [...new Set(jobs.map((j) => j.scriptName))] as scriptName (scriptName)} -

{scriptName}

- - - - - - {#each jobs.filter((j) => j.scriptName === scriptName) as job (job.jobId)} - goto(`/jobs?job=${job.jobId}`)}> - - - - - - {/each} - -
StateStartedDurationExit
- {job.startedUtc && job.completedUtc - ? `${Math.round((new Date(job.completedUtc).getTime() - new Date(job.startedUtc).getTime()) / 1000)}s` - : '—'} - {job.exitCode ?? '—'}
- {/each} -

- Click an execution to open its output. Retention keeps the newest runs per device - (JOB_HISTORY_LIMIT, default 200). -

- {/if} -
- {:else if tab === 'actions'} -
-
-

Actions

-
- - ▶ Run script - -
- {#if actionMessage} -

{actionMessage}

- {/if} - {#if !online} -

Actions are disabled while the agent is offline.

- {/if} -
- -
-

Send file (S3)

-

- Delivers an object from the configured S3 store to the device using a short-lived - presigned URL. -

-
- - - - -
-
-
- {/if} -{/if} - - diff --git a/src/WebUI/src/routes/devices/[clientId]/shell/+page.svelte b/src/WebUI/src/routes/devices/[clientId]/shell/+page.svelte deleted file mode 100644 index 3ec9b7b..0000000 --- a/src/WebUI/src/routes/devices/[clientId]/shell/+page.svelte +++ /dev/null @@ -1,231 +0,0 @@ - - - - Shell · {hostname || clientId} · ExecuteR - - -
-
- -
-

Remote shell

- - {statusText} - -
-
- -
- -
- - diff --git a/src/WebUI/src/routes/functions/+page.svelte b/src/WebUI/src/routes/functions/+page.svelte deleted file mode 100644 index ae1398b..0000000 --- a/src/WebUI/src/routes/functions/+page.svelte +++ /dev/null @@ -1,254 +0,0 @@ - - -
-

Functions

- -
- -

- Reusable PowerShell functions. Attach a module to a script and its definitions are prepended at - run time — keeping individual scripts small and free of duplication. -

- -
-
- {#if modules === null} -
- {#each Array(3) as _, i (i)}
loading…
{/each} -
- {:else if modules.length === 0} - - {:else} -
    - {#each modules as m (m.id)} -
  • - -
  • - {/each} -
- {/if} -
- - {#if selected || creating} -
-
- - {#if statusText}{statusText}{/if} -
- {#if selected}{/if} - {#if selected}{/if} - -
- - -
- {:else} -
- -
- {/if} -
- - diff --git a/src/WebUI/src/routes/groups/+page.svelte b/src/WebUI/src/routes/groups/+page.svelte deleted file mode 100644 index 9823b46..0000000 --- a/src/WebUI/src/routes/groups/+page.svelte +++ /dev/null @@ -1,433 +0,0 @@ - - -
-

Device groups

- -
- -
-
- {#if groups === null} -
- {#each Array(3) as _, i (i)}
loading…
{/each} -
- {:else if groups.length === 0} - - {:else} -
    - {#each groups as g (g.id)} -
  • - -
  • - {/each} -
- {/if} -
- -
-
-
- - -
- {#if statusText}{statusText}{/if} - {#if selected}{/if} - {#if selected}{/if} - -
- -
- - {#if kind === 'dynamic'} -
-
-

Membership rules

- -
- - - {#if selected} -
-

Members — {members.length} device(s)

- {#if members.length > 0} -
    - {#each members as d (d.clientId)} -
  • {d.hostname}
  • - {/each} -
- {:else} -

No devices currently match. Adjust the rules and Save.

- {/if} -
- {/if} - - {#if preview !== null} -
-

Preview (unsaved rules) — {preview.length} device(s)

- {#if preview.length > 0} -
    - {#each preview as d (d.clientId)} -
  • {d.hostname}
  • - {/each} -
- {:else} -

No devices match these rules.

- {/if} -
- {/if} -
- {:else} -
-

Members

-

Tick devices to include them in this static group.

- {#if !selected} -

Save the group first, then choose members.

- {:else} -
    - {#each devices as d (d.clientId)} -
  • - -
  • - {/each} -
- {/if} -
- {/if} - -
-
- - diff --git a/src/WebUI/src/routes/index.tsx b/src/WebUI/src/routes/index.tsx new file mode 100644 index 0000000..de41852 --- /dev/null +++ b/src/WebUI/src/routes/index.tsx @@ -0,0 +1,75 @@ +import { lazy } from 'react'; +import { createBrowserRouter, Navigate, Outlet, useLocation } from 'react-router-dom'; + +// project imports +import Loadable from 'components/Loadable'; +import ScrollTop from 'components/ScrollTop'; +import DashboardLayout from 'layout/Dashboard'; + +const SignIn = Loadable(lazy(() => import('pages/auth/sign-in'))); +const StepUpDone = Loadable(lazy(() => import('pages/auth/step-up-done'))); +const Dashboard = Loadable(lazy(() => import('pages/dashboard'))); +const Devices = Loadable(lazy(() => import('pages/devices'))); +const DeviceDetail = Loadable(lazy(() => import('pages/devices/detail'))); +const DeviceShell = Loadable(lazy(() => import('pages/devices/shell'))); +const Groups = Loadable(lazy(() => import('pages/groups'))); +const Scripts = Loadable(lazy(() => import('pages/scripts'))); +const ScriptEditor = Loadable(lazy(() => import('pages/scripts/editor'))); +const Functions = Loadable(lazy(() => import('pages/functions'))); +const Schedules = Loadable(lazy(() => import('pages/schedules'))); +const Jobs = Loadable(lazy(() => import('pages/jobs'))); +const Run = Loadable(lazy(() => import('pages/runs/detail'))); +const Access = Loadable(lazy(() => import('pages/access'))); +const Settings = Loadable(lazy(() => import('pages/settings'))); +const NotFound = Loadable(lazy(() => import('pages/maintenance/404'))); + +// ==============================|| ROUTING ||============================== // + +function Root() { + return ( + <> + + + + ); +} + +/** Older links to /login keep their query (returnUrl, error) on the way to /sign-in. */ +function LoginRedirect() { + const { search } = useLocation(); + return ; +} + +const router = createBrowserRouter([ + { + element: , + children: [ + { path: '/sign-in', element: }, + { path: '/login', element: }, + { path: '/step-up/done', element: }, + { + path: '/', + element: , + children: [ + { index: true, element: }, + { path: 'devices', element: }, + { path: 'devices/:clientId', element: }, + { path: 'devices/:clientId/shell', element: }, + { path: 'groups', element: }, + { path: 'scripts', element: }, + { path: 'scripts/:id', element: }, + { path: 'functions', element: }, + { path: 'schedules', element: }, + { path: 'jobs', element: }, + { path: 'runs/:runId', element: }, + { path: 'access', element: }, + { path: 'settings', element: }, + { path: 'settings/authentication/:method', element: }, + { path: '*', element: } + ] + } + ] + } +]); + +export default router; diff --git a/src/WebUI/src/routes/jobs/+page.svelte b/src/WebUI/src/routes/jobs/+page.svelte deleted file mode 100644 index ee2d34f..0000000 --- a/src/WebUI/src/routes/jobs/+page.svelte +++ /dev/null @@ -1,256 +0,0 @@ - - -
-

Jobs

- {#if stateFilter} - Filtered: {stateFilter} ✕ - {/if} -
- -
-
- {#if jobs === null} -
- {#each Array(4) as _, i (i)} -
loading…
- {/each} -
- {:else if jobs.length === 0} - - {:else if visibleJobs.length === 0} - - {:else} - - - - - - - - - - - - {#each visibleJobs as job (job.jobId)} - select(job)} - onkeydown={(e) => e.key === 'Enter' && select(job)} - tabindex="0" - > - - - - - - - {/each} - -
StateScriptDeviceCreatedDuration
{job.scriptName}{job.hostname ?? job.clientId.slice(0, 10)}{duration(job)}
- {/if} -
- - -
- - diff --git a/src/WebUI/src/routes/login/+page.svelte b/src/WebUI/src/routes/login/+page.svelte deleted file mode 100644 index c24422b..0000000 --- a/src/WebUI/src/routes/login/+page.svelte +++ /dev/null @@ -1,309 +0,0 @@ - - - - Sign in · ExecuteR - - -
-
-
- X - ExecuteR -
-

{mustChange ? 'Set a new password' : 'Sign in'}

- - {#if error} - - {/if} - - {#if mustChange} -

- This account still uses the default password. Choose a new one to finish signing in as - {username}. -

-
- - - -
- {:else if config?.autoRedirect && !error} -

Redirecting to single sign-on…

- {:else} - {#if showLocal} -
- - - -
- {/if} - - {#if showLocal && showSso} -
or
- {/if} - - {#if showSso} - - Authenticate using OIDC - Provider: {config?.providerName ?? 'OIDC'} - - {/if} - - {#if !showLocal && !showSso} -

No sign-in method is configured.

- {/if} - - {#if !showLocal} - - Use a local account instead - {/if} - {/if} -
-
- - diff --git a/src/WebUI/src/routes/scripts/+page.svelte b/src/WebUI/src/routes/scripts/+page.svelte deleted file mode 100644 index b111d13..0000000 --- a/src/WebUI/src/routes/scripts/+page.svelte +++ /dev/null @@ -1,85 +0,0 @@ - - -
-

Scripts

- + New script -
- -
- {#if scripts === null} -
- {#each Array(3) as _, i (i)} -
loading…
- {/each} -
- {:else if scripts.length === 0} - - Create script - - {:else} - - - - - - - - - - - - {#each scripts as script (script.id)} - goto(`/scripts/${script.id}`)} - onkeydown={(e) => e.key === 'Enter' && goto(`/scripts/${script.id}`)} - tabindex="0" - > - - - - - - - {/each} - -
NameDescriptionLanguageUpdatedBy
{script.name}{script.description ?? '—'}{script.language}{script.updatedBy ?? '—'}
- {/if} -
- - diff --git a/src/WebUI/src/routes/scripts/[id]/+page.svelte b/src/WebUI/src/routes/scripts/[id]/+page.svelte deleted file mode 100644 index 1a2914b..0000000 --- a/src/WebUI/src/routes/scripts/[id]/+page.svelte +++ /dev/null @@ -1,973 +0,0 @@ - - - { - if (e.key === 'Escape' && fullscreen) fullscreen = false; - }} -/> - -
-
-
Scripts / {isNew ? 'New' : name || '…'}
- - -
- - {engineHints[engine]} -
-
-
- {#if statusText} - {statusText} - {/if} - {#if !isNew} - - - {/if} - - -
-
- -
-
-
-

Script Configuration

- - {parameters.length === 0 - ? 'No parameters' - : `${parameters.length} parameter${parameters.length === 1 ? '' : 's'}`} - · {secretBindings.length} secret{secretBindings.length === 1 ? '' : 's'} - · {fileBindings.length} file{fileBindings.length === 1 ? '' : 's'} - · {functionModuleIds.length} function{functionModuleIds.length === 1 ? '' : 's'} - -
- -
- - {#if showParamEditor} -
-
-

Parameters

- -
- -
-

Secrets

- -
- -
-

Files (S3)

- -
- -
-

Functions

- {#if allFunctions.length === 0} -

Nothing here yet — create reusable Functions from the sidebar.

- {:else} -
- {#each allFunctions as fn (fn.id)} - - {/each} -
- {/if} -
-
- {/if} -
- -
-
- {engine === 'Bash' ? 'bash' : 'powershell'} -
- - -
-
- {#if !loaded} -
loading editor…
- {/if} -
-
- -
-
-

Run

- {#if allGroups.length === 0} -

- No groups yet — create one under Groups, then run this script against it. -

- {:else} -

- Select one or more groups. Each runs on every non-orphaned member; offline devices - receive the job when they reconnect. -

-
- {#each allGroups as group (group.id)} - - {/each} -
- {/if} - - {#if parameters.length > 0} -

Execution values

- - {/if} -
- - {#if !isNew && loaded} - - {/if} -
- -{#if !isNew} -
-
-

- - {#if currentRun} - › - - {/if} - {#if currentTarget} - › - {currentTarget.hostname ?? currentTarget.clientId} - {/if} -

- {#if !currentRun} - - {/if} -
- - {#if !currentRun} - - {#if executions.length === 0} -

No executions yet. Select a group above and Run.

- {:else} - - - - {#each executions as ex (ex.runId)} - openExecution(ex.runId)}> - - - - - - {/each} - -
StartedByTargetsResult
{new Date(ex.startedUtc).toLocaleString()}{ex.requestedBy ?? '—'}{ex.total} - {ex.succeeded}✓ - {#if ex.failed > 0}{ex.failed}✗{/if} - {#if ex.pending > 0}{ex.pending}…{/if} -
- {/if} - {:else if !currentTarget} - - - - - {#each currentRun.targets as t (t.jobId)} - openTarget(t)}> - - - - - - {/each} - -
DeviceStateExitFinished
{t.hostname ?? t.clientId}{t.exitCode ?? '—'}{t.completedUtc ? new Date(t.completedUtc).toLocaleString() : '—'}
- {:else} - -
- - {#if outputLines.length > 0} - - - {/if} -
-
- {#if outputLines.length === 0} - - {terminalStates.includes(currentTarget.state) ? 'No output.' : 'Waiting for output…'} - - {:else if filteredOutput.length === 0} - No lines match “{outputSearch}”. - {:else} - {#each filteredOutput as line (line.seq)} -
{line.text}
- {/each} - {/if} -
- {/if} -
-{/if} - - diff --git a/src/WebUI/src/routes/settings/+page.svelte b/src/WebUI/src/routes/settings/+page.svelte deleted file mode 100644 index 80cf1c0..0000000 --- a/src/WebUI/src/routes/settings/+page.svelte +++ /dev/null @@ -1,296 +0,0 @@ - - -
-

Settings

-
- -
-
-

Appearance

-
- {#each themes as option (option.value)} - - {/each} -
-
- -
-

Bootstrap tokens

-

- One-time tokens for agent enrollment. The token value is shown once at creation — install with - msiexec /i Agent.msi /qn SERVERURL=… BOOTSTRAPTOKEN=… -

- -
- - - - -
- - {#if newToken?.token} -
-
New token (copy it now — it will not be shown again):
-
{newToken.token}
- -
-
-
Deploy on a target device (run in an elevated PowerShell):
-
{installCommand}
- -
- Requires Agent.msi in the backend’s AGENT_PACKAGE_PATH. Also usable: - msiexec /i Agent.msi /qn SERVERURL=… BOOTSTRAPTOKEN=… -
-
- {/if} - - {#if tokens.length === 0} - - {:else} -
- - - - - - - - - - - - - {#each tokens as token (token.id)} - - - - - - - - - {/each} - -
CreatedExpiresUsesNoteStatus
{new Date(token.createdUtc).toLocaleString()}{new Date(token.expiresUtc).getFullYear() > 9000 - ? 'Never' - : new Date(token.expiresUtc).toLocaleString()}{token.uses} / {token.maxUses === 0 ? '∞' : token.maxUses}{token.note ?? '—'} - {#if token.revoked} - Revoked - {:else if new Date(token.expiresUtc) < new Date()} - Expired - {:else if token.maxUses > 0 && token.uses >= token.maxUses} - Consumed - {:else} - Active - {/if} - - {#if !token.revoked && (token.maxUses === 0 || token.uses < token.maxUses) && new Date(token.expiresUtc) > new Date()} - - {/if} -
-
- {/if} -
- - -
-
-
-
- - diff --git a/src/WebUI/src/sections/access/PeopleTab.tsx b/src/WebUI/src/sections/access/PeopleTab.tsx new file mode 100644 index 0000000..a5171f8 --- /dev/null +++ b/src/WebUI/src/sections/access/PeopleTab.tsx @@ -0,0 +1,217 @@ +import { MouseEvent, useMemo, useState } from 'react'; + +// material-ui +import InputAdornment from '@mui/material/InputAdornment'; +import MenuItem from '@mui/material/MenuItem'; +import Stack from '@mui/material/Stack'; +import TextField from '@mui/material/TextField'; +import Typography from '@mui/material/Typography'; + +// project imports +import IconButton from 'components/@extended/IconButton'; +import ActionMenu from 'components/ActionMenu'; +import ConfirmDialog from 'components/ConfirmDialog'; +import DataTable, { Column } from 'components/DataTable'; +import { RelativeTime } from 'components/DateTime'; +import EmptyState from 'components/EmptyState'; +import MainCard from 'components/MainCard'; +import StatusChip from 'components/StatusChip'; +import PersonSheet from 'sections/access/PersonSheet'; +import { AccountState, accountMenu, ACTION_TEXT, runAccountAction } from 'sections/settings/authentication/BuiltInAccountsCard'; +import { CardTitle } from 'sections/settings/authentication/MethodControls'; +import OneTimeSecretDialog, { OneTimeSecret } from 'sections/settings/authentication/OneTimeSecretDialog'; +import { PROVIDER_LABELS } from 'api/identity'; +import useSession from 'hooks/useSession'; + +// assets +import MoreOutlined from '@ant-design/icons/MoreOutlined'; +import SearchOutlined from '@ant-design/icons/SearchOutlined'; +import UserOutlined from '@ant-design/icons/UserOutlined'; + +// types +import type { ProviderId, UserView } from 'api/identity'; +import type { DeviceGroupDto, PermissionGroupDto } from 'api/types'; + +interface Props { + users: UserView[] | undefined; + catalog: PermissionGroupDto[]; + groups: DeviceGroupDto[]; + loading: boolean; + refreshing: boolean; + error?: string; + /** Why the person cannot manage access (undefined when they can). */ + gate?: string; +} + +type Pending = { action: Parameters[0]; user: UserView } | null; + +const KINDS: ProviderId[] = ['local', 'windows', 'ldap', 'oidc']; + +/** The groups shown in the list: a built-in account's own, a Windows account's local ones; directory people's are in the sheet. */ +const groupsOf = (u: UserView) => [...u.localGroups.map((g) => g.name ?? g.id), ...u.windowsGroups.map((g) => g.name)].join(', ') || '—'; + +// ==============================|| ACCESS - PEOPLE ||============================== // + +/** Everyone who can sign in or has: built-in accounts and the people of each provider. Built-in accounts are managed on Settings › Authentication. */ +export default function PeopleTab({ users, catalog, groups, loading, refreshing, error, gate }: Props) { + const { session } = useSession(); + const [search, setSearch] = useState(''); + const [kind, setKind] = useState(''); + const [sheet, setSheet] = useState(null); + const [sheetOpen, setSheetOpen] = useState(false); + const [menu, setMenu] = useState<{ user: UserView; anchor: HTMLElement } | null>(null); + const [pending, setPending] = useState(null); + const [secret, setSecret] = useState(null); + + const rows = useMemo(() => { + const needle = search.trim().toLowerCase(); + return users?.filter( + (u) => + (!kind || u.kind === kind) && + (!needle || u.userName.toLowerCase().includes(needle) || (u.displayName ?? '').toLowerCase().includes(needle)) + ); + }, [users, search, kind]); + + // The sheet follows the list, so a change made from its row menu shows in it. + const shown = sheet ? (users?.find((u) => u.id === sheet.id) ?? sheet) : null; + + const columns: Column[] = [ + { + id: 'userName', + header: 'User Name', + nowrap: true, + sortValue: (u) => u.userName, + cell: (u) => ( + + {u.userName} + {u.breakGlass && } + + ) + }, + { id: 'displayName', header: 'Name', sortValue: (u) => u.displayName, cell: (u) => u.displayName ?? '' }, + { id: 'kind', header: 'Kind', nowrap: true, sortValue: (u) => PROVIDER_LABELS[u.kind], cell: (u) => PROVIDER_LABELS[u.kind] ?? u.kind }, + { + id: 'groups', + header: 'Groups', + help: 'Built-in and local Windows groups. Directory and OIDC groups, as of the latest sign-in, are in the person’s sheet.', + cell: (u) => ( + + {groupsOf(u)} + + ) + }, + { + id: 'lastSignIn', + header: 'Last Sign-In', + nowrap: true, + sortValue: (u) => u.lastSignInUtc, + cell: (u) => + }, + { id: 'state', header: 'State', cell: (u) => }, + { + id: 'actions', + header: '', + align: 'right', + width: 56, + cell: (u) => ( + ) => { + e.stopPropagation(); + setMenu({ user: u, anchor: e.currentTarget }); + }} + > + + + ) + } + ]; + + const text = pending ? ACTION_TEXT[pending.action] : null; + + return ( + }> + u.id} + loading={loading} + refreshing={refreshing} + error={error} + defaultSort={{ id: 'userName', direction: 'asc' }} + onRowClick={(u) => { + setSheet(u); + setSheetOpen(true); + }} + activeRowId={sheetOpen ? shown?.id : undefined} + toolbar={ + + setSearch(e.target.value)} + sx={{ width: { xs: '100%', sm: 260 } }} + slotProps={{ + input: { + startAdornment: ( + + + + ) + } + }} + /> + setKind(e.target.value as ProviderId | '')} + sx={{ minWidth: 200 }} + > + All Kinds + {KINDS.map((k) => ( + + {PROVIDER_LABELS[k]} + + ))} + + + } + empty={ + users && users.length > 0 ? ( + } title="No Matching People" detail="Clear the search or the kind." /> + ) : ( + } title="No People Yet" /> + ) + } + /> + + setPending({ action, user: menu.user })) : []} + anchorEl={menu?.anchor} + onClose={() => setMenu(null)} + /> + + setPending(null)} + onConfirm={async () => { + const generated = await runAccountAction(pending!.action, pending!.user); + if (pending!.action === 'delete' && sheet?.id === pending!.user.id) setSheetOpen(false); + if (generated) setSecret(generated); + }} + /> + setSecret(null)} /> + + setSheetOpen(false)} /> + + ); +} diff --git a/src/WebUI/src/sections/access/PersonSheet.tsx b/src/WebUI/src/sections/access/PersonSheet.tsx new file mode 100644 index 0000000..5b2d0e5 --- /dev/null +++ b/src/WebUI/src/sections/access/PersonSheet.tsx @@ -0,0 +1,194 @@ +import { ReactNode, useMemo } from 'react'; + +// material-ui +import Alert from '@mui/material/Alert'; +import Chip from '@mui/material/Chip'; +import Skeleton from '@mui/material/Skeleton'; +import Stack from '@mui/material/Stack'; +import Table from '@mui/material/Table'; +import TableBody from '@mui/material/TableBody'; +import TableCell from '@mui/material/TableCell'; +import TableHead from '@mui/material/TableHead'; +import TableRow from '@mui/material/TableRow'; +import Typography from '@mui/material/Typography'; + +// project imports +import { RelativeTime } from 'components/DateTime'; +import HoverHelp from 'components/HoverHelp'; +import Properties from 'components/Properties'; +import Sheet from 'components/Sheet'; +import { groupPathLabels, UNKNOWN_GROUP } from 'sections/access/groupPaths'; +import { AccountState } from 'sections/settings/authentication/BuiltInAccountsCard'; +import { WindowsAccountDetails } from 'sections/settings/authentication/WindowsAccountsCard'; +import { errorMessage } from 'api/client'; +import { IdentityRoutes, PRINCIPAL_KIND_LABELS, PROVIDER_LABELS } from 'api/identity'; +import useApi from 'hooks/useApi'; + +// types +import type { AccessView, UserView } from 'api/identity'; +import type { DeviceGroupDto, PermissionGroupDto } from 'api/types'; + +interface Props { + open: boolean; + /** The person shown; kept while the sheet slides closed. */ + user: UserView | null; + catalog: PermissionGroupDto[]; + groups: DeviceGroupDto[]; + onClose: () => void; +} + +function Section({ title, help, children }: { title: string; help?: string; children: ReactNode }) { + return ( + + + {title} + {help && } + + {children} + + ); +} + +const none = ( + + None + +); + +// ==============================|| ACCESS - PERSON ||============================== // + +/** What a person may do and where it came from: their groups, each role bound to one of them, the permissions and the device scope. */ +export default function PersonSheet({ open, user, catalog, groups, onClose }: Props) { + const access = useApi(open && user ? IdentityRoutes.userAccess(user.id) : null); + const labels = useMemo(() => groupPathLabels(groups), [groups]); + const permissionLabels = useMemo(() => new Map(catalog.flatMap((g) => g.permissions).map((p) => [p.key, p.label])), [catalog]); + const view = access.data; + + return ( + + {user && ( + + }, + { label: 'State', value: } + ]} + /> + + {access.loading ? ( + + ) : access.error ? ( + {errorMessage(access.error, 'Could not load what this person may do.')} + ) : view ? ( + <> +
+ {view.groups.length === 0 ? ( + none + ) : ( + + {view.groups.map((g) => ( + + ))} + + )} +
+ +
+ {view.breakGlass ? ( + + Full Access + + + ) : view.grants.length === 0 ? ( + none + ) : ( + + + + Role + Through + + + + {view.grants.map((grant) => ( + + {grant.roleName} + + + {grant.principalName ?? grant.principalId} + + + {` · ${PRINCIPAL_KIND_LABELS[grant.principalKind]}`} + + + + ))} + +
+ )} +
+ +
+ {view.permissions.includes('*') ? ( + Everything + ) : view.permissions.length === 0 ? ( + none + ) : ( + + {view.permissions.map((p) => ( + + ))} + + )} +
+ +
+ {view.deviceScopeGroupIds === null ? ( + All Devices + ) : view.deviceScopeGroupIds.length === 0 ? ( + none + ) : ( + + {view.deviceScopeGroupIds.map((id) => ( + + ))} + + )} +
+ + ) : null} + + {user.kind === 'windows' && ( +
+ +
+ )} +
+ )} +
+ ); +} diff --git a/src/WebUI/src/sections/access/RoleSheet.tsx b/src/WebUI/src/sections/access/RoleSheet.tsx new file mode 100644 index 0000000..43a6f8b --- /dev/null +++ b/src/WebUI/src/sections/access/RoleSheet.tsx @@ -0,0 +1,259 @@ +import { FormEvent, useMemo, useState } from 'react'; +import { mutate } from 'swr'; +import { enqueueSnackbar } from 'notistack'; + +// material-ui +import Alert from '@mui/material/Alert'; +import Autocomplete from '@mui/material/Autocomplete'; +import Box from '@mui/material/Box'; +import Button from '@mui/material/Button'; +import Checkbox from '@mui/material/Checkbox'; +import Chip from '@mui/material/Chip'; +import FormControlLabel from '@mui/material/FormControlLabel'; +import Grid from '@mui/material/Grid'; +import Stack from '@mui/material/Stack'; +import TextField from '@mui/material/TextField'; +import Typography from '@mui/material/Typography'; + +// project imports +import GatedButton from 'components/GatedButton'; +import HoverHelp from 'components/HoverHelp'; +import Sheet from 'components/Sheet'; +import { groupPathLabels, UNKNOWN_GROUP } from 'sections/access/groupPaths'; +import { api, errorMessage, keys } from 'api/client'; +import { plural } from 'utils/format'; + +// assets +import CopyOutlined from '@ant-design/icons/CopyOutlined'; + +// types +import type { DeviceGroupDto, PermissionGroupDto, RoleDto } from 'api/types'; + +interface Props { + open: boolean; + /** The role being edited or viewed (system roles are read-only); null creates one. */ + role: RoleDto | null; + catalog: PermissionGroupDto[]; + groups: DeviceGroupDto[]; + /** Why the user cannot manage access (undefined when they can). */ + gate?: string; + onClose: () => void; + /** Clones the shown role (offered for read-only system roles). */ + onClone: (role: RoleDto) => void; +} + +// ==============================|| ROLE SHEET ||============================== // + +/** Creates or edits a custom role, or shows a system role read-only. Mount with a fresh `key` per open. */ +export default function RoleSheet({ open, role, catalog, groups, gate, onClose, onClone }: Props) { + const [name, setName] = useState(role?.name ?? ''); + const [description, setDescription] = useState(role?.description ?? ''); + const [permissions, setPermissions] = useState(role?.permissions ?? []); + const [scope, setScope] = useState(role?.deviceScopeGroupIds ?? []); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(''); + + const readOnly = Boolean(gate) || Boolean(role?.isSystem); + const everything = permissions.includes('*'); + const valid = name.trim().length > 0 && permissions.length > 0; + + const labels = useMemo(() => groupPathLabels(groups), [groups]); + // Ids only, so a scope group that no longer exists still shows (and survives a save). + const scopeOptions = useMemo( + () => [...new Set([...groups.map((g) => g.id), ...scope])].sort((a, b) => (labels.get(a) ?? '').localeCompare(labels.get(b) ?? '')), + [groups, scope, labels] + ); + + const togglePermissions = (keysToToggle: string[], on: boolean) => + setPermissions((current) => (on ? [...new Set([...current, ...keysToToggle])] : current.filter((p) => !keysToToggle.includes(p)))); + + const save = async (event?: FormEvent) => { + event?.preventDefault(); + if (!valid || busy || readOnly) return; + setBusy(true); + setError(''); + try { + const body = { + name: name.trim(), + description: description || undefined, + permissions, + deviceScopeGroupIds: scope + }; + if (role) await api.updateRole(role.id, body); + else await api.createRole(body); + await mutate(keys.roles); + enqueueSnackbar(role ? 'Role saved' : 'Role created', { variant: 'success' }); + onClose(); + } catch (e) { + setError(errorMessage(e, 'Save failed.')); + } finally { + setBusy(false); + } + }; + + return ( + + System Role + + + ) : ( + <> + {`Custom Role · ${plural(role.bindingCount, 'binding')}`} + + + ) + ) : undefined + } + actions={ + role?.isSystem ? ( + <> + + } onClick={() => onClone(role)}> + Clone + + + ) : ( + <> + + void save()} disabled={busy || !valid}> + {busy ? 'Saving…' : role ? 'Save Changes' : 'Create Role'} + + + ) + } + > + + {error && {error}} + + + + setName(e.target.value)} + disabled={readOnly} + autoFocus={!role} + slotProps={{ htmlInput: { maxLength: 64 } }} + /> + + + setDescription(e.target.value)} + disabled={readOnly} + /> + + + + {/* permissions */} + + + Permissions + + {everything ? 'Everything' : permissions.length === 0 ? 'Grant at least one.' : `${permissions.length} granted`} + {everything && } + + + + {catalog.map((group) => { + const groupKeys = group.permissions.map((p) => p.key); + const granted = groupKeys.filter((k) => everything || permissions.includes(k)).length; + return ( + + + {group.group}} + disabled={readOnly || everything} + control={ + 0} + indeterminate={granted > 0 && granted < groupKeys.length} + onChange={(e) => togglePermissions(groupKeys, e.target.checked)} + /> + } + /> + + {group.permissions.map((perm) => ( + + {perm.label} + {perm.description && } + + } + control={ + togglePermissions([perm.key], e.target.checked)} + /> + } + /> + ))} + + + + ); + })} + + + + {/* device scope */} + + + Device Scope + + + setScope(value)} + getOptionLabel={(id) => labels.get(id) ?? UNKNOWN_GROUP} + disabled={readOnly} + noOptionsText="No device groups exist yet." + renderValue={(value, getItemProps) => + value.map((id, index) => { + const { key, ...itemProps } = getItemProps({ index }); + return ( + + ); + }) + } + renderInput={(params) => } + /> + + + {/* Enter submits. */} + + + + + + ); +} diff --git a/src/WebUI/src/sections/dashboard/RecentRuns.tsx b/src/WebUI/src/sections/dashboard/RecentRuns.tsx new file mode 100644 index 0000000..2a3cf6d --- /dev/null +++ b/src/WebUI/src/sections/dashboard/RecentRuns.tsx @@ -0,0 +1,73 @@ +import { Link as RouterLink, useNavigate } from 'react-router-dom'; + +// material-ui +import Link from '@mui/material/Link'; +import Typography from '@mui/material/Typography'; + +// project imports +import DataTable, { Column } from 'components/DataTable'; +import { RelativeTime } from 'components/DateTime'; +import EmptyState from 'components/EmptyState'; +import { JobStateChip } from 'components/StatusChip'; +import type { JobDto } from 'api/types'; + +const jobLink = (run: JobDto) => `/jobs?job=${encodeURIComponent(run.jobId)}`; + +const columns: Column[] = [ + { id: 'state', header: 'State', cell: (run) => , width: 120, nowrap: true }, + { + id: 'script', + header: 'Script', + cell: (run) => ( + e.stopPropagation()} underline="hover" color="text.primary"> + + {run.scriptName} + + + ) + }, + { + id: 'device', + header: 'Device', + cell: (run) => ( + e.stopPropagation()} + underline="hover" + color="text.secondary" + variant="body2" + sx={run.hostname ? undefined : { fontFamily: 'var(--font-mono)' }} + > + {run.hostname ?? run.clientId} + + ) + }, + { + id: 'requestedBy', + header: 'Requested By', + cell: (run) => ( + + {run.requestedBy ?? '—'} + + ) + }, + { id: 'created', header: 'Started', cell: (run) => , align: 'right', nowrap: true } +]; + +// ==============================|| DASHBOARD - LATEST EXECUTIONS ||============================== // + +export default function RecentRuns({ runs }: { runs: JobDto[] }) { + const navigate = useNavigate(); + return ( + run.jobId} + paged={false} + minWidth={560} + onRowClick={(run) => navigate(jobLink(run))} + empty={} + /> + ); +} diff --git a/src/WebUI/src/sections/devices/AddDeviceDialog.tsx b/src/WebUI/src/sections/devices/AddDeviceDialog.tsx new file mode 100644 index 0000000..0505c05 --- /dev/null +++ b/src/WebUI/src/sections/devices/AddDeviceDialog.tsx @@ -0,0 +1,302 @@ +import { useEffect, useRef, useState } from 'react'; +import { mutate } from 'swr'; + +// material-ui +import Alert from '@mui/material/Alert'; +import Box from '@mui/material/Box'; +import Button from '@mui/material/Button'; +import Checkbox from '@mui/material/Checkbox'; +import Dialog from '@mui/material/Dialog'; +import DialogActions from '@mui/material/DialogActions'; +import DialogContent from '@mui/material/DialogContent'; +import DialogTitle from '@mui/material/DialogTitle'; +import FormControlLabel from '@mui/material/FormControlLabel'; +import Radio from '@mui/material/Radio'; +import RadioGroup from '@mui/material/RadioGroup'; +import Stack from '@mui/material/Stack'; +import TextField from '@mui/material/TextField'; +import Typography from '@mui/material/Typography'; + +// project imports +import GatedButton from 'components/GatedButton'; +import HoverHelp from 'components/HoverHelp'; +import IconButton from 'components/@extended/IconButton'; +import { api, errorMessage } from 'api/client'; +import useApi from 'hooks/useApi'; +import { useGate } from 'hooks/useSession'; +import { CommandBox, PlatformPicker, WindowsPackagePicker } from 'sections/settings/InstallControls'; +import { installCommand, InstallPlatform, SERVICE_KIND, WindowsPackage } from 'sections/settings/installCommands'; +import { SETTINGS_KEYS, SETTINGS_PERMISSION, SETTINGS_PERMISSION_LABEL } from 'sections/settings/keys'; + +// assets +import CloseOutlined from '@ant-design/icons/CloseOutlined'; + +// types +import type { ServerInfoDto } from 'api/types'; + +type Scope = 'single' | 'multi'; + +interface Limits { + scope: Scope; + multiUses: string; + unlimited: boolean; + noExpiry: boolean; +} + +/** Max uses the token is issued with (0 = unlimited). */ +function effectiveUses({ scope, multiUses, unlimited }: Limits): number { + if (scope === 'single') return 1; + if (unlimited) return 0; + return Math.min(9999, Math.max(1, Math.floor(Number(multiUses) || 1))); +} + +interface Props { + open: boolean; + onClose: () => void; +} + +// ==============================|| ADD DEVICE DIALOG ||============================== // + +export default function AddDeviceDialog({ open, onClose }: Props) { + // Every opening starts from a clean form: the key changes once the close + // transition has finished, remounting the content. + const [instance, setInstance] = useState(0); + + return ( + setInstance((n) => n + 1) } }} + > + + + ); +} + +function AddDeviceContent({ open, onClose }: Props) { + const gate = useGate(SETTINGS_PERMISSION, SETTINGS_PERMISSION_LABEL); + const { data: serverInfo, error: serverError } = useApi(SETTINGS_KEYS.serverInfo); + + const [platform, setPlatform] = useState('windows'); + const [windowsPackage, setWindowsPackage] = useState('msi'); + const [scope, setScopeState] = useState('single'); + const [multiUses, setMultiUses] = useState('1'); + const [unlimited, setUnlimited] = useState(false); + const [noExpiry, setNoExpiry] = useState(false); + const [token, setToken] = useState(''); + const [error, setError] = useState(''); + const [busy, setBusy] = useState(false); + + // The debounced re-issue reads the latest limits and token id, not the + // values captured when it was scheduled. + const limits: Limits = { scope, multiUses, unlimited, noExpiry }; + const latest = useRef(limits); + latest.current = limits; + const tokenId = useRef(''); + const regenTimer = useRef(undefined); + + // A pending debounce firing after dismissal would mint an orphan token. + useEffect(() => { + if (!open) window.clearTimeout(regenTimer.current); + }, [open]); + useEffect(() => () => window.clearTimeout(regenTimer.current), []); + + const baseUrl = serverInfo?.baseUrl ?? (serverError ? window.location.origin : ''); + // Server-informed (no operator toggle): true when this origin is the + // self-signed listener reached directly, so the target's own fetch must + // skip verification. False behind a real-cert proxy. + const selfSignedDirect = serverInfo?.selfSignedDirect ?? false; + const uses = effectiveUses(limits); + + /** Nothing is created until this issues the bootstrap token. */ + const generate = async () => { + const current = latest.current; + const maxUses = effectiveUses(current); + setBusy(true); + setError(''); + try { + // A superseded token would otherwise stay live for 24 hours. + if (tokenId.current) { + await api.revokeBootstrapToken(tokenId.current).catch(() => undefined); + tokenId.current = ''; + } + const created = await api.createBootstrapToken({ + validMinutes: current.scope === 'multi' && current.noExpiry ? 0 : 24 * 60, + maxUses, + note: + current.scope === 'single' + ? 'Add device (single use)' + : `Add device (${current.unlimited ? 'unlimited uses' : `${maxUses} uses`})` + }); + tokenId.current = created.id; + setToken(created.token ?? ''); + void mutate(SETTINGS_KEYS.bootstrapTokens); + } catch (e) { + setError(errorMessage(e, 'Could not create a bootstrap token.')); + } finally { + setBusy(false); + } + }; + + /** + * Limits are properties of the token. Before the first Generate, changes + * just update the form; afterwards they re-issue live (debounced, with the + * superseded token revoked). + */ + const limitsChanged = () => { + if (!token && !busy) return; + window.clearTimeout(regenTimer.current); + regenTimer.current = window.setTimeout(() => void generate(), 600); + }; + + const setScope = (next: Scope) => { + if (scope === next) return; + setScopeState(next); + // A single device is a one-time enrollment; no-expiry is a multi-device convenience only. + if (next === 'single') setNoExpiry(false); + limitsChanged(); + }; + + const command = token && baseUrl ? installCommand({ platform, baseUrl, token, selfSignedDirect, windowsPackage }) : ''; + const shellHint = + platform === 'windows' ? 'Paste into a PowerShell prompt on the device.' : 'Paste into a terminal on the device (needs sudo).'; + const usesText = scope === 'single' ? 'one use' : unlimited ? 'unlimited uses' : `up to ${uses} use${uses === 1 ? '' : 's'}`; + + return ( + <> + + Add Device + + + + + + + + {platform === 'windows' && } + + + setScope(e.target.value as Scope)} aria-label="Devices"> + } + label={ + <> + Single Device + + + } + /> + } label="Multiple Devices" /> + + {scope === 'multi' && ( + + { + setMultiUses(e.target.value); + limitsChanged(); + }} + slotProps={{ htmlInput: { min: 1, max: 9999 } }} + sx={{ width: 120 }} + /> + { + setUnlimited(e.target.checked); + limitsChanged(); + }} + /> + } + label="Unlimited" + /> + { + setNoExpiry(e.target.checked); + limitsChanged(); + }} + /> + } + label={ + <> + No Expiry + + + } + /> + + )} + + + {error && {error}} + + {command ? ( + + + {platform === 'windows' && !busy && Run this command from an elevated PowerShell terminal.} + + {busy ? ( + 'Updating the token…' + ) : ( + <> + {shellHint} + + + )} + + + ) : ( + + Token: {usesText}, {noExpiry ? 'no expiry' : '24-hour expiry'}. + + + )} + + {baseUrl && ( + + Devices reach this server at{' '} + + {baseUrl} + + + + )} + + + + + {command ? ( + + ) : ( + + {busy ? 'Generating…' : 'Generate Command'} + + )} + + + ); +} diff --git a/src/WebUI/src/sections/devices/DeviceHardware.tsx b/src/WebUI/src/sections/devices/DeviceHardware.tsx new file mode 100644 index 0000000..97bfb8d --- /dev/null +++ b/src/WebUI/src/sections/devices/DeviceHardware.tsx @@ -0,0 +1,160 @@ +// material-ui +import Chip from '@mui/material/Chip'; +import Grid from '@mui/material/Grid'; +import LinearProgress from '@mui/material/LinearProgress'; +import Stack from '@mui/material/Stack'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; + +// project imports +import CopyButton from 'components/CopyButton'; +import EmptyState from 'components/EmptyState'; +import MainCard from 'components/MainCard'; +import Properties from 'components/Properties'; +import { formatBytes } from 'utils/format'; +import type { InventoryReport } from 'api/types'; + +type Volume = InventoryReport['volumes'][number]; + +function VolumeBar({ volume }: { volume: Volume }) { + const used = volume.totalSizeBytes - volume.freeSpaceBytes; + const pct = volume.totalSizeBytes > 0 ? Math.round((used / volume.totalSizeBytes) * 100) : 0; + return ( + + + + {volume.driveLetter} + + + {volume.fileSystem ?? '—'} + + + {formatBytes(volume.freeSpaceBytes)} free of {formatBytes(volume.totalSizeBytes)} + + + + = 85 ? 'error' : pct >= 70 ? 'warning' : 'primary'} + sx={{ height: 6, borderRadius: 3 }} + /> + + + ); +} + +// ==============================|| DEVICE - HARDWARE ||============================== // + +export default function DeviceHardware({ inventory }: { inventory?: InventoryReport }) { + if (!inventory) { + return ( + + + + ); + } + + // By physical disk number (falling back to report order), so Disk 0 comes first. + const disks = inventory.disks.map((disk, i) => ({ disk, index: disk.index ?? i })).sort((a, b) => a.index - b.index); + const unmapped = inventory.volumes.filter((v) => v.diskIndex == null || !disks.some((d) => d.index === v.diskIndex)); + + return ( + + + + + + + + + + + {inventory.memory.map((dimm, i) => ( + + {dimm.deviceLocator ?? `DIMM ${i + 1}`}: {formatBytes(dimm.capacityBytes)} + {dimm.speedMhz ? ` @ ${dimm.speedMhz} MHz` : ''} + {dimm.manufacturer ? ` (${dimm.manufacturer})` : ''} + + ))} + + + + + + + + + + + + {disks.map(({ disk, index }) => { + const volumes = inventory.volumes.filter((v) => v.diskIndex === index); + return ( + + + {disk.model ?? `Disk ${index}`} + + {disk.busType && } + + {formatBytes(disk.sizeBytes)} + + {disk.serialNumber && ( + + + {disk.serialNumber} + + + + )} + + {volumes.length === 0 ? ( + + No mapped volumes. + + ) : ( + + {volumes.map((v) => ( + + + + ))} + + )} + + ); + })} + {unmapped.length > 0 && ( + + + Volumes Without a Disk Mapping + + + {unmapped.map((v) => ( + + + + ))} + + + )} + + + + + ); +} diff --git a/src/WebUI/src/sections/devices/DeviceHistory.tsx b/src/WebUI/src/sections/devices/DeviceHistory.tsx new file mode 100644 index 0000000..eb1933a --- /dev/null +++ b/src/WebUI/src/sections/devices/DeviceHistory.tsx @@ -0,0 +1,83 @@ +// material-ui +import Chip, { ChipProps } from '@mui/material/Chip'; +import Typography from '@mui/material/Typography'; + +// project imports +import DataTable, { Column } from 'components/DataTable'; +import { RelativeTime } from 'components/DateTime'; +import EmptyState from 'components/EmptyState'; +import HoverHelp from 'components/HoverHelp'; +import MainCard from 'components/MainCard'; +import useApi from 'hooks/useApi'; +import useLiveRefresh from 'hooks/useLiveRefresh'; +import { keys } from 'api/client'; +import type { DeviceHistoryEventDto } from 'api/types'; + +/** Short title and tone per history action. */ +const EVENTS: Record = { + 'device-enrolled': { label: 'Enrolled', color: 'success' }, + 'device-renamed': { label: 'Renamed', color: 'info' }, + 'device-os-changed': { label: 'OS Changed', color: 'primary' }, + 'agent-upgraded': { label: 'Agent Upgraded', color: 'success' }, + 'agent-rolled-back': { label: 'Agent Rolled Back', color: 'warning' }, + 'agent-upgrade-failed': { label: 'Agent Upgrade Failed', color: 'error' } +}; + +// ==============================|| DEVICE - HISTORY ||============================== // + +export default function DeviceHistory({ clientId }: { clientId: string }) { + const { data, error, loading, mutate } = useApi(keys.deviceHistory(clientId)); + useLiveRefresh( + () => mutate(), + (event) => event.clientId === clientId + ); + + const columns: Column[] = [ + { + id: 'event', + header: 'Event', + sortValue: (e) => EVENTS[e.action]?.label ?? e.action, + cell: (e) => ( + + ) + }, + { + id: 'detail', + header: 'Detail', + cell: (e) => ( + + {e.detail ?? '—'} + + ) + }, + { id: 'when', header: 'When', nowrap: true, sortValue: (e) => e.id, cell: (e) => } + ]; + + return ( + + Device History + + + } + > + String(e.id)} + loading={loading} + error={error?.message} + defaultSort={{ id: 'when', direction: 'desc' }} + empty={} + /> + + ); +} diff --git a/src/WebUI/src/sections/devices/DeviceJobs.tsx b/src/WebUI/src/sections/devices/DeviceJobs.tsx new file mode 100644 index 0000000..bb13262 --- /dev/null +++ b/src/WebUI/src/sections/devices/DeviceJobs.tsx @@ -0,0 +1,90 @@ +import { useState } from 'react'; +import { Link as RouterLink } from 'react-router-dom'; + +// material-ui +import Link from '@mui/material/Link'; +import Typography from '@mui/material/Typography'; + +// project imports +import DataTable, { Column } from 'components/DataTable'; +import { RelativeTime } from 'components/DateTime'; +import EmptyState from 'components/EmptyState'; +import HoverHelp from 'components/HoverHelp'; +import MainCard from 'components/MainCard'; +import { JobStateChip } from 'components/StatusChip'; +import JobOutputDrawer from 'sections/jobs/JobOutputDrawer'; +import useApi from 'hooks/useApi'; +import useLiveRefresh from 'hooks/useLiveRefresh'; +import { keys } from 'api/client'; +import { formatDuration } from 'utils/format'; +import type { JobDto } from 'api/types'; + +// ==============================|| DEVICE - EXECUTION HISTORY ||============================== // + +export default function DeviceJobs({ clientId }: { clientId: string }) { + const [openJob, setOpenJob] = useState(null); + const { data, error, loading, mutate } = useApi(keys.jobs({ clientId, limit: 200 })); + useLiveRefresh( + () => mutate(), + (event) => event.clientId === clientId + ); + + const columns: Column[] = [ + { + id: 'script', + header: 'Script', + sortValue: (j) => j.scriptName, + cell: (j) => ( + e.stopPropagation()}> + {j.scriptName} + + ) + }, + { id: 'state', header: 'State', sortValue: (j) => j.state, cell: (j) => }, + { id: 'created', header: 'Queued', nowrap: true, sortValue: (j) => j.createdUtc, cell: (j) => }, + { + id: 'duration', + header: 'Duration', + sortValue: (j) => (j.startedUtc && j.completedUtc ? new Date(j.completedUtc).getTime() - new Date(j.startedUtc).getTime() : null), + cell: (j) => formatDuration(j.startedUtc, j.completedUtc) + }, + { + id: 'exit', + header: 'Exit', + align: 'right', + sortValue: (j) => j.exitCode, + cell: (j) => {j.exitCode ?? '—'} + }, + { id: 'by', header: 'Requested By', sortValue: (j) => j.requestedBy, cell: (j) => j.requestedBy ?? '—' } + ]; + + return ( + + Execution History + + + } + secondary={ + + Open in Jobs + + } + > + j.jobId} + loading={loading} + error={error?.message} + defaultSort={{ id: 'created', direction: 'desc' }} + onRowClick={(j) => setOpenJob(j.jobId)} + activeRowId={openJob ?? undefined} + empty={} + /> + setOpenJob(null)} /> + + ); +} diff --git a/src/WebUI/src/sections/devices/DeviceNetwork.tsx b/src/WebUI/src/sections/devices/DeviceNetwork.tsx new file mode 100644 index 0000000..f754ddc --- /dev/null +++ b/src/WebUI/src/sections/devices/DeviceNetwork.tsx @@ -0,0 +1,77 @@ +// material-ui +import Box from '@mui/material/Box'; +import Grid from '@mui/material/Grid'; +import Stack from '@mui/material/Stack'; +import Typography from '@mui/material/Typography'; + +// project imports +import CopyButton from 'components/CopyButton'; +import EmptyState from 'components/EmptyState'; +import MainCard from 'components/MainCard'; +import type { InventoryReport } from 'api/types'; + +// ==============================|| DEVICE - NETWORK ||============================== // + +export default function DeviceNetwork({ inventory }: { inventory?: InventoryReport }) { + if (!inventory || inventory.network.length === 0) { + return ( + + + + ); + } + + return ( + + {inventory.network.map((adapter, i) => { + const rows = [ + { label: 'Interface', values: adapter.interfaceName ? [adapter.interfaceName] : [] }, + { label: 'MAC', values: adapter.macAddress ? [adapter.macAddress] : [] }, + { label: 'IPv4', values: adapter.ipv4Addresses }, + { label: 'IPv6', values: adapter.ipv6Addresses }, + { label: 'Gateways', values: adapter.gateways }, + { label: 'DNS', values: adapter.dnsServers } + ]; + const title = adapter.interfaceName ?? adapter.description ?? `Adapter ${i + 1}`; + return ( + + + + {rows.map((row) => ( + + + {row.label} + + + {row.values.length === 0 ? ( + + — + + ) : ( + row.values.map((value) => ( + + + {value} + + + + )) + )} + + + ))} + + + + ); + })} + + ); +} diff --git a/src/WebUI/src/sections/devices/DeviceOverview.tsx b/src/WebUI/src/sections/devices/DeviceOverview.tsx new file mode 100644 index 0000000..0907943 --- /dev/null +++ b/src/WebUI/src/sections/devices/DeviceOverview.tsx @@ -0,0 +1,274 @@ +import { KeyboardEvent, useState } from 'react'; +import { Link as RouterLink } from 'react-router-dom'; + +// material-ui +import Button from '@mui/material/Button'; +import Chip from '@mui/material/Chip'; +import Grid from '@mui/material/Grid'; +import Stack from '@mui/material/Stack'; +import TextField from '@mui/material/TextField'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; + +// third-party +import { enqueueSnackbar } from 'notistack'; + +// project imports +import CopyButton from 'components/CopyButton'; +import { AbsoluteTime, RelativeTime } from 'components/DateTime'; +import HoverHelp from 'components/HoverHelp'; +import MainCard from 'components/MainCard'; +import Properties from 'components/Properties'; +import { deviceUpgradesKey } from 'sections/devices/DeviceUpgrades'; +import { newestFor } from 'sections/upgrades/agentVersions'; +import { AgentVersion, UpgradeStateChip } from 'sections/upgrades/UpgradeChips'; +import { isOpenUpgrade } from 'sections/upgrades/upgradeLabels'; +import useApi from 'hooks/useApi'; +import useLiveRefresh from 'hooks/useLiveRefresh'; +import { api, errorMessage, keys } from 'api/client'; +import type { AgentUpgradeDto, AgentVersionDto, DeviceDetailDto } from 'api/types'; + +// assets +import EyeInvisibleOutlined from '@ant-design/icons/EyeInvisibleOutlined'; +import EyeOutlined from '@ant-design/icons/EyeOutlined'; + +interface Props { + detail: DeviceDetailDto; + canManage: boolean; + onChanged: () => void; +} + +// ==============================|| DEVICE - OVERVIEW ||============================== // + +export default function DeviceOverview({ detail, canManage, onChanged }: Props) { + const { device, inventory } = detail; + const [tagInput, setTagInput] = useState(''); + // The public IP is operationally sensitive; keep it masked until asked. + const [showPublicIp, setShowPublicIp] = useState(false); + + const saveTags = async (tags: string[]) => { + try { + await api.updateDeviceTags(device.clientId, tags); + onChanged(); + } catch (e) { + enqueueSnackbar(errorMessage(e, 'Failed to update tags.'), { variant: 'error' }); + } + }; + + const addTag = async () => { + const value = tagInput.trim(); + if (!value) return; + await saveTags([...(device.tags ?? []), value]); + setTagInput(''); + }; + + const groups = detail.groups ?? []; + + const { data: versions } = useApi(keys.agentVersions); + const { data: upgrades, mutate: refreshUpgrades } = useApi(deviceUpgradesKey(device.clientId)); + useLiveRefresh( + () => refreshUpgrades(), + (event) => event.clientId === device.clientId + ); + // Newest first: the open one (at most one), and the last that finished. + const byNewest = [...(upgrades ?? [])].sort((a, b) => b.createdUtc.localeCompare(a.createdUtc)); + const open = byNewest.find((u) => isOpenUpgrade(u.state)); + const last = byNewest.find((u) => !isOpenUpgrade(u.state) && u.finishedUtc); + + return ( + + + + + + + + + : undefined } + ]} + /> + + + + + }, + { label: 'IP Addresses', value: device.ipAddresses.join(', '), mono: true }, + { + label: 'Public IP', + value: device.publicIp ? ( + + + {showPublicIp ? device.publicIp : '•••.•••.•••.•••'} + + + + + {showPublicIp && } + + ) : undefined + }, + { label: 'Inventory Updated', value: } + ]} + /> + + + + + + }, + ...(open + ? [ + { + label: 'Upgrade', + value: ( + + + + to {open.targetVersion} + + + ) + } + ] + : []), + { + label: 'Last Upgrade', + value: last ? ( + + + + {last.targetVersion} + + + + ) : undefined + }, + { label: 'Enrolled', value: }, + { + label: 'Client ID', + value: ( + + + {device.clientId} + + + + ) + } + ]} + /> + + + + + Groups + + + } + > + {groups.length === 0 ? ( + + Not in any group. + + ) : ( + + {groups.map((g) => ( + + + + ))} + + )} + + + + + Tags + + + } + > + + + {(device.tags ?? []).length === 0 && ( + + No tags. + + )} + {(device.tags ?? []).map((tag) => ( + void saveTags((device.tags ?? []).filter((t) => t !== tag)) : undefined} + /> + ))} + + {canManage && ( + + setTagInput(e.target.value)} + onKeyDown={(e: KeyboardEvent) => e.key === 'Enter' && void addTag()} + /> + + + )} + + + + + ); +} diff --git a/src/WebUI/src/sections/devices/DeviceUpgrades.tsx b/src/WebUI/src/sections/devices/DeviceUpgrades.tsx new file mode 100644 index 0000000..9be376c --- /dev/null +++ b/src/WebUI/src/sections/devices/DeviceUpgrades.tsx @@ -0,0 +1,81 @@ +// material-ui +import Stack from '@mui/material/Stack'; + +// project imports +import EmptyState from 'components/EmptyState'; +import GatedButton from 'components/GatedButton'; +import HoverHelp from 'components/HoverHelp'; +import MainCard from 'components/MainCard'; +import { isUpgradeActivity } from 'sections/upgrades/agentVersions'; +import UpgradeTable from 'sections/upgrades/UpgradeTable'; +import useAgentUpgrades from 'sections/upgrades/useAgentUpgrades'; +import useApi from 'hooks/useApi'; +import useLiveRefresh from 'hooks/useLiveRefresh'; +import { useGate } from 'hooks/useSession'; +import { keys } from 'api/client'; +import type { AgentUpgradeDto, DeviceDto } from 'api/types'; + +// assets +import CloudSyncOutlined from '@ant-design/icons/CloudSyncOutlined'; +import RollbackOutlined from '@ant-design/icons/RollbackOutlined'; + +/** The device's upgrade attempts (the Agent card reads the same list). */ +export const deviceUpgradesKey = (clientId: string) => keys.agentUpgrades({ clientId, limit: 100 }); + +// ==============================|| DEVICE - AGENT UPGRADES ||============================== // + +export default function DeviceUpgrades({ device }: { device: DeviceDto }) { + const gate = useGate('devices.manage', 'Manage Devices'); + const upgrades = useAgentUpgrades(); + const { data, error, loading, validating, mutate } = useApi(deviceUpgradesKey(device.clientId)); + useLiveRefresh( + () => mutate(), + (event) => event.clientId === device.clientId || (!event.clientId && isUpgradeActivity(event)) + ); + + const target = { clientIds: [device.clientId], name: { device: device.hostname } }; + + return ( + + Agent Upgrades + + + } + secondary={ + + } + gate={gate} + onClick={() => upgrades.upgrade(target)} + > + Upgrade Agent + + } + gate={gate} + onClick={() => upgrades.rollBack(target)} + > + Roll Back + + + } + > + } + /> + {upgrades.elements} + + ); +} diff --git a/src/WebUI/src/sections/devices/SendFileCard.tsx b/src/WebUI/src/sections/devices/SendFileCard.tsx new file mode 100644 index 0000000..c6a9418 --- /dev/null +++ b/src/WebUI/src/sections/devices/SendFileCard.tsx @@ -0,0 +1,91 @@ +import { useState } from 'react'; +import { useNavigate } from 'react-router-dom'; + +// material-ui +import Alert from '@mui/material/Alert'; +import Stack from '@mui/material/Stack'; +import TextField from '@mui/material/TextField'; + +// project imports +import GatedButton from 'components/GatedButton'; +import HoverHelp from 'components/HoverHelp'; +import MainCard from 'components/MainCard'; +import { useGate } from 'hooks/useSession'; +import { api, errorMessage } from 'api/client'; +import { platformOf } from 'components/OsIcon'; +import type { DeviceDto } from 'api/types'; + +// assets +import CloudDownloadOutlined from '@ant-design/icons/CloudDownloadOutlined'; + +// ==============================|| DEVICE - SEND FILE (S3) ||============================== // + +export default function SendFileCard({ device }: { device: DeviceDto }) { + const navigate = useNavigate(); + const gate = useGate('files.send', 'Send Files'); + const [objectKey, setObjectKey] = useState(''); + const [destination, setDestination] = useState( + platformOf(device.osCaption) === 'windows' ? 'C:\\ProgramData\\ExecuteR\\downloads\\' : '/var/tmp/executer/' + ); + const [sha, setSha] = useState(''); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(''); + + const send = async () => { + setError(''); + if (!objectKey.trim() || !destination.trim()) return setError('Object key and destination path are required.'); + setBusy(true); + try { + const job = await api.sendFile(device.clientId, { + objectKey: objectKey.trim(), + destinationPath: destination.trim(), + sha256: sha.trim() || undefined + }); + navigate(`/jobs?job=${job.jobId}`); + } catch (e) { + setError(errorMessage(e, 'File delivery failed.')); + } finally { + setBusy(false); + } + }; + + return ( + + Send File + + + } + > + + setObjectKey(e.target.value)} + /> + setDestination(e.target.value)} /> + setSha(e.target.value)} + slotProps={{ htmlInput: { style: { fontFamily: 'var(--font-mono)' } } }} + /> + {error && {error}} +
+ } + onClick={send} + disabled={busy} + gate={gate ?? (device.isOrphaned ? 'The device is orphaned.' : undefined)} + > + {busy ? 'Sending…' : 'Send to Device'} + +
+
+
+ ); +} diff --git a/src/WebUI/src/sections/devices/useDeviceActions.tsx b/src/WebUI/src/sections/devices/useDeviceActions.tsx new file mode 100644 index 0000000..4384874 --- /dev/null +++ b/src/WebUI/src/sections/devices/useDeviceActions.tsx @@ -0,0 +1,229 @@ +import { useState } from 'react'; +import { useNavigate } from 'react-router-dom'; + +// material-ui +import Autocomplete from '@mui/material/Autocomplete'; +import Chip from '@mui/material/Chip'; +import TextField from '@mui/material/TextField'; + +// third-party +import { enqueueSnackbar } from 'notistack'; +import { mutate } from 'swr'; + +// project imports +import ConfirmDialog from 'components/ConfirmDialog'; +import { MenuEntry } from 'components/ActionMenu'; +import HoverHelp from 'components/HoverHelp'; +import GroupEditor from 'sections/groups/GroupEditor'; +import useAgentUpgrades, { UpgradeTarget } from 'sections/upgrades/useAgentUpgrades'; +import useApi from 'hooks/useApi'; +import useAutomation from 'hooks/useAutomation'; +import useSession from 'hooks/useSession'; +import { api, keys } from 'api/client'; +import { deviceActionMenu } from 'utils/deviceActions'; +import { plural } from 'utils/format'; +import { buildGroupTree, flattenTree, groupPath } from 'utils/groupTree'; +import type { DeviceDto, DeviceGroupDto } from 'api/types'; + +/** Sentinel option: create a new static group from the chosen devices. */ +const NEW_GROUP = '__new__'; + +const upgradeTarget = (devices: DeviceDto[]): UpgradeTarget => ({ + clientIds: devices.map((d) => d.clientId), + name: devices.length === 1 ? { device: devices[0].hostname } : { devices: devices.length } +}); + +// ==============================|| DEVICE ACTIONS (MENU + DIALOGS) ||============================== // + +/** + * Everything the device "…" and bulk Actions menus can do. Render `elements` + * once; `menuFor(devices)` builds the entries for one device or a selection. + */ +export default function useDeviceActions(options: { staticGroup?: DeviceGroupDto | null; onDone?: () => void } = {}) { + const navigate = useNavigate(); + const { can } = useSession(); + const { openRun, openSchedule } = useAutomation(); + const { data: groups } = useApi(keys.groups); + + const [grouping, setGrouping] = useState(null); + const [groupChoice, setGroupChoice] = useState(null); + const [newGroupFor, setNewGroupFor] = useState(null); + const [tagging, setTagging] = useState(null); + const [tags, setTags] = useState([]); + const [removing, setRemoving] = useState(null); + + const upgrades = useAgentUpgrades(); + + const refresh = () => Promise.all([mutate(keys.devices), mutate(keys.groups)]); + const staticGroups = flattenTree(buildGroupTree(groups ?? [])).filter((n) => n.group.kind === 'static'); + + const refreshInventory = async (devices: DeviceDto[]) => { + const results = await Promise.allSettled(devices.map((d) => api.refreshInventory(d.clientId))); + const failed = results.filter((r) => r.status === 'rejected').length; + enqueueSnackbar( + failed === 0 + ? `Inventory refresh requested for ${plural(devices.length, 'device')}.` + : `Requested for ${devices.length - failed}; ${failed} could not be reached.`, + { variant: failed === 0 ? 'success' : 'warning' } + ); + }; + + const menuFor = (devices: DeviceDto[]): MenuEntry[] => + deviceActionMenu( + devices, + can, + { staticGroup: options.staticGroup }, + { + run: () => openRun({ targets: devices.filter((d) => !d.isOrphaned).map((d) => ({ kind: 'device', id: d.clientId })) }), + schedule: () => openSchedule({ preset: { target: { kind: 'device', id: devices[0].clientId } } }), + shell: () => navigate(`/devices/${encodeURIComponent(devices[0].clientId)}/shell`), + addToGroup: () => { + setGroupChoice(null); + setGrouping(devices); + }, + removeFromGroup: () => setRemoving(devices.filter((d) => options.staticGroup && d.groupIds?.includes(options.staticGroup.id))), + tags: () => { + setTags(devices.length === 1 ? (devices[0].tags ?? []) : []); + setTagging(devices); + }, + refreshInventory: () => void refreshInventory(devices), + upgradeAgent: () => upgrades.upgrade(upgradeTarget(devices)), + rollBackAgent: () => upgrades.rollBack(upgradeTarget(devices)), + details: () => navigate(`/devices/${encodeURIComponent(devices[0].clientId)}`), + history: () => navigate(`/jobs?clientId=${encodeURIComponent(devices[0].clientId)}`), + copyId: () => + void navigator.clipboard + .writeText(devices[0].clientId) + .then(() => enqueueSnackbar('Client ID copied.', { variant: 'info' })) + .catch(() => undefined) + } + ); + + const knownTags = [...new Set((tagging ?? []).flatMap((d) => d.tags ?? []))]; + + const elements = ( + <> + {upgrades.elements} + setGrouping(null)} + onConfirm={async () => { + if (groupChoice === NEW_GROUP) { + setNewGroupFor(grouping); + return; + } + await api.updateGroupMembers( + groupChoice!, + grouping!.map((d) => d.clientId), + [] + ); + await refresh(); + enqueueSnackbar(`Added to “${groupPath(groups ?? [], groupChoice!)}”.`, { variant: 'success' }); + options.onDone?.(); + }} + > + n.group.id)]} + value={groupChoice} + onChange={(_, value) => setGroupChoice(value)} + getOptionLabel={(id) => (id === NEW_GROUP ? 'New Static Group…' : groupPath(groups ?? [], id))} + renderInput={(params) => ( + + Static Group + + + } + autoFocus + /> + )} + /> + + + setNewGroupFor(null)} + preset={{ kind: 'static', memberIds: newGroupFor?.map((d) => d.clientId) }} + onSaved={() => options.onDone?.()} + /> + + setRemoving(null)} + onConfirm={async () => { + await api.updateGroupMembers( + options.staticGroup!.id, + [], + removing!.map((d) => d.clientId) + ); + await refresh(); + options.onDone?.(); + }} + /> + + 1 ? `These tags are added to ${plural(tagging.length, 'device')}; existing tags stay.` : undefined + } + confirmLabel="Save Tags" + maxWidth="sm" + onClose={() => setTagging(null)} + onConfirm={async () => { + const cleaned = tags.map((t) => t.trim()).filter(Boolean); + await Promise.all( + tagging!.map((d) => + api.updateDeviceTags(d.clientId, tagging!.length === 1 ? cleaned : [...new Set([...(d.tags ?? []), ...cleaned])]) + ) + ); + await refresh(); + }} + > + setTags(value)} + renderValue={(value, getItemProps) => + value.map((tag, index) => { + const { key, ...itemProps } = getItemProps({ index }); + return ; + }) + } + renderInput={(params) => ( + + Tags + + + } + placeholder="Type and press Enter" + autoFocus + /> + )} + /> + + + ); + + return { menuFor, elements }; +} diff --git a/src/WebUI/src/sections/functions/FunctionEditor.tsx b/src/WebUI/src/sections/functions/FunctionEditor.tsx new file mode 100644 index 0000000..3a207b2 --- /dev/null +++ b/src/WebUI/src/sections/functions/FunctionEditor.tsx @@ -0,0 +1,231 @@ +import { useEffect, useState } from 'react'; +import { mutate } from 'swr'; +import { enqueueSnackbar } from 'notistack'; + +// material-ui +import Alert from '@mui/material/Alert'; +import Chip from '@mui/material/Chip'; +import Grid from '@mui/material/Grid'; +import Stack from '@mui/material/Stack'; +import TextField from '@mui/material/TextField'; +import Typography from '@mui/material/Typography'; + +// project imports +import CodeEditor from 'components/CodeEditor'; +import ConfirmDialog from 'components/ConfirmDialog'; +import { RelativeTime } from 'components/DateTime'; +import GatedButton from 'components/GatedButton'; +import MainCard from 'components/MainCard'; +import { api, errorMessage, keys } from 'api/client'; + +// assets +import CopyOutlined from '@ant-design/icons/CopyOutlined'; +import DeleteOutlined from '@ant-design/icons/DeleteOutlined'; +import SaveOutlined from '@ant-design/icons/SaveOutlined'; + +// types +import type { FunctionModuleDto } from 'api/types'; + +interface Props { + /** The module being edited; null for a new one. */ + module: FunctionModuleDto | null; + /** Every module name, for naming clones. */ + existingNames: string[]; + /** Why the user cannot change modules (undefined when they can). */ + gate?: string; + /** Switches the page to another module (null: none). */ + onSelect: (id: string | null) => void; + onDirtyChange: (dirty: boolean) => void; +} + +interface Draft { + name: string; + description: string; + content: string; +} + +const NEW_MODULE: Draft = { + name: '', + description: '', + content: 'function Write-ExecuteRLog {\n param([string]$Message)\n Write-Output "[ExecuteR] $Message"\n}\n' +}; + +const copyName = (base: string, existing: string[]) => { + let candidate = `${base} (copy)`; + for (let i = 2; existing.includes(candidate); i++) candidate = `${base} (copy ${i})`; + return candidate; +}; + +// ==============================|| FUNCTION EDITOR ||============================== // + +/** Name, description and code of one function module. Mount with `key` per module so the draft resets. */ +export default function FunctionEditor({ module, existingNames, gate, onSelect, onDirtyChange }: Props) { + const [saved, setSaved] = useState(() => + module ? { name: module.name, description: module.description ?? '', content: module.content } : NEW_MODULE + ); + const [draft, setDraft] = useState(saved); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(''); + const [confirmDelete, setConfirmDelete] = useState(false); + + const dirty = draft.name !== saved.name || draft.description !== saved.description || draft.content !== saved.content; + useEffect(() => { + onDirtyChange(dirty); + return () => onDirtyChange(false); + }, [dirty, onDirtyChange]); + + const update = (patch: Partial) => setDraft((current) => ({ ...current, ...patch })); + + const save = async () => { + if (!draft.name.trim()) { + setError('Name is required.'); + return; + } + setBusy(true); + setError(''); + try { + const body = { name: draft.name.trim(), description: draft.description, content: draft.content }; + if (module) { + await api.updateFunction(module.id, body); + setSaved({ ...draft, name: body.name }); + setDraft((current) => ({ ...current, name: body.name })); + await mutate(keys.functions); + } else { + const created = await api.createFunction(body); + await mutate(keys.functions); + onSelect(created.id); + } + enqueueSnackbar('Saved', { variant: 'success' }); + } catch (e) { + setError(errorMessage(e, 'Save failed.')); + } finally { + setBusy(false); + } + }; + + /** Copies the current editor state into a new module and switches to it. */ + const clone = async () => { + setBusy(true); + setError(''); + try { + const created = await api.createFunction({ + name: copyName(draft.name.trim() || saved.name, existingNames), + description: draft.description, + content: draft.content + }); + await mutate(keys.functions); + onSelect(created.id); + enqueueSnackbar('Cloned — you are editing the copy.', { variant: 'success' }); + } catch (e) { + setError(errorMessage(e, 'Clone failed.')); + } finally { + setBusy(false); + } + }; + + const remove = async () => { + await api.deleteFunction(module!.id); + await mutate(keys.functions); + onSelect(null); + enqueueSnackbar(`Deleted ${module!.name}`, { variant: 'success' }); + }; + + return ( + + + {module ? saved.name : 'New Function'} + + {module && dirty && } + + } + subheader={ + module && ( + <> + Updated + {module.updatedBy ? ` by ${module.updatedBy}` : ''} + + ) + } + secondary={ + + {module && ( + } + onClick={() => setConfirmDelete(true)} + disabled={busy} + > + Delete + + )} + {module && ( + } onClick={clone} disabled={busy}> + Clone + + )} + } + onClick={save} + disabled={busy || (Boolean(module) && !dirty)} + > + {busy ? 'Saving…' : 'Save'} + + + } + > + + {error && {error}} + + + update({ name: e.target.value })} + disabled={Boolean(gate)} + autoFocus={!module} + /> + + + update({ description: e.target.value })} + disabled={Boolean(gate)} + /> + + + update({ content })} + language="powershell" + readOnly={Boolean(gate)} + original={module ? saved.content : undefined} + height="max(420px, calc(100vh - 420px))" + /> + + + {module && ( + setConfirmDelete(false)} + /> + )} + + ); +} diff --git a/src/WebUI/src/sections/groups/GroupEditor.tsx b/src/WebUI/src/sections/groups/GroupEditor.tsx new file mode 100644 index 0000000..324d1f6 --- /dev/null +++ b/src/WebUI/src/sections/groups/GroupEditor.tsx @@ -0,0 +1,306 @@ +import { useEffect, useMemo, useRef, useState } from 'react'; + +// material-ui +import Alert from '@mui/material/Alert'; +import Autocomplete from '@mui/material/Autocomplete'; +import Button from '@mui/material/Button'; +import Chip from '@mui/material/Chip'; +import Divider from '@mui/material/Divider'; +import Stack from '@mui/material/Stack'; +import TextField from '@mui/material/TextField'; +import ToggleButton from '@mui/material/ToggleButton'; +import ToggleButtonGroup from '@mui/material/ToggleButtonGroup'; +import Typography from '@mui/material/Typography'; + +// third-party +import { enqueueSnackbar } from 'notistack'; +import { mutate } from 'swr'; + +// project imports +import RuleBuilder from './RuleBuilder'; +import HoverHelp from 'components/HoverHelp'; +import Sheet from 'components/Sheet'; +import { DeviceStatusChip } from 'components/StatusChip'; +import useApi from 'hooks/useApi'; +import { api, errorMessage, keys } from 'api/client'; +import { buildGroupTree, canNestUnder, flattenTree, groupPath } from 'utils/groupTree'; +import { plural } from 'utils/format'; +import type { DeviceDto, DeviceGroupDto, GroupFieldDescriptor, GroupKind, GroupRuleSet } from 'api/types'; + +export interface GroupPreset { + parentId?: string | null; + kind?: GroupKind; + /** Devices to list in a new static group ("New Group from Selection"). */ + memberIds?: string[]; +} + +interface Props { + open: boolean; + onClose: () => void; + /** Edit this group; otherwise create one from the preset. */ + group?: DeviceGroupDto | null; + preset?: GroupPreset; + onSaved?: (group: DeviceGroupDto) => void; +} + +const KIND_HELP: Record = { + dynamic: 'Members are the devices matching the rules, re-evaluated as inventory, tags and status change.', + static: 'Members are the devices you list.', + folder: 'Holds no devices of its own; organizes groups nested under it.' +}; + +const EMPTY_RULES: GroupRuleSet = { combine: 'and', groups: [] }; + +/** Live rule preview: how many devices match, and a few of them (debounced). */ +function useRulePreview(rules: GroupRuleSet, active: boolean) { + const [state, setState] = useState<{ devices: DeviceDto[] | null; error?: string }>({ devices: null }); + const key = JSON.stringify(rules); + + useEffect(() => { + if (!active) return; + let cancelled = false; + const timer = window.setTimeout(() => { + api + .previewGroup(JSON.parse(key) as GroupRuleSet) + .then((devices) => !cancelled && setState({ devices })) + .catch((e) => !cancelled && setState({ devices: null, error: errorMessage(e) })); + }, 400); + return () => { + cancelled = true; + window.clearTimeout(timer); + }; + }, [key, active]); + + return state; +} + +// ==============================|| GROUP EDITOR ||============================== // + +export default function GroupEditor({ open, onClose, group, preset, onSaved }: Props) { + const { data: groups } = useApi(open ? keys.groups : null); + const { data: devices } = useApi(open ? keys.devices : null); + const { data: fields } = useApi(open ? keys.groupFields : null); + + const [name, setName] = useState(''); + const [description, setDescription] = useState(''); + const [parentId, setParentId] = useState(null); + const [kind, setKind] = useState('dynamic'); + const [rules, setRules] = useState(EMPTY_RULES); + const [members, setMembers] = useState([]); + const [initialMembers, setInitialMembers] = useState([]); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(''); + // Static members are seeded from the device list once per opening; later + // refreshes of that list (live presence, focus) must not wipe edits. + const membersSeeded = useRef(false); + // A group created by an earlier Save attempt whose member update failed: + // retrying updates it instead of creating a second one. + const [createdId, setCreatedId] = useState(null); + + // Seed once per opening; the device list only seeds static members. + useEffect(() => { + if (!open) return; + membersSeeded.current = false; + setCreatedId(null); + setError(''); + setName(group?.name ?? ''); + setDescription(group?.description ?? ''); + setParentId(group ? (group.parentId ?? null) : (preset?.parentId ?? null)); + setKind(group?.kind ?? preset?.kind ?? (preset?.memberIds ? 'static' : 'dynamic')); + setRules(group?.rules ?? EMPTY_RULES); + setMembers(preset?.memberIds ?? []); + setInitialMembers([]); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [open, group]); + + useEffect(() => { + if (!open || !group || group.kind !== 'static' || !devices || membersSeeded.current) return; + membersSeeded.current = true; + const current = devices.filter((d) => d.groupIds?.includes(group.id)).map((d) => d.clientId); + setMembers(current); + setInitialMembers(current); + }, [open, group, devices]); + + const preview = useRulePreview(rules, open && kind === 'dynamic'); + + const parentOptions = useMemo( + () => flattenTree(buildGroupTree(groups ?? [])).filter(({ group: g }) => !group || canNestUnder(groups ?? [], group.id, g.id)), + [groups, group] + ); + + const droppingMembers = group?.kind === 'static' && kind !== 'static' && initialMembers.length > 0; + const deviceById = useMemo(() => new Map((devices ?? []).map((d) => [d.clientId, d])), [devices]); + + const save = async () => { + if (!name.trim()) return setError('Give the group a name.'); + setBusy(true); + setError(''); + try { + const body = { + name: name.trim(), + description: description.trim() || undefined, + kind, + parentId, + rules: kind === 'dynamic' ? rules : undefined + }; + const existingId = group?.id ?? createdId; + const saved = existingId ? await api.updateGroup(existingId, body) : await api.createGroup(body); + if (!existingId) setCreatedId(saved.id); + if (kind === 'static') { + const add = members.filter((m) => !initialMembers.includes(m)); + const remove = group?.kind === 'static' ? initialMembers.filter((m) => !members.includes(m)) : []; + if (add.length > 0 || remove.length > 0) await api.updateGroupMembers(saved.id, add, remove); + } + await Promise.all([mutate(keys.groups), mutate(keys.devices)]); + enqueueSnackbar(group ? `Saved “${saved.name}”.` : `Created “${saved.name}”.`, { variant: 'success' }); + onSaved?.(saved); + onClose(); + } catch (e) { + setError(errorMessage(e, 'The group could not be saved.')); + } finally { + setBusy(false); + } + }; + + return ( + undefined : onClose} + title={group ? `Edit “${group.name}”` : 'New Group'} + subtitle={ + <> + Targets for runs, schedules and role scopes. + + + } + actions={ + <> + + + + } + > + + setName(e.target.value)} autoFocus required /> + setDescription(e.target.value)} multiline minRows={2} /> + + o.group.id === parentId) ?? null} + onChange={(_, chosen) => setParentId(chosen?.group.id ?? null)} + getOptionLabel={(o) => groupPath(groups ?? [], o.group.id)} + isOptionEqualToValue={(a, b) => a.group.id === b.group.id} + renderOption={({ key, ...props }, o) => ( +
  • + {o.group.name} +
  • + )} + renderInput={(params) => } + /> + + + + Kind + + + value && setKind(value)}> + Dynamic (Rules) + Static (Listed) + Folder + + {droppingMembers && ( + + Saving as {kind === 'folder' ? 'a folder' : 'a dynamic group'} drops the {plural(initialMembers.length, 'listed device')}. + + )} + + + + + {kind === 'dynamic' && ( + + Rules + + + {preview.error ? ( + + {preview.error} + + ) : preview.devices === null ? ( + + Checking matches… + + ) : ( + <> + Matches {plural(preview.devices.length, 'device')} now + {preview.devices.length > 0 && ( + + {preview.devices.slice(0, 12).map((d) => ( + + ))} + {preview.devices.length > 12 && } + + )} + + )} + + + )} + + {kind === 'static' && ( + + Devices + d.clientId)} + value={members} + onChange={(_, chosen) => setMembers(chosen)} + getOptionLabel={(id) => deviceById.get(id)?.hostname ?? id} + filterOptions={(options, state) => { + const query = state.inputValue.trim().toLowerCase(); + return query + ? options.filter((id) => { + const d = deviceById.get(id); + return [d?.hostname, id, ...(d?.ipAddresses ?? [])].some((v) => v?.toLowerCase().includes(query)); + }) + : options; + }} + renderOption={({ key, ...props }, id) => { + const d = deviceById.get(id); + return ( +
  • + + + {d?.hostname ?? id} + + {d && } + +
  • + ); + }} + renderInput={(params) => } + /> + + {plural(members.length, 'device')} listed. + + +
    + )} + + {kind === 'folder' && ( + + Add groups to it after saving. + + + )} + + {error && {error}} +
    +
    + ); +} diff --git a/src/WebUI/src/sections/groups/GroupTreePanel.tsx b/src/WebUI/src/sections/groups/GroupTreePanel.tsx new file mode 100644 index 0000000..85553c6 --- /dev/null +++ b/src/WebUI/src/sections/groups/GroupTreePanel.tsx @@ -0,0 +1,220 @@ +import { useEffect, useMemo, useState } from 'react'; + +// material-ui +import Box from '@mui/material/Box'; +import Skeleton from '@mui/material/Skeleton'; +import Stack from '@mui/material/Stack'; +import Tooltip from '@mui/material/Tooltip'; + +// project imports +import ActionMenu, { MenuEntry } from 'components/ActionMenu'; +import IconButton from 'components/@extended/IconButton'; +import MainCard from 'components/MainCard'; +import TreeList, { TreeMenuAnchor, TreeNode } from 'components/TreeList'; +import { buildGroupTree, devicesInGroup, GroupNode, ungroupedDevices } from 'utils/groupTree'; +import type { DeviceDto, DeviceGroupDto } from 'api/types'; + +// assets +import ApartmentOutlined from '@ant-design/icons/ApartmentOutlined'; +import ClusterOutlined from '@ant-design/icons/ClusterOutlined'; +import DisconnectOutlined from '@ant-design/icons/DisconnectOutlined'; +import FilterOutlined from '@ant-design/icons/FilterOutlined'; +import FolderOutlined from '@ant-design/icons/FolderOutlined'; +import NodeCollapseOutlined from '@ant-design/icons/NodeCollapseOutlined'; +import NodeExpandOutlined from '@ant-design/icons/NodeExpandOutlined'; +import PlusOutlined from '@ant-design/icons/PlusOutlined'; + +/** Tree selection: a group id, or one of the two virtual nodes. */ +export const ALL_NODE = 'all'; +export const UNGROUPED_NODE = 'ungrouped'; + +const EXPANDED_KEY = 'executer-group-tree-expanded'; + +const KIND_ICON = { folder: FolderOutlined, dynamic: FilterOutlined, static: ApartmentOutlined } as const; + +function loadExpanded(): Set { + try { + const saved = window.localStorage.getItem(EXPANDED_KEY); + return new Set(saved ? (JSON.parse(saved) as string[]) : [ALL_NODE]); + } catch { + return new Set([ALL_NODE]); + } +} + +interface Props { + groups: DeviceGroupDto[] | undefined; + devices: DeviceDto[] | undefined; + selectedId: string; + onSelect: (id: string) => void; + /** Context menu entries for a group node. */ + menuFor?: (group: DeviceGroupDto) => MenuEntry[]; + /** Drag and drop re-parenting (parentId null = top level). */ + canMove?: (groupId: string, parentId: string | null) => boolean; + onMove?: (groupId: string, parentId: string | null) => void; + /** "New Group" in the header; undefined hides it, a string disables it with that reason. */ + onNewGroup?: () => void; + newGroupGate?: string; + showUngrouped?: boolean; + /** Groups can be dragged onto other groups (the caller checks Manage Groups). */ + draggable?: boolean; +} + +// ==============================|| GROUP TREE PANEL ||============================== // + +export default function GroupTreePanel({ + groups, + devices, + selectedId, + onSelect, + menuFor, + canMove, + onMove, + onNewGroup, + newGroupGate, + showUngrouped = true, + draggable = false +}: Props) { + const [expanded, setExpanded] = useState>(loadExpanded); + const [menu, setMenu] = useState<{ group: DeviceGroupDto; anchor: TreeMenuAnchor } | null>(null); + + useEffect(() => { + try { + window.localStorage.setItem(EXPANDED_KEY, JSON.stringify([...expanded])); + } catch { + // Storage unavailable: expansion lasts for the tab. + } + }, [expanded]); + + // Reveal the selected group and what is in it: expand it and every ancestor. + useEffect(() => { + if (!groups || selectedId === ALL_NODE || selectedId === UNGROUPED_NODE) return; + const byId = new Map(groups.map((g) => [g.id, g])); + const toOpen: string[] = [ALL_NODE, selectedId]; + for ( + let cursor = byId.get(selectedId)?.parentId; + cursor && byId.has(cursor) && !toOpen.includes(cursor); + cursor = byId.get(cursor)?.parentId + ) { + toOpen.push(cursor); + } + setExpanded((current) => (toOpen.every((id) => current.has(id)) ? current : new Set([...current, ...toOpen]))); + }, [groups, selectedId]); + + const nodes = useMemo(() => { + if (!groups || !devices) return []; + const toNode = ({ group, children }: GroupNode): TreeNode => { + const members = devicesInGroup(devices, groups, group.id); + const online = members.filter((d) => d.status === 'online').length; + const Icon = KIND_ICON[group.kind]; + return { + id: group.id, + label: group.name, + icon: , + secondary: ( + + {members.length} + + ), + children: children.map(toNode) + }; + }; + const root: TreeNode = { + id: ALL_NODE, + label: 'All Devices', + icon: , + secondary: devices.length, + children: buildGroupTree(groups).map(toNode) + }; + const ungrouped = ungroupedDevices(devices).length; + return showUngrouped && groups.length > 0 + ? [root, { id: UNGROUPED_NODE, label: 'Ungrouped', icon: , secondary: ungrouped }] + : [root]; + }, [groups, devices, showUngrouped]); + + const groupById = useMemo(() => new Map((groups ?? []).map((g) => [g.id, g])), [groups]); + const virtual = (id: string) => id === ALL_NODE || id === UNGROUPED_NODE; + + const toggleAll = (open: boolean) => setExpanded(open ? new Set([ALL_NODE, ...(groups ?? []).map((g) => g.id)]) : new Set([ALL_NODE])); + + return ( + + + toggleAll(true)} aria-label="Expand all groups"> + + + + + toggleAll(false)} aria-label="Collapse all groups"> + + + + {onNewGroup && ( + + + + + + + + )} + + } + > + + {!groups || !devices ? ( + + {Array.from({ length: 5 }, (_, i) => ( + + ))} + + ) : ( + onSelect(node.id)} + expanded={expanded} + onToggle={(id, open) => + setExpanded((current) => { + const next = new Set(current); + if (open) next.add(id); + else next.delete(id); + return next; + }) + } + onContextMenu={ + menuFor + ? (node, anchor) => { + const group = groupById.get(node.id); + if (group) setMenu({ group, anchor }); + } + : undefined + } + drag={ + canMove && onMove + ? { + canDrag: (node) => draggable && !virtual(node.id), + canDrop: (draggedId, target) => + target.id !== UNGROUPED_NODE && canMove(draggedId, target.id === ALL_NODE ? null : target.id), + onDrop: (draggedId, target) => onMove(draggedId, target.id === ALL_NODE ? null : target.id) + } + : undefined + } + /> + )} + + {menu && menuFor && setMenu(null)} entries={menuFor(menu.group)} />} + + ); +} diff --git a/src/WebUI/src/sections/groups/RuleBuilder.tsx b/src/WebUI/src/sections/groups/RuleBuilder.tsx new file mode 100644 index 0000000..0063a89 --- /dev/null +++ b/src/WebUI/src/sections/groups/RuleBuilder.tsx @@ -0,0 +1,284 @@ +// material-ui +import Box from '@mui/material/Box'; +import Button from '@mui/material/Button'; +import Checkbox from '@mui/material/Checkbox'; +import Chip from '@mui/material/Chip'; +import FormControlLabel from '@mui/material/FormControlLabel'; +import ListSubheader from '@mui/material/ListSubheader'; +import MenuItem from '@mui/material/MenuItem'; +import Stack from '@mui/material/Stack'; +import TextField from '@mui/material/TextField'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; + +// project imports +import IconButton from 'components/@extended/IconButton'; +import HoverHelp from 'components/HoverHelp'; +import type { GroupFieldDescriptor, GroupRuleSet, RuleCondition, RuleGroup, RuleOperator } from 'api/types'; + +// assets +import CloseOutlined from '@ant-design/icons/CloseOutlined'; +import PlusOutlined from '@ant-design/icons/PlusOutlined'; + +interface OperatorInfo { + value: RuleOperator; + label: string; + needsValue: boolean; + /** Which fields offer it. */ + applies: 'any' | 'text' | 'numeric' | 'address'; +} + +const OPERATORS: OperatorInfo[] = [ + { value: 'equals', label: 'equals', needsValue: true, applies: 'any' }, + { value: 'notEquals', label: 'does not equal', needsValue: true, applies: 'any' }, + { value: 'contains', label: 'contains', needsValue: true, applies: 'text' }, + { value: 'notContains', label: 'does not contain', needsValue: true, applies: 'text' }, + { value: 'startsWith', label: 'starts with', needsValue: true, applies: 'text' }, + { value: 'endsWith', label: 'ends with', needsValue: true, applies: 'text' }, + { value: 'regex', label: 'matches regex', needsValue: true, applies: 'text' }, + { value: 'in', label: 'is one of', needsValue: true, applies: 'any' }, + { value: 'notIn', label: 'is none of', needsValue: true, applies: 'any' }, + { value: 'greaterThan', label: '>', needsValue: true, applies: 'numeric' }, + { value: 'greaterOrEqual', label: '≥', needsValue: true, applies: 'numeric' }, + { value: 'lessThan', label: '<', needsValue: true, applies: 'numeric' }, + { value: 'lessOrEqual', label: '≤', needsValue: true, applies: 'numeric' }, + { value: 'exists', label: 'has a value', needsValue: false, applies: 'any' }, + { value: 'notExists', label: 'has no value', needsValue: false, applies: 'any' }, + { value: 'inCidr', label: 'is in CIDR range', needsValue: true, applies: 'address' }, + { value: 'notInCidr', label: 'is not in CIDR range', needsValue: true, applies: 'address' } +]; + +const isAddressField = (field?: GroupFieldDescriptor) => Boolean(field && /ipv4|ipaddress|address/i.test(field.field)); + +function operatorsFor(field?: GroupFieldDescriptor): OperatorInfo[] { + return OPERATORS.filter( + (op) => + op.applies === 'any' || + (op.applies === 'numeric' && field?.numeric) || + (op.applies === 'text' && !field?.numeric) || + (op.applies === 'address' && isAddressField(field)) + ); +} + +const needsValue = (op: RuleOperator) => OPERATORS.find((o) => o.value === op)?.needsValue ?? true; + +const newCondition = (): RuleCondition => ({ field: 'hostname', operator: 'contains', value: '' }); + +interface Props { + rules: GroupRuleSet; + fields: GroupFieldDescriptor[]; + onChange: (rules: GroupRuleSet) => void; + disabled?: boolean; +} + +// ==============================|| DYNAMIC GROUP RULE BUILDER ||============================== // + +export default function RuleBuilder({ rules, fields, onChange, disabled }: Props) { + const groups = rules.groups ?? []; + const categories = [...new Set(fields.map((f) => f.category))]; + const fieldFor = (name: string) => fields.find((f) => f.field === name); + + const setGroups = (next: RuleGroup[]) => onChange({ ...rules, groups: next }); + const updateGroup = (index: number, patch: Partial) => setGroups(groups.map((g, i) => (i === index ? { ...g, ...patch } : g))); + const updateCondition = (gi: number, ci: number, patch: Partial) => + updateGroup(gi, { conditions: (groups[gi].conditions ?? []).map((c, i) => (i === ci ? { ...c, ...patch } : c)) }); + + const placeholder = (condition: RuleCondition) => { + if (condition.operator === 'in' || condition.operator === 'notIn') return 'a, b, c'; + if (condition.operator === 'regex') return '^PC-\\d+$'; + if (condition.operator === 'inCidr' || condition.operator === 'notInCidr') return '10.0.0.0/8, 192.168.1.0/24'; + return fieldFor(condition.field)?.numeric ? 'Number' : 'Value'; + }; + + return ( + + + + A device matches when + + onChange({ ...rules, combine: e.target.value as GroupRuleSet['combine'] })} + disabled={disabled} + sx={{ minWidth: 180 }} + > + every block matches + any block matches + + + + + + {groups.length === 0 && ( + + No rules; matches no devices. + + )} + + {groups.map((group, gi) => ( + + + + updateGroup(gi, { combine: e.target.value as RuleGroup['combine'] })} + disabled={disabled} + sx={{ minWidth: 200 }} + > + All conditions match + Any condition matches + + + updateGroup(gi, { negate: e.target.checked })} /> + } + label="Not" + disabled={disabled} + /> + + + + setGroups(groups.filter((_, i) => i !== gi))} + > + + + + + + {(group.conditions ?? []).map((condition, ci) => { + const field = fieldFor(condition.field); + const operators = operatorsFor(field); + return ( + + { + const nextField = fieldFor(e.target.value); + // Keep the operator only if the new field still offers it. + const keep = operatorsFor(nextField).some((o) => o.value === condition.operator); + updateCondition(gi, ci, { field: e.target.value, operator: keep ? condition.operator : 'equals' }); + }} + sx={{ minWidth: 220 }} + > + {categories.flatMap((category) => [ + {category}, + ...fields + .filter((f) => f.category === category) + .map((f) => ( + + {f.displayName} + + )) + ])} + + o.value === condition.operator) ? condition.operator : ''} + onChange={(e) => updateCondition(gi, ci, { operator: e.target.value as RuleOperator })} + disabled={disabled} + sx={{ minWidth: 170 }} + > + {operators.map((op) => ( + + {op.label} + + ))} + + {needsValue(condition.operator) ? ( + + Value + + + ) : ( + 'Value' + ) + } + value={condition.value ?? ''} + placeholder={placeholder(condition)} + onChange={(e) => updateCondition(gi, ci, { value: e.target.value })} + disabled={disabled} + sx={{ flex: 1, minWidth: 160 }} + /> + ) : ( + + )} + + updateCondition(gi, ci, { negate: e.target.checked })} + /> + } + label="Not" + disabled={disabled} + /> + + updateGroup(gi, { conditions: (group.conditions ?? []).filter((_, i) => i !== ci) })} + > + + + + ); + })} + {(group.conditions ?? []).length === 0 && ( + + No conditions; this block matches nothing. + + )} + + + ))} + + ); +} diff --git a/src/WebUI/src/sections/groups/useGroupActions.tsx b/src/WebUI/src/sections/groups/useGroupActions.tsx new file mode 100644 index 0000000..e4ce945 --- /dev/null +++ b/src/WebUI/src/sections/groups/useGroupActions.tsx @@ -0,0 +1,279 @@ +import { ReactNode, useCallback, useState } from 'react'; +import { useNavigate } from 'react-router-dom'; + +// material-ui +import Typography from '@mui/material/Typography'; + +// third-party +import { enqueueSnackbar } from 'notistack'; +import { mutate } from 'swr'; + +// project imports +import GroupEditor, { GroupPreset } from './GroupEditor'; +import ConfirmDialog from 'components/ConfirmDialog'; +import { MenuEntry } from 'components/ActionMenu'; +import useAgentUpgrades from 'sections/upgrades/useAgentUpgrades'; +import useApi from 'hooks/useApi'; +import useAutomation from 'hooks/useAutomation'; +import useSession from 'hooks/useSession'; +import { api, errorMessage, keys } from 'api/client'; +import { plural } from 'utils/format'; +import { groupPath, subtreeIds } from 'utils/groupTree'; +import type { DeviceDto, DeviceGroupDto, ScriptTriggerDto } from 'api/types'; + +// assets +import CalendarOutlined from '@ant-design/icons/CalendarOutlined'; +import CloudSyncOutlined from '@ant-design/icons/CloudSyncOutlined'; +import CopyOutlined from '@ant-design/icons/CopyOutlined'; +import DeleteOutlined from '@ant-design/icons/DeleteOutlined'; +import DesktopOutlined from '@ant-design/icons/DesktopOutlined'; +import EditOutlined from '@ant-design/icons/EditOutlined'; +import PlayCircleOutlined from '@ant-design/icons/PlayCircleOutlined'; +import PlusOutlined from '@ant-design/icons/PlusOutlined'; +import RollbackOutlined from '@ant-design/icons/RollbackOutlined'; +import VerticalAlignTopOutlined from '@ant-design/icons/VerticalAlignTopOutlined'; + +const NEEDS = (label: string) => `Needs the ${label} permission.`; + +/** Menu entries for one group, as data (the tree's context menu and the group panel share it). */ +export function groupMenu( + group: DeviceGroupDto, + can: (permission: string) => boolean, + handlers: { + run: () => void; + schedule: () => void; + newChild: () => void; + edit: () => void; + duplicate: () => void; + toTop: () => void; + viewDevices: () => void; + upgradeAgents: () => void; + rollBackAgents: () => void; + remove: () => void; + } +): MenuEntry[] { + const manage = can('groups.manage') ? undefined : NEEDS('Manage Groups'); + const empty = group.memberCount === 0 ? 'No devices in this group yet.' : undefined; + const manageDevices = can('devices.manage') ? empty : NEEDS('Manage Devices'); + return [ + { kind: 'header', label: group.name }, + { + kind: 'item', + id: 'run', + label: 'Run Script…', + icon: , + disabledReason: can('jobs.run') ? empty : NEEDS('Run Jobs'), + onSelect: handlers.run + }, + { + kind: 'item', + id: 'schedule', + label: 'Schedule Script…', + icon: , + disabledReason: can('automation.manage') ? undefined : NEEDS('Manage Automation'), + onSelect: handlers.schedule + }, + { kind: 'item', id: 'devices', label: 'View Devices', icon: , onSelect: handlers.viewDevices }, + { kind: 'divider' }, + { + kind: 'item', + id: 'upgrade-agents', + label: 'Upgrade Agents…', + icon: , + disabledReason: manageDevices, + onSelect: handlers.upgradeAgents + }, + { + kind: 'item', + id: 'roll-back-agents', + label: 'Roll Back Agents…', + icon: , + disabledReason: manageDevices, + onSelect: handlers.rollBackAgents + }, + { kind: 'divider' }, + { kind: 'item', id: 'new', label: 'New Group Here…', icon: , disabledReason: manage, onSelect: handlers.newChild }, + { kind: 'item', id: 'edit', label: 'Edit…', icon: , disabledReason: manage, onSelect: handlers.edit }, + { kind: 'item', id: 'duplicate', label: 'Duplicate', icon: , disabledReason: manage, onSelect: handlers.duplicate }, + ...(group.parentId + ? [ + { + kind: 'item' as const, + id: 'top', + label: 'Move to Top Level', + icon: , + disabledReason: manage, + onSelect: handlers.toTop + } + ] + : []), + { kind: 'divider' }, + { + kind: 'item', + id: 'delete', + label: 'Delete…', + icon: , + destructive: true, + disabledReason: manage, + onSelect: handlers.remove + } + ]; +} + +const copyName = (base: string, existing: string[]) => { + let candidate = `${base} (Copy)`; + for (let i = 2; existing.includes(candidate); i++) candidate = `${base} (Copy ${i})`; + return candidate; +}; + +// ==============================|| GROUP ACTIONS (MENU + DIALOGS) ||============================== // + +/** + * Group actions with their dialogs. Render `elements` once; call `menuFor` + * for a context menu, `openEditor` for New/Edit, `requestMove` for drops. + */ +export default function useGroupActions( + options: { onDeleted?: (group: DeviceGroupDto) => void; onSaved?: (group: DeviceGroupDto) => void } = {} +) { + const navigate = useNavigate(); + const { can } = useSession(); + const { openRun, openSchedule } = useAutomation(); + const { data: groups } = useApi(keys.groups); + const { data: devices } = useApi(keys.devices); + const { data: triggers } = useApi(can('automation.view') ? keys.triggers : null); + + const [editor, setEditor] = useState<{ group?: DeviceGroupDto; preset?: GroupPreset } | null>(null); + const [deleting, setDeleting] = useState(null); + const [moving, setMoving] = useState<{ group: DeviceGroupDto; parent: DeviceGroupDto | null } | null>(null); + + const upgrades = useAgentUpgrades(); + + const refresh = () => Promise.all([mutate(keys.groups), mutate(keys.devices)]); + + const openEditor = useCallback((request: { group?: DeviceGroupDto; preset?: GroupPreset } = {}) => setEditor(request), []); + + const requestMove = useCallback( + (groupId: string, parentId: string | null) => { + const group = groups?.find((g) => g.id === groupId); + if (!group) return; + setMoving({ group, parent: parentId ? (groups?.find((g) => g.id === parentId) ?? null) : null }); + }, + [groups] + ); + + const duplicate = async (group: DeviceGroupDto) => { + try { + const created = await api.createGroup({ + name: copyName( + group.name, + (groups ?? []).map((g) => g.name) + ), + description: group.description, + kind: group.kind, + rules: group.kind === 'dynamic' ? group.rules : undefined, + parentId: group.parentId ?? null + }); + if (group.kind === 'static') { + // Only the group's own list: nested groups' devices are not copied in. + const direct = (devices ?? []).filter((d) => d.groupIds?.includes(group.id)).map((d) => d.clientId); + if (direct.length > 0) await api.updateGroupMembers(created.id, direct, []); + } + await refresh(); + enqueueSnackbar(`Created “${created.name}”.`, { variant: 'success' }); + setEditor({ group: created }); + } catch (e) { + enqueueSnackbar(errorMessage(e, 'The group could not be duplicated.'), { variant: 'error' }); + } + }; + + const menuFor = (group: DeviceGroupDto): MenuEntry[] => + groupMenu(group, can, { + run: () => openRun({ targets: [{ kind: 'group', id: group.id }] }), + schedule: () => openSchedule({ preset: { target: { kind: 'group', id: group.id } } }), + newChild: () => openEditor({ preset: { parentId: group.id } }), + edit: () => openEditor({ group }), + duplicate: () => void duplicate(group), + toTop: () => requestMove(group.id, null), + viewDevices: () => navigate(`/devices?group=${group.id}`), + upgradeAgents: () => upgrades.upgrade({ groupIds: [group.id], name: { group: groupPath(groups ?? [], group.id) } }), + rollBackAgents: () => upgrades.rollBack({ groupIds: [group.id], name: { group: groupPath(groups ?? [], group.id) } }), + remove: () => setDeleting(group) + }); + + const deletingDetail = (group: DeviceGroupDto): ReactNode => { + const children = (groups ?? []).filter((g) => g.parentId === group.id); + const schedules = (triggers ?? []).filter((t) => t.groupId === group.id); + const parent = group.parentId ? (groups ?? []).find((g) => g.id === group.parentId) : undefined; + return ( + <> + + Devices are not affected; only the group goes. + + {children.length > 0 && ( + + {plural(children.length, 'nested group')} move up to {parent ? `“${parent.name}”` : 'the top level'}. + + )} + {schedules.length > 0 && ( + + {plural(schedules.length, 'schedule')} targeting it will be disabled. + + )} + + ); + }; + + const elements = ( + <> + {upgrades.elements} + setEditor(null)} + group={editor?.group ?? null} + preset={editor?.preset} + onSaved={options.onSaved} + /> + setDeleting(null)} + onConfirm={async () => { + await api.deleteGroup(deleting!.id); + await Promise.all([refresh(), mutate(keys.triggers)]); + enqueueSnackbar(`Deleted “${deleting!.name}”.`, { variant: 'success' }); + options.onDeleted?.(deleting!); + }} + > + {deleting && deletingDetail(deleting)} + + setMoving(null)} + message={ + moving && + (moving.parent + ? `Move “${moving.group.name}” into “${groupPath(groups ?? [], moving.parent.id)}”? Runs, schedules and role scopes on “${moving.parent.name}” will then include its devices.` + : `Move “${moving.group.name}” to the top level?`) + } + onConfirm={async () => { + await api.moveGroup(moving!.group.id, moving!.parent?.id ?? null); + await refresh(); + }} + /> + + ); + + /** True when `groupId` may be dropped onto `parentId` (null = top level). */ + const canMove = (groupId: string, parentId: string | null) => { + const group = groups?.find((g) => g.id === groupId); + if (!group || !can('groups.manage')) return false; + if ((group.parentId ?? null) === parentId) return false; + return parentId === null || !subtreeIds(groups ?? [], groupId).has(parentId); + }; + + return { menuFor, elements, openEditor, requestMove, canMove }; +} diff --git a/src/WebUI/src/sections/jobs/JobOutputDrawer.tsx b/src/WebUI/src/sections/jobs/JobOutputDrawer.tsx new file mode 100644 index 0000000..0a7dc5e --- /dev/null +++ b/src/WebUI/src/sections/jobs/JobOutputDrawer.tsx @@ -0,0 +1,470 @@ +import { ReactNode, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; +import { Link as RouterLink } from 'react-router-dom'; + +// material-ui +import Alert from '@mui/material/Alert'; +import Box from '@mui/material/Box'; +import Chip from '@mui/material/Chip'; +import Divider from '@mui/material/Divider'; +import Drawer from '@mui/material/Drawer'; +import Grid from '@mui/material/Grid'; +import InputAdornment from '@mui/material/InputAdornment'; +import LinearProgress from '@mui/material/LinearProgress'; +import Link from '@mui/material/Link'; +import Skeleton from '@mui/material/Skeleton'; +import Stack from '@mui/material/Stack'; +import TextField from '@mui/material/TextField'; +import MuiIconButton from '@mui/material/IconButton'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; + +// project imports +import IconButton from 'components/@extended/IconButton'; +import CopyButton from 'components/CopyButton'; +import { AbsoluteTime } from 'components/DateTime'; +import { JobStateChip, TERMINAL_JOB_STATES } from 'components/StatusChip'; +import { api, downloads, errorMessage } from 'api/client'; +import useApi from 'hooks/useApi'; +import { nats, useLiveState } from 'messaging/nats'; +import { formatAbsolute, formatDuration, plural } from 'utils/format'; + +// assets +import ClockCircleOutlined from '@ant-design/icons/ClockCircleOutlined'; +import CloseOutlined from '@ant-design/icons/CloseOutlined'; +import DownloadOutlined from '@ant-design/icons/DownloadOutlined'; +import SearchOutlined from '@ant-design/icons/SearchOutlined'; +import VerticalAlignBottomOutlined from '@ant-design/icons/VerticalAlignBottomOutlined'; + +// types +import type { JobDto, JobOutputRecordDto, JobProgressPayload, OutputStreamKind } from 'api/types'; + +interface Props { + /** The job to show; null closes the drawer. */ + jobId: string | null; + onClose: () => void; +} + +/** Polling fallback while a job runs: quick when live updates are down, a safety net when they are up. */ +const POLL_FAST_MS = 3_000; +const POLL_SLOW_MS = 10_000; + +const STREAMS: { kind: OutputStreamKind; label: string; color: string }[] = [ + { kind: 'output', label: 'Output', color: 'text.primary' }, + { kind: 'error', label: 'Error', color: 'error.main' }, + { kind: 'warning', label: 'Warning', color: 'warning.main' }, + { kind: 'information', label: 'Information', color: 'info.main' }, + { kind: 'verbose', label: 'Verbose', color: 'text.disabled' }, + { kind: 'debug', label: 'Debug', color: 'text.disabled' }, + { kind: 'progress', label: 'Progress', color: 'text.secondary' } +]; + +const STREAM_COLOR = Object.fromEntries(STREAMS.map((s) => [s.kind, s.color])) as Record; + +const jobPath = (jobId: string) => `/api/jobs/${jobId}`; + +/** Adds records by sequence, so stored, polled and live output can overlap freely. */ +function mergeRecords(current: JobOutputRecordDto[], incoming: JobOutputRecordDto[]): JobOutputRecordDto[] { + if (incoming.length === 0) return current; + const last = current.length > 0 ? current[current.length - 1].sequence : -Infinity; + if (incoming.every((r, i) => r.sequence > (i === 0 ? last : incoming[i - 1].sequence))) { + return [...current, ...incoming]; + } + const bySequence = new Map(current.map((r) => [r.sequence, r])); + for (const record of incoming) bySequence.set(record.sequence, record); + return [...bySequence.values()].sort((a, b) => a.sequence - b.sequence); +} + +/** + * The last sequence held with nothing missing before it (sequences start at + * 1). Polling resumes from here, so records lost from the live stream (a NATS + * reconnect) are fetched instead of being skipped over for good. + */ +function contiguousEnd(records: JobOutputRecordDto[]): number { + let cursor = 0; + for (const record of records) { + if (record.sequence <= cursor) continue; + if (record.sequence !== cursor + 1) break; + cursor = record.sequence; + } + return cursor; +} + +/** The server returns at most this many records per call. */ +const OUTPUT_PAGE = 10_000; + +/** Stored output in full, paging past the per-call cap. */ +async function loadAllOutput(jobId: string): Promise { + const all: JobOutputRecordDto[] = []; + let after: number | undefined; + for (;;) { + const page = await api.jobOutput(jobId, after); + all.push(...page); + if (page.length < OUTPUT_PAGE) return all; + after = page[page.length - 1].sequence; + } +} + +const timeOfDay = (value: string) => { + const date = new Date(value); + return Number.isNaN(date.getTime()) ? '' : date.toLocaleTimeString(undefined, { hour12: false }); +}; + +// ==============================|| JOB OUTPUT DRAWER ||============================== // + +/** Right-hand panel with a job's details and its stored plus live output. */ +export default function JobOutputDrawer({ jobId, onClose }: Props) { + // Keep showing the last job while the drawer slides closed. + const [shownId, setShownId] = useState(jobId); + if (jobId && jobId !== shownId) setShownId(jobId); + + return ( + + {shownId && } + + ); +} + +function JobOutputPanel({ jobId, onClose }: { jobId: string; onClose: () => void }) { + const liveState = useLiveState(); + const pollMs = liveState === 'connected' ? POLL_SLOW_MS : POLL_FAST_MS; + const { + data: job, + error: jobError, + mutate: mutateJob + } = useApi(jobPath(jobId), { + refreshInterval: (latest) => (latest && TERMINAL_JOB_STATES.includes(latest.state) ? 0 : pollMs) + }); + const running = job ? !TERMINAL_JOB_STATES.includes(job.state) : false; + + const [records, setRecords] = useState([]); + const [outputLoaded, setOutputLoaded] = useState(false); + const [outputError, setOutputError] = useState(''); + const [progress, setProgress] = useState(null); + + const [search, setSearch] = useState(''); + const [streams, setStreams] = useState>(new Set()); + const [showTimes, setShowTimes] = useState(false); + const [follow, setFollow] = useState(true); + + const lastSequence = useRef(null); + useEffect(() => { + lastSequence.current = contiguousEnd(records); + }, [records]); + + /** Fetches everything after the last gap-free record we hold (the polling fallback). */ + const fetchNewOutput = useCallback(async () => { + try { + const more = await api.jobOutput(jobId, lastSequence.current || undefined); + setRecords((current) => mergeRecords(current, more)); + setOutputError(''); + } catch (e) { + setOutputError(errorMessage(e, 'Could not load the output.')); + } + }, [jobId]); + + // Stored output, in full. + useEffect(() => { + let cancelled = false; + loadAllOutput(jobId) + .then((stored) => { + if (!cancelled) setRecords((current) => mergeRecords(current, stored)); + }) + .catch((e) => { + if (!cancelled) setOutputError(errorMessage(e, 'Could not load the output.')); + }) + .finally(() => { + if (!cancelled) setOutputLoaded(true); + }); + return () => { + cancelled = true; + }; + }, [jobId]); + + // Live output, progress and state changes. + useEffect( + () => + nats.onJobEvent((id, event) => { + if (id !== jobId) return; + if (event.type === 'job.output') { + const { sequence, stream, timestampUtc, text } = event.payload; + setRecords((current) => mergeRecords(current, [{ sequence, stream, timestampUtc, text }])); + } else if (event.type === 'job.progress') { + setProgress(event.payload); + } else { + const { state, exitCode } = event.payload; + void mutateJob((current) => current && { ...current, state, exitCode: exitCode ?? current.exitCode }); + if (TERMINAL_JOB_STATES.includes(state)) setProgress(null); + } + }), + [jobId, mutateJob] + ); + + // Poll while running; once it finishes, one last fetch picks up the tail. + const wasRunning = useRef(false); + useEffect(() => { + if (running) { + wasRunning.current = true; + const timer = window.setInterval(() => void fetchNewOutput(), pollMs); + return () => window.clearInterval(timer); + } + if (wasRunning.current) { + wasRunning.current = false; + setProgress(null); + void fetchNewOutput(); + } + return undefined; + }, [running, pollMs, fetchNewOutput]); + + const counts = useMemo(() => { + const result = new Map(); + for (const record of records) result.set(record.stream, (result.get(record.stream) ?? 0) + 1); + return result; + }, [records]); + + const visible = useMemo(() => { + const needle = search.trim().toLowerCase(); + return records.filter((r) => (streams.size === 0 || streams.has(r.stream)) && (!needle || r.text.toLowerCase().includes(needle))); + }, [records, streams, search]); + + const filtered = visible.length !== records.length; + const visibleText = useMemo(() => visible.map((r) => r.text).join('\n'), [visible]); + + // Auto-scroll: stay pinned to the end until the reader scrolls up. + const outputRef = useRef(null); + useLayoutEffect(() => { + const el = outputRef.current; + if (el && follow) el.scrollTop = el.scrollHeight; + }, [visible, follow, showTimes]); + + const onScroll = () => { + const el = outputRef.current; + if (!el) return; + const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 24; + if (atEnd !== follow) setFollow(atEnd); + }; + + const toggleStream = (kind: OutputStreamKind) => + setStreams((current) => { + const next = new Set(current); + if (next.has(kind)) next.delete(kind); + else next.add(kind); + return next; + }); + + return ( + <> + {/* header */} + + + + + {job?.scriptName ?? (jobError ? 'Job' : )} + + {job && } + + {job && ( + + {job.hostname ?? job.clientId} · Requested by {job.requestedBy ?? '—'} + + )} + + + + + + {running ? : } + + + {jobError && !job && {errorMessage(jobError, 'Could not load the job.')}} + + {job && ( + + + + {job.hostname ?? job.clientId} + + + + + {job.scriptName} + + + + + {job.exitCode ?? '—'} + + + + + + + + + {formatDuration(job.startedUtc, job.completedUtc)} + + + + {job.jobId} + + + + + {job.outputSummary && ( + + {job.outputSummary} + + )} + + )} + + {progress && ( + + + {progress.activity} + {progress.statusDescription ? ` — ${progress.statusDescription}` : ''} + {progress.percentComplete != null && progress.percentComplete >= 0 ? ` (${progress.percentComplete}%)` : ''} + + = 0 ? 'determinate' : 'indeterminate'} + value={Math.min(Math.max(progress.percentComplete ?? 0, 0), 100)} + sx={{ mt: 0.5 }} + /> + + )} + + {/* output toolbar */} + + setSearch(e.target.value)} + sx={{ width: { xs: '100%', sm: 220 } }} + slotProps={{ + input: { + startAdornment: ( + + + + ) + } + }} + /> + {STREAMS.filter((s) => counts.has(s.kind)).map((s) => ( + toggleStream(s.kind)} + /> + ))} + + + {filtered ? `${visible.length.toLocaleString()} of ${plural(records.length, 'line')}` : plural(records.length, 'line')} + + + setShowTimes((v) => !v)} + aria-label="Toggle Timestamps" + > + + + + + + + {/* The whole stored log from the server, not just the lines filtered in view. */} + + + + + + + setFollow(true)} aria-label="Follow Output"> + + + + + + {outputError && {outputError}} + + {/* output */} + + {!outputLoaded && records.length === 0 ? ( + + {Array.from({ length: 4 }, (_, i) => ( + + ))} + + ) : records.length === 0 ? ( + + {running ? 'Waiting for output…' : 'No output recorded.'} + + ) : visible.length === 0 ? ( + + No lines match the filter. + + ) : ( + visible.map((record) => ( + + {showTimes && ( + + {timeOfDay(record.timestampUtc)} + + )} + {record.text} + + )) + )} + + + + ); +} + +function Meta({ label, wide, children }: { label: string; wide?: boolean; children: ReactNode }) { + return ( + + + {label} + + {children} + + ); +} diff --git a/src/WebUI/src/sections/runs/RecentRuns.tsx b/src/WebUI/src/sections/runs/RecentRuns.tsx new file mode 100644 index 0000000..aa3b05b --- /dev/null +++ b/src/WebUI/src/sections/runs/RecentRuns.tsx @@ -0,0 +1,187 @@ +import { MouseEvent, useCallback, useMemo, useState } from 'react'; +import { Link as RouterLink, useNavigate } from 'react-router-dom'; + +// material-ui +import Chip from '@mui/material/Chip'; +import InputAdornment from '@mui/material/InputAdornment'; +import Link from '@mui/material/Link'; +import MenuItem from '@mui/material/MenuItem'; +import Stack from '@mui/material/Stack'; +import TextField from '@mui/material/TextField'; +import Typography from '@mui/material/Typography'; + +// project imports +import DataTable, { Column } from 'components/DataTable'; +import { RelativeTime } from 'components/DateTime'; +import EmptyState from 'components/EmptyState'; +import { RUN_SOURCE_LABEL, RunProgressSummary, runFinished } from 'sections/runs/RunProgress'; +import { errorMessage, keys } from 'api/client'; +import useApi from 'hooks/useApi'; +import useLiveRefresh from 'hooks/useLiveRefresh'; +import { plural } from 'utils/format'; + +// assets +import HistoryOutlined from '@ant-design/icons/HistoryOutlined'; +import SearchOutlined from '@ant-design/icons/SearchOutlined'; + +// types +import type { ExecutionSummaryDto, RunCountsDto } from 'api/types'; + +const LIMITS = [50, 100, 200]; + +/** Counts for a summary (derived for servers that predate them). */ +export const summaryCounts = (run: ExecutionSummaryDto): RunCountsDto => + run.counts ?? { + targets: run.total, + pending: run.pending, + running: 0, + succeeded: run.succeeded, + failed: run.failed, + cancelled: Math.max(0, run.total - run.succeeded - run.failed - run.pending), + skipped: 0, + online: 0 + }; + +const stop = (event: MouseEvent) => event.stopPropagation(); + +export const runColumns = (showScript: boolean): Column[] => [ + ...(showScript + ? [ + { + id: 'script', + header: 'Script', + sortValue: (r: ExecutionSummaryDto) => r.scriptName, + cell: (r: ExecutionSummaryDto) => ( + + {r.scriptName ?? 'Script'} + + ) + } + ] + : []), + { + id: 'targets', + header: 'Targets', + sortValue: (r) => summaryCounts(r).targets, + cell: (r) => { + const count = plural(summaryCounts(r).targets, 'device'); + // A label that is only a count ("3 devices") is not repeated under itself. + const label = r.targetsLabel && !/^\d+ devices?$/.test(r.targetsLabel) ? r.targetsLabel : undefined; + return ( + + + {label ?? count} + + {label && ( + + {count} + + )} + + ); + } + }, + { + id: 'progress', + header: 'Progress', + sortValue: (r) => { + const c = summaryCounts(r); + return (c.succeeded + c.failed + c.cancelled) / Math.max(1, c.targets - c.skipped); + }, + cell: (r) => + }, + { + id: 'source', + header: 'Source', + width: 130, + sortValue: (r) => r.source, + cell: (r) => (r.source ? : '—') + }, + { + id: 'by', + header: 'Requested By', + sortValue: (r) => r.requestedBy, + cell: (r) => ( + + {r.requestedBy ?? '—'} + + ) + }, + { + id: 'started', + header: 'Started', + nowrap: true, + sortValue: (r) => r.startedUtc, + cell: (r) => + } +]; + +// ==============================|| RECENT RUNS ||============================== // + +/** Every recent run across scripts; a row opens its progress. */ +export default function RecentRuns() { + const navigate = useNavigate(); + const [limit, setLimit] = useState(50); + const [search, setSearch] = useState(''); + const runs = useApi(keys.executions(limit), { + refreshInterval: (latest) => (latest?.some((r) => !runFinished(summaryCounts(r))) ? 5_000 : 0) + }); + const { mutate } = runs; + const refresh = useCallback(() => void mutate(), [mutate]); + useLiveRefresh(refresh, (event) => Boolean(event.jobId)); + + const rows = useMemo(() => { + const needle = search.trim().toLowerCase(); + return needle + ? runs.data?.filter((r) => [r.scriptName, r.targetsLabel, r.requestedBy].some((v) => v?.toLowerCase().includes(needle))) + : runs.data; + }, [runs.data, search]); + + return ( + r.runId} + loading={runs.loading} + refreshing={runs.validating && !runs.loading} + error={runs.error ? errorMessage(runs.error, 'Could not load runs.') : undefined} + onRowClick={(r) => navigate(`/runs/${r.runId}`)} + defaultSort={{ id: 'started', direction: 'desc' }} + empty={} title={search ? 'No Matching Runs' : 'No Runs Yet'} />} + toolbar={ + + setSearch(e.target.value)} + sx={{ width: { xs: '100%', sm: 260 } }} + slotProps={{ + input: { + startAdornment: ( + + + + ) + } + }} + /> + setLimit(Number(e.target.value))} + sx={{ minWidth: 130 }} + > + {LIMITS.map((n) => ( + + Latest {n} + + ))} + + + } + /> + ); +} diff --git a/src/WebUI/src/sections/runs/RunProgress.tsx b/src/WebUI/src/sections/runs/RunProgress.tsx new file mode 100644 index 0000000..48f3b91 --- /dev/null +++ b/src/WebUI/src/sections/runs/RunProgress.tsx @@ -0,0 +1,526 @@ +import { MouseEvent, ReactNode, useCallback, useEffect, useMemo, useState } from 'react'; +import { Link as RouterLink } from 'react-router-dom'; + +// material-ui +import { alpha, keyframes, useTheme } from '@mui/material/styles'; +import Box from '@mui/material/Box'; +import Button from '@mui/material/Button'; +import ButtonBase from '@mui/material/ButtonBase'; +import CircularProgress from '@mui/material/CircularProgress'; +import InputAdornment from '@mui/material/InputAdornment'; +import Link from '@mui/material/Link'; +import Stack from '@mui/material/Stack'; +import TextField from '@mui/material/TextField'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; + +// project imports +import Dot from 'components/@extended/Dot'; +import DataTable, { Column } from 'components/DataTable'; +import { RelativeTime } from 'components/DateTime'; +import EmptyState from 'components/EmptyState'; +import StatusChip, { JobStateChip } from 'components/StatusChip'; +import { downloads, errorMessage, keys } from 'api/client'; +import useApi from 'hooks/useApi'; +import useLiveRefresh from 'hooks/useLiveRefresh'; +import { nats } from 'messaging/nats'; +import { formatDuration } from 'utils/format'; +import { enqueueSnackbar } from 'notistack'; + +// assets +import DownloadOutlined from '@ant-design/icons/DownloadOutlined'; +import SearchOutlined from '@ant-design/icons/SearchOutlined'; + +// types +import type { ExecutionDetailDto, JobState, RunCountsDto } from 'api/types'; + +/** Re-read cadence while anything in the run can still change (live events usually come first). */ +const POLL_MS = 3_000; + +type Segment = 'succeeded' | 'failed' | 'cancelled' | 'running' | 'pending' | 'skipped'; +export type RunFilter = 'all' | 'online' | Segment; + +/** Bar order, tone and hover text for each part of a run. */ +const SEGMENTS: { key: Segment; label: string; tone: 'success' | 'error' | 'secondary' | 'primary' | 'info' | 'warning'; help: string }[] = + [ + { key: 'succeeded', label: 'Succeeded', tone: 'success', help: 'Finished with exit code 0.' }, + { key: 'failed', label: 'Failed', tone: 'error', help: 'Failed or timed out; open one for its output.' }, + { key: 'cancelled', label: 'Cancelled', tone: 'secondary', help: 'Stopped before finishing.' }, + { key: 'running', label: 'Running', tone: 'primary', help: 'Running on the device now.' }, + { + key: 'pending', + label: 'Pending', + tone: 'info', + help: 'Queued or sent, waiting for the device. Offline devices run it when they reconnect.' + }, + { key: 'skipped', label: 'Skipped', tone: 'warning', help: 'Given no job: orphaned, or offline while Only Devices Online Now was on.' } + ]; + +const PENDING: JobState[] = ['queued', 'dispatched']; + +/** How a run was started, as shown in lists and headers. */ +export const RUN_SOURCE_LABEL: Record = { manual: 'Run Now', schedule: 'Schedule', trigger: 'Event Trigger' }; + +/** Counts from the detail (server) or derived from its rows (older servers). */ +export function runCounts(run: ExecutionDetailDto): RunCountsDto { + if (run.counts) return run.counts; + const count = (states: JobState[]) => run.targets.filter((t) => states.includes(t.state)).length; + const skipped = run.skipped?.length ?? 0; + return { + targets: run.targets.length + skipped, + pending: count(PENDING), + running: count(['running']), + succeeded: count(['succeeded']), + failed: count(['failed', 'timedOut']), + cancelled: count(['cancelled']), + skipped, + online: run.targets.filter((t) => t.online).length + }; +} + +export const runFinished = (counts: RunCountsDto) => counts.pending + counts.running === 0; + +const stripes = keyframes`from { background-position: 0 0; } to { background-position: 28px 0; }`; + +// ==============================|| RUN PROGRESS BAR ||============================== // + +/** One bar for the whole run: succeeded, failed, cancelled, running, pending and skipped, in proportion. */ +export function RunProgressBar({ counts, height = 10 }: { counts: RunCountsDto; height?: number }) { + const theme = useTheme(); + const total = Math.max(counts.targets, 1); + return ( + + {SEGMENTS.map(({ key, label, tone }) => { + const value = counts[key]; + if (!value) return null; + const color = theme.palette[tone].main; + return ( + + + + ); + })} + + ); +} + +/** "8 of 12" and percent, for lists. */ +export function RunProgressSummary({ counts }: { counts: RunCountsDto }) { + const jobs = counts.targets - counts.skipped; + const done = counts.succeeded + counts.failed + counts.cancelled; + return ( + + + + {done} of {jobs} Finished{counts.failed ? ` · ${counts.failed} Failed` : ''} + {counts.skipped ? ` · ${counts.skipped} Skipped` : ''} + + + ); +} + +// ==============================|| RUN COUNTERS ||============================== // + +function Counter({ + label, + value, + help, + tone, + active, + onClick +}: { + label: string; + value: number; + help: string; + tone?: 'success' | 'error' | 'secondary' | 'primary' | 'info' | 'warning'; + active: boolean; + onClick: () => void; +}) { + return ( + + { + const color = tone ? theme.palette[tone].main : theme.palette.text.primary; + return { + flex: '1 1 96px', + minWidth: 96, + px: 1.75, + py: 1.25, + gap: 0.25, + flexDirection: 'column', + alignItems: 'flex-start', + borderRadius: 1.5, + border: '1px solid', + borderColor: active ? color : 'divider', + bgcolor: active ? alpha(color, 0.08) : 'transparent', + transition: 'border-color 120ms, background-color 120ms', + '&:hover': { borderColor: color, bgcolor: alpha(color, 0.05) }, + '&.Mui-focusVisible': { outline: `2px solid ${theme.palette.primary.main}`, outlineOffset: 1 } + }; + }} + > + + {value.toLocaleString()} + + + {label} + + + + ); +} + +/** Totals for the run; each one filters the target list to its devices. */ +export function RunCounters({ + counts, + filter, + onFilter +}: { + counts: RunCountsDto; + filter: RunFilter; + onFilter: (filter: RunFilter) => void; +}) { + const toggle = (next: RunFilter) => onFilter(filter === next ? 'all' : next); + return ( + + onFilter('all')} + /> + toggle('online')} + /> + {SEGMENTS.filter((s) => s.key !== 'cancelled' || counts.cancelled > 0).map((s) => ( + toggle(s.key)} + /> + ))} + + ); +} + +// ==============================|| LIVE RUN ||============================== // + +/** The run, re-read on job events and polled while it can still change. */ +export function useRun(runId: string | null | undefined) { + const execution = useApi(runId ? keys.execution(runId) : null, { + refreshInterval: (latest) => (latest && runFinished(runCounts(latest)) ? 0 : POLL_MS) + }); + const { mutate } = execution; + const refresh = useCallback(() => void mutate(), [mutate]); + useLiveRefresh(refresh, (event) => Boolean(event.jobId)); + + // State changes arrive on the job channel; coalesce bursts from large runs. + useEffect(() => { + if (!runId) return; + let timer: number | undefined; + const off = nats.onJobEvent((_, event) => { + if (event.type !== 'job.state') return; + window.clearTimeout(timer); + timer = window.setTimeout(refresh, 400); + }); + return () => { + window.clearTimeout(timer); + off(); + }; + }, [runId, refresh]); + + return execution; +} + +// ==============================|| RUN TARGETS ||============================== // + +interface Row { + id: string; + jobId?: string; + clientId: string; + hostname: string; + state: JobState | 'skipped'; + reason?: 'orphaned' | 'offline'; + exitCode?: number; + startedUtc?: string; + completedUtc?: string; + online?: boolean; + summary?: string; +} + +const segmentOf = (row: Row): Segment => + row.state === 'skipped' + ? 'skipped' + : row.state === 'timedOut' + ? 'failed' + : PENDING.includes(row.state) + ? 'pending' + : (row.state as Segment); + +const stop = (event: MouseEvent) => event.stopPropagation(); + +const columns: Column[] = [ + { + id: 'device', + header: 'Device', + sortValue: (r) => r.hostname, + cell: (r) => ( + + {r.hostname} + + ) + }, + { + id: 'state', + header: 'State', + width: 140, + sortValue: (r) => SEGMENTS.findIndex((s) => s.key === segmentOf(r)), + cell: (r) => + r.state === 'skipped' ? ( + + ) : ( + + ) + }, + { + id: 'online', + header: 'Online', + width: 100, + sortValue: (r) => Boolean(r.online), + cell: (r) => + r.state === 'skipped' ? ( + '—' + ) : ( + + + + {r.online ? 'Online' : 'Offline'} + + + ) + }, + { + id: 'exit', + header: 'Exit Code', + align: 'right', + width: 100, + sortValue: (r) => r.exitCode, + cell: (r) => {r.exitCode ?? '—'} + }, + { + id: 'duration', + header: 'Duration', + nowrap: true, + sortValue: (r) => (r.startedUtc && r.completedUtc ? new Date(r.completedUtc).getTime() - new Date(r.startedUtc).getTime() : null), + cell: (r) => formatDuration(r.startedUtc, r.completedUtc) + }, + { + id: 'finished', + header: 'Finished', + nowrap: true, + sortValue: (r) => r.completedUtc, + cell: (r) => + }, + { + id: 'summary', + header: 'Result', + sortValue: (r) => r.summary, + cell: (r) => + r.summary ? ( + + + {r.summary} + + + ) : ( + '—' + ) + } +]; + +interface Props { + run: ExecutionDetailDto | undefined; + loading?: boolean; + refreshing?: boolean; + error?: string; + /** The job open in the output drawer. */ + openJobId?: string | null; + onOpenJob: (jobId: string) => void; + /** Left of the toolbar (breadcrumbs in a panel). */ + toolbarStart?: ReactNode; + initialFilter?: RunFilter; +} + +/** + * A run at a glance: one progress bar, a counter per outcome (each filters + * the list) and every target, skipped devices included; a row opens that + * device's output. + */ +export default function RunProgress({ run, loading, refreshing, error, openJobId, onOpenJob, toolbarStart, initialFilter = 'all' }: Props) { + const [filter, setFilter] = useState(initialFilter); + const [search, setSearch] = useState(''); + const [chosen, setChosen] = useState>(new Set()); + const [saving, setSaving] = useState(false); + const runId = run?.runId; + useEffect(() => setChosen(new Set()), [runId]); + const counts = run && runCounts(run); + + const choose = useCallback((ids: string[], on: boolean) => { + setChosen((prev) => { + const next = new Set(prev); + for (const id of ids) { + if (on) next.add(id); + else next.delete(id); + } + return next; + }); + }, []); + + // Every job's log when nothing is checked; skipped targets have none. + const saveLogs = async () => { + if (!run) return; + setSaving(true); + try { + await downloads.executionLogs(run.runId, [...chosen]); + } catch (err) { + enqueueSnackbar(errorMessage(err, 'The logs could not be downloaded.'), { variant: 'error' }); + } finally { + setSaving(false); + } + }; + const jobsInRun = run?.targets.length ?? 0; + + const rows = useMemo(() => { + if (!run) return undefined; + const jobs: Row[] = run.targets.map((t) => ({ ...t, id: t.jobId, hostname: t.hostname ?? t.clientId })); + const skipped: Row[] = (run.skipped ?? []).map((s) => ({ + id: `skip:${s.clientId}`, + clientId: s.clientId, + hostname: s.hostname, + state: 'skipped', + reason: s.reason + })); + return [...jobs, ...skipped]; + }, [run]); + + const shown = useMemo(() => { + const needle = search.trim().toLowerCase(); + return rows?.filter( + (r) => + (filter === 'all' || (filter === 'online' ? r.online : segmentOf(r) === filter)) && + (!needle || [r.hostname, r.clientId, r.summary].some((v) => v?.toLowerCase().includes(needle))) + ); + }, [rows, filter, search]); + + const jobCount = counts ? counts.targets - counts.skipped : 0; + const done = counts ? counts.succeeded + counts.failed + counts.cancelled : 0; + const percent = jobCount ? Math.round((done / jobCount) * 100) : 100; + + return ( + r.id} + loading={loading} + refreshing={refreshing} + error={error} + onRowClick={(r) => r.jobId && onOpenJob(r.jobId)} + selection={{ selected: chosen, onChange: choose, selectable: (r) => Boolean(r.jobId) }} + rowLabel={(r) => r.hostname} + activeRowId={openJobId ?? undefined} + defaultSort={{ id: 'state', direction: 'desc' }} + empty={filter !== 'all' || search ? : } + toolbar={ + + {toolbarStart} + {counts && ( + + + {runFinished(counts) ? 'Complete' : `${done} of ${jobCount} Finished`} + + {percent}% + + + + + )} + {counts && } + + setSearch(e.target.value)} + sx={{ width: { xs: '100%', sm: 260 } }} + slotProps={{ + input: { + startAdornment: ( + + + + ) + } + }} + /> + + + + + + + + } + /> + ); +} diff --git a/src/WebUI/src/sections/runs/RunScriptDialog.tsx b/src/WebUI/src/sections/runs/RunScriptDialog.tsx new file mode 100644 index 0000000..c5750f2 --- /dev/null +++ b/src/WebUI/src/sections/runs/RunScriptDialog.tsx @@ -0,0 +1,704 @@ +import { ReactNode, useEffect, useMemo, useState } from 'react'; +import { useNavigate } from 'react-router-dom'; + +// material-ui +import Alert from '@mui/material/Alert'; +import Box from '@mui/material/Box'; +import Button from '@mui/material/Button'; +import Checkbox from '@mui/material/Checkbox'; +import Chip from '@mui/material/Chip'; +import Dialog from '@mui/material/Dialog'; +import DialogActions from '@mui/material/DialogActions'; +import DialogContent from '@mui/material/DialogContent'; +import DialogTitle from '@mui/material/DialogTitle'; +import FormControlLabel from '@mui/material/FormControlLabel'; +import InputAdornment from '@mui/material/InputAdornment'; +import List from '@mui/material/List'; +import ListItemButton from '@mui/material/ListItemButton'; +import MenuItem from '@mui/material/MenuItem'; +import Radio from '@mui/material/Radio'; +import Stack from '@mui/material/Stack'; +import Switch from '@mui/material/Switch'; +import Tab from '@mui/material/Tab'; +import Tabs from '@mui/material/Tabs'; +import TextField from '@mui/material/TextField'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; + +// third-party +import { enqueueSnackbar } from 'notistack'; +import { mutate } from 'swr'; + +// project imports +import Dot from 'components/@extended/Dot'; +import DataTable, { Column } from 'components/DataTable'; +import { RelativeTime } from 'components/DateTime'; +import EmptyState from 'components/EmptyState'; +import HoverHelp from 'components/HoverHelp'; +import ParameterInputs from 'components/ParameterInputs'; +import { DeviceStatusChip } from 'components/StatusChip'; +import { RunTarget } from './TargetPicker'; +import { ENGINES, engineOf } from 'sections/scripts/scriptModel'; +import useApi from 'hooks/useApi'; +import { api, errorMessage, keys } from 'api/client'; +import { ArgumentDraft, collectArguments, initialDraft, validateArguments } from 'utils/argumentValues'; +import { plural } from 'utils/format'; +import { buildGroupTree, flattenTree, groupPath, reach } from 'utils/groupTree'; +import type { DeviceDto, DeviceGroupDto, GroupRunDto, ScriptDto } from 'api/types'; + +// assets +import ApartmentOutlined from '@ant-design/icons/ApartmentOutlined'; +import FolderOutlined from '@ant-design/icons/FolderOutlined'; +import LockOutlined from '@ant-design/icons/LockOutlined'; +import PlayCircleOutlined from '@ant-design/icons/PlayCircleOutlined'; +import SearchOutlined from '@ant-design/icons/SearchOutlined'; + +interface Props { + open: boolean; + onClose: () => void; + /** Preselected (and fixed) script, e.g. from the script page. */ + scriptId?: string; + /** Preselected targets, e.g. the chosen devices or a group. */ + targets?: RunTarget[]; +} + +type TabId = 'script' | 'devices' | 'groups' | 'parameters' | 'review'; +type StatusFilter = 'all' | 'online' | 'offline'; + +/** "Queued on 12 devices; 2 orphaned and 1 offline skipped." */ +export function runHeadline(result: GroupRunDto): string { + const skipped = [ + result.skippedOrphaned.length > 0 ? `${result.skippedOrphaned.length} orphaned` : '', + (result.skippedOffline?.length ?? 0) > 0 ? `${result.skippedOffline!.length} offline` : '' + ].filter(Boolean); + const queued = result.jobs.length > 0 ? `Queued on ${plural(result.jobs.length, 'device')}` : 'Nothing queued'; + return skipped.length > 0 ? `${queued}; ${skipped.join(' and ')} skipped.` : `${queued}.`; +} + +const engineLabel = (language: string) => ENGINES.find((e) => e.value === engineOf(language))?.label ?? language; + +function SearchField({ value, onChange, placeholder }: { value: string; onChange: (value: string) => void; placeholder: string }) { + return ( + onChange(e.target.value)} + autoFocus + sx={{ width: { xs: '100%', sm: 280 } }} + slotProps={{ + input: { + startAdornment: ( + + + + ) + } + }} + /> + ); +} + +/** A tab label with a count, red when the tab needs attention. */ +function TabLabel({ label, count, problem }: { label: string; count?: number | string; problem?: boolean }) { + return ( + + {label} + {(Boolean(count) || problem) && ( + + )} + + ); +} + +function ReviewRow({ label, children }: { label: string; children: ReactNode }) { + return ( + + + {label} + + {children} + + ); +} + +// ==============================|| RUN SCRIPT (RUN NOW) ||============================== // + +/** + * Run Now as tabs: pick the script, the devices (searchable, multi-select) + * and groups, fill in parameters, review and run. Opened from a script the + * script is fixed; from devices the devices come preselected. Starting the + * run opens its progress. + */ +export default function RunScriptDialog({ open, onClose, scriptId, targets: initialTargets }: Props) { + const navigate = useNavigate(); + const { data: scripts } = useApi(open ? keys.scripts : null); + const { data: devices } = useApi(open ? keys.devices : null); + const { data: groups } = useApi(open ? keys.groups : null); + + const [tab, setTab] = useState('script'); + const [chosenScriptId, setChosenScriptId] = useState(scriptId ?? null); + const [deviceIds, setDeviceIds] = useState>(new Set()); + const [groupIds, setGroupIds] = useState>(new Set()); + const [draft, setDraft] = useState({ scalars: {}, bools: {}, arrays: {}, hashes: {} }); + const [onlineOnly, setOnlineOnly] = useState(false); + const [showErrors, setShowErrors] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(''); + const [scriptSearch, setScriptSearch] = useState(''); + const [deviceSearch, setDeviceSearch] = useState(''); + const [statusFilter, setStatusFilter] = useState('all'); + const [groupSearch, setGroupSearch] = useState(''); + + // Each opening starts from the caller's preselection, on the first tab that still needs a choice. + useEffect(() => { + if (!open) return; + const preset = initialTargets ?? []; + setChosenScriptId(scriptId ?? null); + setDeviceIds(new Set(preset.filter((t) => t.kind === 'device').map((t) => t.id))); + setGroupIds(new Set(preset.filter((t) => t.kind === 'group').map((t) => t.id))); + setTab( + !scriptId ? 'script' : preset.some((t) => t.kind === 'group') && !preset.some((t) => t.kind === 'device') ? 'groups' : 'devices' + ); + setOnlineOnly(false); + setShowErrors(false); + setError(''); + setScriptSearch(''); + setDeviceSearch(''); + setStatusFilter('all'); + setGroupSearch(''); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [open]); + + const script = scripts?.find((s) => s.id === chosenScriptId) ?? null; + const parameters = useMemo(() => script?.parameters ?? [], [script]); + + // Fresh defaults for every opening and every script: never the last run's values. + useEffect(() => { + if (!open) return; + setDraft(initialDraft(parameters)); + setShowErrors(false); + }, [parameters, open]); + + const reached = useMemo( + () => reach(devices ?? [], groups ?? [], { clientIds: [...deviceIds], groupIds: [...groupIds] }), + [devices, groups, deviceIds, groupIds] + ); + const orphaned = reached.filter((d) => d.isOrphaned).length; + const online = reached.filter((d) => d.status === 'online' && !d.isOrphaned).length; + const offline = reached.length - orphaned - online; + const willRun = onlineOnly ? online : reached.length - orphaned; + const skipped = reached.length - willRun; + + const errors = validateArguments(parameters, draft); + const invalid = Object.keys(errors).length > 0; + const hasTargets = deviceIds.size + groupIds.size > 0; + + // ── Script tab ────────────────────────────────────────────────────── + const scriptRows = useMemo(() => { + const needle = scriptSearch.trim().toLowerCase(); + return needle ? scripts?.filter((s) => [s.name, s.description].some((v) => v?.toLowerCase().includes(needle))) : scripts; + }, [scripts, scriptSearch]); + + const scriptColumns: Column[] = [ + { + id: 'pick', + header: '', + width: 48, + cell: (s) => ( + + ) + }, + { + id: 'name', + header: 'Name', + sortValue: (s) => s.name, + cell: (s) => ( + + + {s.name} + + {s.description && ( + + {s.description} + + )} + + ) + }, + { + id: 'engine', + header: 'Engine', + width: 140, + sortValue: (s) => engineLabel(s.language), + cell: (s) => + }, + { + id: 'parameters', + header: 'Parameters', + align: 'right', + width: 110, + sortValue: (s) => s.parameters.length, + cell: (s) => s.parameters.length || '—' + }, + { + id: 'updated', + header: 'Updated', + nowrap: true, + sortValue: (s) => s.updatedUtc, + cell: (s) => + } + ]; + + // ── Devices tab ───────────────────────────────────────────────────── + const deviceRows = useMemo(() => { + const needle = deviceSearch.trim().toLowerCase(); + return devices?.filter( + (d) => + (statusFilter === 'all' || + (statusFilter === 'online' ? d.status === 'online' && !d.isOrphaned : d.status !== 'online' || d.isOrphaned)) && + (!needle || + [d.hostname, d.clientId, d.osCaption, d.manufacturer, d.model, d.publicIp, ...d.ipAddresses, ...(d.tags ?? [])].some((v) => + v?.toLowerCase().includes(needle) + )) + ); + }, [devices, deviceSearch, statusFilter]); + + const deviceColumns: Column[] = [ + { + id: 'hostname', + header: 'Device', + sortValue: (d) => d.hostname, + cell: (d) => ( + + {d.hostname} + + ) + }, + { + id: 'status', + header: 'Status', + width: 130, + sortValue: (d) => (d.isOrphaned ? 'z' : d.status), + cell: (d) => + }, + { + id: 'os', + header: 'Operating System', + sortValue: (d) => d.osCaption, + cell: (d) => ( + + {d.osCaption ?? '—'} + + ) + }, + { + id: 'groups', + header: 'Groups', + sortValue: (d) => d.groupIds?.length ?? 0, + cell: (d) => { + const names = (d.groupIds ?? []).map((id) => groupPath(groups ?? [], id)); + return names.length ? ( + + + {names.join(', ')} + + + ) : ( + '—' + ); + } + }, + { id: 'seen', header: 'Last Seen', nowrap: true, sortValue: (d) => d.lastSeenUtc, cell: (d) => } + ]; + + const chooseDevices = (ids: string[], on: boolean) => + setDeviceIds((current) => { + const next = new Set(current); + ids.forEach((id) => (on ? next.add(id) : next.delete(id))); + return next; + }); + + // ── Groups tab ────────────────────────────────────────────────────── + const groupRows = useMemo(() => { + const flat = flattenTree(buildGroupTree(groups ?? [])); + const needle = groupSearch.trim().toLowerCase(); + return needle + ? flat.filter(({ group }) => + groupPath(groups ?? [], group.id) + .toLowerCase() + .includes(needle) + ) + : flat; + }, [groups, groupSearch]); + + const toggleGroup = (id: string) => + setGroupIds((current) => { + const next = new Set(current); + if (next.has(id)) next.delete(id); + else next.add(id); + return next; + }); + + // ── Flow ──────────────────────────────────────────────────────────── + const order: TabId[] = ['script', 'devices', 'groups', ...(parameters.length ? (['parameters'] as TabId[]) : []), 'review']; + const nextTab = order[order.indexOf(tab) + 1]; + + const start = async () => { + if (!script) return setTab('script'); + if (invalid) { + setShowErrors(true); + setTab('parameters'); + return; + } + setBusy(true); + setError(''); + try { + const result = await api.runScript({ + scriptId: script.id, + clientIds: [...deviceIds], + groupIds: [...groupIds], + arguments: parameters.length > 0 ? collectArguments(parameters, draft) : undefined, + onlineOnly + }); + void mutate(keys.dashboard); + void mutate(keys.scriptExecutions(script.id)); + enqueueSnackbar(`“${script.name}”: ${runHeadline(result)}`, { variant: result.jobs.length > 0 ? 'success' : 'warning' }); + onClose(); + if (result.runId) navigate(`/runs/${result.runId}`); + } catch (e) { + setError(errorMessage(e, 'The run could not be started.')); + } finally { + setBusy(false); + } + }; + + const runBlocked = !script + ? 'Choose a script.' + : !hasTargets + ? 'Choose devices or groups.' + : willRun === 0 + ? 'None of the chosen devices can run it now.' + : undefined; + + return ( + + + + Run Script + {script && ( + : undefined} /> + )} + + + setTab(next)} + variant="scrollable" + sx={{ px: 3, borderBottom: 1, borderColor: 'divider' }} + > + } /> + } /> + } /> + } + /> + + + + + {tab === 'script' && + (scriptId && script ? ( + + + {script.name} + + + + {script.description && ( + + {script.description} + + )} + + ) : ( + s.id} + loading={!scripts} + onRowClick={(s) => setChosenScriptId(s.id)} + activeRowId={chosenScriptId ?? undefined} + defaultSort={{ id: 'name', direction: 'asc' }} + pageSize={25} + empty={} + toolbar={} + /> + ))} + + {tab === 'devices' && ( + d.clientId} + loading={!devices} + selection={{ selected: deviceIds, onChange: chooseDevices }} + rowLabel={(d) => `Choose ${d.hostname}`} + onRowClick={(d) => chooseDevices([d.clientId], !deviceIds.has(d.clientId))} + defaultSort={{ id: 'hostname', direction: 'asc' }} + pageSize={25} + empty={} + toolbar={ + + + setStatusFilter(e.target.value as StatusFilter)} + sx={{ minWidth: 140 }} + > + All + Online + Not Online + + + + + + + {deviceIds.size > 0 && ( + + )} + + } + /> + )} + + {tab === 'groups' && ( + + + + {groupIds.size > 0 && ( + + )} + + {groupRows.length === 0 ? ( + + ) : ( + + {groupRows.map(({ group, depth }) => ( + toggleGroup(group.id)} + selected={groupIds.has(group.id)} + sx={{ pl: 1 + depth * 2.5, borderRadius: 1, gap: 1 }} + > + + + {group.kind === 'folder' ? : } + + + {group.name} + + + + + + {group.onlineCount}/{group.memberCount} + + + + + ))} + + )} + + )} + + {tab === 'parameters' && ( + + + + )} + + {tab === 'review' && ( + + + {script ? ( + + {script.name} + + {(script.secretBindings?.length ?? 0) > 0 && ( + + } + label={plural(script.secretBindings!.length, 'Secret')} + /> + + )} + + ) : ( + + )} + + + {hasTargets ? ( + + {[...groupIds].map((id) => ( + } + label={groupPath(groups ?? [], id)} + onDelete={() => toggleGroup(id)} + /> + ))} + {deviceIds.size > 0 && ( + setDeviceIds(new Set())} + /> + )} + + ) : ( + + )} + + + + + {reached.length} {reached.length === 1 ? 'Device' : 'Devices'} + + + {online} Online + + + + {offline} Offline + + + {orphaned > 0 && ( + + + {orphaned} Orphaned + + + )} + + + + setOnlineOnly(e.target.checked)} />} + label={ + + Only Devices Online Now + + + } + /> + + {parameters.length > 0 && ( + + {invalid ? ( + + ) : ( + + {Object.entries(collectArguments(parameters, draft)) + .map(([name, value]) => `-${name} ${JSON.stringify(value)}`) + .join(' ') || '—'} + + )} + + )} + + )} + + + {error && ( + setError('')}> + {error} + + )} + + + {hasTargets && ( + + {plural(reached.length, 'Device')} · {online} Online{skipped > 0 ? ` · ${skipped} Skipped` : ''} + + )} + + + {nextTab && ( + + )} + + + + + + + + ); +} diff --git a/src/WebUI/src/sections/runs/TargetPicker.tsx b/src/WebUI/src/sections/runs/TargetPicker.tsx new file mode 100644 index 0000000..a2448d8 --- /dev/null +++ b/src/WebUI/src/sections/runs/TargetPicker.tsx @@ -0,0 +1,190 @@ +import { useMemo } from 'react'; + +// material-ui +import Autocomplete from '@mui/material/Autocomplete'; +import Box from '@mui/material/Box'; +import Chip from '@mui/material/Chip'; +import Stack from '@mui/material/Stack'; +import TextField from '@mui/material/TextField'; +import Typography from '@mui/material/Typography'; + +// project imports +import Dot from 'components/@extended/Dot'; +import { buildGroupTree, flattenTree, groupPath } from 'utils/groupTree'; +import type { DeviceDto, DeviceGroupDto } from 'api/types'; + +// assets +import ApartmentOutlined from '@ant-design/icons/ApartmentOutlined'; +import DesktopOutlined from '@ant-design/icons/DesktopOutlined'; +import FolderOutlined from '@ant-design/icons/FolderOutlined'; +import GlobalOutlined from '@ant-design/icons/GlobalOutlined'; + +/** A run or schedule target; 'all' means every enrolled device. */ +export type RunTarget = { kind: 'device' | 'group'; id: string } | { kind: 'all'; id: 'all' }; + +export const targetKey = (t: RunTarget) => `${t.kind}:${t.id}`; + +interface Option { + target: RunTarget; + label: string; + /** Hostname / group path used for matching. */ + search: string; + section: string; + depth: number; + detail?: string; + device?: DeviceDto; + group?: DeviceGroupDto; +} + +interface BaseProps { + devices: DeviceDto[]; + groups: DeviceGroupDto[]; + label?: string; + disabled?: boolean; + error?: string; +} + +interface MultipleProps extends BaseProps { + multiple: true; + value: RunTarget[]; + onChange: (value: RunTarget[]) => void; + allowAll?: false; +} + +interface SingleProps extends BaseProps { + multiple?: false; + value: RunTarget | null; + onChange: (value: RunTarget | null) => void; + /** Offer "All Devices" (schedules and event triggers). */ + allowAll?: boolean; +} + +export function targetLabel(target: RunTarget, devices: DeviceDto[], groups: DeviceGroupDto[]): string { + if (target.kind === 'all') return 'All Devices'; + if (target.kind === 'group') return groupPath(groups, target.id); + return devices.find((d) => d.clientId === target.id)?.hostname ?? target.id; +} + +// ==============================|| TARGET PICKER (DEVICES + GROUPS) ||============================== // + +export default function TargetPicker(props: MultipleProps | SingleProps) { + const { devices, groups, label = 'Targets', disabled, error } = props; + + const options = useMemo(() => { + const all: Option[] = props.allowAll + ? [{ target: { kind: 'all', id: 'all' }, label: 'All Devices', search: 'all devices', section: 'Everything', depth: 0 }] + : []; + const groupOptions = flattenTree(buildGroupTree(groups)).map(({ group, depth }) => ({ + target: { kind: 'group' as const, id: group.id }, + label: group.name, + search: groupPath(groups, group.id), + section: 'Groups', + depth, + detail: `${group.memberCount} device${group.memberCount === 1 ? '' : 's'}`, + group + })); + const deviceOptions = [...devices] + .sort((a, b) => a.hostname.localeCompare(b.hostname, undefined, { numeric: true })) + .map((device) => ({ + target: { kind: 'device' as const, id: device.clientId }, + label: device.hostname, + search: `${device.hostname} ${device.clientId} ${device.ipAddresses.join(' ')}`, + section: 'Devices', + depth: 0, + detail: device.osCaption, + device + })); + return [...all, ...groupOptions, ...deviceOptions]; + }, [devices, groups, props.allowAll]); + + const byKey = useMemo(() => new Map(options.map((o) => [targetKey(o.target), o])), [options]); + const toOption = (t: RunTarget): Option => + byKey.get(targetKey(t)) ?? { target: t, label: targetLabel(t, devices, groups), search: '', section: '', depth: 0 }; + + const renderOption = (optionProps: React.HTMLAttributes & { key: React.Key }, option: Option) => { + const { key, ...rest } = optionProps; + const Icon = + option.target.kind === 'all' + ? GlobalOutlined + : option.group + ? option.group.kind === 'folder' + ? FolderOutlined + : ApartmentOutlined + : DesktopOutlined; + return ( + + + + + + + {option.label} + + {option.device && ( + + )} + {option.detail && ( + + {option.detail} + + )} + + + ); + }; + + const common = { + options, + disabled, + groupBy: (o: Option) => o.section, + getOptionLabel: (o: Option) => (o.group ? o.search : o.label), + isOptionEqualToValue: (a: Option, b: Option) => targetKey(a.target) === targetKey(b.target), + filterOptions: (list: Option[], state: { inputValue: string }) => { + const query = state.inputValue.trim().toLowerCase(); + return query ? list.filter((o) => o.search.toLowerCase().includes(query) || o.label.toLowerCase().includes(query)) : list; + }, + renderOption, + renderInput: (params: object) => ( + + ) + }; + + if (props.multiple) { + return ( + props.onChange(chosen.map((o) => o.target))} + renderValue={(chosen, getItemProps) => + chosen.map((option, index) => { + const { key, ...itemProps } = getItemProps({ index }); + return ( + : } + label={option.group ? option.search : option.label} + {...itemProps} + /> + ); + }) + } + /> + ); + } + + return ( + props.onChange(chosen ? chosen.target : null)} + /> + ); +} diff --git a/src/WebUI/src/sections/schedules/CadenceEditor.tsx b/src/WebUI/src/sections/schedules/CadenceEditor.tsx new file mode 100644 index 0000000..3d88a0a --- /dev/null +++ b/src/WebUI/src/sections/schedules/CadenceEditor.tsx @@ -0,0 +1,227 @@ +import { useEffect, useState } from 'react'; + +// material-ui +import Alert from '@mui/material/Alert'; +import Autocomplete from '@mui/material/Autocomplete'; +import Grid from '@mui/material/Grid'; +import MenuItem from '@mui/material/MenuItem'; +import Stack from '@mui/material/Stack'; +import TextField from '@mui/material/TextField'; +import ToggleButton from '@mui/material/ToggleButton'; +import ToggleButtonGroup from '@mui/material/ToggleButtonGroup'; +import Typography from '@mui/material/Typography'; + +// project imports +import HoverHelp from 'components/HoverHelp'; +import { api } from 'api/client'; +import { buildCron, CadenceForm, cadenceProblem, describeCron, FREQUENCIES, Frequency, TIME_ZONES, WEEKDAYS } from 'utils/cron'; +import { formatAbsolute, formatRelative } from 'utils/format'; + +interface Props { + value: CadenceForm; + onChange: (value: CadenceForm) => void; + disabled?: boolean; + /** Whether the schedule will be enabled; a disabled one-shot may keep a past time. */ + enabled?: boolean; +} + +/** Server-evaluated upcoming runs for the cron being built (debounced). */ +function useSchedulePreview(cron: string | null, timeZoneId: string) { + const [state, setState] = useState<{ occurrences: string[]; error?: string; loading: boolean }>({ occurrences: [], loading: false }); + + useEffect(() => { + if (!cron) { + setState({ occurrences: [], loading: false }); + return; + } + let cancelled = false; + setState((s) => ({ ...s, loading: true })); + const timer = window.setTimeout(() => { + api + .previewSchedule(cron, timeZoneId, 5) + .then((result) => !cancelled && setState({ occurrences: result.occurrences, error: result.error ?? undefined, loading: false })) + .catch(() => !cancelled && setState({ occurrences: [], loading: false })); + }, 350); + return () => { + cancelled = true; + window.clearTimeout(timer); + }; + }, [cron, timeZoneId]); + + return state; +} + +// ==============================|| CADENCE EDITOR ||============================== // + +export default function CadenceEditor({ value, onChange, disabled, enabled = true }: Props) { + const set = (patch: Partial) => onChange({ ...value, ...patch }); + const cron = buildCron(value); + const preview = useSchedulePreview(value.frequency === 'once' ? null : cron, value.timeZoneId); + const problem = cadenceProblem(value, enabled); + const summary = + value.frequency === 'once' + ? value.onceLocal + ? `Once at ${formatAbsolute(value.onceLocal)}` + : 'Pick a date and time.' + : cron + ? (describeCron(cron) ?? 'Custom cron') + : ''; + + return ( + + + + set({ frequency: e.target.value as Frequency })} + disabled={disabled} + > + {FREQUENCIES.map((f) => ( + + {f.label} + + ))} + + + + {(value.frequency === 'minutes' || value.frequency === 'hours') && ( + + set({ every: Number(e.target.value) })} + slotProps={{ htmlInput: { min: 1, max: value.frequency === 'minutes' ? 59 : 23 } }} + disabled={disabled} + /> + + )} + + {(value.frequency === 'daily' || value.frequency === 'weekly' || value.frequency === 'monthly') && ( + + set({ atTime: e.target.value })} + slotProps={{ inputLabel: { shrink: true } }} + disabled={disabled} + /> + + )} + + {value.frequency === 'monthly' && ( + + set({ monthDay: Number(e.target.value) })} + slotProps={{ htmlInput: { min: 1, max: 31 } }} + helperText={value.monthDay > 28 ? 'Months without this day are skipped.' : undefined} + disabled={disabled} + /> + + )} + + {value.frequency === 'once' && ( + + set({ onceLocal: e.target.value })} + slotProps={{ inputLabel: { shrink: true } }} + disabled={disabled} + /> + + )} + + {value.frequency === 'cron' && ( + + set({ cron: e.target.value })} + helperText="minute hour day-of-month month day-of-week" + slotProps={{ htmlInput: { style: { fontFamily: 'var(--font-mono)' } } }} + disabled={disabled} + /> + + )} + + {value.frequency !== 'once' && ( + + set({ timeZoneId: zone ?? 'UTC' })} + disableClearable + disabled={disabled} + renderInput={(params) => ( + + Time Zone + + + } + /> + )} + /> + + )} + + + {value.frequency === 'weekly' && ( + set({ weekdays: days })} + aria-label="Days of the week" + disabled={disabled} + > + {WEEKDAYS.map((day) => ( + + {day.charAt(0) + day.slice(1).toLowerCase()} + + ))} + + )} + + + {summary} + {problem ? ( + + {problem} + + ) : value.frequency !== 'once' && preview.error ? ( + + {preview.error} + + ) : ( + value.frequency !== 'once' && + preview.occurrences.length > 0 && ( + + Next:{' '} + {preview.occurrences + .slice(0, 3) + .map((o) => `${formatAbsolute(o)} (${formatRelative(o)})`) + .join(' · ')} + + ) + )} + + + ); +} diff --git a/src/WebUI/src/sections/schedules/ScheduleEditor.tsx b/src/WebUI/src/sections/schedules/ScheduleEditor.tsx new file mode 100644 index 0000000..46c876f --- /dev/null +++ b/src/WebUI/src/sections/schedules/ScheduleEditor.tsx @@ -0,0 +1,223 @@ +import { useEffect, useMemo, useState } from 'react'; + +// material-ui +import Alert from '@mui/material/Alert'; +import Autocomplete from '@mui/material/Autocomplete'; +import Button from '@mui/material/Button'; +import Divider from '@mui/material/Divider'; +import FormControlLabel from '@mui/material/FormControlLabel'; +import Stack from '@mui/material/Stack'; +import Switch from '@mui/material/Switch'; +import TextField from '@mui/material/TextField'; +import ToggleButton from '@mui/material/ToggleButton'; +import ToggleButtonGroup from '@mui/material/ToggleButtonGroup'; +import Typography from '@mui/material/Typography'; + +// third-party +import { enqueueSnackbar } from 'notistack'; +import { mutate } from 'swr'; + +// project imports +import CadenceEditor from './CadenceEditor'; +import HoverHelp from 'components/HoverHelp'; +import ParameterInputs from 'components/ParameterInputs'; +import Sheet from 'components/Sheet'; +import TargetPicker, { RunTarget } from 'sections/runs/TargetPicker'; +import useApi from 'hooks/useApi'; +import { api, errorMessage, keys } from 'api/client'; +import { ArgumentDraft, collectArguments, initialDraft, validateArguments } from 'utils/argumentValues'; +import { cadenceBody, cadenceProblem, CadenceForm, defaultCadence, parseCadence } from 'utils/cron'; +import type { DeviceDto, DeviceGroupDto, ScriptDto, ScriptTriggerDto, ScriptTriggerType } from 'api/types'; + +export interface SchedulePreset { + scriptId?: string; + target?: RunTarget; + triggerType?: ScriptTriggerType; +} + +interface Props { + open: boolean; + onClose: () => void; + /** Edit this trigger; otherwise create a new one from the preset. */ + trigger?: ScriptTriggerDto | null; + preset?: SchedulePreset; +} + +const WHEN_HELP: Record = { + scheduled: 'Runs on a cadence against everything the target holds at that moment.', + onRegistration: 'Runs once on each device the first time it enrolls.', + onAgentReady: 'Runs once on each device when its agent first connects and is ready for jobs.' +}; + +function targetOf(trigger: ScriptTriggerDto): RunTarget { + if (trigger.clientId) return { kind: 'device', id: trigger.clientId }; + if (trigger.groupId) return { kind: 'group', id: trigger.groupId }; + return { kind: 'all', id: 'all' }; +} + +// ==============================|| SCHEDULE / TRIGGER EDITOR ||============================== // + +export default function ScheduleEditor({ open, onClose, trigger, preset }: Props) { + const { data: scripts } = useApi(open ? keys.scripts : null); + const { data: devices } = useApi(open ? keys.devices : null); + const { data: groups } = useApi(open ? keys.groups : null); + + const [name, setName] = useState(''); + const [scriptId, setScriptId] = useState(null); + const [when, setWhen] = useState('scheduled'); + const [cadence, setCadence] = useState(defaultCadence); + const [target, setTarget] = useState(null); + const [enabled, setEnabled] = useState(true); + const [draft, setDraft] = useState({ scalars: {}, bools: {}, arrays: {}, hashes: {} }); + const [showErrors, setShowErrors] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(''); + + // Seed the form each time the sheet opens. + useEffect(() => { + if (!open) return; + setError(''); + setShowErrors(false); + if (trigger) { + setName(trigger.name ?? ''); + setScriptId(trigger.scriptId); + setWhen(trigger.triggerType); + setCadence(trigger.triggerType === 'scheduled' ? parseCadence(trigger) : defaultCadence()); + setTarget(targetOf(trigger)); + setEnabled(trigger.enabled); + } else { + setName(''); + setScriptId(preset?.scriptId ?? null); + setWhen(preset?.triggerType ?? 'scheduled'); + setCadence(defaultCadence()); + setTarget(preset?.target ?? null); + setEnabled(true); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [open, trigger]); + + // A trigger without an id is a copy to create (Duplicate), not one to update. + const editing = Boolean(trigger?.id); + const script = scripts?.find((s) => s.id === scriptId) ?? null; + const parameters = useMemo(() => script?.parameters ?? [], [script]); + + // Saved arguments only apply to the script they were captured for. + useEffect(() => { + setDraft(initialDraft(parameters, trigger && trigger.scriptId === scriptId ? trigger.arguments : undefined)); + }, [parameters, trigger, scriptId]); + + const argumentErrors = validateArguments(parameters, draft); + const timingProblem = when === 'scheduled' ? cadenceProblem(cadence, enabled) : null; + const ready = Boolean(script && target) && !timingProblem; + + const save = async () => { + if (!script || !target) return; + if (Object.keys(argumentErrors).length > 0) { + setShowErrors(true); + return; + } + setBusy(true); + setError(''); + try { + const body = { + name: name.trim() || undefined, + scriptId: script.id, + triggerType: when, + enabled, + clientId: target.kind === 'device' ? target.id : undefined, + groupId: target.kind === 'group' ? target.id : undefined, + arguments: parameters.length > 0 ? collectArguments(parameters, draft) : undefined, + ...(when === 'scheduled' ? cadenceBody(cadence) : {}) + }; + if (editing) await api.updateTrigger(trigger!.id, body); + else await api.createTrigger(body); + await mutate(keys.triggers); + enqueueSnackbar(editing ? 'Schedule saved.' : 'Schedule created.', { variant: 'success' }); + onClose(); + } catch (e) { + setError(errorMessage(e, 'The schedule could not be saved.')); + } finally { + setBusy(false); + } + }; + + return ( + undefined : onClose} + title={editing ? 'Edit Schedule' : 'New Schedule'} + subtitle="Run a script on a cadence or on device events." + actions={ + <> + + + + } + > + + setName(e.target.value)} + helperText="Defaults to the script name." + slotProps={{ htmlInput: { maxLength: 200 } }} + /> + + setScriptId(chosen?.id ?? null)} + getOptionLabel={(s) => s.name} + isOptionEqualToValue={(a, b) => a.id === b.id} + renderInput={(params) => } + /> + + + + When + + + value && setWhen(value)}> + On a Schedule + On Enrollment + On Agent Ready + + + + {when === 'scheduled' && } + + + + + A device, a group or All Devices. + + + + + {parameters.length > 0 && ( + <> + + Arguments + + + )} + + setEnabled(e.target.checked)} />} label="Enabled" /> + + {error && {error}} + + + ); +} diff --git a/src/WebUI/src/sections/schedules/ScheduleTable.tsx b/src/WebUI/src/sections/schedules/ScheduleTable.tsx new file mode 100644 index 0000000..9e63df6 --- /dev/null +++ b/src/WebUI/src/sections/schedules/ScheduleTable.tsx @@ -0,0 +1,318 @@ +import { MouseEvent, ReactNode, useState } from 'react'; +import { Link as RouterLink } from 'react-router-dom'; + +// material-ui +import Link from '@mui/material/Link'; +import Stack from '@mui/material/Stack'; +import Switch from '@mui/material/Switch'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; + +// third-party +import { enqueueSnackbar } from 'notistack'; +import { mutate } from 'swr'; + +// project imports +import ActionMenu, { MenuEntry } from 'components/ActionMenu'; +import ConfirmDialog from 'components/ConfirmDialog'; +import DataTable, { Column } from 'components/DataTable'; +import { RelativeTime } from 'components/DateTime'; +import EmptyState from 'components/EmptyState'; +import IconButton from 'components/@extended/IconButton'; +import useAutomation from 'hooks/useAutomation'; +import useSession from 'hooks/useSession'; +import { api, errorMessage, keys } from 'api/client'; +import { scheduleCadence } from 'utils/cron'; +import type { ScriptTriggerDto } from 'api/types'; + +// assets +import CalendarOutlined from '@ant-design/icons/CalendarOutlined'; +import CopyOutlined from '@ant-design/icons/CopyOutlined'; +import DeleteOutlined from '@ant-design/icons/DeleteOutlined'; +import EditOutlined from '@ant-design/icons/EditOutlined'; +import MoreOutlined from '@ant-design/icons/MoreOutlined'; +import PauseCircleOutlined from '@ant-design/icons/PauseCircleOutlined'; +import PlayCircleOutlined from '@ant-design/icons/PlayCircleOutlined'; + +const EVENT_LABELS = { onRegistration: 'On Enrollment', onAgentReady: 'On Agent Ready', scheduled: 'Scheduled' } as const; + +export const whenText = (t: ScriptTriggerDto) => (t.triggerType === 'scheduled' ? scheduleCadence(t) : EVENT_LABELS[t.triggerType]); + +export const targetText = (t: ScriptTriggerDto) => + t.clientId ? (t.clientHostname ?? t.clientId) : t.groupId ? (t.groupName ?? '(deleted group)') : 'All Devices'; + +interface Gates { + manage?: string; + run?: string; +} + +/** The row "…" menu as data: who may do what, and why not. */ +export function scheduleMenu( + trigger: ScriptTriggerDto, + gates: Gates, + handlers: { edit: () => void; runNow: () => void; duplicate: () => void; toggle: () => void; remove: () => void } +): MenuEntry[] { + return [ + { kind: 'item', id: 'edit', label: 'Edit…', icon: , disabledReason: gates.manage, onSelect: handlers.edit }, + { kind: 'item', id: 'run', label: 'Run Now', icon: , disabledReason: gates.run, onSelect: handlers.runNow }, + { + kind: 'item', + id: 'duplicate', + label: 'Duplicate…', + icon: , + disabledReason: gates.manage, + onSelect: handlers.duplicate + }, + { + kind: 'item', + id: 'toggle', + label: trigger.enabled ? 'Disable' : 'Enable', + icon: trigger.enabled ? : , + disabledReason: gates.manage, + onSelect: handlers.toggle + }, + { kind: 'divider' }, + { + kind: 'item', + id: 'delete', + label: 'Delete…', + icon: , + destructive: true, + disabledReason: gates.manage, + onSelect: handlers.remove + } + ]; +} + +interface Props { + triggers: ScriptTriggerDto[] | undefined; + loading?: boolean; + error?: string; + /** Omit columns that are fixed by the surrounding page. */ + hideScript?: boolean; + hideTarget?: boolean; + toolbar?: ReactNode; + empty?: ReactNode; +} + +// ==============================|| SCHEDULE TABLE ||============================== // + +export default function ScheduleTable({ triggers, loading, error, hideScript, hideTarget, toolbar, empty }: Props) { + const { can } = useSession(); + const { openSchedule } = useAutomation(); + const [menu, setMenu] = useState<{ anchor: HTMLElement; trigger: ScriptTriggerDto } | null>(null); + const [deleting, setDeleting] = useState(null); + + const gates: Gates = { + manage: can('automation.manage') ? undefined : 'Needs the Manage Automation permission.', + run: can('jobs.run') ? undefined : 'Needs the Run Jobs permission.' + }; + + const refresh = () => mutate(keys.triggers); + + const toggle = async (trigger: ScriptTriggerDto) => { + try { + await api.setTriggerEnabled(trigger.id, !trigger.enabled); + await refresh(); + } catch (e) { + enqueueSnackbar(errorMessage(e), { variant: 'error' }); + } + }; + + const runNow = async (trigger: ScriptTriggerDto) => { + try { + const result = await api.runTrigger(trigger.id); + await refresh(); + enqueueSnackbar(`${trigger.name ?? trigger.scriptName}: ${result.message}`, { variant: result.queued > 0 ? 'success' : 'warning' }); + } catch (e) { + enqueueSnackbar(errorMessage(e), { variant: 'error' }); + } + }; + + const duplicate = (trigger: ScriptTriggerDto) => + openSchedule({ + trigger: { ...trigger, id: '', name: trigger.name ? `${trigger.name} (copy)` : undefined }, + preset: undefined + }); + + const columns: Column[] = [ + { + id: 'name', + header: hideScript ? 'Schedule' : 'Schedule / Script', + sortValue: (t) => t.name ?? t.scriptName, + cell: (t) => ( + + + {t.name ?? t.scriptName} + + {!hideScript && t.name && ( + e.stopPropagation()} + > + {t.scriptName} + + )} + + ) + }, + { + id: 'when', + header: 'When', + sortValue: (t) => whenText(t), + cell: (t) => {whenText(t)} + }, + ...(!hideTarget + ? [ + { + id: 'target', + header: 'Target', + sortValue: (t: ScriptTriggerDto) => targetText(t), + cell: (t: ScriptTriggerDto) => + t.clientId ? ( + e.stopPropagation()}> + {targetText(t)} + + ) : t.groupId ? ( + e.stopPropagation()}> + {targetText(t)} + + ) : ( + {targetText(t)} + ) + } satisfies Column + ] + : []), + { + id: 'next', + header: 'Next Run', + nowrap: true, + sortValue: (t) => (t.enabled ? t.nextRunUtc : undefined), + cell: (t) => + t.triggerType !== 'scheduled' ? ( + + On event + + ) : ( + + ) + }, + { + id: 'last', + header: 'Last Run', + sortValue: (t) => t.lastRunUtc, + cell: (t) => ( + + + {t.lastResult && ( + + {t.lastRunId ? ( + e.stopPropagation()} + > + {t.lastResult} + + ) : ( + + {t.lastResult} + + )} + + )} + + ) + }, + { + id: 'enabled', + header: 'Enabled', + width: 90, + sortValue: (t) => t.enabled, + cell: (t) => ( + + + e.stopPropagation()} + onChange={() => void toggle(t)} + slotProps={{ input: { 'aria-label': `${t.enabled ? 'Disable' : 'Enable'} ${t.name ?? t.scriptName}` } }} + /> + + + ) + }, + { + id: 'actions', + header: '', + width: 56, + align: 'right', + cell: (t) => ( + ) => { + e.stopPropagation(); + setMenu({ anchor: e.currentTarget, trigger: t }); + }} + > + + + ) + } + ]; + + return ( + <> + t.id} + loading={loading} + error={error} + toolbar={toolbar} + defaultSort={{ id: 'next', direction: 'asc' }} + onRowClick={gates.manage ? undefined : (t) => openSchedule({ trigger: t })} + empty={ + empty ?? ( + } title="No Schedules" detail="Run a script on a cadence or on device events." /> + ) + } + /> + {menu && ( + setMenu(null)} + entries={scheduleMenu(menu.trigger, gates, { + edit: () => openSchedule({ trigger: menu.trigger }), + runNow: () => void runNow(menu.trigger), + duplicate: () => duplicate(menu.trigger), + toggle: () => void toggle(menu.trigger), + remove: () => setDeleting(menu.trigger) + })} + /> + )} + setDeleting(null)} + onConfirm={async () => { + await api.deleteTrigger(deleting!.id); + await refresh(); + }} + /> + + ); +} diff --git a/src/WebUI/src/sections/scripts/ExecutionsPanel.tsx b/src/WebUI/src/sections/scripts/ExecutionsPanel.tsx new file mode 100644 index 0000000..08294e4 --- /dev/null +++ b/src/WebUI/src/sections/scripts/ExecutionsPanel.tsx @@ -0,0 +1,136 @@ +import { useCallback, useState } from 'react'; +import { Link as RouterLink, useSearchParams } from 'react-router-dom'; + +// material-ui +import Breadcrumbs from '@mui/material/Breadcrumbs'; +import Button from '@mui/material/Button'; +import Link from '@mui/material/Link'; +import Stack from '@mui/material/Stack'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; + +// project imports +import IconButton from 'components/@extended/IconButton'; +import DataTable from 'components/DataTable'; +import EmptyState from 'components/EmptyState'; +import JobOutputDrawer from 'sections/jobs/JobOutputDrawer'; +import RunProgress, { useRun } from 'sections/runs/RunProgress'; +import { runColumns } from 'sections/runs/RecentRuns'; +import { downloads, keys } from 'api/client'; +import useApi from 'hooks/useApi'; +import useLiveRefresh from 'hooks/useLiveRefresh'; +import { formatAbsolute } from 'utils/format'; + +// assets +import DownloadOutlined from '@ant-design/icons/DownloadOutlined'; +import ExpandOutlined from '@ant-design/icons/ExpandOutlined'; +import HistoryOutlined from '@ant-design/icons/HistoryOutlined'; +import ReloadOutlined from '@ant-design/icons/ReloadOutlined'; +import RightOutlined from '@ant-design/icons/RightOutlined'; + +// types +import type { ExecutionSummaryDto } from 'api/types'; + +const columns = runColumns(false); +const summaryId = (ex: ExecutionSummaryDto) => ex.runId; + +// ==============================|| SCRIPT EXECUTIONS (RUNS → TARGETS → OUTPUT) ||============================== // + +export default function ExecutionsPanel({ scriptId }: { scriptId: string }) { + const [params, setParams] = useSearchParams(); + const runId = params.get('run'); + const [jobId, setJobId] = useState(null); + + const executions = useApi(keys.scriptExecutions(scriptId)); + const execution = useRun(runId); + const run = execution.data; + const { mutate: mutateExecutions } = executions; + const refresh = useCallback(() => void mutateExecutions(), [mutateExecutions]); + useLiveRefresh(refresh, (event) => Boolean(event.jobId)); + + const openRun = (id: string | null) => + setParams((current) => { + const next = new URLSearchParams(current); + if (id) next.set('run', id); + else next.delete('run'); + return next; + }); + + return ( + <> + {runId ? ( + + } aria-label="Execution"> + openRun(null)}> + Executions + + + {run ? formatAbsolute(run.startedUtc) : 'Run'} + + + + {run?.requestedBy && ( + + by {run.requestedBy} + + )} + + + + + + + } + /> + ) : ( + openRun(ex.runId)} + defaultSort={{ id: 'started', direction: 'desc' }} + empty={} title="No Executions Yet" />} + toolbar={ + + + void mutateExecutions()} aria-label="Refresh executions"> + + + + + } + /> + )} + setJobId(null)} /> + + ); +} diff --git a/src/WebUI/src/sections/scripts/FileBindingsEditor.tsx b/src/WebUI/src/sections/scripts/FileBindingsEditor.tsx new file mode 100644 index 0000000..04bec34 --- /dev/null +++ b/src/WebUI/src/sections/scripts/FileBindingsEditor.tsx @@ -0,0 +1,184 @@ +// material-ui +import Alert from '@mui/material/Alert'; +import Button from '@mui/material/Button'; +import Checkbox from '@mui/material/Checkbox'; +import FormControlLabel from '@mui/material/FormControlLabel'; +import Grid from '@mui/material/Grid'; +import Stack from '@mui/material/Stack'; +import TextField from '@mui/material/TextField'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; + +// project imports +import EmptyState from 'components/EmptyState'; +import HoverHelp from 'components/HoverHelp'; +import IconButton from 'components/@extended/IconButton'; +import { isCompleteFile } from 'sections/scripts/scriptModel'; + +// assets +import CloudDownloadOutlined from '@ant-design/icons/CloudDownloadOutlined'; +import DeleteOutlined from '@ant-design/icons/DeleteOutlined'; +import PlusOutlined from '@ant-design/icons/PlusOutlined'; + +// types +import type { ScriptFileBinding } from 'api/types'; + +interface Props { + bindings: ScriptFileBinding[]; + onChange: (bindings: ScriptFileBinding[]) => void; + /** Per-row validation messages (see validateDraft). */ + problems: (string | undefined)[]; + readOnly?: boolean; +} + +/** + * A directory delivery unpacks a tree INTO the destination — a leaf file + * path (extension on the last segment) is a mistake the server rejects. + */ +const looksLikeFile = (path: string) => + /\.[A-Za-z][A-Za-z0-9]{0,6}$/.test( + path + .replace(/[\\/]+$/, '') + .split(/[\\/]/) + .pop() ?? '' + ); + +const mono = { style: { fontFamily: 'var(--font-mono)' } }; + +// ==============================|| FILE BINDINGS EDITOR ||============================== // + +export default function FileBindingsEditor({ bindings, onChange, problems, readOnly }: Props) { + const update = (index: number, patch: Partial) => + onChange(bindings.map((b, i) => (i === index ? { ...b, ...patch } : b))); + const add = () => onChange([...bindings, { name: '', objectKey: '', destinationPath: '', directory: false, continueOnFailure: false }]); + const remove = (index: number) => onChange(bindings.filter((_, i) => i !== index)); + const incomplete = bindings.some((b) => !isCompleteFile(b)); + + const addButton = ( + + ); + + return ( + + + Downloaded to the device before the script runs. + + + + {bindings.length === 0 ? ( + } + title="No Files" + detail="Deliver S3 objects to the device." + action={readOnly ? undefined : addButton} + /> + ) : ( + <> + {bindings.map((binding, i) => ( + + + + update(i, { name: e.target.value })} + error={Boolean(problems[i])} + helperText={problems[i]} + disabled={readOnly} + slotProps={{ htmlInput: mono }} + /> + + + update(i, { objectKey: e.target.value })} + disabled={readOnly} + slotProps={{ htmlInput: mono }} + /> + + + update(i, { destinationPath: e.target.value })} + disabled={readOnly} + slotProps={{ htmlInput: mono }} + /> + + + + + remove(i)} disabled={readOnly} aria-label="Remove file binding"> + + + + + + + + update(i, { directory: e.target.checked })} + /> + } + label={ + + Directory + + + } + /> + update(i, { continueOnFailure: e.target.checked })} + /> + } + label={ + + Continue on Failure + + + } + /> + + {binding.directory && looksLikeFile(binding.destinationPath) && ( + + Give a directory, not a file path. + + + )} + + ))} + {incomplete && ( + + Incomplete rows are skipped when saving. + + + )} + {!readOnly &&
    {addButton}
    } + + )} +
    + ); +} diff --git a/src/WebUI/src/sections/scripts/FunctionModulesPicker.tsx b/src/WebUI/src/sections/scripts/FunctionModulesPicker.tsx new file mode 100644 index 0000000..14b4ac8 --- /dev/null +++ b/src/WebUI/src/sections/scripts/FunctionModulesPicker.tsx @@ -0,0 +1,176 @@ +import { useMemo } from 'react'; +import { Link as RouterLink } from 'react-router-dom'; + +// material-ui +import Alert from '@mui/material/Alert'; +import Autocomplete from '@mui/material/Autocomplete'; +import Link from '@mui/material/Link'; +import List from '@mui/material/List'; +import ListItem from '@mui/material/ListItem'; +import ListItemText from '@mui/material/ListItemText'; +import Skeleton from '@mui/material/Skeleton'; +import Stack from '@mui/material/Stack'; +import TextField from '@mui/material/TextField'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; + +// project imports +import EmptyState from 'components/EmptyState'; +import HoverHelp from 'components/HoverHelp'; +import IconButton from 'components/@extended/IconButton'; +import { errorMessage, keys } from 'api/client'; +import useApi from 'hooks/useApi'; + +// assets +import ArrowDownOutlined from '@ant-design/icons/ArrowDownOutlined'; +import ArrowUpOutlined from '@ant-design/icons/ArrowUpOutlined'; +import CloseOutlined from '@ant-design/icons/CloseOutlined'; +import FunctionOutlined from '@ant-design/icons/FunctionOutlined'; + +// types +import type { FunctionModuleDto } from 'api/types'; + +interface Props { + /** Attached modules, in load order. */ + selectedIds: string[]; + onChange: (ids: string[]) => void; + readOnly?: boolean; +} + +// ==============================|| FUNCTION MODULES PICKER ||============================== // + +export default function FunctionModulesPicker({ selectedIds, onChange, readOnly }: Props) { + const { data: modules, error, loading } = useApi(keys.functions); + const byId = useMemo(() => new Map((modules ?? []).map((m) => [m.id, m])), [modules]); + const available = useMemo(() => (modules ?? []).filter((m) => !selectedIds.includes(m.id)), [modules, selectedIds]); + + const move = (index: number, delta: number) => { + const next = [...selectedIds]; + [next[index], next[index + delta]] = [next[index + delta], next[index]]; + onChange(next); + }; + + if (loading) return ; + if (error) return {errorMessage(error, 'Functions could not be loaded.')}; + + if (!modules || modules.length === 0) { + return ( + } + title="No Functions Yet" + detail={ + <> + Create reusable{' '} + + Functions + {' '} + to share code between scripts. + + } + /> + ); + } + + return ( + + + Attached functions load before the script, in the order listed. + + + + {selectedIds.length === 0 ? ( + } title="No Functions Attached" detail="Attach one below." /> + ) : ( + + {selectedIds.map((id, index) => { + const module = byId.get(id); + return ( + + + + move(index, -1)} + aria-label="Move up" + > + + + + + + + move(index, 1)} + aria-label="Move down" + > + + + + + + onChange(selectedIds.filter((x) => x !== id))} + aria-label="Detach" + > + + + + + ) + } + > + + {index + 1}. + + + + ); + })} + + )} + + {!readOnly && available.length > 0 && ( + m.name} + onChange={(_, module) => module && onChange([...selectedIds, module.id])} + renderOption={({ key, ...props }, m) => ( +
  • + + {m.name} + {m.description && ( + + {m.description} + + )} + +
  • + )} + renderInput={(params) => } + sx={{ maxWidth: 420 }} + /> + )} + + ); +} diff --git a/src/WebUI/src/sections/scripts/ParameterSchemaEditor.tsx b/src/WebUI/src/sections/scripts/ParameterSchemaEditor.tsx new file mode 100644 index 0000000..f77311d --- /dev/null +++ b/src/WebUI/src/sections/scripts/ParameterSchemaEditor.tsx @@ -0,0 +1,212 @@ +// material-ui +import Button from '@mui/material/Button'; +import Checkbox from '@mui/material/Checkbox'; +import MenuItem from '@mui/material/MenuItem'; +import Stack from '@mui/material/Stack'; +import Table from '@mui/material/Table'; +import TableBody from '@mui/material/TableBody'; +import TableCell from '@mui/material/TableCell'; +import TableContainer from '@mui/material/TableContainer'; +import TableHead from '@mui/material/TableHead'; +import TableRow from '@mui/material/TableRow'; +import TextField from '@mui/material/TextField'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; + +// project imports +import EmptyState from 'components/EmptyState'; +import HoverHelp from 'components/HoverHelp'; +import IconButton from 'components/@extended/IconButton'; + +// assets +import DeleteOutlined from '@ant-design/icons/DeleteOutlined'; +import PlusOutlined from '@ant-design/icons/PlusOutlined'; +import SlidersOutlined from '@ant-design/icons/SlidersOutlined'; + +// types +import type { PrimitiveType, ScriptParameter, ScriptParameterType } from 'api/types'; + +const PARAM_TYPES: ScriptParameterType[] = ['string', 'number', 'boolean', 'array', 'hashtable']; +const PRIMITIVES: PrimitiveType[] = ['string', 'number', 'boolean']; + +/** Expansion only applies where string values can occur. */ +function canExpand(p: ScriptParameter): boolean { + return p.type === 'string' || p.type === 'hashtable' || (p.type === 'array' && p.elementType !== 'number' && p.elementType !== 'boolean'); +} + +interface Props { + parameters: ScriptParameter[]; + onChange: (parameters: ScriptParameter[]) => void; + /** Per-row validation messages (see validateDraft). */ + problems: (string | undefined)[]; + readOnly?: boolean; +} + +// ==============================|| PARAMETER SCHEMA EDITOR ||============================== // + +export default function ParameterSchemaEditor({ parameters, onChange, problems, readOnly }: Props) { + const update = (index: number, patch: Partial) => + onChange(parameters.map((p, i) => (i === index ? { ...p, ...patch } : p))); + const add = () => onChange([...parameters, { name: '', type: 'string', required: false, expansion: 'auto' }]); + const remove = (index: number) => onChange(parameters.filter((_, i) => i !== index)); + + const addButton = ( + + ); + + if (parameters.length === 0) { + return ( + } + title="No Parameters" + detail="Typed inputs for each run." + action={readOnly ? undefined : addButton} + /> + ); + } + + return ( + + + + + + Name + Type + + Items + + + Description + + Literal + + + + Required + + + + + + {parameters.map((param, i) => ( + + + update(i, { name: e.target.value })} + error={Boolean(problems[i])} + helperText={problems[i]} + disabled={readOnly} + slotProps={{ htmlInput: { 'aria-label': 'Parameter name', style: { fontFamily: 'var(--font-mono)' } } }} + /> + + + { + const type = e.target.value as ScriptParameterType; + update(i, { type, elementType: type === 'array' ? param.elementType : undefined }); + }} + disabled={readOnly} + slotProps={{ htmlInput: { 'aria-label': 'Parameter type' } }} + > + {PARAM_TYPES.map((t) => ( + + {t} + + ))} + + + + {param.type === 'array' ? ( + update(i, { elementType: (e.target.value || undefined) as PrimitiveType | undefined })} + disabled={readOnly} + slotProps={{ htmlInput: { 'aria-label': 'Element type' }, select: { displayEmpty: true } }} + > + + + Any + + + {PRIMITIVES.map((p) => ( + + {p} + + ))} + + ) : ( + + {param.type === 'hashtable' ? 'Typed per entry' : '—'} + + )} + + + update(i, { description: e.target.value || undefined })} + disabled={readOnly} + slotProps={{ htmlInput: { 'aria-label': 'Description' } }} + /> + + + {canExpand(param) ? ( + + update(i, { expansion: e.target.checked ? 'literal' : 'auto' })} + disabled={readOnly} + slotProps={{ input: { 'aria-label': 'Literal value' } }} + /> + + ) : ( + + — + + )} + + + update(i, { required: e.target.checked })} + disabled={readOnly} + slotProps={{ input: { 'aria-label': 'Required' } }} + /> + + + + + remove(i)} disabled={readOnly} aria-label="Remove parameter"> + + + + + + + ))} + +
    +
    + {!readOnly &&
    {addButton}
    } +
    + ); +} diff --git a/src/WebUI/src/sections/scripts/SecretBindingsEditor.tsx b/src/WebUI/src/sections/scripts/SecretBindingsEditor.tsx new file mode 100644 index 0000000..098a21e --- /dev/null +++ b/src/WebUI/src/sections/scripts/SecretBindingsEditor.tsx @@ -0,0 +1,412 @@ +import { Fragment, useCallback, useEffect, useRef, useState } from 'react'; +import { Link as RouterLink } from 'react-router-dom'; + +// material-ui +import Alert from '@mui/material/Alert'; +import Button from '@mui/material/Button'; +import InputAdornment from '@mui/material/InputAdornment'; +import Link from '@mui/material/Link'; +import MenuItem from '@mui/material/MenuItem'; +import Skeleton from '@mui/material/Skeleton'; +import Stack from '@mui/material/Stack'; +import Table from '@mui/material/Table'; +import TableBody from '@mui/material/TableBody'; +import TableCell from '@mui/material/TableCell'; +import TableContainer from '@mui/material/TableContainer'; +import TableHead from '@mui/material/TableHead'; +import TableRow from '@mui/material/TableRow'; +import TextField from '@mui/material/TextField'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; + +// project imports +import EmptyState from 'components/EmptyState'; +import HoverHelp from 'components/HoverHelp'; +import IconButton from 'components/@extended/IconButton'; +import { api, errorMessage } from 'api/client'; +import useApi from 'hooks/useApi'; +import { isCompleteSecret } from 'sections/scripts/scriptModel'; + +// assets +import ArrowUpOutlined from '@ant-design/icons/ArrowUpOutlined'; +import DeleteOutlined from '@ant-design/icons/DeleteOutlined'; +import EditOutlined from '@ant-design/icons/EditOutlined'; +import FolderOutlined from '@ant-design/icons/FolderOutlined'; +import KeyOutlined from '@ant-design/icons/KeyOutlined'; +import PlusOutlined from '@ant-design/icons/PlusOutlined'; +import UnorderedListOutlined from '@ant-design/icons/UnorderedListOutlined'; + +// types +import type { SecretBinding, SecretsProviderDto, SecretsProvidersResponse } from 'api/types'; + +/** SWR key for the providers list (shared with the settings page's reads of the same path). */ +const PROVIDERS_KEY = '/api/secrets/providers'; + +/** Folder paths and secret names for one provider + path; values never reach the browser — names only. */ +type Listing = { folders: string[]; names: string[] } | { error: string }; + +const cacheKey = (providerId: string, path: string) => `${providerId}|${path}`; + +function defaultPath(providers: SecretsProviderDto[], providerId: string): string { + return providers.find((p) => p.id === providerId)?.config?.path || '/'; +} + +function parentOf(path: string, root: string): string | null { + if (path === root || path === '/') return null; + const trimmed = path.replace(/\/+$/, ''); + const parent = trimmed.slice(0, trimmed.lastIndexOf('/')) || '/'; + // Never browse above the provider's default path. + return parent.length >= root.length || root === '/' ? parent : null; +} + +const mono = { style: { fontFamily: 'var(--font-mono)' } }; + +interface Props { + bindings: SecretBinding[]; + onChange: (bindings: SecretBinding[]) => void; + variableName: string; + onVariableNameChange: (name: string) => void; + /** Per-row validation messages, plus one for the variable name (see validateDraft). */ + problems: (string | undefined)[]; + variableProblem?: string; + readOnly?: boolean; +} + +// ==============================|| SECRET BINDINGS EDITOR ||============================== // + +export default function SecretBindingsEditor({ + bindings, + onChange, + variableName, + onVariableNameChange, + problems, + variableProblem, + readOnly +}: Props) { + const { data, error, loading } = useApi(PROVIDERS_KEY); + const providers = data?.providers; + const [listings, setListings] = useState>({}); + const requested = useRef(new Set()); + // Rows that chose free-text secret entry. + const [manual, setManual] = useState>(new Set()); + + const browse = useCallback((providerId: string, path: string) => { + const key = cacheKey(providerId, path); + if (!providerId || requested.current.has(key)) return; + requested.current.add(key); + Promise.all([api.secretFolders(providerId, path), api.secretNames(providerId, path)]) + .then(([folders, names]) => setListings((current) => ({ ...current, [key]: { folders, names } }))) + .catch((e) => setListings((current) => ({ ...current, [key]: { error: errorMessage(e, 'Listing failed.') } }))); + }, []); + + const effectivePath = (binding: SecretBinding) => binding.path || defaultPath(providers ?? [], binding.providerId); + + // List whatever each row is looking at (once per provider + path). + useEffect(() => { + if (!providers) return; + for (const binding of bindings) browse(binding.providerId, binding.path || defaultPath(providers, binding.providerId)); + }, [bindings, providers, browse]); + + const update = (index: number, patch: Partial) => onChange(bindings.map((b, i) => (i === index ? { ...b, ...patch } : b))); + + const add = () => { + const providerId = providers?.[0]?.id ?? ''; + onChange([ + ...bindings, + { name: '', providerId, secretName: '', path: providerId ? defaultPath(providers ?? [], providerId) : undefined } + ]); + }; + + const remove = (index: number) => { + onChange(bindings.filter((_, i) => i !== index)); + setManual((current) => new Set([...current].filter((i) => i !== index).map((i) => (i > index ? i - 1 : i)))); + }; + + const setManualRow = (index: number, on: boolean) => + setManual((current) => { + const next = new Set(current); + if (on) next.add(index); + else next.delete(index); + return next; + }); + + if (loading) return ; + if (error) return {errorMessage(error, 'Secrets providers could not be loaded.')}; + + if (!providers || providers.length === 0) { + return ( + } + title="No Secrets Providers" + detail={ + <> + Add one under{' '} + + Settings → Secrets Providers + {' '} + first. + + } + /> + ); + } + + const effectiveVar = variableName.trim() || 'Secrets'; + const incomplete = bindings.some((b) => !isCompleteSecret(b) && (b.name.trim() || b.secretName.trim())); + + const addButton = ( + + ); + + return ( + + + onVariableNameChange(e.target.value)} + error={Boolean(variableProblem)} + helperText={variableProblem} + disabled={readOnly} + sx={{ width: 200, flexShrink: 0 }} + slotProps={{ + input: { startAdornment: $ }, + htmlInput: mono + }} + /> + + Use{' '} + + ${effectiveVar}.{bindings[0]?.name || 'SecretName'} + {' '} + in the script. + + + + + {bindings.length === 0 ? ( + } + title="No Secrets" + detail="Bind vault secrets to keys." + action={readOnly ? undefined : addButton} + /> + ) : ( + <> + + + + + Key (${effectiveVar}.…) + Provider + Path + Secret + + + + + {bindings.map((binding, i) => { + const path = effectivePath(binding); + const root = defaultPath(providers, binding.providerId); + const parent = parentOf(path, root); + const listing = listings[cacheKey(binding.providerId, path)]; + const failed = listing && 'error' in listing ? listing.error : undefined; + const folders = listing && 'folders' in listing ? listing.folders : []; + const names = listing && 'names' in listing ? listing.names : undefined; + const typed = manual.has(i) || Boolean(failed) || (names !== undefined && names.length === 0); + const knownProvider = providers.some((p) => p.id === binding.providerId); + + return ( + + + + update(i, { name: e.target.value })} + error={Boolean(problems[i])} + helperText={problems[i]} + disabled={readOnly} + slotProps={{ htmlInput: { ...mono, 'aria-label': 'Dictionary key' } }} + /> + + + { + const providerId = e.target.value; + update(i, { providerId, path: defaultPath(providers, providerId), secretName: '' }); + }} + disabled={readOnly} + slotProps={{ htmlInput: { 'aria-label': 'Provider' } }} + > + {!knownProvider && ( + + (deleted provider) + + )} + {providers.map((provider) => ( + + {provider.name} + + ))} + + + + {failed ? ( + update(i, { path: e.target.value })} + disabled={readOnly} + slotProps={{ htmlInput: { ...mono, 'aria-label': 'Secret path' } }} + /> + ) : ( + + update(i, { path: e.target.value, secretName: '' })} + disabled={readOnly} + slotProps={{ + htmlInput: { 'aria-label': 'Secret path' }, + select: { sx: { fontFamily: 'var(--font-mono)' } } + }} + > + {path} + {parent !== null && ( + + + {parent} + + )} + {folders + .filter((folder) => folder !== path && folder !== parent) + .map((folder) => ( + + + {folder} + + ))} + + + )} + + + + {typed ? ( + update(i, { secretName: e.target.value })} + disabled={readOnly} + slotProps={{ htmlInput: { ...mono, 'aria-label': 'Secret name' } }} + /> + ) : names === undefined ? ( + + ) : ( + update(i, { secretName: e.target.value })} + disabled={readOnly} + slotProps={{ htmlInput: { 'aria-label': 'Secret name' }, select: { displayEmpty: true } }} + > + + + Select… + + + {binding.secretName && !names.includes(binding.secretName) && ( + {binding.secretName} + )} + {names.map((name) => ( + + {name} + + ))} + + )} + {typed && names && names.length > 0 && ( + + + setManualRow(i, false)} disabled={readOnly}> + + + + + )} + {!typed && names !== undefined && ( + + + setManualRow(i, true)} disabled={readOnly}> + + + + + )} + + + + + + remove(i)} + disabled={readOnly} + aria-label="Remove secret" + > + + + + + + + {failed && ( + + + + Listing failed; type the path and secret name. + + + + + )} + + ); + })} + +
    +
    + {incomplete && ( + + Incomplete rows are skipped when saving. + + + )} + {!readOnly &&
    {addButton}
    } + + )} +
    + ); +} diff --git a/src/WebUI/src/sections/scripts/scriptMenu.tsx b/src/WebUI/src/sections/scripts/scriptMenu.tsx new file mode 100644 index 0000000..259fc0d --- /dev/null +++ b/src/WebUI/src/sections/scripts/scriptMenu.tsx @@ -0,0 +1,65 @@ +// project imports +import type { MenuEntry } from 'components/ActionMenu'; +import useSession from 'hooks/useSession'; + +// assets +import CalendarOutlined from '@ant-design/icons/CalendarOutlined'; +import CopyOutlined from '@ant-design/icons/CopyOutlined'; +import DeleteOutlined from '@ant-design/icons/DeleteOutlined'; +import EditOutlined from '@ant-design/icons/EditOutlined'; +import PlayCircleOutlined from '@ant-design/icons/PlayCircleOutlined'; + +export interface ScriptGates { + manage?: string; + run?: string; + automate?: string; +} + +/** Why each script action is unavailable to this session (undefined when allowed). */ +export function useScriptGates(): ScriptGates { + const { can } = useSession(); + return { + manage: can('scripts.manage') ? undefined : 'Needs the Manage Scripts permission.', + run: can('jobs.run') ? undefined : 'Needs the Run Jobs permission.', + automate: can('automation.manage') ? undefined : 'Needs the Manage Automation permission.' + }; +} + +/** The script "…" menu as data; `open` is omitted on the script's own page. */ +export function scriptMenu( + gates: ScriptGates, + handlers: { open?: () => void; run: () => void; schedule: () => void; duplicate: () => void; remove: () => void } +): MenuEntry[] { + return [ + ...(handlers.open + ? [{ kind: 'item', id: 'open', label: 'Open', icon: , onSelect: handlers.open } satisfies MenuEntry] + : []), + { kind: 'item', id: 'run', label: 'Run…', icon: , disabledReason: gates.run, onSelect: handlers.run }, + { + kind: 'item', + id: 'schedule', + label: 'Schedule…', + icon: , + disabledReason: gates.automate, + onSelect: handlers.schedule + }, + { kind: 'divider' }, + { + kind: 'item', + id: 'duplicate', + label: 'Duplicate', + icon: , + disabledReason: gates.manage, + onSelect: handlers.duplicate + }, + { + kind: 'item', + id: 'delete', + label: 'Delete…', + icon: , + destructive: true, + disabledReason: gates.manage, + onSelect: handlers.remove + } + ]; +} diff --git a/src/WebUI/src/sections/scripts/scriptModel.ts b/src/WebUI/src/sections/scripts/scriptModel.ts new file mode 100644 index 0000000..d68090c --- /dev/null +++ b/src/WebUI/src/sections/scripts/scriptModel.ts @@ -0,0 +1,194 @@ +// project imports +import type { SaveScriptBody } from 'api/client'; +import type { ScriptDto, ScriptFileBinding, ScriptParameter, SecretBinding } from 'api/types'; +import type { CodeLanguage } from 'components/CodeEditor'; + +export type ScriptEngine = 'PowerShell' | 'WindowsPowerShell' | 'Bash'; + +export const ENGINES: { value: ScriptEngine; label: string; hint: string; color: 'primary' | 'info' | 'warning' }[] = [ + { + value: 'PowerShell', + label: 'PowerShell 7', + hint: 'Runs inside the agent — full progress, parameters and secrets on every platform.', + color: 'primary' + }, + { + value: 'WindowsPowerShell', + label: 'PowerShell 5', + hint: 'Runs via powershell.exe on Windows devices. Near parity; live progress bars are not captured.', + color: 'info' + }, + { + value: 'Bash', + label: 'Bash', + hint: 'Runs on Linux/macOS devices (or Windows with Git Bash). Parameters and secrets arrive as environment variables.', + color: 'warning' + } +]; + +/** The stored `language` as an engine; anything unknown is the default PowerShell 7. */ +export const engineOf = (language?: string): ScriptEngine => + language === 'WindowsPowerShell' || language === 'Bash' ? language : 'PowerShell'; + +export const engineInfo = (engine: ScriptEngine) => ENGINES.find((e) => e.value === engine) ?? ENGINES[0]; + +export const editorLanguage = (engine: ScriptEngine): CodeLanguage => (engine === 'Bash' ? 'shell' : 'powershell'); + +/** Everything the editor changes, in the shape that is saved. */ +export interface ScriptDraft { + name: string; + description: string; + content: string; + engine: ScriptEngine; + parameters: ScriptParameter[]; + functionModuleIds: string[]; + secretBindings: SecretBinding[]; + secretsVariableName: string; + fileBindings: ScriptFileBinding[]; +} + +const SAMPLE_CONTENT = + '1..10 | ForEach-Object {\n Write-Progress -Activity \'Working\' -Status "Step $_ of 10" -PercentComplete ($_ * 10)\n Write-Output "Completed step $_"\n Start-Sleep -Seconds 1\n}\n'; + +export const NEW_SCRIPT_DRAFT: ScriptDraft = { + name: '', + description: '', + content: SAMPLE_CONTENT, + engine: 'PowerShell', + parameters: [], + functionModuleIds: [], + secretBindings: [], + secretsVariableName: 'Secrets', + fileBindings: [] +}; + +export function draftFromScript(script: ScriptDto): ScriptDraft { + return { + name: script.name, + description: script.description ?? '', + content: script.content, + engine: engineOf(script.language), + parameters: script.parameters ?? [], + functionModuleIds: script.functionModuleIds ?? [], + secretBindings: script.secretBindings ?? [], + secretsVariableName: script.secretsVariableName ?? 'Secrets', + fileBindings: script.fileBindings ?? [] + }; +} + +export const isCompleteSecret = (b: SecretBinding) => Boolean(b.name.trim() && b.secretName.trim()); +export const isCompleteFile = (b: ScriptFileBinding) => Boolean(b.name.trim() && b.objectKey.trim() && b.destinationPath.trim()); + +/** The draft as it will be stored: incomplete secret and file rows are dropped. */ +export function normalizeDraft(draft: ScriptDraft): ScriptDraft { + return { + ...draft, + secretBindings: draft.secretBindings.filter(isCompleteSecret), + fileBindings: draft.fileBindings.filter(isCompleteFile) + }; +} + +export function saveBody(draft: ScriptDraft, name = draft.name): SaveScriptBody { + const stored = normalizeDraft(draft); + return { + name, + description: stored.description, + content: stored.content, + engine: stored.engine, + parameters: stored.parameters, + functionModuleIds: stored.functionModuleIds, + secretBindings: stored.secretBindings, + secretsVariableName: stored.secretsVariableName.trim() || undefined, + fileBindings: stored.fileBindings + }; +} + +/** Body for a copy of a stored script ("Name (copy)"). */ +export const duplicateBody = (script: ScriptDto | ScriptDraft) => { + const draft = 'id' in script ? draftFromScript(script) : script; + return saveBody(draft, `${draft.name} (copy)`); +}; + +// ── Validation ───────────────────────────────────────────────────────── + +/** A name usable as a PowerShell variable ($Name) or dictionary member ($Secrets.Name). */ +export const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/; +const IDENTIFIER_HINT = 'Letters, digits and _ only; not starting with a digit.'; +/** Not flagged on a freshly added row until a save is attempted. */ +export const PARAMETER_NAME_REQUIRED = 'Name is required.'; + +export interface DraftProblems { + name?: string; + /** Per parameter row. */ + parameters: (string | undefined)[]; + secretsVariable?: string; + /** Per secret row. */ + secrets: (string | undefined)[]; + /** Per file row. */ + files: (string | undefined)[]; +} + +/** Flags names that are used more than once (case-insensitive), by row. */ +function duplicates(names: string[]): boolean[] { + const seen = new Map(); + for (const n of names) { + const key = n.trim().toLowerCase(); + if (key) seen.set(key, (seen.get(key) ?? 0) + 1); + } + return names.map((n) => (seen.get(n.trim().toLowerCase()) ?? 0) > 1); +} + +export function validateDraft(draft: ScriptDraft): DraftProblems { + const secretsVar = draft.secretsVariableName.trim() || 'Secrets'; + const reserved = new Map(); + if (draft.secretBindings.length > 0) reserved.set(secretsVar.toLowerCase(), `Reserved for $${secretsVar}`); + if (draft.fileBindings.length > 0) reserved.set('files', 'Reserved for $Files'); + + const paramDupes = duplicates(draft.parameters.map((p) => p.name)); + const parameters = draft.parameters.map((p, i) => { + const name = p.name.trim(); + if (!name) return PARAMETER_NAME_REQUIRED; + if (!IDENTIFIER.test(name)) return IDENTIFIER_HINT; + if (paramDupes[i]) return 'Another parameter has this name.'; + return reserved.get(name.toLowerCase()); + }); + + const secretDupes = duplicates(draft.secretBindings.map((b) => b.name)); + const secrets = draft.secretBindings.map((b, i) => { + const name = b.name.trim(); + if (!name) return undefined; + if (!IDENTIFIER.test(name)) return IDENTIFIER_HINT; + return secretDupes[i] ? 'Another secret uses this key.' : undefined; + }); + + const fileDupes = duplicates(draft.fileBindings.map((b) => b.name)); + const files = draft.fileBindings.map((b, i) => { + const name = b.name.trim(); + if (!name) return undefined; + if (!IDENTIFIER.test(name)) return IDENTIFIER_HINT; + return fileDupes[i] ? 'Another file uses this name.' : undefined; + }); + + const variable = draft.secretsVariableName.trim(); + return { + name: draft.name.trim() ? undefined : 'Script name is required.', + parameters, + secretsVariable: variable && !IDENTIFIER.test(variable) ? IDENTIFIER_HINT : undefined, + secrets, + files + }; +} + +export type EditorTab = 'code' | 'parameters' | 'functions' | 'secrets' | 'files' | 'executions' | 'schedules'; + +/** The first problem and the tab that shows it, or null when the draft can be saved. */ +export function firstProblem(problems: DraftProblems): { message: string; tab: EditorTab } | null { + if (problems.name) return { message: problems.name, tab: 'code' }; + const param = problems.parameters.find(Boolean); + if (param) return { message: `Check the parameters: ${param}`, tab: 'parameters' }; + const secret = problems.secretsVariable ?? problems.secrets.find(Boolean); + if (secret) return { message: `Check the secrets: ${secret}`, tab: 'secrets' }; + const file = problems.files.find(Boolean); + if (file) return { message: `Check the files: ${file}`, tab: 'files' }; + return null; +} diff --git a/src/WebUI/src/sections/settings/AgentUpgradeSettings.tsx b/src/WebUI/src/sections/settings/AgentUpgradeSettings.tsx new file mode 100644 index 0000000..9637fb7 --- /dev/null +++ b/src/WebUI/src/sections/settings/AgentUpgradeSettings.tsx @@ -0,0 +1,363 @@ +import { useMemo, useState } from 'react'; +import { enqueueSnackbar } from 'notistack'; + +// material-ui +import Alert from '@mui/material/Alert'; +import Autocomplete from '@mui/material/Autocomplete'; +import Button from '@mui/material/Button'; +import Chip from '@mui/material/Chip'; +import FormControlLabel from '@mui/material/FormControlLabel'; +import Grid from '@mui/material/Grid'; +import Skeleton from '@mui/material/Skeleton'; +import Stack from '@mui/material/Stack'; +import Switch from '@mui/material/Switch'; +import TextField from '@mui/material/TextField'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; + +// project imports +import ConfirmDialog from 'components/ConfirmDialog'; +import DataTable, { Column } from 'components/DataTable'; +import { RelativeTime } from 'components/DateTime'; +import EmptyState from 'components/EmptyState'; +import GatedButton from 'components/GatedButton'; +import HoverHelp from 'components/HoverHelp'; +import MainCard from 'components/MainCard'; +import { groupPathLabels, UNKNOWN_GROUP } from 'sections/access/groupPaths'; +import { isUpgradeActivity, refreshUpgrades, versionSortKey } from 'sections/upgrades/agentVersions'; +import UpgradeTable from 'sections/upgrades/UpgradeTable'; +import { PACKAGE_ORDER, PACKAGE_TYPES } from 'sections/upgrades/upgradeLabels'; +import { api, errorMessage, keys } from 'api/client'; +import useApi from 'hooks/useApi'; +import useLiveRefresh from 'hooks/useLiveRefresh'; +import { useGate } from 'hooks/useSession'; +import { plural } from 'utils/format'; +import Field from './Field'; +import useDraft from './useDraft'; +import { SETTINGS_PERMISSION, SETTINGS_PERMISSION_LABEL } from './keys'; + +// assets +import DeleteOutlined from '@ant-design/icons/DeleteOutlined'; +import SaveOutlined from '@ant-design/icons/SaveOutlined'; + +// types +import type { AgentUpgradeDto, AgentUpgradeSettingsDto, AgentVersionDto, DeviceGroupDto } from 'api/types'; + +const mono = { fontFamily: 'var(--font-mono)' }; + +// ==============================|| SETTINGS - AUTOMATIC UPGRADES ||============================== // + +function AutomaticUpgradesCard() { + const { data, error, loading, mutate } = useApi(keys.agentUpgradeSettings); + const { data: groups } = useApi(keys.groups); + const { form, set, reset, dirty } = useDraft(data); + const gate = useGate(SETTINGS_PERMISSION, SETTINGS_PERMISSION_LABEL); + const [busy, setBusy] = useState(false); + const [saveError, setSaveError] = useState(''); + + const labels = useMemo(() => groupPathLabels(groups ?? []), [groups]); + const groupOptions = useMemo(() => [...labels.keys()].sort((a, b) => labels.get(a)!.localeCompare(labels.get(b)!)), [labels]); + + if (loading) return ; + if (error || !form) return {errorMessage(error, 'Could not load the agent upgrade settings.')}; + + const save = async () => { + setBusy(true); + setSaveError(''); + try { + const saved = await api.saveAgentUpgradeSettings(form); + await (saved ? mutate(saved, { revalidate: false }) : mutate()); + reset(); + enqueueSnackbar('Saved', { variant: 'success' }); + } catch (e) { + setSaveError(errorMessage(e, 'Save failed.')); + } finally { + setBusy(false); + } + }; + + const number = (value: string) => (value === '' ? 0 : Number(value)); + + return ( + + Automatic Upgrades + + + } + secondary={ + set({ automaticUpgrades: e.target.checked })} />} + label="Automatic Upgrades" + labelPlacement="start" + /> + } + > + + + + + set({ startWithinMinutes: number(e.target.value) })} + slotProps={{ htmlInput: { min: 1, max: 30 } }} + /> + + + + + set({ healthDeadlineMinutes: number(e.target.value) })} + slotProps={{ htmlInput: { min: 1 } }} + /> + + + + + set({ keepVersions: number(e.target.value) })} + slotProps={{ htmlInput: { min: 1 } }} + /> + + + + + set({ excludedGroupIds: value })} + getOptionLabel={(id) => labels.get(id) ?? UNKNOWN_GROUP} + noOptionsText="No device groups exist yet." + renderValue={(value, getItemProps) => + value.map((id, index) => { + const { key, ...itemProps } = getItemProps({ index }); + return ( + + ); + }) + } + renderInput={(params) => ( + + )} + /> + + + + + {saveError && {saveError}} + + + {dirty && ( + + )} + } onClick={save} disabled={busy || !dirty}> + {busy ? 'Saving…' : 'Save Changes'} + + + + + ); +} + +// ==============================|| SETTINGS - AGENT VERSIONS ||============================== // + +function AgentVersionsCard() { + const { data, error, loading, validating } = useApi(keys.agentVersions); + const gate = useGate(SETTINGS_PERMISSION, SETTINGS_PERMISSION_LABEL); + const [removing, setRemoving] = useState(null); + + const columns: Column[] = [ + { + id: 'version', + header: 'Version', + nowrap: true, + sortValue: (v) => versionSortKey(v.version), + cell: (v) => ( + + + {v.version} + + {v.newest && ( + + + + )} + + ) + }, + { + id: 'platforms', + header: 'Platforms', + cell: (v) => ( + + {[...v.packages] + .sort((a, b) => PACKAGE_ORDER.indexOf(a.packageType) - PACKAGE_ORDER.indexOf(b.packageType)) + .map((p) => ( + + + + ))} + + ) + }, + { id: 'devices', header: 'Devices', align: 'right', sortValue: (v) => v.deviceCount, cell: (v) => v.deviceCount.toLocaleString() }, + { + id: 'imported', + header: 'Imported', + nowrap: true, + sortValue: (v) => v.importedUtc, + cell: (v) => + }, + { + id: 'remove', + header: '', + align: 'right', + width: 64, + cell: (v) => { + const reason = gate ?? v.removeBlockedReason ?? undefined; + return ( + + + + + + ); + } + } + ]; + + return ( + + Agent Versions + + + } + > + v.version} + loading={loading} + refreshing={validating && !loading} + error={error?.message} + defaultSort={{ id: 'version', direction: 'desc' }} + paged={false} + empty={} + /> + setRemoving(null)} + onConfirm={async () => { + await api.removeAgentVersion(removing!.version); + await refreshUpgrades(); + enqueueSnackbar(`Removed ${removing!.version}.`, { variant: 'success' }); + }} + /> + + ); +} + +// ==============================|| SETTINGS - RECENT UPGRADES ||============================== // + +function RecentUpgradesCard() { + const [openOnly, setOpenOnly] = useState(false); + const { data, error, loading, validating, mutate } = useApi( + keys.agentUpgrades({ open: openOnly || undefined, limit: 200 }) + ); + useLiveRefresh(() => mutate(), isUpgradeActivity); + + return ( + + Recent Upgrades + + + } + secondary={ + setOpenOnly(e.target.checked)} />} + label="Open Only" + labelPlacement="start" + /> + } + > + } + /> + + ); +} + +// ==============================|| SETTINGS - AGENT UPGRADES ||============================== // + +export default function AgentUpgradeSettings() { + return ( + + + + + + ); +} diff --git a/src/WebUI/src/sections/settings/AppearanceSettings.tsx b/src/WebUI/src/sections/settings/AppearanceSettings.tsx new file mode 100644 index 0000000..dc84a4a --- /dev/null +++ b/src/WebUI/src/sections/settings/AppearanceSettings.tsx @@ -0,0 +1,48 @@ +// material-ui +import { useColorScheme } from '@mui/material/styles'; +import Stack from '@mui/material/Stack'; +import ToggleButton from '@mui/material/ToggleButton'; +import ToggleButtonGroup from '@mui/material/ToggleButtonGroup'; + +// project imports +import MainCard from 'components/MainCard'; +import { DEFAULT_THEME_MODE, ThemeMode } from 'config'; + +// assets +import BulbOutlined from '@ant-design/icons/BulbOutlined'; +import MoonOutlined from '@ant-design/icons/MoonOutlined'; +import SunOutlined from '@ant-design/icons/SunOutlined'; + +const MODES = [ + { mode: ThemeMode.SYSTEM, label: 'Match System', icon: BulbOutlined }, + { mode: ThemeMode.LIGHT, label: 'Light', icon: SunOutlined }, + { mode: ThemeMode.DARK, label: 'Dark', icon: MoonOutlined } +]; + +// ==============================|| SETTINGS - APPEARANCE ||============================== // + +/** Colour scheme for this browser (stored locally, same as the header toggle). */ +export default function AppearanceSettings() { + const { mode, setMode } = useColorScheme(); + + return ( + + next && setMode(next)} + aria-label="Colour scheme" + > + {MODES.map(({ mode: value, label, icon: Icon }) => ( + + + + {label} + + + ))} + + + ); +} diff --git a/src/WebUI/src/sections/settings/AuthenticationSettings.tsx b/src/WebUI/src/sections/settings/AuthenticationSettings.tsx new file mode 100644 index 0000000..8fd1244 --- /dev/null +++ b/src/WebUI/src/sections/settings/AuthenticationSettings.tsx @@ -0,0 +1,104 @@ +import { ComponentType, useCallback, useState } from 'react'; +import { useNavigate, useParams } from 'react-router-dom'; + +// material-ui +import Box from '@mui/material/Box'; +import Stack from '@mui/material/Stack'; +import Tab from '@mui/material/Tab'; +import Tabs from '@mui/material/Tabs'; +import Tooltip from '@mui/material/Tooltip'; + +// project imports +import Dot from 'components/@extended/Dot'; +import BuiltInSignInTab from './authentication/BuiltInSignInTab'; +import LdapSignInTab from './authentication/LdapSignInTab'; +import LocalSignInTab from './authentication/LocalSignInTab'; +import { AuthenticationDirtyContext, useAuthenticationSummary, useManageGate } from './authentication/MethodControls'; +import OidcSignInTab from './authentication/OidcSignInTab'; + +// types +import type { ProviderId } from 'api/identity'; + +type MethodTab = 'built-in' | 'local' | 'ldap' | 'oidc'; + +/** Settings › Authentication's tabs, as StifleR names them; each is `/settings/authentication/{id}`. */ +const TABS: { id: MethodTab; label: string; method: ProviderId; Section: ComponentType<{ dirtyKey: string }> }[] = [ + { id: 'built-in', label: 'Built-In', method: 'local', Section: BuiltInSignInTab }, + { id: 'local', label: 'Local Windows Accounts', method: 'windows', Section: LocalSignInTab }, + { id: 'ldap', label: 'LDAP', method: 'ldap', Section: LdapSignInTab }, + { id: 'oidc', label: 'OIDC', method: 'oidc', Section: OidcSignInTab } +]; + +function TabLabel({ label, on, dirty }: { label: string; on: boolean | undefined; dirty: boolean }) { + return ( + + {on !== undefined && ( + + + + + + )} + {label} + {dirty && ( + + • + + )} + + ); +} + +// ==============================|| SETTINGS - AUTHENTICATION ||============================== // + +/** The four sign-in methods, a tab each: its switch, its settings, its test and the roles bound to its groups. */ +export default function AuthenticationSettings() { + const { method } = useParams(); + const navigate = useNavigate(); + const gate = useManageGate(); + const { summary } = useAuthenticationSummary(); + const current = TABS.find((tab) => tab.id === method) ?? TABS[0]; + + // Tabs stay mounted once visited, so unsaved edits survive a switch; the dot on a tab says it has some. + const [visited, setVisited] = useState([current.id]); + if (!visited.includes(current.id)) setVisited([...visited, current.id]); + const [dirty, setDirty] = useState>({}); + const report = useCallback((key: string, value: boolean) => setDirty((was) => (was[key] === value ? was : { ...was, [key]: value })), []); + + return ( + + + + navigate(`/settings/authentication/${id}`, { replace: true })} + variant="scrollable" + scrollButtons="auto" + aria-label="Sign-in methods" + > + {TABS.map((tab) => ( + m.id === tab.method)?.enabled} + dirty={!!dirty[`authentication/${tab.id}`]} + /> + } + /> + ))} + + + + {TABS.filter((tab) => visited.includes(tab.id)).map(({ id, label, Section }) => ( +