Compare commits

...

41 Commits

Author SHA1 Message Date
undergroundwires
9e34e64449 win, mac, linux: fix typos and dead URLs #367
- Fix multiple spelling errors in various scripts.
- Fix dead URLs with archived versions.
- Fix incorrect registry keys previously introduced in commit
  cec0b4b4f6.

Co-authored-by: RainRat <rainrat78@yahoo.ca>
2024-05-27 14:54:17 +02:00
undergroundwires
ce4cfdd169 win: add script to disable Recall feature 2024-05-27 10:44:11 +02:00
undergroundwires
12b1f183f7 win: document disabling firewall #115 #152 #364
This commit updates documentation to clarify the impacts of disabling
firewall services, specifically how they affect Windows Sandbox, Docker
and WSL.

This update responds to user feedback from issues #115, #152, #364. The
documentation now guides users more clearly on the consequences of their
actions, potentially preventing unintended service disruptions.

Changes include:

- Expand the caution notes to explicitly mention the impact on
  virtualization and isolation features like Windows Sandbox, Docker and
  WSL.
- Expand script titles to briefly mention affects on these features.
- Expand documentation to suggest system restart.
- Add an informative message to restart the computer in terminal outputs
  after service changes to ensure the settings are applied.
2024-05-26 13:42:25 +02:00
undergroundwires
4212c7b9e0 Improve context for errors thrown by compiler
This commit introduces a custom error object to provide additional
context for errors throwing during parsing and compiling operations,
improving troubleshooting.

By integrating error context handling, the error messages become more
informative and user-friendly, providing sequence of trace with context
to aid in troubleshooting.

Changes include:

- Introduce custom error object that extends errors with contextual
  information. This replaces previous usages of `AggregateError` which
  is not displayed well by browsers when logged.
- Improve parsing functions to encapsulate error context with more
  details.
- Increase unit test coverage and refactor the related code to be more
  testable.
2024-05-25 13:55:30 +02:00
undergroundwires
7794846185 win: discourage blocking app access #121 #339 #350
This commit adjusts the recommendation level for scripts that disable
UWP app access to accommodate user issues #121, #339, #350. It also
extends their documentation to reflect the new changes and with
cautions.

Changes:

- Add caution text for all scripts about potential impacts.
- Move disabling app access to notifications from 'Standard' to
  'Strict'. This addresses #121 and #339, where users report lack of
  notification as unintended side-effects.
- Move disabling app access to phone calls from 'Standard' to 'Strict'.
  This addresses #350 where its effect on the Phone Link app was
  reported as an unintended side-effect.
2024-05-24 10:45:23 +02:00
undergroundwires
150e067039 win: improve printing removal /w Print Queue #279
- Consolidate removal of printing UIs under the same category.
- Improve documentation for printing app removal scripts.
- Add removal of previously unlisted 'Print Queue' app, #279.
- Combine removal of `Microsoft.Print3D` and `Windows.Print3D`
  into a single script.
- Highlight the importance of removing 'Print 3D' app due to
  security risks and recommend it on 'Standard'.
2024-05-23 09:27:14 +02:00
undergroundwires
f347fde0c8 win: document and discourage RSA key script #363
This commit improves the documentation of RSA key handling script and
changes its recommendation level to address potential issues with
Hyper-V (as reported in #363).

Changes:

- Add documentation to describe potential disruptions caused by stronger
  RSA key requirements.
- Move RSA key script from 'Standard' to 'Strict' due to its impact on
  Hyper-V VMs.
- Use bullet points for easier expansion in cautions of secret key
  hardening scripts.
2024-05-22 08:10:37 +02:00
undergroundwires
ff3d5c4841 win: improve app access disabling and docs #138
This commit improves disabling app access by correcting minor issues,
adding missing access control configurations and adding more
documentation to increase maintainability and user understanding of
privacy settings, resolving #138.

- Introduce shared functions to streamline modifications of app access,
  improving maintainability and simplifying the codebase.
- Move disabling app access to first position in the category.
- Improve code comments for better clarity on generated outputs.
- Resolve error display in revert codes due to incorrect use of `reg
  delete` commands.
- Fix disabling app access to trusted devices disables access to account
  information, name and picture on older versions of Windows.
- Add missing privacy settings and configurations.
- Add more documentation to scripts
- Rename script names for consistency and clarity.
- Move disabling access to SMS/MMS to phone access disablement category.
- Set empty `REG_MULTI_SZ` values to null for GPO access settings to
  maintain registry integrity.
2024-05-21 13:02:48 +02:00
undergroundwires
292362135d Centralize and optimize ResizeObserver usage
This commit addresses failures in end-to-end tests that occurred due to
`ResizeObserver` loop limit exceptions.

These errors were triggered by Vue dependency upgrades in the commit
aae5434451.
The errors had the following message:
> `ResizeObserver loop completed with undelivered notifications`

This error happens when there are too many observations and the observer
is not able to deliver all observations within a single animation frame.
See: WICG/resize-observer#38

his commit resolves the issue by controlling how many observations are
delivered per animation frame and limiting it to only one.

It improves performance by reducing layout trashing, improving frame
rates, and managing resources more effectively.

Changes:

- Introduce an animation frame control to manage observations more
  efficiently.
- Centralized `ResizeObserver` management within the `UseResizeObserver`
  hook to improve consistency and reuse across the application.
2024-05-20 10:36:49 +02:00
undergroundwires
aae5434451 Bump Vue to latest and fix universal selector CSS
This commit updates the Vue package from v3.4.21 to v3.4.27.

This version change addressed styling issues introduced by changes in
CSS universal selector handling in Vue 3.4.22.
The change that has caused this:
- vuejs/core#10551
- vuejs/core#10548
- vuejs/core@54a6afa75a

This commit fixes two main issues that this has led to:

1. Universal CSS selector causing 'Revert' buttons to stretch and
   truncate incorrectly.
   This is fixed by modifying selectors to apply styles more
   specifically, maintaining correct display of toggle buttons.
2. Universal `*` selector that's used to understand parent HTML
   structure causing information tooltip icons to be misaligned.
   This is fixed by replacing `*` with a new `InfoTooltipWrapper`
   component, which manages layout concerns more explicitly and
   maintainably.
2024-05-19 15:02:38 +02:00
undergroundwires
2390530d92 ci/cd: fix quality checks not running on all OSes
Previously, quality checks were mistakenly configured to run only on
Ubuntu.

This commit modifies the CI/CD workflow to use the matrix strategy,
allowing the quality checks to be executed on macOS, Ubuntu and Windows.

Additionally, this update resolves the `MD034/no-bare-urls Bare URL
used` linting error that surfaced when testing on Windows.
2024-05-18 13:14:05 +02:00
undergroundwires
9ab3ff75b0 Migrate to GitHub issue forms
This commit transitions from HTML-based issue templates to GitHub issue
forms, enhancing user experience by preventing accidental submissions
with comment-like metadata. This change makes submitting issues more
intuitive and reduces the chances of user errors (such as #355).

Key change include:

- Use a friendlier tone in the templates.
- Detail examples and descriptions to guide users more effectively.
- Rename templates for improved clarity and easy navigation.
- Add "a note from the maintainer".
- Include a direct link for donations to support the project.
2024-05-17 17:52:14 +02:00
undergroundwires
d25c4e8c81 Add support for macOS universal binary #348, #362
This commit introduces a universal binary format in the distributed MDG
files for macOS, improving support for both Apple Silicon (ARM) and
Intel (x64) architectures.

It uses `electron-builder` to package both architectures into a single
executable, ensuring the application can natively on any macOS hardware
without depending on the GitHub runners' architecture. It fixes the
issue related to prior releases that supported only the architecture of
the build environment itself, which is subject to change.

Changes:

- Update DMG distribution to include both ARM64 and x64 architectures.
- Enhance system requirements documentation to reflect support for both
  architectures.
- Modify CI/CD workflows to check desktop runtime errors for both ARM64
  and x64 versions on macOS.

Resolves:

- Issue #348: Initial request for Apple Silicon support.
- Issue #362: Correction of distribution limited to ARM64 in release
  0.13.3.

`electron-builder` support:
- electron-userland/electron-builder#5475
- electron-userland/electron-builder#5689
- electron-userland/electron-builder#5426
2024-05-16 10:53:55 +02:00
undergroundwires
4a7efa27c8 Fix e2e test failing on Windows
The recent addition of revert logic in first visible card on Windows
(Privacy Cleanup) in cec0b4b, introduced an issue where end-to-end (e2e)
started failing due to the handling of hidden elements.

This commit improves the test to correctly handle the hidden card
scenario, explicitly filtering visible elements to ensure that only
visible elements are handled.
2024-05-15 09:03:18 +02:00
undergroundwires
cec0b4b4f6 win: standardize registry edit + delete on revert
This commit standardizes the management of registry keys and their
corresponding revert on delete action across all scripts using
`SetRegistryValue` function.

It improves script reliability, addresses previous errors, and corrects
the revert actions to match the default OS state when not explicitly set
by the OS.

Key changes:

- Use SetRegistryValue for uniformity.
- Remove error messages for non-existent registry keys, recognizing them
  as expected states rather than errors.
- Add missing revert actions to scripts where they were absent.
- Correct the revert logic in existing scripts to match the default OS
  configurations, particularly when the OS does not set a default value.
- Update documentation about default OS state for the related scripts.

This change improves maintainability by centralizing and standardizing
registry interactions, reducing the risk of errors and inconsistencies
in script behaviors.
2024-05-14 12:41:20 +02:00
undergroundwires
a1922c50c1 ci/cd: fix recent Docker build failures on macOS
The GitHub workflow for testing Docker builds on macOS was consistently
failing. This commit downgrades the macOS version used for Docker tests
to `macos-13`, which is the latest Intel-based macOS runner, instead of
the ARM-based `macos-14` which `macos-latest` points to.

This change is necessary because the hypervisor framework required for
Docker is not supported on the ARM-based macOS runners provided by
GitHub. This issue was causing failures when attempting to run Colima
with QEMU using `-accel hvf`, which is unsupported on these runners.
Switching to an Intel-based runner resolves this issue.

Related issues:
- actions/runner-images#9460
- actions/runner-images#9741
- abiosoft/colima#1023
2024-05-13 11:09:58 +02:00
undergroundwires
870120bc13 Add specific empty function name compiler error
This commit adds checks to rjeect functions with empty or whitespace
names. The compiler throws a specific errror when it encounters a
function data object lacking a proper name.

This provides early detection and clear feedback on invalid function
definitions, helping in faster debugging and ensuring script integrity
in the compilation process.

The enhancement aims to provide early detection and clear feedback
on invalid function definitions, aiding in faster debugging and
ensuring script integrity in the compilation process.

when it encounters a function data object lacking a proper name.
It covers scenarios where the function name might be an empty string,
undefined, or solely consist of whitespace.
2024-05-12 12:32:42 +02:00
undergroundwires-bot
f38cf73485 ⬆️ bump everywhere to 0.13.3 2024-05-11 09:58:21 +00:00
undergroundwires
9fd193e676 win: categorize and rename network security #131
This commit restructures the categorization of network security-related
scripts to improve clarity and align with user expectations. It involves
renaming and reorganizing categories to more accurately reflect their
functions beyond just IIS configurations.

This reorganization helps users find and utilize network security
scripts more efficiently and ensures that the categorization accurately
reflects the broader application of the scripts beyond server
configurations.

Changes:

- Merge network security enhancements under a single category.
- Rename categories for simplicity and increased technical accuracy.
- Flatten nested categories to streamline navigation and enhance
  clarity.
- Update documentation to match the new category structures.
- Revise script recommendations to encourage broader use.
- Fix revert codes of some related scripts to reflect default OS
  settings.
2024-05-11 11:39:28 +02:00
undergroundwires
52a4730073 ci/cd: remove check-latest from setup-node
This commit addresses the issue where Windows GitHub runners experience
failures due to unstable Node.js releases, particularly version 20.13.0,
as detailed in nodejs/node#52884 and nodejs/node#52682.

The 'check-latest' input in the 'setup-node' GitHub Action forces
every job to verify and potentially install the latest Node.js version.
This input was originally introduced to reduce maintenance efforts to
keep CI/CD setup up-to-date with the latest Node version.

However, the necessity to always run the latest Node.js version is not
critical for the CI/CD setup. Additionally, it causes increased network
requests and may inadvertently introduce unstable Node.js versions.

This commit removes the 'check-latest' option to prevent the immediate
adoption of new, potentially unstable Node.js releases, thus simplifying
the CI/CD pipeline. This keeps  CI/CD process is robust and predictable,
reducing the chances of unexpected disruptions in service deployment.
2024-05-10 12:18:16 +02:00
undergroundwires
bc4879cfe9 Fix Chromium scrollbar-induced layout shifts
This commit addresses an issue in Chromium on Linux and Windows where
the appearance of a vertical scrollbar causes unexpected horizontal
layout shifts. This behavior typically occurs when the window is
resized, a card is opened or a script is selected, resulting in content
being pushed to the left.

The solution implemented involves using `scrollbar-gutter: stable` to
ensure space is always allocated for the scrollbar, thus preventing any
shift in the page layout. This fix primarily affects Chromium-based
browsers on Linux and Windows. It has no impact on Firefox on any
platform, or any browser on macOS (including Chromium). Because these
render the scrollbar as an overlay, and do not suffer from this issue.

Steps to reproduce the issue using Chromium browser on Linux/Windows:

1. Open the app with a height large enough where a vertical scrollbar is
   not visible.
2. Resize the window to a height that triggers a vertical scrollbar.
3. Notice the layout shift as the body content moves to the right.

Changes:

- Add a CSS mixin to handle scrollbar gutter allocation with a fallback.
- Add support for modal dialog background lock to handle
  `scrollbar-gutter: stable;` in calculations to avoid layout shift when
  a modal is open.
- Add E2E test to avoid regression.
- Update DevToolkit to accommodate new scrollbar spacing.
2024-05-09 18:35:02 +02:00
undergroundwires
dd71536316 Fix misaligned tooltip positions in modal dialogs
This commit fixes a bug that causes tooltips to be slightly misaligned.

Tooltip positioning was incorrect during modal transitions due to their
initial movement, causing tooltips to align incorrectly at the start of
the animation rather than the end.

One way to solve this would be using `autoUpdate` from `floating-ui`
with `animationFrame: true`. However, this recalculates positions tens
of times per second, impacting performance. This is a monkey solution.

This commit adopts a more efficient approach by updating tooltip
positions only at the end of the transitions, which reduces calculations
and conserves resources.

Key changes:

- Addd transition end event listener for updating tooltip positions.
- Use throttling to eliminate excessive position recalculations.

Other supporting changes:

- Improve throttle function to support efficient recalculations of
  positions:
  - Add ability to optionally exclude the first execution (leading
    call).
  - Refactor to simplify it make it easier to follow and read.
  - Fix a bug where initial calls were incorrectly throttled if
    `dateNow()` returned `0`.
- Introduce and use a global hook for efficient DOM event management.
  This greatily introduce safety, reuse and testability of event
  listening.
2024-05-08 15:24:12 +02:00
undergroundwires
a3343205b1 Fix win execution with whitespace in username #351
This commit addresses the issue where scripts fail to execute on Windows
environments with usernames containing spaces. The problem stemmed from
PowerShell and cmd shell's handling of spaces in quoted arguments.

The solution involves encoding PowerShell commands before execution,
which mitigates the quoting issues previously causing script failures.
This approach is now integrated into the execution flow, ensuring that
commands are correctly handled irrespective of user names or other
variables that may include spaces.

Changes:

- Implement encoding for PowerShell commands to handle spaces in usernames
  and other similar scenarios.
- Update script documentation URLs to reflect changes in directory
  structure.

Fixes #351
2024-05-07 13:57:19 +02:00
undergroundwires
1d7cafc831 Fix VSCode script issues with added CI/CD tests
- Correct incorrect attribute in `configure_vscode.py`.
- Introduce CI tests for early error detection in the script.
- Replace emojis with ASCII in CI logs to avoid Windows encoding issues.
2024-05-06 17:18:19 +02:00
undergroundwires
c75df1c8c1 win: improve enabling secure connections #175
This commit refines the configuration of TLS and DTLS protocols on
Windows to enhance compatibility and stability across different
Windows versions.

Changes:

- Enable TLS 1.3 exclusively on Windows 11 and newer, addressing
  stability concerns with previous Windows versions, and resolving
  issue #175.
- Enable DTLS 1.2, replacing DTLS 1.3 due to lack of support in
  Windows. DTLS is enabled only on Windows 10 version 16007 and later
  for compatibility.
- Reorganize script categories for better clarity and manageability.
- Update revert codes for registry deletions to prevent false negative
  error outputs.
- Adjust recommendation levels to encourage more scripts due to system
  stability and documentation improvements introduced in this commit.
- Remove incorrect registry keys previously set for .NET apps.
- Add missing 64-bit registry keys for .NET apps.
- Rename scripts for improved simplicity and consistency.
- Improve documentation for affected scripts, correcting the
  misleading information about DTLS 1.2 vulnerability.
- Convert hexadecimal values to decimal in scripts to improve
  clarity.
- Introduce shared functions to reduce redundancy and improve
  script maintainability.
- Add more comments in generated code and simplify existing comments.
2024-05-05 10:57:45 +02:00
undergroundwires
ab25e0a066 Improve desktop icon quality and generation
This commit refactors the icon and logo generation process by replacing
multiple dependencies with ImageMagick. This simplifies the build
process and enhances maintainability.

Key changes:

- Remove unnecessary icon files for macOS (.icns) and Linux
  (size-specific PNGs). Electron-builder can now auto-generate these
  from a single `logo.png` starting from version 19.54.0, see:
  - electron-userland/electron-builder#1682
  - electron-userland/electron-builder#2533
- Retain `ico` generation with multiple sizes to fix pixelated/bad
  looking icons on Windows, see:
  - electron-userland/electron-builder#7328
  - electron-userland/electron-builder#3867
- Replaced `svgexport`, `icon-gen`, and `electron-icon-builder`
  dependencies with ImageMagick, addressing issues with outdated
  dependencies and unreliable CI/CD builds.
- Move electron-builder build resources to
  `src/presentation/electron/build` for better project structure.
- Improve `electron-builder` configuration file by making it
  importable/reusable without prebuilding the Electron application.
2024-05-04 12:09:42 +02:00
undergroundwires
813d820b85 Fix blank window on load on desktop version #348
This commit updates the application startup behavior to prevent showing
a blank window until it's fully loaded on all platforms. This enhancement
improves the user experience by ensuring the UI only becomes visible
when it is ready to interact with.

This fix contributes to a smoother user experience by aligning the
window display timing with content readiness, thus avoiding the brief
display of an empty screen.

Changes:

- Set window to initially hide until fully loaded using the
  `ready-to-show` event.
- Show the window, focus on it and bring it front once it is loaded.
  Windows requires additional logic to put Window to front, see
  electron/electron#2867.
- Parametrize the behavior of opening developer tools for easier
  configuration during testing.
2024-05-03 12:03:36 +02:00
undergroundwires
66a56888a4 win: fix Copilot by excluding r.bing.com #329
This commit modifies the blocking behavior of `r.bing.com` due to its
extensive use across multiple Windows features, including Copilot and
Maps. Previously, included in the 'Cortana and Live Tiles' block list,
this host was causing issues for Copilot functionalites, as noted in
issue #329. By excluding `r.bing.com` from block list, this update aims
to prevent unintended disruptions without compromising the privacy gains
of other scripts.

Changes include:

- Exclude `r.bing.com` from the "Cortana and Live Tiles" block list.
- Improve documentation to clarify the role and exclusions.
- Improve documentation with consistent header for blocked hosts.
2024-05-02 13:52:09 +02:00
undergroundwires
4ef16cea56 win: improve disabling protocols
This commit groups scripts related to disabling protocols under same
category, streamlining the process for disabling protocols like NetBios,
SMBv1, and various TLS/SSL versions. It improves the documentation and
scripts of the related scripts.

Key changes:

- Introduce new category for disabling insecure protocols and move
  related scripts under it.
- Remove .NET configuration from TLS 1.0 disabling to prevent unwanted
  side effects on .NET applications, maintaining system integrity.
- Remove the script disabling DTLS 1.1 as this protocol does not exist.
- Recommend previously not recommended scripts:
  - SSL 2.0 in 'Standard' because it's already removed from Windows.
  - SSL 3.0 in 'Standard' because it's already disabled by default.
  - TLS 1.0 in 'Strict' as it's deprecated on Windows.
  - TLS 1.1 in 'Strict' as it's deprecated on Windows.
- Rename and reorder scripts for consistency and enhanced readability.
- Fix revert codes to accurately reflect successful operations, by
  adding `2>nul` on `reg delete` commands.
- Expand documentation to include detailed precautions and references,
  aiding users in understanding the implications of their actions
  (addressing user feedback from #57, #131, #183, #185).

Other supporting changes:

- Convert hexadecimal values to decimal to enhance script readability.
- Refactor scripts to utilize shared functions, improving maintainability.
- Add detailed comments within the scripts to aid in comprehension.
- Minor updates to other crypto scripts for consistency.
- Reorganize protocol listing by age for a logical script flow.
- Standardize comments across various TLS configuration scripts for
  clarity.
- Fix enabling DTLS 1.3 being categorized as disabling insecure
  connection.
2024-05-01 12:18:55 +02:00
undergroundwires
8c17396285 Fix script cancellation with new dialog on Linux
This commit improves the management of script execution process by
enhancing the way terminal commands are handled, paving the way for
easier future modifications and providing clearer feedback to users when
scripts are cancelled.

Previously, the UI displayed a generic error message which could lead to
confusion if the user intentionally cancelled the script execution. Now,
a specific error dialog will appear, improving the user experience by
accurately reflecting the action taken by the user.

This change affects code execution on Linux where closing GNOME terminal
returns exit code `137` which is then treated by script cancellation by
privacy.sexy to show the accurate error dialog. It does not affect macOS
and Windows as curret commands result in success (`0`) exit code on
cancellation.

Additionally, this update encapsulates OS-specific logic into dedicated
classes, promoting better separation of concerns and increasing the
modularity of the codebase. This makes it simpler to maintain and extend
the application.

Key changes:

- Display a specific error message for script cancellations.
- Refactor command execution into dedicated classes.
- Improve file permission setting flexibility and avoid setting file
  permissions on Windows as it's not required to execute files.
- Introduce more granular error types for script execution.
- Increase logging for shell commands to aid in debugging.
- Expand test coverage to ensure reliability.
- Fix error dialogs not showing the error messages due to incorrect
  propagation of errors.

Other supported changes:

- Update `SECURITY.md` with details on script readback and verification.
- Fix a typo in `IpcRegistration.spec.ts`.
- Document antivirus scans in `desktop-vs-web-features.md`.
2024-04-30 15:04:59 +02:00
undergroundwires
694bf1a74d win, linux, mac: fix various typos #349
This commit fixes various typos in documentation and code.

Co-authored-by: RainRat <rainrat78@yahoo.ca>
2024-04-29 13:04:33 +02:00
undergroundwires
0fc2ffc1ea Add system requirements documentation #134
- Create system requirements documentation for desktop versions,
  addressing issue #134.
- Reorganize related documents into `docs/desktop` for improved
  structure and accessibility.
- Update references to address ARM chip emulation issues noted in user
  feedback, issue #348.
2024-04-28 16:57:55 +02:00
undergroundwires
d19dde603d win: improve disabling insecure hashes #131
This commit addresses reports in issue #131 about third-party cloud
services like MEGA and Dropbox being affected by hash disabling. It
updates the documentation to guide users on the potential impact,
adjusts the recommendation levels along with other minor improvements.

- Recommend hash disabling scripts in 'Strict'.
- Expand and refine documentation, adding warnings to inform user
  decisions (addressing issues #57, #131, #175, #183).
- Add a new shared function to standardize hash disabling, increasing
  code maintainability.
- Change from hexadecimal to decimal in scripts for clarity.
- Improve code comments for better understanding.
- Add comments in generated to code to make it easier to follow.
- Fix revert codes showing errors by using `2>nul` in `reg delete`
  commands.
- Rename scripts for consistent naming conventions.

Supporting changes in other SSL/TLS handshake scripts:

- Update documentation for consistency.
- Rename shared functions for consistency and clarity.
- Improve generated code comments for clarity.
2024-04-27 11:27:26 +02:00
undergroundwires
23bac0fc76 ci/cd: lint Python scripts using pylint
This commit integrates `pylint` into the CI/CD pipeline to improve the
quality of Python scripts within the project. By enforcing stricter
linting standards, the aim is to identify and correct potential issues
more efficiently, ultimately contributing to more reliable and
maintainable code.

Changes:

- Introduce `npm run lint:pylint` command to facilitate unified way to
  run linting on different environments.
- Include `npm run lint:pylint` in the CI/CD workflow to ensure all
  commits adhere to established Python coding standards.
- Fix an issue identified by `pylint` in `configure_vscode.py`.
- Rename the workflow to match the latest naming convention.
2024-04-26 17:03:38 +02:00
undergroundwires
e18907ca91 win: improve 'Snipping Tool' removal #343
Due to changes in how Windows handles the Snipping Tool, this commit
reclassifies the tool's disablement into its own distinct category.
This update introduces alternative methods to disable the tool,
enhances documentation, and improves script functionality.

Changes include:

- Move Snipping Tool removal to a standalone category for clearer
  navigation.
- Expand documentation to better describe the tool's impact on privacy.
- Add methods to disable the tool without removing the app.
- Implement a shared function to disable specific Windows hotkeys.
- Rename Cortana shortcut disablement script for consistency.
2024-04-25 10:36:33 +02:00
undergroundwires
4e21f05031 ci/cd: add check for TODO comments
This commit introduces a new GitHub Actions job within the quality
checks workflow that scans the latest commit for TODO comments. The
intention is to prevent such comments from being merged into the main
branch, promoting cleaner and more maintainable code.

The script uses a specific pattern to avoid IDE detection and
misclassification of the script line as a TODO item itself. If any TODO
comments are found, the script exists with a non-zero status,
indicating an issue that must be addressed before proceeding.
2024-04-24 23:59:55 +02:00
undergroundwires
8b224eefe7 win: doc, improve, encourage cipher disabling
- Introduce 'Disable insecure ciphers' category to organize and group
  cipher disabling scripts.
- Expand documentation, adding cautionary notes to help users make
  informed decisions, addressing issues #57, #131, #175, and #183.
- Implement `DisableCipherAlgorithm` function to standardize the
  approach to disabling cipher algorithms, enhancing maintainability
  and promoting code reuse.
- Replace hexadecimal numbers with decimals in scripts to improve
  readability.
- Add comments to generated code for better understandability.
- Update revert codes to avoid incorrect error messages when
  operations are successful, using `2>nul` in `reg delete` commands.
- Rename scripts for consistency, incorporating 'insecure' in titles.
- Adjust recommendations to disable all insecure ciphers in 'Strict'
  mode due to security risks, and recommend disabling `NULL` in
  'Standard' mode as it removes encryption.
- Remove disabling of `DES 56`, correcting a redundancy as this cipher
  configuration does not exist.
2024-04-21 14:31:00 +02:00
undergroundwires
f261ab4cd9 win: improve disabling insecure renegotiations
This commit improves script clarity and user guidance on disabling
insecure renegotiations.

- Update script name for clarity.
- Improve documentation for better understanding.
- Recommend the script as 'Strict' to align with its security focus.
- Modify revert codes to suppress misleading error messages upon
  successful reversion by including `2>nul` in `reg delete` commands.
- Convert hexadecimal to decimal in registry commands to improve
  readability.
2024-04-20 19:18:52 +02:00
undergroundwires
f584fabb50 win: improve disabling SMBv1 protocol
- Improve documentation.
- Add disabling `mrxsmb10` service (enabled with SMB1 feature).
- Configure Windows Server service for server side.
2024-04-19 16:16:00 +02:00
undergroundwires
2eed6f4afb win: organize and document network disablement
Reorganize and document scripts for disabling network features,
enhancing their discoverability and manageability. This commit
categorizes scripts related to disabling insecure network connections,
improves documentation, and makes these scripts more accessible.

- Group scripts under `Disable insecure connections` category.
- Move SMBv1 and NetBios disablement scripts to this new category.
- Improve documentation, highlighting the security improvements
  and potential compatibility issues with older systems.

Addresses issues #57, #115, #183, #175, and #185 by simplifying the
process of troubleshooting and reversing changes if necessary.
2024-04-17 21:35:56 +02:00
undergroundwires-bot
1c9dc93246 ⬆️ bump everywhere to 0.13.2 2024-04-16 07:45:17 +00:00
230 changed files with 15728 additions and 9215 deletions

View File

@@ -1,57 +0,0 @@
---
name: Bug report (script bug or unexpected script behavior)
about: Create a bug report for generated scripts to help privacy.sexy improve
labels: bug
title: '[BUG]: '
---
<!--
Thank you for reporting an issue with generated script(s).
Please fill in as much of the template below as you're able.
As a small open source project with small community, it can sometimes take a long time for issues to be addressed so please be patient.
-->
### Description
<!--
A clear and concise description of what the bug is.
-->
### OS
<!--
Which OS are you using? What version of OS you were using?
On Windows: Open "Start button" > "Settings" > "System" > "About".
On macOS: Open "Apple menu (top left corner)" > "About This Mac".
On Linux: Open terminal > type: lsb_release -a > copy paste the result.
-->
### Reproduction steps
<!--
How can the bug be recreated?
It's the most important information in the bug report. Bugs that cannot be reproduced cannot be fixed and verified.
E.g.
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
-->
### Scripts
<!--
If applicable, please attach the generated privacy.sexy file instead of copy pasting which becomes too long.
-->
### Screenshots
<!--
If applicable, add screenshots to help explain your problem.
-->
### Additional information
<!--
If applicable, add any other context about the problem here.
-->

View File

@@ -0,0 +1,114 @@
name: "Bug Report: Script Issues"
description: 🐛 Report issues with generated scripts to enhance privacy.sexy
labels: [ 'bug' ]
title: '[Bug]: '
body:
-
type: markdown
attributes:
value: |-
Thank you for contributing to privacy.sexy and guiding our direction! 🌟
Please complete as much of the form below as possible.
Your feedback is valuable, even if you can't provide all details.
-
type: textarea
attributes:
label: Description
description: A clear and concise description of what the bug is.
placeholder: >-
For example: "After running the cleanup script, music playback stopped functioning."
validations:
required: true
-
type: textarea
attributes:
label: How can the bug be recreated?
description: |-
This is the most important information in the bug report.
Bugs that cannot be reproduced cannot be fixed or verified.
placeholder: |-
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
validations:
required: true
-
type: textarea
attributes:
label: Operating system
description: |-
Please specify your operating system and its version.
- On Windows: Open "Start button" > "Settings" > "System" > "About".
- On macOS: Open "Apple menu (top left corner)" > "About This Mac".
- On Linux: Open terminal > type: lsb_release -a > copy paste the result.
placeholder: >-
For example: "Windows 11 Pro 22H3"
validations:
required: false
-
type: textarea
attributes:
label: Script file
description: |-
If applicable, share the generated privacy.sexy file.
GitHub may restrict script file attachments.
Upload your script file to a service like [GitHub Gist](https://gist.github.com/) and share the link here.
If you used the desktop version to run the script, it is already stored on your system.
See the [documentation to locate it](https://github.com/undergroundwires/privacy.sexy/blob/master/docs/desktop/desktop-vs-web-features.md#secure-script-executionstorage).
> **💡 Tip:** You can attach script files by dragging them into this area.
placeholder: |-
Attach the script, or post GitHub Gist link.
For example: https://gist.github.com/privacysexy-forks/6d85ad8ca27acc8c6a5417d4af28c9b6.
validations:
required: false
-
type: textarea
attributes:
label: Screenshots
description: |-
If applicable, add screenshots to help explain your problem.
> **💡 Tip:** You can attach screenshots by clicking this area to highlight it and then pasting them or dragging files in.
placeholder: Attach screenshots here or link to image hosting.
validations:
required: false
-
type: textarea
attributes:
label: Additional information
description: |-
If applicable, add any other context about the problem here.
Helpful information includes:
- Application logs (desktop version only), see: [how to find application logs](https://github.com/undergroundwires/privacy.sexy/blob/master/docs/desktop/desktop-vs-web-features.md#logging).
- Terminal output
- Proposed solutions
- Other related context such as related issues, software behavior, etc.
> **💡 Tip:** You can attach log files by dragging them into this area.
placeholder: >-
For example: "Here are the logs I get from the privacy.sexy 0.13.2 desktop application: ..."
validations:
required: false
-
type: markdown
attributes:
value: |-
---
**✉️ A friendly note from the maintainer:**
> [!NOTE]
> We are a small open-source project with a small community.
> It can sometimes take a long time for issues to be addressed, so please be patient.
> Consider [donating](https://undergroundwires.dev/donate) to keep privacy.sexy alive and improve support ❤️.
> But your issue will eventually get attention regardless.
> <p align="right">@undergroundwires</p>
---

View File

@@ -0,0 +1,104 @@
name: "Bug Report: General"
description: 🐛 Report general issues to enhance privacy.sexy
labels: [ 'bug' ]
title: '[Bug]: '
body:
-
type: markdown
attributes:
value: |-
Thank you for contributing to privacy.sexy and guiding our direction! 🌟
Please complete as much of the form below as possible.
Your feedback is valuable, even if you can't provide all details.
-
type: textarea
attributes:
label: Description
description: Provide a clear and concise description of the issue.
placeholder: >-
For example: "I cannot select any scripts."
validations:
required: true
-
type: textarea
attributes:
label: Reproduction steps
description: |-
This is the most important information in the bug report.
Bugs that cannot be reproduced cannot be fixed or verified.
placeholder: |-
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
validations:
required: true
-
type: textarea
attributes:
label: Expected behavior
description: Describe what you expected to happen when the error occurred.
placeholder: >-
For example: "I expected the settings menu to open smoothly without crashing.".
validations:
required: true
-
type: textarea
attributes:
label: Screenshots
description: |-
If applicable, add screenshots to help explain your problem.
> **💡 Tip:** You can attach screenshots by clicking this area to highlight it and then pasting them or dragging files in.
placeholder: >-
Attach screenshots here or link to image hosting.
validations:
required: false
-
type: textarea
attributes:
label: privacy.sexy environment details
description: |-
If applicable, mention how you were using privacy.sexy when the bug occurred:
- Web (on which operating system and browser?)
- Or desktop (Windows, macOS, or Linux?)
placeholder: >-
For example: "The web version on Edge browser on Windows 11 23H2."
validations:
required: false
-
type: textarea
attributes:
label: Additional context
description: |-
If applicable, add any other context about the problem here.
Helpful information includes:
- Application logs (desktop version only), see: [how to find application logs](https://github.com/undergroundwires/privacy.sexy/blob/master/docs/desktop/desktop-vs-web-features.md#logging).
- Terminal output
- Proposed solutions
- Other related context such as related issues, software behavior, etc.
> **💡 Tip:** You can attach log files by dragging them into this area.
placeholder: >-
For example: "Here are the logs I get from the privacy.sexy 0.13.2 desktop application: ..."
validations:
required: false
-
type: markdown
attributes:
value: |-
---
**✉️ A friendly note from the maintainer:**
> [!NOTE]
> We are a small open-source project with a small community.
> It can sometimes take a long time for issues to be addressed, so please be patient.
> Consider [donating](https://undergroundwires.dev/donate) to keep privacy.sexy alive and improve support ❤️.
> But your issue will eventually get attention regardless.
> <p align="right">@undergroundwires</p>
---

View File

@@ -1,55 +0,0 @@
---
name: Bug report (unrelated to generated scripts)
about: Create a bug report that's not related to generated scripts to help privacy.sexy improve
labels: bug
title: '[BUG]: '
---
<!--
Thank you for reporting an issue.
Please fill in as much of the template below as you're able.
As a small open source project with small community, it can sometimes take a long time for issues to be addressed so please be patient.
-->
### Description
<!--
A clear and concise description of what the bug is.
-->
### Reproduction steps
<!--
It's the most important information in the bug report. Bugs that cannot be reproduced cannot be fixed and verified.
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
-->
### Expected behavior
<!--
A clear and concise description of what you expected to happen.
-->
### Screenshots
<!--
If applicable, add screenshots to help explain your problem.
-->
### Distribution
<!--
If applicable, mention how you were using privacy.sexy when the bug was encountered:
- Web (on Desktop or mobile?)
- Or desktop (Windows, macOS or Linux?)
-->
### Additional context
<!--
If applicable, add any other context about the problem here.
-->

View File

@@ -1,36 +0,0 @@
---
name: Feature request
about: Suggest an idea for privacy.sexy
labels: enhancement
---
<!--
Thank you for suggesting an idea to improve privacy better 🤗.
Please fill in as much of the template below as you're able.
-->
### Problem description
<!--
What are we trying to solve?
Please add a clear and concise description of the problem you are seeking to solve with this feature request.
E.g. I'm always frustrated when [...]
-->
### Proposed solution
<!--
Describe the solution you'd like in a clear and concise manner.
-->
### Alternatives considered
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
### Additional information
<!--
If applicable, add any other context or screenshots about the feature request here.
-->

View File

@@ -0,0 +1,73 @@
name: "Suggestion: Feature"
description: 💡 Suggest new ideas to enhance privacy.sexy
labels: [ 'enhancement' ]
title: '[Feature]: '
body:
-
type: markdown
attributes:
value: |-
Thank you for contributing to privacy.sexy and guiding our direction! 🌟
Please complete as much of the form below as possible.
Your feedback is valuable, even if you can't provide all details.
-
type: textarea
attributes:
label: Problem statement
description: |-
What are we trying to solve?
Please add a clear and concise description of the problem you are seeking to solve with this feature request.
placeholder: >-
For example: "Every time I use the app, I struggle with..."
validations:
required: true
-
type: textarea
attributes:
label: Proposed solution
description: |-
Describe the solution you'd like in a clear and concise manner.
placeholder: >-
For example: "It would be great if the app could..."
validations:
required: true
-
type: textarea
attributes:
label: Alternatives considered
description: |-
Have you considered any alternative solutions or features?
Different perspectives can inspire new ideas.
placeholder: >-
For example: "We could also solve it by...".
validations:
required: false
-
type: textarea
attributes:
label: Additional information
description: |-
If applicable, add any other context or screenshots about the feature request here.
> **💡 Tip:** You can attach files or screenshots by dragging them into this area.
placeholder: >-
For example: "Challenges can be ..., but I'm unsure about ..., here is some documentation about it: ..."
validations:
required: false
-
type: markdown
attributes:
value: |-
---
**✉️ A friendly note from the maintainer:**
> [!NOTE]
> We are a small open-source project with a small community.
> It can sometimes take a long time for issues to be addressed, so please be patient.
> Consider [donating](https://undergroundwires.dev/donate) to keep privacy.sexy alive and improve support ❤️.
> But your issue will eventually get attention regardless.
> <p align="right">@undergroundwires</p>
---

View File

@@ -1,60 +0,0 @@
---
name: New script suggestion
about: Suggest a new script for privacy.sexy
labels: enhancement
---
<!--
Thank you for contributing to privacy.sexy! 🌟
For guidance, see our script guidelines: https://github.com/undergroundwires/privacy.sexy/blob/master/docs/script-guidelines.md.
Consider submitting a PR for faster implementation: https://github.com/undergroundwires/privacy.sexy/blob/master/CONTRIBUTING.md#extend-scripts.
-->
### Operating system
<!--
Specify the OS: Windows, macOS, or Linux.
-->
### Name
<!--
Suggest a name for the script.
Naming conventions: https://github.com/undergroundwires/privacy.sexy/blob/master/docs/script-guidelines.md#name.
-->
### Code
<!--
Provide or explain the code to execute when the script runs.
Code guidelines: https://github.com/undergroundwires/privacy.sexy/blob/master/docs/script-guidelines.md#code.
-->
### Revert code
<!--
Include code to revert changes to the default state.
Leave blank for non-reversible scripts.
-->
### Category
<!--
Suggest a category for the script.
If unsure, leave blank for maintainers to decide.
-->
### Recommendation level
<!--
Suggest a recommendation level: STANDARD (non-breaking), STRICT (limits functionality), or NONE (for advanced users).
If unsure, leave blank for maintainers to decide.
-->
### Documentation/References
<!--
Provide any relevant documentation or references.
Prefer high-quality sources such as vendor documentation.
Documentation guidelines: https://github.com/undergroundwires/privacy.sexy/blob/master/docs/script-guidelines.md#documentation.
-->

View File

@@ -0,0 +1,133 @@
name: "Suggestion: New Script"
description: 💡 Suggest new scripts to enhance privacy.sexy
labels: [ 'enhancement' ]
title: '[New script]: '
body:
-
type: markdown
attributes:
value: |-
Thank you for contributing to privacy.sexy and guiding our direction! 🌟
Please complete as much of the form below as possible.
Your feedback is valuable, even if you can't provide all details.
For guidance, see our [script guidelines](https://github.com/undergroundwires/privacy.sexy/blob/master/docs/script-guidelines.md).
Consider submitting a PR to get your script added more quickly: (see [CONTRIBUTING.md](https://github.com/undergroundwires/privacy.sexy/blob/master/CONTRIBUTING.md#extend-scripts))
-
type: dropdown
attributes:
label: Operating system
description: Which operating system will the new script configure?
options:
- macOS
- Windows
- Linux
- All of them
validations:
required: false
-
type: textarea
attributes:
label: Name of the script
description: |-
Suggest a name for the script that clearly describes its function.
See [script naming conventions](https://github.com/undergroundwires/privacy.sexy/blob/master/docs/script-guidelines.md#name) for best practices.
placeholder: E.g, "Disable error data submission"
validations:
required: true
-
type: textarea
attributes:
label: Documentation/References
description: |-
Provide any relevant documentation or references.
Prefer high-quality sources such as vendor documentation.
See [documentation guidelines](https://github.com/undergroundwires/privacy.sexy/blob/master/docs/script-guidelines.md#documentation) for best practices.
placeholder: >-
For example: "This script will disable the error data submission, see https://microsoft.com/...".
validations:
required: true
-
type: textarea
attributes:
label: Code
description: |-
If possible, provide or explain the code that the script should execute.
See [script code guidelines](https://github.com/undergroundwires/privacy.sexy/blob/master/docs/script-guidelines.md#code).
placeholder: |-
For example: "Set registry key like this `reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection" /v "AllowTelemetry" /t "REG_DWORD" /d "1"`".
validations:
required: false
-
type: textarea
attributes:
label: Revert code
description: |-
If applicable, provide revert code to restore the changes made by the script.
The revert code restores changes to their default state before script execution.
Leave blank for non-reversible scripts.
placeholder: |-
For example: "Revert to operating system default like this `reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection" /v "AllowTelemetry" /t "REG_DWORD" /d "0"`".
validations:
required: false
-
type: textarea
attributes:
label: Suggested category
description: |-
Suggest a category for the script.
If unsure, leave blank for maintainers to decide.
placeholder: >-
For example: "Privacy Cleanup > Clear system logs"
-
type: dropdown
attributes:
label: Recommendation level
description: |-
Suggest a recommendation level for the script:
- **Standard**: Recommended for most users without side-effects.
- **Strict**: Provides improved privacy at the cost of some functionality.
- **None**: For advanced users or specific needs.
If unsure, leave blank for maintainers to decide.
options:
- Standard
- Strict
- None (do not recommend)
validations:
required: false
-
type: textarea
attributes:
label: Additional information
description: |-
If applicable, add any other context or screenshots about the script request here.
> **💡 Tip:** You can attach additional documents or screenshots by dragging them into this area or pasting directly.
placeholder: >-
For example: "Challenges can be ..., but I am unsure about ..."
validations:
required: false
-
type: markdown
attributes:
value: |-
---
**✉️ A friendly note from the maintainer:**
> [!NOTE]
> We are a small open-source project with a small community.
> It can sometimes take a long time for issues to be addressed, so please be patient.
> Consider [donating](https://undergroundwires.dev/donate) to keep privacy.sexy alive and improve support ❤️.
> But your issue will eventually get attention regardless.
> <p align="right">@undergroundwires</p>
---

View File

@@ -1 +1,7 @@
blank_issues_enabled: true # This file must be named `config.yml`. GitHub does not recognize the file if it is named `config.yaml`.
blank_issues_enabled: true
contact_links:
- name: Donate
url: https://undergroundwires.dev/donate/
about: ❤️ Donate to support the free software you love to keep it alive.
# A separate link for reporting vulnerabilities is not included here because GitHub generates it automatically.

View File

@@ -6,4 +6,4 @@ runs:
uses: actions/setup-node@v4 uses: actions/setup-node@v4
with: with:
node-version: 20.x node-version: 20.x
check-latest: true # check-latest: true # Newest versions can potentially have undiscovered bugs or regressions

View File

@@ -72,16 +72,19 @@ jobs:
build-docker: build-docker:
strategy: strategy:
matrix: matrix:
os: [ macos, ubuntu ] # Windows runners do not support Linux containers os:
- macos-13 # Downgraded due to lack of nested virtualization support in ARM-based runners (See: actions/runner-images#9460, actions/runner-images#9741, abiosoft/colima#1023)
- ubuntu-latest
# - windows-latest # Windows runners do not support Linux containers
fail-fast: false # Allows to see results from other combinations fail-fast: false # Allows to see results from other combinations
runs-on: ${{ matrix.os }}-latest runs-on: ${{ matrix.os }}
steps: steps:
- -
name: Checkout name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- -
name: Install Docker on macOS name: Install Docker on macOS
if: matrix.os == 'macos' # macOS runner is missing Docker if: contains(matrix.os, 'macos') # macOS runner is missing Docker
run: |- run: |-
# Install Docker # Install Docker
brew install docker brew install docker

View File

@@ -9,9 +9,13 @@ jobs:
run-check: run-check:
strategy: strategy:
matrix: matrix:
os: [ macos, ubuntu, windows ] os:
- macos-latest # Apple silicon (ARM64)
- macos-13 # Intel-based (x86-64)
- ubuntu-latest
- windows-latest
fail-fast: false # Allows to see results from other combinations fail-fast: false # Allows to see results from other combinations
runs-on: ${{ matrix.os }}-latest runs-on: ${{ matrix.os }}
steps: steps:
- -
name: Checkout name: Checkout
@@ -24,7 +28,7 @@ jobs:
uses: ./.github/actions/npm-install-dependencies uses: ./.github/actions/npm-install-dependencies
- -
name: Configure Ubuntu name: Configure Ubuntu
if: matrix.os == 'ubuntu' if: contains(matrix.os, 'ubuntu') # macOS runner is missing Docker
shell: bash shell: bash
run: |- run: |-
sudo apt update sudo apt update

View File

@@ -1,10 +1,10 @@
name: quality-checks name: checks.quality
on: [ push, pull_request ] on: [ push, pull_request ]
jobs: jobs:
lint: lint:
runs-on: ubuntu-latest runs-on: ${{ matrix.os }}-latest
strategy: strategy:
matrix: matrix:
lint-command: lint-command:
@@ -28,3 +28,49 @@ jobs:
- -
name: Lint name: Lint
run: ${{ matrix.lint-command }} run: ${{ matrix.lint-command }}
todo-check:
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@v4
-
name: Scan latest commit for TODO comments
shell: bash
run: |-
readonly todo_comment_search_pattern='TODO'':' # Define search pattern in parts to prevent IDE from flagging this script line as a TODO item
if git grep "$todo_comment_search_pattern" HEAD; then
echo 'TODO comments found in the latest commit.'
exit 1
else
echo 'No TODO comments found in the latest commit.'
exit 0
fi
pylint:
runs-on: ${{ matrix.os }}-latest
strategy:
matrix:
os: [ macos, ubuntu, windows ]
fail-fast: false # Still interested to see results from other combinations
steps:
-
name: Checkout
uses: actions/checkout@v4
-
name: Setup node
uses: ./.github/actions/setup-node
-
name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.x'
-
name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install pylint
-
name: Analyzing the code with pylint
run: npm run lint:pylint

View File

@@ -15,6 +15,10 @@ jobs:
- -
name: Checkout name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
-
name: Install ImageMagick on macOS
if: matrix.os == 'macos'
run: brew install imagemagick
- -
name: Setup node name: Setup node
uses: ./.github/actions/setup-node uses: ./.github/actions/setup-node
@@ -53,3 +57,31 @@ jobs:
- -
name: Run install-deps name: Run install-deps
run: ${{ matrix.install-command }} run: ${{ matrix.install-command }}
configure-vscode:
runs-on: ${{ matrix.os.name }}-latest
strategy:
matrix:
os:
- name: macos
install-vscode-command: brew install --cask visual-studio-code
- name: ubuntu
install-vscode-command: sudo snap install code --classic
- name: windows
install-vscode-command: choco install vscode
fail-fast: false # Still interested to see results from other combinations
steps:
-
name: Checkout
uses: actions/checkout@v4
-
name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.x'
-
name: Install VSCode
run: ${{ matrix.os.install-vscode-command }}
-
name: Configure VSCode
run: python3 ./scripts/configure_vscode.py

View File

@@ -1,5 +1,58 @@
# Changelog # Changelog
## 0.13.3 (2024-05-11)
* win: organize and document network disablement | [2eed6f4](https://github.com/undergroundwires/privacy.sexy/commit/2eed6f4afb6cf85fdc1d6acb808f82405a35cafd)
* win: improve disabling SMBv1 protocol | [f584fab](https://github.com/undergroundwires/privacy.sexy/commit/f584fabb50c7de70ba43751d721af94d8fa2fa8a)
* win: improve disabling insecure renegotiations | [f261ab4](https://github.com/undergroundwires/privacy.sexy/commit/f261ab4cd9a53e31325e5c6da9129542971fe84b)
* win: doc, improve, encourage cipher disabling | [8b224ee](https://github.com/undergroundwires/privacy.sexy/commit/8b224eefe71be6a556a1085d8fe20dbd4b889430)
* ci/cd: add check for TODO comments | [4e21f05](https://github.com/undergroundwires/privacy.sexy/commit/4e21f05031d6cc90cda684bd598bec4735f8103b)
* win: improve 'Snipping Tool' removal #343 | [e18907c](https://github.com/undergroundwires/privacy.sexy/commit/e18907ca91e483255b44d14d7d923d7eef92afbd)
* ci/cd: lint Python scripts using `pylint` | [23bac0f](https://github.com/undergroundwires/privacy.sexy/commit/23bac0fc76ad697abb34f3fb327df5cdeb40286a)
* win: improve disabling insecure hashes #131 | [d19dde6](https://github.com/undergroundwires/privacy.sexy/commit/d19dde603ddac47022ee2e0ea865d53857560c26)
* Add system requirements documentation #134 | [0fc2ffc](https://github.com/undergroundwires/privacy.sexy/commit/0fc2ffc1ea36a9248c6a92da85a29f7b04b33796)
* win, linux, mac: fix various typos #349 | [694bf1a](https://github.com/undergroundwires/privacy.sexy/commit/694bf1a74d935531d7cd46891823af1fa58c3c8c)
* Fix script cancellation with new dialog on Linux | [8c17396](https://github.com/undergroundwires/privacy.sexy/commit/8c173962857a39dc0c9e5886cb2af4937e6618e7)
* win: improve disabling protocols | [4ef16ce](https://github.com/undergroundwires/privacy.sexy/commit/4ef16cea56789120cd041412d86b5577cccf0725)
* win: fix Copilot by excluding `r.bing.com` #329 | [66a5688](https://github.com/undergroundwires/privacy.sexy/commit/66a56888a4b3ead1a6bfef0feffa0218535701fe)
* Fix blank window on load on desktop version #348 | [813d820](https://github.com/undergroundwires/privacy.sexy/commit/813d820b85e1b623c50f8e0325ad372bf2f344f9)
* Improve desktop icon quality and generation | [ab25e0a](https://github.com/undergroundwires/privacy.sexy/commit/ab25e0a066be14ea979dafd0f80e1091bd5d33f8)
* win: improve enabling secure connections #175 | [c75df1c](https://github.com/undergroundwires/privacy.sexy/commit/c75df1c8c1151b64cbf014383dea0b748a8c78b3)
* Fix VSCode script issues with added CI/CD tests | [1d7cafc](https://github.com/undergroundwires/privacy.sexy/commit/1d7cafc831dcc339a10646794410dad7096bfe60)
* Fix win execution with whitespace in username #351 | [a334320](https://github.com/undergroundwires/privacy.sexy/commit/a3343205b1196d5a81fd3cee2ae661ce871a7bef)
* Fix misaligned tooltip positions in modal dialogs | [dd71536](https://github.com/undergroundwires/privacy.sexy/commit/dd71536316ec819caeb418b8635d544ac80e58ad)
* Fix Chromium scrollbar-induced layout shifts | [bc4879c](https://github.com/undergroundwires/privacy.sexy/commit/bc4879cfe97becac3c54f6b40780a89464d3b772)
* ci/cd: remove `check-latest` from `setup-node` | [52a4730](https://github.com/undergroundwires/privacy.sexy/commit/52a4730073b8ebfb2ce9d530b44e4a179f5849fe)
* win: categorize and rename network security #131 | [9fd193e](https://github.com/undergroundwires/privacy.sexy/commit/9fd193e676f1f0646898f5130fbfaaf25050b2e3)
[compare](https://github.com/undergroundwires/privacy.sexy/compare/0.13.2...0.13.3)
## 0.13.2 (2024-04-15)
* Update documentation for `logo-update.js` script | [4a9b430](https://github.com/undergroundwires/privacy.sexy/commit/4a9b430702bc6082426b50ecc3a06362b5720796)
* win: improve and document removing Phone apps #279 | [8924337](https://github.com/undergroundwires/privacy.sexy/commit/89243371faa5d6aef5fce52b0d54a442143cdd39)
* Fix bottom gap in card expansion panel | [79183d6](https://github.com/undergroundwires/privacy.sexy/commit/79183d64173e588d88bf074d5b50a52a71c2d885)
* ci/cd: Fix macOS Docker build reliability issues | [8a5592f](https://github.com/undergroundwires/privacy.sexy/commit/8a5592f92be4366a806afc9eee9135696a1dd993)
* ci/cd: fix IPv6 timeouts with `force-ipv4` action | [52fadcd](https://github.com/undergroundwires/privacy.sexy/commit/52fadcd6177ed06216be9c67dad57192ae02a4f9)
* ci/cd: bump Node.js environment to 20.x | [59decd1](https://github.com/undergroundwires/privacy.sexy/commit/59decd17e273bada1493eaa855c43cbabf90308f)
* ci/cd: trigger URL checks more, and limit amount | [4fb6302](https://github.com/undergroundwires/privacy.sexy/commit/4fb6302c67f2a3fedff419e8c22872593cf800ef)
* Fix overflow in tree node content on small screens | [557cea3](https://github.com/undergroundwires/privacy.sexy/commit/557cea3f4866dc33236874f5fe4d2d69ee963dae)
* Fix horizontal layout shift after script selection | [bc7e1fa](https://github.com/undergroundwires/privacy.sexy/commit/bc7e1faa1c3f2b61bf2046fdd6d6a4141b484662)
* Fix card header expansion glitch on card collapse | [5d940b5](https://github.com/undergroundwires/privacy.sexy/commit/5d940b57ef2a4c219932cd15201401f8550cfb41)
* Ignore `ResizeObserver` errors in Cypress tests | [4472c28](https://github.com/undergroundwires/privacy.sexy/commit/4472c2852e4b87083bda7979471ab9f377d17a01)
* win: improve and document secret key scripts | [49f22f0](https://github.com/undergroundwires/privacy.sexy/commit/49f22f048f39e7388633c488b5fe59101b831984)
* Fix card arrow not being animated in sync | [7b546c5](https://github.com/undergroundwires/privacy.sexy/commit/7b546c567c4683a37fe94595362f4c2bf92ffd59)
* win: improve Windows feature disablement scripts | [b68711e](https://github.com/undergroundwires/privacy.sexy/commit/b68711ef88982c0ee2b1d41b4452e899821adc64)
* Fix top script menu overflow on small screens | [b7a20d9](https://github.com/undergroundwires/privacy.sexy/commit/b7a20d9d41ea8bcefdd553b87641f3c22b4cde97)
* win: fix Visual Studio remote analysis script #327 | [4142d08](https://github.com/undergroundwires/privacy.sexy/commit/4142d084f64a3b540487ff68b28032977d12006d)
* win: improve firewall docs /w `winget` impact #142 | [ffd647d](https://github.com/undergroundwires/privacy.sexy/commit/ffd647d1529375474b81900cc7bee4c32fbf861f)
* Centralize and use global spacing variables | [ae17200](https://github.com/undergroundwires/privacy.sexy/commit/ae172000a64416e5a3e2b2e32b7846f039f445f0)
* win: improve service revert and docs | [b87b7aa](https://github.com/undergroundwires/privacy.sexy/commit/b87b7aac7d118a23a0d1bfb881e385347de4adb7)
* Bump dependencies to latest, hold ESLint | [f3571ab](https://github.com/undergroundwires/privacy.sexy/commit/f3571abeafdbe1e6d152958fab26de91a9c08bc3)
* Fix inability to tap outside modal on mobile | [cb144ae](https://github.com/undergroundwires/privacy.sexy/commit/cb144ae47273deeb7058d4b1380e480ebccdaf81)
[compare](https://github.com/undergroundwires/privacy.sexy/compare/0.13.1...0.13.2)
## 0.13.1 (2024-03-22) ## 0.13.1 (2024-03-22)
* ci/cd: Fix cross-platform git command compability | [255c51c](https://github.com/undergroundwires/privacy.sexy/commit/255c51c8a0524d3ea8a3b16ffc1b178650525010) * ci/cd: Fix cross-platform git command compability | [255c51c](https://github.com/undergroundwires/privacy.sexy/commit/255c51c8a0524d3ea8a3b16ffc1b178650525010)

View File

@@ -60,8 +60,8 @@
<br /> <br />
<a href="https://github.com/undergroundwires/privacy.sexy/actions/workflows/checks.quality.yaml" target="_blank" rel="noopener noreferrer"> <a href="https://github.com/undergroundwires/privacy.sexy/actions/workflows/checks.quality.yaml" target="_blank" rel="noopener noreferrer">
<img <img
alt="Quality checks status" alt="Status of quality checks"
src="https://github.com/undergroundwires/privacy.sexy/workflows/quality-checks/badge.svg" src="https://github.com/undergroundwires/privacy.sexy/workflows/checks.quality/badge.svg"
/> />
</a> </a>
<a href="https://github.com/undergroundwires/privacy.sexy/actions/workflows/checks.build.yaml" target="_blank" rel="noopener noreferrer"> <a href="https://github.com/undergroundwires/privacy.sexy/actions/workflows/checks.build.yaml" target="_blank" rel="noopener noreferrer">
@@ -122,9 +122,12 @@
## Get started ## Get started
- 🌍️ **Online**: [https://privacy.sexy](https://privacy.sexy). - 🌍️ **Online**: [https://privacy.sexy](https://privacy.sexy).
- 🖥️ **Offline**: Download directly for: [Windows](https://github.com/undergroundwires/privacy.sexy/releases/download/0.13.1/privacy.sexy-Setup-0.13.1.exe), [macOS](https://github.com/undergroundwires/privacy.sexy/releases/download/0.13.1/privacy.sexy-0.13.1.dmg), [Linux](https://github.com/undergroundwires/privacy.sexy/releases/download/0.13.1/privacy.sexy-0.13.1.AppImage). For more options, see [here](#additional-install-options). - 🖥️ **Offline**: Download directly for: [Windows](https://github.com/undergroundwires/privacy.sexy/releases/download/0.13.3/privacy.sexy-Setup-0.13.3.exe), [macOS](https://github.com/undergroundwires/privacy.sexy/releases/download/0.13.3/privacy.sexy-0.13.3.dmg), [Linux](https://github.com/undergroundwires/privacy.sexy/releases/download/0.13.3/privacy.sexy-0.13.3.AppImage). For more options, see [here](#additional-install-options).
For a detailed comparison of features between the desktop and web versions of privacy.sexy, see [Desktop vs. Web Features](./docs/desktop-vs-web-features.md). See also:
- [Desktop vs. Web Features](./docs/desktop/desktop-vs-web-features.md): Differences and unique aspects of desktop and web versions.
- [System Requirements](./docs/desktop/system-requirements.md): Hardware and software requirements for the desktop version.
💡 Regularly applying your configuration with privacy.sexy is recommended, especially after each new release and major operating system updates. Each version updates scripts to enhance stability, privacy, and security. 💡 Regularly applying your configuration with privacy.sexy is recommended, especially after each new release and major operating system updates. Each version updates scripts to enhance stability, privacy, and security.

View File

@@ -43,10 +43,17 @@ privacy.sexy adopts a defense in depth strategy to protect users on multiple lay
elevation of privileges for system modifications with explicit user consent and logs every action taken with high privileges. This elevation of privileges for system modifications with explicit user consent and logs every action taken with high privileges. This
approach actively minimizes potential security risks by limiting privileged operations and aligning with the principle of least privilege. approach actively minimizes potential security risks by limiting privileged operations and aligning with the principle of least privilege.
- **Secure Script Execution/Storage:** - **Secure Script Execution/Storage:**
Before executing any script, the desktop application stores a copy to allow antivirus software to perform scans. This safeguards against - **Antivirus scans:**
any unwanted modifications. Furthermore, the application incorporates integrity checks for tamper protection. If the script file differs from Before executing any script, the desktop application stores a copy to allow antivirus software to perform scans.
the user's selected script, the application will not execute or save the script, ensuring the processing of authentic scripts. This step allows confirming that the scripts are secure and safe to use.
Recognizing that some users prefer not to keep these records, privacy.sexy provides specialized scripts for deletion of these scripts. - **Tamper protection:**
The application incorporates integrity checks for tamper protection.
If the script file differs from the user's selected script, the application will not execute or save the script, ensuring the processing
of authentic scripts.
This safeguards against any unwanted modifications.
- **Clean-up:**
Recognizing that some users prefer not to keep these records, privacy.sexy provides specialized scripts for deletion of these scripts.
This allows users to maintain their privacy by removing traces of their usage patterns or script preferences.
### Update Security and Integrity ### Update Security and Integrity

View File

@@ -1,5 +0,0 @@
# build
This folder contains files that are used by Electron to serve the desktop version.
Icons are created from the main logo file and should not be changed manually, see [related documentation](./../img/README.md).

Binary file not shown.

Before

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 553 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 963 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

View File

@@ -1,6 +1,6 @@
# Desktop vs. Web Features # Desktop vs. Web Features
This table highlights differences between the desktop and web versions of `privacy.sexy`. This table outlines the differences between the desktop and web versions of `privacy.sexy`.
| Feature | Desktop | Web | | Feature | Desktop | Web |
| ------- | ------- | --- | | ------- | ------- | --- |
@@ -8,10 +8,8 @@ This table highlights differences between the desktop and web versions of `priva
| [Offline usage](#offline-usage) | 🟢 Available | 🟡 Partially available | | [Offline usage](#offline-usage) | 🟢 Available | 🟡 Partially available |
| [Auto-updates](#auto-updates) | 🟢 Available | 🟢 Available | | [Auto-updates](#auto-updates) | 🟢 Available | 🟢 Available |
| [Logging](#logging) | 🟢 Available | 🔴 Not available | | [Logging](#logging) | 🟢 Available | 🔴 Not available |
| [Script execution](#script-execution) | 🟢 Available | 🔴 Not available |
| [Error handling](#error-handling) | 🟢 Advanced | 🟡 Limited |
| [Native dialogs](#native-dialogs) | 🟢 Available | 🔴 Not available |
| [Secure script execution/storage](#secure-script-executionstorage) | 🟢 Available | 🔴 Not available | | [Secure script execution/storage](#secure-script-executionstorage) | 🟢 Available | 🔴 Not available |
| [Native dialogs](#native-dialogs) | 🟢 Available | 🔴 Not available |
## Feature descriptions ## Feature descriptions
@@ -30,11 +28,11 @@ Desktop version inherently allows offline usage.
### Auto-updates ### Auto-updates
Both the desktop and web versions of privacy.sexy provide timely access to the latest features and security improvements. The updates are automatically deployed from source code, reflecting the latest changes for enhanced security and reliability. For more details, see [CI/CD documentation](./ci-cd.md). Both the desktop and web versions of privacy.sexy provide timely access to the latest features and security improvements. The updates are automatically deployed from source code, reflecting the latest changes for enhanced security and reliability. For more details, see [CI/CD documentation](./../ci-cd.md).
The desktop version ensures secure delivery through cryptographic signatures and version checks. The desktop version ensures secure delivery through cryptographic signatures and version checks.
[Security is a top priority](./../SECURITY.md#update-security-and-integrity) at privacy.sexy. [Security is a top priority](./../../SECURITY.md#update-security-and-integrity) at privacy.sexy.
> **Note for macOS users:** On macOS, the desktop version's auto-update process involves manual steps due to Apple's code signing costs. > **Note for macOS users:** On macOS, the desktop version's auto-update process involves manual steps due to Apple's code signing costs.
> Users get notified about updates but might need to complete the installation manually. > Users get notified about updates but might need to complete the installation manually.
@@ -53,7 +51,7 @@ Log file locations vary by operating system:
> 💡 privacy.sexy provides scripts to securely erase these logs. > 💡 privacy.sexy provides scripts to securely erase these logs.
### Script execution ### Secure script execution/storage
The desktop version of privacy.sexy enables direct script execution, providing a seamless and integrated experience. The desktop version of privacy.sexy enables direct script execution, providing a seamless and integrated experience.
This direct execution capability isn't available in the web version due to inherent browser restrictions. This direct execution capability isn't available in the web version due to inherent browser restrictions.
@@ -69,31 +67,27 @@ These locations vary based on the operating system:
> 💡 privacy.sexy provides scripts to securely erase your script execution history. > 💡 privacy.sexy provides scripts to securely erase your script execution history.
### Error handling **Script antivirus scans:**
The desktop version of privacy.sexy features advanced error handling capabilities. To enhance system protection, the desktop version of privacy.sexy automatically verifies the security of script
It employs robust and reliable execution strategies, including self-healing mechanisms, and provides guidance and troubleshooting information to resolve issues effectively. execution files by reading them back.
In contrast, the web version has more basic error handling due to browser limitations and the nature of web applications. This process triggers antivirus scans to verify that scripts are safe before the execution.
### Native dialogs **Script integrity checks:**
The desktop version uses native dialogs, offering more features and reliability compared to the browser's file system dialogs.
These native dialogs provide a more integrated and user-friendly experience, aligning with the operating system's standard interface and functionalities.
### Secure script execution/storage
**Integrity checks:**
The desktop version of privacy.sexy implements robust integrity checks for both script execution and storage. The desktop version of privacy.sexy implements robust integrity checks for both script execution and storage.
Featuring tamper protection, the application actively verifies the integrity of script files before executing or saving them. Featuring tamper protection, the application actively verifies the integrity of script files before executing or saving them.
If the actual contents of a script file do not align with the expected contents, the application refuses to execute or save the script. If the actual contents of a script file do not align with the expected contents, the application refuses to execute or save the script.
This proactive approach ensures only unaltered and verified scripts undergo processing, thereby enhancing both security and reliability. This proactive approach ensures only unaltered and verified scripts undergo processing, thereby enhancing both security and reliability.
Due to browser constraints, this feature is absent in the web version.
**Error handling:** **Error handling:**
The desktop version of privacy.sexy features advanced error handling capabilities.
In scenarios where script execution or storage encounters failure, the desktop application initiates automated troubleshooting and self-healing processes. In scenarios where script execution or storage encounters failure, the desktop application initiates automated troubleshooting and self-healing processes.
It also guides users through potential issues with filesystem or third-party software, such as antivirus interventions. It employs robust and reliable execution strategies, including self-healing mechanisms, and provides guidance and troubleshooting information to resolve issues effectively.
Specifically, the application is capable of identifying when antivirus software blocks or removes a script, providing users with tailored error messages This proactive error handling and user guidance enhances the application's security and reliability.
and detailed resolution steps. This level of proactive error handling and user guidance enhances the application's security and reliability,
offering a feature not achievable in the web version due to browser limitations. ### Native dialogs
The desktop version uses native dialogs, offering more features and reliability compared to the browser's file system dialogs.
These native dialogs provide a more integrated and user-friendly experience, aligning with the operating system's standard interface and functionalities.

View File

@@ -0,0 +1,36 @@
# System Requirements for the Desktop Version
The following system requirements are the official ones for the desktop version.
While we have tested and confirmed these requirements, the application might also work on other
systems or configurations that haven't undergone official testing.
## Windows
- **Version:** Windows 10 and later.
- **Processor:** Intel Pentium 4 or later.
- **Architecture:** 64-bit (x86-64), ARM (ARM64).
> **⚠️ Compatibility Note:**
> ARM version is only compatible with Windows 11 and later.
> It runs non-natively, leading to slower performance due to emulation [1].
## macOS
- **Version:** macOS Catalina (10.15) and later.
- **Architecture:** Intel-based (x86-64), Apple silicon (ARM64).
## Linux
- **Version:** Ubuntu 18.04 and later, Fedora 32 and later, and Debian 10 and later.
- **Processor:** Intel Pentium 4 or later.
- **Architecture:** 64-bit (x86-64).
## References
System requirements reflect Electron's platform capabilities [2] and Chromium's recommended configurations [3].
For details on the build process, see [electron-builder configuration file](./../../electron-builder.cjs).
[1]: https://web.archive.org/web/20240428082726/https://learn.microsoft.com/en-us/windows/arm/add-arm-support#emulation-on-arm-based-devices-for-x86-or-x64-windows-apps "Add support Arm devices to your Windows app | Microsoft Learn | learn.microsoft.com"
[2]: https://archive.ph/2024.04.28-082958/https://github.com/electron/electron/blob/main/README.md#platform-support "Platform Support | electron/README.md at main · electron/electron · GitHub | github.com"
[3]: https://web.archive.org/web/20240428082945/https://support.google.com/chrome/a/answer/7100626?hl=en "Chrome browser system requirements - Chrome Enterprise and Education Help | support.google.com"

View File

@@ -23,8 +23,10 @@ The presentation layer uses an event-driven architecture for bidirectional react
- [**`styles/`**](./../src/presentation/assets/styles/): Contains shared styles. - [**`styles/`**](./../src/presentation/assets/styles/): Contains shared styles.
- [**`main.scss`**](./../src/presentation/assets/styles/main.scss): Main Sass file, imported by other components as single entrypoint.. - [**`main.scss`**](./../src/presentation/assets/styles/main.scss): Main Sass file, imported by other components as single entrypoint..
- [**`electron/`**](./../src/presentation/electron/): Contains Electron code. - [**`electron/`**](./../src/presentation/electron/): Contains Electron code.
- [`/main/` **`index.ts`**](./../src/presentation/main.ts): Main entry for Electron, managing application windows and lifecycle events. - [`/main/` **`index.ts`**](./../src/presentation/electron/main/index.ts): Main entry for Electron, managing application windows and lifecycle events.
- [`/preload/` **`index.ts`**](./../src/presentation/main.ts): Script executed before the renderer, securing Node.js features for renderer use. - [`/preload/` **`index.ts`**](./../src/presentation/electron/preload/index.ts): Script executed before the renderer, securing Node.js features for renderer use.
- [**`/shared/`**](./../src/presentation/electron/shared/): Shared logic between different Electron processes.
- [**`/build/`**](./../src/presentation/electron/build/): `electron-builder` build resources directory, [README.md](./../src/presentation/electron/build/README.md).
- [**`/vite.config.ts`**](./../vite.config.ts): Contains Vite configurations for building web application. - [**`/vite.config.ts`**](./../vite.config.ts): Contains Vite configurations for building web application.
- [**`/electron.vite.config.ts`**](./../electron.vite.config.ts): Contains Vite configurations for building desktop applications. - [**`/electron.vite.config.ts`**](./../electron.vite.config.ts): Contains Vite configurations for building desktop applications.
- [**`/postcss.config.cjs`**](./../postcss.config.cjs): Contains PostCSS configurations for Vite. - [**`/postcss.config.cjs`**](./../postcss.config.cjs): Contains PostCSS configurations for Vite.

View File

@@ -27,6 +27,7 @@ Key attributes of a good script:
- `Minimize` over `Limit`, `Reduce` - `Minimize` over `Limit`, `Reduce`
- `Maximize` over `Extend`, `Delay`, `Postpone`, `Prolong` - `Maximize` over `Extend`, `Delay`, `Postpone`, `Prolong`
- `Remove` over `Uninstall` - `Remove` over `Uninstall`
- `Improve` over `Increase`
- Structure your phrases for clarity, examples: - Structure your phrases for clarity, examples:
- Prefer `Disable XX telemetry` over `Disable telemetry in XX` - Prefer `Disable XX telemetry` over `Disable telemetry in XX`
- Prefer `Clear XX data` over `Clear data from XX`, or `Clear data of XX`. - Prefer `Clear XX data` over `Clear data from XX`, or `Clear data of XX`.

View File

@@ -1,7 +1,7 @@
/* eslint-disable no-template-curly-in-string */ /* eslint-disable no-template-curly-in-string */
const { join } = require('node:path'); const { join, resolve } = require('node:path');
const { readdirSync } = require('fs'); const { readdirSync, existsSync } = require('node:fs');
const { electronBundled, electronUnbundled } = require('./dist-dirs.json'); const { electronBundled, electronUnbundled } = require('./dist-dirs.json');
/** /**
@@ -17,6 +17,7 @@ module.exports = {
}, },
directories: { directories: {
output: electronBundled, output: electronBundled,
buildResources: resolvePathFromProjectRoot('src/presentation/electron/build'),
}, },
extraMetadata: { extraMetadata: {
main: findMainEntryFile( main: findMainEntryFile(
@@ -42,7 +43,10 @@ module.exports = {
// macOS // macOS
mac: { mac: {
target: 'dmg', target: {
target: 'dmg',
arch: 'universal',
},
}, },
dmg: { dmg: {
artifactName: '${name}-${version}.${ext}', artifactName: '${name}-${version}.${ext}',
@@ -53,10 +57,18 @@ module.exports = {
* Finds by accommodating different JS file extensions and module formats. * Finds by accommodating different JS file extensions and module formats.
*/ */
function findMainEntryFile(parentDirectory) { function findMainEntryFile(parentDirectory) {
const files = readdirSync(parentDirectory); const absoluteParentDirectory = resolvePathFromProjectRoot(parentDirectory);
if (!existsSync(absoluteParentDirectory)) {
return null; // Avoid disrupting other processes such `npm install`.
}
const files = readdirSync(absoluteParentDirectory);
const entryFile = files.find((file) => /^index\.(cjs|mjs|js)$/.test(file)); const entryFile = files.find((file) => /^index\.(cjs|mjs|js)$/.test(file));
if (!entryFile) { if (!entryFile) {
throw new Error(`Main entry file not found in ${parentDirectory}.`); throw new Error(`Main entry file not found in ${absoluteParentDirectory}.`);
} }
return join(parentDirectory, entryFile); return join(parentDirectory, entryFile);
} }
function resolvePathFromProjectRoot(pathSegment) {
return resolve(__dirname, pathSegment);
}

4181
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{ {
"name": "privacy.sexy", "name": "privacy.sexy",
"version": "0.13.1", "version": "0.13.3",
"private": true, "private": true,
"slogan": "Privacy is sexy", "slogan": "Privacy is sexy",
"description": "Enforce privacy & security best-practices on Windows, macOS and Linux, because privacy is sexy.", "description": "Enforce privacy & security best-practices on Windows, macOS and Linux, because privacy is sexy.",
@@ -14,7 +14,7 @@
"test:integration": "vitest run --dir tests/integration", "test:integration": "vitest run --dir tests/integration",
"test:cy:run": "start-server-and-test \"vite build && vite preview --port 7070\" http://localhost:7070 \"cypress run --config baseUrl=http://localhost:7070\"", "test:cy:run": "start-server-and-test \"vite build && vite preview --port 7070\" http://localhost:7070 \"cypress run --config baseUrl=http://localhost:7070\"",
"test:cy:open": "start-server-and-test \"vite --port 7070 --mode production\" http://localhost:7070 \"cypress open --config baseUrl=http://localhost:7070\"", "test:cy:open": "start-server-and-test \"vite --port 7070 --mode production\" http://localhost:7070 \"cypress open --config baseUrl=http://localhost:7070\"",
"lint": "npm run lint:md && npm run lint:md:consistency && npm run lint:md:relative-urls && npm run lint:eslint && npm run lint:yaml", "lint": "npm run lint:md && npm run lint:md:consistency && npm run lint:md:relative-urls && npm run lint:eslint && npm run lint:yaml && npm run lint:pylint",
"install-deps": "node scripts/npm-install.js", "install-deps": "node scripts/npm-install.js",
"icons:build": "node scripts/logo-update.js", "icons:build": "node scripts/logo-update.js",
"check:desktop": "vitest run --dir tests/checks/desktop-runtime-errors --environment node", "check:desktop": "vitest run --dir tests/checks/desktop-runtime-errors --environment node",
@@ -29,6 +29,7 @@
"lint:md:consistency": "remark . --frail --use remark-preset-lint-consistent", "lint:md:consistency": "remark . --frail --use remark-preset-lint-consistent",
"lint:md:relative-urls": "remark . --frail --use remark-validate-links", "lint:md:relative-urls": "remark . --frail --use remark-validate-links",
"lint:yaml": "yamllint **/*.yaml --ignore=node_modules/**/*.yaml", "lint:yaml": "yamllint **/*.yaml --ignore=node_modules/**/*.yaml",
"lint:pylint": "pylint **/*.py",
"postinstall": "electron-builder install-app-deps", "postinstall": "electron-builder install-app-deps",
"postuninstall": "electron-builder install-app-deps" "postuninstall": "electron-builder install-app-deps"
}, },
@@ -41,7 +42,7 @@
"electron-updater": "^6.1.9", "electron-updater": "^6.1.9",
"file-saver": "^2.0.5", "file-saver": "^2.0.5",
"markdown-it": "^14.1.0", "markdown-it": "^14.1.0",
"vue": "^3.4.21" "vue": "^3.4.27"
}, },
"devDependencies": { "devDependencies": {
"@modyfi/vite-plugin-yaml": "^1.1.0", "@modyfi/vite-plugin-yaml": "^1.1.0",
@@ -61,13 +62,11 @@
"electron": "^29.3.0", "electron": "^29.3.0",
"electron-builder": "^24.13.3", "electron-builder": "^24.13.3",
"electron-devtools-installer": "^3.2.0", "electron-devtools-installer": "^3.2.0",
"electron-icon-builder": "^2.0.1",
"electron-vite": "^2.1.0", "electron-vite": "^2.1.0",
"eslint": "8.57.0", "eslint": "8.57.0",
"eslint-plugin-cypress": "^2.15.1", "eslint-plugin-cypress": "^2.15.1",
"eslint-plugin-vue": "^9.25.0", "eslint-plugin-vue": "^9.25.0",
"eslint-plugin-vuejs-accessibility": "^2.2.1", "eslint-plugin-vuejs-accessibility": "^2.2.1",
"icon-gen": "^4.0.0",
"jsdom": "^24.0.0", "jsdom": "^24.0.0",
"markdownlint-cli": "^0.39.0", "markdownlint-cli": "^0.39.0",
"postcss": "^8.4.38", "postcss": "^8.4.38",
@@ -77,7 +76,6 @@
"remark-validate-links": "^13.0.1", "remark-validate-links": "^13.0.1",
"sass": "^1.75.0", "sass": "^1.75.0",
"start-server-and-test": "^2.0.3", "start-server-and-test": "^2.0.3",
"svgexport": "^0.4.2",
"terser": "^5.30.3", "terser": "^5.30.3",
"tslib": "^2.6.2", "tslib": "^2.6.2",
"typescript": "^5.4.5", "typescript": "^5.4.5",

View File

@@ -1,6 +1,10 @@
""" """
This script configures project-level VSCode settings in '.vscode/settings.json' for Description:
development and installs recommended extensions from '.vscode/extensions.json'. This script configures project-level VSCode settings in '.vscode/settings.json' for
development and installs recommended extensions from '.vscode/extensions.json'.
Usage:
python3 ./scripts/configure_vscode.py
""" """
# pylint: disable=missing-function-docstring # pylint: disable=missing-function-docstring
@@ -40,7 +44,7 @@ def ensure_setting_file_exists() -> None:
print_success(f"Created empty {VSCODE_SETTINGS_JSON_FILE}") print_success(f"Created empty {VSCODE_SETTINGS_JSON_FILE}")
except IOError as error: except IOError as error:
print_error(f"Error creating file {VSCODE_SETTINGS_JSON_FILE}: {error}") print_error(f"Error creating file {VSCODE_SETTINGS_JSON_FILE}: {error}")
print(f"📄 Created empty {VSCODE_SETTINGS_JSON_FILE}") print_success(f"Created empty {VSCODE_SETTINGS_JSON_FILE}")
def add_or_update_settings() -> None: def add_or_update_settings() -> None:
configure_setting_key('eslint.validate', ['vue', 'javascript', 'typescript']) configure_setting_key('eslint.validate', ['vue', 'javascript', 'typescript'])
@@ -98,7 +102,8 @@ def locate_vscode_cli() -> Optional[str]:
if vscode_alias: if vscode_alias:
return vscode_alias return vscode_alias
potential_vscode_cli_paths = [ potential_vscode_cli_paths = [
'/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code' # macOS VS Code may not register 'code' command in PATH # VS Code on macOS may not register 'code' command in PATH
'/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code'
] ]
for vscode_cli_candidate_path in potential_vscode_cli_paths: for vscode_cli_candidate_path in potential_vscode_cli_paths:
if Path(vscode_cli_candidate_path).is_file(): if Path(vscode_cli_candidate_path).is_file():
@@ -109,7 +114,7 @@ def remove_json_comments(json_like: str) -> str:
pattern: str = r'(?:"(?:\\.|[^"\\])*"|/\*[\s\S]*?\*/|//.*)|([^:]//.*$)' pattern: str = r'(?:"(?:\\.|[^"\\])*"|/\*[\s\S]*?\*/|//.*)|([^:]//.*$)'
return re.sub( return re.sub(
pattern, pattern,
lambda m: '' if m.group(1) else m.agroup(0), json_like, flags=re.MULTILINE, lambda m: '' if m.group(1) else m.group(0), json_like, flags=re.MULTILINE,
) )
def install_vscode_extensions(vscode_cli_path: str, extensions: list[str]) -> None: def install_vscode_extensions(vscode_cli_path: str, extensions: list[str]) -> None:
@@ -166,16 +171,16 @@ def print_installation_results(successful_installations: int, total_extensions:
print_error("Failed to install any of the recommended extensions.") print_error("Failed to install any of the recommended extensions.")
def print_error(message: str) -> None: def print_error(message: str) -> None:
print(f"💀 Error: {message}", file=sys.stderr) print(f"[ERROR] {message}", file=sys.stderr)
def print_success(message: str) -> None: def print_success(message: str) -> None:
print(f"✅ Success: {message}") print(f"[SUCCESS] {message}")
def print_skip(message: str) -> None: def print_skip(message: str) -> None:
print(f"⏩ Skipped: {message}") print(f"[SKIPPED] {message}")
def print_warning(message: str) -> None: def print_warning(message: str) -> None:
print(f"⚠️ Warning: {message}", file=sys.stderr) print(f"[WARNING] {message}", file=sys.stderr)
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@@ -2,94 +2,119 @@
* Description: * Description:
* This script updates the logo images across the project based on the primary * This script updates the logo images across the project based on the primary
* logo file ('img/logo.svg' file). * logo file ('img/logo.svg' file).
*
* It handles the creation and update of various icon sizes for different purposes, * It handles the creation and update of various icon sizes for different purposes,
* including desktop launcher icons, tray icons, and web favicons from a single source * including desktop launcher icons, tray icons, and web favicons from a single source
* SVG logo file. * SVG logo file.
* *
* Usage: * Usage:
* node ./scripts/logo-update.js * node ./scripts/logo-update.js
*
* Notes:
* ImageMagick must be installed and accessible in the system's PATH
*/ */
import { resolve, join } from 'node:path'; import { resolve, join, dirname } from 'node:path';
import { rm, mkdtemp, stat } from 'node:fs/promises'; import { stat } from 'node:fs/promises';
import { spawn } from 'node:child_process'; import { spawn } from 'node:child_process';
import { URL, fileURLToPath } from 'node:url'; import { URL, fileURLToPath } from 'node:url';
import electronBuilderConfig from '../electron-builder.cjs';
class Paths { class ImageAssetPaths {
constructor(selfDirectory) { constructor(currentScriptDirectory) {
const projectRoot = resolve(selfDirectory, '../'); const projectRoot = resolve(currentScriptDirectory, '../');
this.sourceImage = join(projectRoot, 'img/logo.svg'); this.sourceImage = join(projectRoot, 'img/logo.svg');
this.publicDirectory = join(projectRoot, 'src/presentation/public'); this.publicDirectory = join(projectRoot, 'src/presentation/public');
this.electronBuildDirectory = join(projectRoot, 'build'); this.electronBuildResourcesDirectory = electronBuilderConfig.directories.buildResources;
}
get electronTrayIconFile() {
return join(this.publicDirectory, 'icon.png');
}
get webFaviconFile() {
return join(this.publicDirectory, 'favicon.ico');
} }
toString() { toString() {
return `Source image: ${this.sourceImage}\n` return `Source image: ${this.sourceImage}`
+ `Public directory: ${this.publicDirectory}\n` + `\nPublic directory: ${this.publicDirectory}`
+ `Electron build directory: ${this.electronBuildDirectory}`; + `\n\t Electron tray icon file: ${this.electronTrayIconFile}`
+ `\n\t Web favicon file: ${this.webFaviconFile}`
+ `\nElectron build directory: ${this.electronBuildResourcesDirectory}`;
} }
} }
async function main() { async function main() {
const paths = new Paths(getCurrentScriptDirectory()); const paths = new ImageAssetPaths(getCurrentScriptDirectory());
console.log(`Paths:\n\t${paths.toString().replaceAll('\n', '\n\t')}`); console.log(`Paths:\n\t${paths.toString().replaceAll('\n', '\n\t')}`);
await updateDesktopLauncherAndTrayIcon(paths.sourceImage, paths.publicDirectory); const convertCommand = await findAvailableImageMagickCommand();
await updateWebFavicon(paths.sourceImage, paths.publicDirectory); await generateDesktopAndTrayIcons(
await updateDesktopIcons(paths.sourceImage, paths.electronBuildDirectory); paths.sourceImage,
paths.electronTrayIconFile,
convertCommand,
);
await generateWebFavicon(
paths.sourceImage,
paths.webFaviconFile,
convertCommand,
);
await generateDesktopIcons(
paths.sourceImage,
paths.electronBuildResourcesDirectory,
convertCommand,
);
console.log('🎉 (Re)created icons successfully.'); console.log('🎉 (Re)created icons successfully.');
} }
async function updateDesktopLauncherAndTrayIcon(sourceImage, publicFolder) { async function generateDesktopAndTrayIcons(sourceImage, targetFile, convertCommand) {
// Reference: https://web.archive.org/web/20240502124306/https://www.electronjs.org/docs/latest/api/tray
console.log(`Updating desktop launcher and tray icon at ${targetFile}.`);
await ensureFileExists(sourceImage); await ensureFileExists(sourceImage);
await ensureFolderExists(publicFolder); await ensureParentFolderExists(targetFile);
const electronTrayIconFile = join(publicFolder, 'icon.png'); await convertFromSvgToPng(
console.log(`Updating desktop launcher and tray icon at ${electronTrayIconFile}.`); convertCommand,
await runCommand(
'npx',
'svgexport',
sourceImage, sourceImage,
electronTrayIconFile, targetFile,
'512x512',
); );
} }
async function updateWebFavicon(sourceImage, faviconFolder) { async function generateWebFavicon(sourceImage, faviconFilePath, convertCommand) {
console.log('Updating favicon'); console.log(`Updating favicon at ${faviconFilePath}.`);
await ensureFileExists(sourceImage); await ensureFileExists(sourceImage);
await ensureFolderExists(faviconFolder); await ensureParentFolderExists(faviconFilePath);
await runCommand( await convertFromSvgToIco(
'npx', convertCommand,
'icon-gen', sourceImage,
`--input ${sourceImage}`, faviconFilePath,
`--output ${faviconFolder}`, [16, 24, 32, 48, 64, 128, 256],
'--ico',
'--ico-name \'favicon\'',
'--report',
); );
} }
async function updateDesktopIcons(sourceImage, electronIconsDir) { async function generateDesktopIcons(sourceImage, electronBuildResourcesDirectory, convertCommand) {
console.log(`Creating Electron icon files to ${electronBuildResourcesDirectory}.`);
// Reference: https://web.archive.org/web/20240501103645/https://www.electron.build/icons.html
await ensureFolderExists(electronBuildResourcesDirectory);
await ensureFileExists(sourceImage); await ensureFileExists(sourceImage);
await ensureFolderExists(electronIconsDir); const electronMainIconFile = join(electronBuildResourcesDirectory, 'icon.png');
const temporaryDir = await mkdtemp('icon-'); await convertFromSvgToPng(
const temporaryPngFile = join(temporaryDir, 'icon.png'); convertCommand,
console.log(`Converting from SVG (${sourceImage}) to PNG: ${temporaryPngFile}`); // required by `icon-builder`
await runCommand(
'npx',
'svgexport',
sourceImage, sourceImage,
temporaryPngFile, electronMainIconFile,
'1024:1024', '1024x1024', // Should be at least 512x512
); );
console.log(`Creating electron icons to ${electronIconsDir}.`); // Relying on `electron-builder`s conversion from png to ico results in pixelated look on Windows
await runCommand( // 10 and 11 according to tests, see:
'npx', // - https://web.archive.org/web/20240502114650/https://github.com/electron-userland/electron-builder/issues/7328
'electron-icon-builder', // - https://web.archive.org/web/20240502115448/https://github.com/electron-userland/electron-builder/issues/3867
`--input="${temporaryPngFile}"`, const electronWindowsIconFile = join(electronBuildResourcesDirectory, 'icon.ico');
`--output="${electronIconsDir}"`, await convertFromSvgToIco(
'--flatten', convertCommand,
sourceImage,
electronWindowsIconFile,
[16, 24, 32, 48, 64, 128, 256],
); );
console.log('Cleaning up temporary directory.');
await rm(temporaryDir, { recursive: true, force: true });
} }
async function ensureFileExists(filePath) { async function ensureFileExists(filePath) {
@@ -100,12 +125,60 @@ async function ensureFileExists(filePath) {
} }
async function ensureFolderExists(folderPath) { async function ensureFolderExists(folderPath) {
if (!folderPath) {
throw new Error('Path is missing');
}
const path = await stat(folderPath); const path = await stat(folderPath);
if (!path.isDirectory()) { if (!path.isDirectory()) {
throw new Error(`Not a directory: ${folderPath}`); throw new Error(`Not a directory: ${folderPath}`);
} }
} }
function ensureParentFolderExists(filePath) {
return ensureFolderExists(dirname(filePath));
}
const BaseImageMagickConvertArguments = Object.freeze([
'-background none', // Transparent, so they do not get filled with white.
'-strip', // Strip metadata.
'-gravity Center', // Center the image when there's empty space
]);
async function convertFromSvgToIco(
convertCommand,
inputFile,
outputFile,
sizes,
) {
await runCommand(
convertCommand,
...BaseImageMagickConvertArguments,
`-density ${Math.max(...sizes).toString()}`, // High enough for sharpness
`-define icon:auto-resize=${sizes.map((s) => s.toString()).join(',')}`, // Automatically store multiple sizes in an ico image
'-compress None',
inputFile,
outputFile,
);
}
async function convertFromSvgToPng(
convertCommand,
inputFile,
outputFile,
size = undefined,
) {
await runCommand(
convertCommand,
...BaseImageMagickConvertArguments,
...(size === undefined ? [] : [
`-resize ${size}`,
`-density ${size}`, // High enough for sharpness
]),
inputFile,
outputFile,
);
}
async function runCommand(...args) { async function runCommand(...args) {
const command = args.join(' '); const command = args.join(' ');
console.log(`Running command: ${command}`); console.log(`Running command: ${command}`);
@@ -135,4 +208,27 @@ function getCurrentScriptDirectory() {
return fileURLToPath(new URL('.', import.meta.url)); return fileURLToPath(new URL('.', import.meta.url));
} }
async function findAvailableImageMagickCommand() {
// Reference: https://web.archive.org/web/20240502120041/https://imagemagick.org/script/convert.php
const potentialBaseCommands = [
'convert', // Legacy command, usually available on Linux/macOS installations
'magick convert', // Newer command, available on Windows installations
];
for (const baseCommand of potentialBaseCommands) {
const testCommand = `${baseCommand} -version`;
try {
await runCommand(testCommand); // eslint-disable-line no-await-in-loop
console.log(`Confirmed: ImageMagick command '${baseCommand}' is available and operational.`);
return baseCommand;
} catch (err) {
console.log(`Error: The command '${baseCommand}' is not found or failed to execute. Detailed error: ${err.message}"`);
}
}
throw new Error([
'Unable to locate any operational ImageMagick command.',
`Attempted commands were: ${potentialBaseCommands.join(', ')}.`,
'Please ensure ImageMagick is correctly installed and accessible.',
].join('\n'));
}
await main(); await main();

View File

@@ -11,10 +11,11 @@ export type CodeRunErrorType =
| 'FileWriteError' | 'FileWriteError'
| 'FileReadbackVerificationError' | 'FileReadbackVerificationError'
| 'FilePathGenerationError' | 'FilePathGenerationError'
| 'UnsupportedOperatingSystem' | 'UnsupportedPlatform'
| 'FileExecutionError'
| 'DirectoryCreationError' | 'DirectoryCreationError'
| 'UnexpectedError'; | 'FilePermissionChangeError'
| 'FileExecutionError'
| 'ExternalProcessTermination';
interface CodeRunStatus { interface CodeRunStatus {
readonly success: boolean; readonly success: boolean;

View File

@@ -1,4 +1,4 @@
import { isFunction } from '@/TypeHelpers'; import { isFunction, type ConstructorArguments } from '@/TypeHelpers';
/* /*
Provides a unified and resilient way to extend errors across platforms. Provides a unified and resilient way to extend errors across platforms.
@@ -12,8 +12,8 @@ import { isFunction } from '@/TypeHelpers';
> https://web.archive.org/web/20230810014143/https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work > https://web.archive.org/web/20230810014143/https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
*/ */
export abstract class CustomError extends Error { export abstract class CustomError extends Error {
constructor(message?: string, options?: ErrorOptions) { constructor(...args: ConstructorArguments<typeof Error>) {
super(message, options); super(...args);
fixPrototype(this, new.target.prototype); fixPrototype(this, new.target.prototype);
ensureStackTrace(this); ensureStackTrace(this);

View File

@@ -1,44 +1,164 @@
/* eslint-disable max-classes-per-file */
import { PlatformTimer } from './PlatformTimer'; import { PlatformTimer } from './PlatformTimer';
import type { Timer, TimeoutType } from './Timer'; import type { Timer, TimeoutType } from './Timer';
export type CallbackType = (..._: readonly unknown[]) => void; export type CallbackType = (..._: readonly unknown[]) => void;
export function throttle( export interface ThrottleOptions {
callback: CallbackType, /** Skip the immediate execution of the callback on the first invoke */
waitInMs: number, readonly excludeLeadingCall: boolean;
timer: Timer = PlatformTimer, readonly timer: Timer;
): CallbackType {
const throttler = new Throttler(timer, waitInMs, callback);
return (...args: unknown[]) => throttler.invoke(...args);
} }
class Throttler { const DefaultOptions: ThrottleOptions = {
private queuedExecutionId: TimeoutType | undefined; excludeLeadingCall: false,
timer: PlatformTimer,
};
private previouslyRun: number; export interface ThrottleFunction {
(
callback: CallbackType,
waitInMs: number,
options?: Partial<ThrottleOptions>,
): CallbackType;
}
export const throttle: ThrottleFunction = (
callback: CallbackType,
waitInMs: number,
options: Partial<ThrottleOptions> = DefaultOptions,
): CallbackType => {
const defaultedOptions: ThrottleOptions = {
...DefaultOptions,
...options,
};
const throttler = new Throttler(waitInMs, callback, defaultedOptions);
return (...args: unknown[]) => throttler.invoke(...args);
};
class Throttler {
private lastExecutionTime: number | null = null;
private executionScheduler: DelayedCallbackScheduler;
constructor( constructor(
private readonly timer: Timer,
private readonly waitInMs: number, private readonly waitInMs: number,
private readonly callback: CallbackType, private readonly callback: CallbackType,
private readonly options: ThrottleOptions,
) { ) {
if (!waitInMs) { throw new Error('missing delay'); } if (!waitInMs) { throw new Error('missing delay'); }
if (waitInMs < 0) { throw new Error('negative delay'); } if (waitInMs < 0) { throw new Error('negative delay'); }
this.executionScheduler = new DelayedCallbackScheduler(options.timer);
} }
public invoke(...args: unknown[]): void { public invoke(...args: unknown[]): void {
const now = this.timer.dateNow(); switch (true) {
if (this.queuedExecutionId !== undefined) { case this.isLeadingCallWithinThrottlePeriod(): {
this.timer.clearTimeout(this.queuedExecutionId); if (this.options.excludeLeadingCall) {
this.queuedExecutionId = undefined; this.scheduleNext(args);
} return;
if (!this.previouslyRun || (now - this.previouslyRun >= this.waitInMs)) { }
this.callback(...args); this.executeNow(args);
this.previouslyRun = now; return;
} else { }
const nextCall = () => this.invoke(...args); case this.isAlreadyScheduled(): {
const nextCallDelayInMs = this.waitInMs - (now - this.previouslyRun); this.updateNextScheduled(args);
this.queuedExecutionId = this.timer.setTimeout(nextCall, nextCallDelayInMs); return;
}
case !this.isThrottlePeriodPassed(): {
this.scheduleNext(args);
return;
}
default:
throw new Error('Throttle logical error: no conditions for execution or scheduling were met.');
} }
} }
private isLeadingCallWithinThrottlePeriod(): boolean {
return this.isThrottlePeriodPassed()
&& !this.isAlreadyScheduled();
}
private isThrottlePeriodPassed(): boolean {
if (this.lastExecutionTime === null) {
return true;
}
const timeSinceLastExecution = this.options.timer.dateNow() - this.lastExecutionTime;
const isThrottleTimePassed = timeSinceLastExecution >= this.waitInMs;
return isThrottleTimePassed;
}
private isAlreadyScheduled(): boolean {
return this.executionScheduler.getNext() !== null;
}
private scheduleNext(args: unknown[]): void {
if (this.executionScheduler.getNext()) {
throw new Error('An execution is already scheduled.');
}
this.executionScheduler.resetNext(
() => this.executeNow(args),
this.waitInMs,
);
}
private updateNextScheduled(args: unknown[]): void {
const nextScheduled = this.executionScheduler.getNext();
if (!nextScheduled) {
throw new Error('A non-existent scheduled execution cannot be updated.');
}
const nextDelay = nextScheduled.scheduledTime - this.dateNow();
this.executionScheduler.resetNext(
() => this.executeNow(args),
nextDelay,
);
}
private executeNow(args: unknown[]): void {
this.callback(...args);
this.lastExecutionTime = this.dateNow();
}
private dateNow(): number {
return this.options.timer.dateNow();
}
}
interface ScheduledCallback {
readonly scheduleTimeoutId: TimeoutType;
readonly scheduledTime: number;
}
class DelayedCallbackScheduler {
private scheduledCallback: ScheduledCallback | null = null;
constructor(
private readonly timer: Timer,
) { }
public getNext(): ScheduledCallback | null {
return this.scheduledCallback;
}
public resetNext(
callback: () => void,
delayInMs: number,
) {
this.clear();
this.scheduledCallback = {
scheduledTime: this.timer.dateNow() + delayInMs,
scheduleTimeoutId: this.timer.setTimeout(() => {
this.clear();
callback();
}, delayInMs),
};
}
private clear() {
if (this.scheduledCallback === null) {
return;
}
this.timer.clearTimeout(this.scheduledCallback.scheduleTimeoutId);
this.scheduledCallback = null;
}
} }

View File

@@ -3,10 +3,12 @@ import type {
} from '@/application/collections/'; } from '@/application/collections/';
import { Script } from '@/domain/Script'; import { Script } from '@/domain/Script';
import { Category } from '@/domain/Category'; import { Category } from '@/domain/Category';
import { NodeValidator } from '@/application/Parser/NodeValidation/NodeValidator'; import { wrapErrorWithAdditionalContext, type ErrorWithContextWrapper } from '@/application/Parser/ContextualError';
import { NodeType } from '@/application/Parser/NodeValidation/NodeType'; import type { ICategory } from '@/domain/ICategory';
import { parseDocs } from './DocumentationParser'; import { parseDocs, type DocsParser } from './DocumentationParser';
import { parseScript } from './Script/ScriptParser'; import { parseScript, type ScriptParser } from './Script/ScriptParser';
import { createNodeDataValidator, type NodeDataValidator, type NodeDataValidatorFactory } from './NodeValidation/NodeDataValidator';
import { NodeDataType } from './NodeValidation/NodeDataType';
import type { ICategoryCollectionParseContext } from './Script/ICategoryCollectionParseContext'; import type { ICategoryCollectionParseContext } from './Script/ICategoryCollectionParseContext';
let categoryIdCounter = 0; let categoryIdCounter = 0;
@@ -14,96 +16,108 @@ let categoryIdCounter = 0;
export function parseCategory( export function parseCategory(
category: CategoryData, category: CategoryData,
context: ICategoryCollectionParseContext, context: ICategoryCollectionParseContext,
factory: CategoryFactoryType = CategoryFactory, utilities: CategoryParserUtilities = DefaultCategoryParserUtilities,
): Category { ): Category {
return parseCategoryRecursively({ return parseCategoryRecursively({
categoryData: category, categoryData: category,
context, context,
factory, utilities,
}); });
} }
interface ICategoryParseContext { interface CategoryParseContext {
readonly categoryData: CategoryData, readonly categoryData: CategoryData;
readonly context: ICategoryCollectionParseContext, readonly context: ICategoryCollectionParseContext;
readonly factory: CategoryFactoryType, readonly parentCategory?: CategoryData;
readonly parentCategory?: CategoryData, readonly utilities: CategoryParserUtilities;
} }
function parseCategoryRecursively(context: ICategoryParseContext): Category | never { function parseCategoryRecursively(
ensureValidCategory(context.categoryData, context.parentCategory); context: CategoryParseContext,
const children: ICategoryChildren = { ): Category | never {
subCategories: new Array<Category>(), const validator = ensureValidCategory(context);
subScripts: new Array<Script>(), const children: CategoryChildren = {
subcategories: new Array<Category>(),
subscripts: new Array<Script>(),
}; };
for (const data of context.categoryData.children) { for (const data of context.categoryData.children) {
parseNode({ parseNode({
nodeData: data, nodeData: data,
children, children,
parent: context.categoryData, parent: context.categoryData,
factory: context.factory, utilities: context.utilities,
context: context.context, context: context.context,
}); });
} }
try { try {
return context.factory( return context.utilities.createCategory({
/* id: */ categoryIdCounter++, id: categoryIdCounter++,
/* name: */ context.categoryData.category, name: context.categoryData.category,
/* docs: */ parseDocs(context.categoryData), docs: context.utilities.parseDocs(context.categoryData),
/* categories: */ children.subCategories, subcategories: children.subcategories,
/* scripts: */ children.subScripts, scripts: children.subscripts,
});
} catch (error) {
throw context.utilities.wrapError(
error,
validator.createContextualErrorMessage('Failed to parse category.'),
); );
} catch (err) {
return new NodeValidator({
type: NodeType.Category,
selfNode: context.categoryData,
parentNode: context.parentCategory,
}).throw(err.message);
} }
} }
function ensureValidCategory(category: CategoryData, parentCategory?: CategoryData) { function ensureValidCategory(
new NodeValidator({ context: CategoryParseContext,
type: NodeType.Category, ): NodeDataValidator {
selfNode: category, const category = context.categoryData;
parentNode: parentCategory, const validator: NodeDataValidator = context.utilities.createValidator({
}) type: NodeDataType.Category,
.assertDefined(category) selfNode: context.categoryData,
.assertValidName(category.category) parentNode: context.parentCategory,
.assert( });
() => category.children.length > 0, validator.assertDefined(category);
`"${category.category}" has no children.`, validator.assertValidName(category.category);
); validator.assert(
() => Boolean(category.children) && category.children.length > 0,
`"${category.category}" has no children.`,
);
return validator;
} }
interface ICategoryChildren { interface CategoryChildren {
subCategories: Category[]; readonly subcategories: Category[];
subScripts: Script[]; readonly subscripts: Script[];
} }
interface INodeParseContext { interface NodeParseContext {
readonly nodeData: CategoryOrScriptData; readonly nodeData: CategoryOrScriptData;
readonly children: ICategoryChildren; readonly children: CategoryChildren;
readonly parent: CategoryData; readonly parent: CategoryData;
readonly factory: CategoryFactoryType;
readonly context: ICategoryCollectionParseContext; readonly context: ICategoryCollectionParseContext;
readonly utilities: CategoryParserUtilities;
} }
function parseNode(context: INodeParseContext) {
const validator = new NodeValidator({ selfNode: context.nodeData, parentNode: context.parent }); function parseNode(context: NodeParseContext) {
const validator: NodeDataValidator = context.utilities.createValidator({
selfNode: context.nodeData,
parentNode: context.parent,
});
validator.assertDefined(context.nodeData); validator.assertDefined(context.nodeData);
validator.assert(
() => isCategory(context.nodeData) || isScript(context.nodeData),
'Node is neither a category or a script.',
);
if (isCategory(context.nodeData)) { if (isCategory(context.nodeData)) {
const subCategory = parseCategoryRecursively({ const subCategory = parseCategoryRecursively({
categoryData: context.nodeData, categoryData: context.nodeData,
context: context.context, context: context.context,
factory: context.factory,
parentCategory: context.parent, parentCategory: context.parent,
utilities: context.utilities,
}); });
context.children.subCategories.push(subCategory); context.children.subcategories.push(subCategory);
} else if (isScript(context.nodeData)) { } else { // A script
const script = parseScript(context.nodeData, context.context); const script = context.utilities.parseScript(context.nodeData, context.context);
context.children.subScripts.push(script); context.children.subscripts.push(script);
} else {
validator.throw('Node is neither a category or a script.');
} }
} }
@@ -123,11 +137,35 @@ function hasCall(data: unknown) {
return hasProperty(data, 'call'); return hasProperty(data, 'call');
} }
function hasProperty(object: unknown, propertyName: string) { function hasProperty(
object: unknown,
propertyName: string,
): object is NonNullable<object> {
if (typeof object !== 'object') {
return false;
}
if (object === null) { // `typeof object` is `null`
return false;
}
return Object.prototype.hasOwnProperty.call(object, propertyName); return Object.prototype.hasOwnProperty.call(object, propertyName);
} }
export type CategoryFactoryType = ( export type CategoryFactory = (
...parameters: ConstructorParameters<typeof Category>) => Category; ...parameters: ConstructorParameters<typeof Category>
) => ICategory;
const CategoryFactory: CategoryFactoryType = (...parameters) => new Category(...parameters); interface CategoryParserUtilities {
readonly createCategory: CategoryFactory;
readonly wrapError: ErrorWithContextWrapper;
readonly createValidator: NodeDataValidatorFactory;
readonly parseScript: ScriptParser;
readonly parseDocs: DocsParser;
}
const DefaultCategoryParserUtilities: CategoryParserUtilities = {
createCategory: (...parameters) => new Category(...parameters),
wrapError: wrapErrorWithAdditionalContext,
createValidator: createNodeDataValidator,
parseScript,
parseDocs,
};

View File

@@ -0,0 +1,42 @@
import { CustomError } from '@/application/Common/CustomError';
export interface ErrorWithContextWrapper {
(
error: Error,
additionalContext: string,
): Error;
}
export const wrapErrorWithAdditionalContext: ErrorWithContextWrapper = (
error: Error,
additionalContext: string,
) => {
return (error instanceof ContextualError ? error : new ContextualError(error))
.withAdditionalContext(additionalContext);
};
/* AggregateError is similar but isn't well-serialized or displayed by browsers */
class ContextualError extends CustomError {
private readonly additionalContext = new Array<string>();
constructor(
public readonly innerError: Error,
) {
super();
}
public withAdditionalContext(additionalContext: string): this {
this.additionalContext.push(additionalContext);
return this;
}
public get message(): string { // toString() is not used when Chromium logs it on console
return [
'\n',
this.innerError.message,
'\n',
'Additional context:',
...this.additionalContext.map((context, index) => `${index + 1}: ${context}`),
].join('\n');
}
}

View File

@@ -1,7 +1,7 @@
import type { DocumentableData, DocumentationData } from '@/application/collections/'; import type { DocumentableData, DocumentationData } from '@/application/collections/';
import { isString, isArray } from '@/TypeHelpers'; import { isString, isArray } from '@/TypeHelpers';
export function parseDocs(documentable: DocumentableData): readonly string[] { export const parseDocs: DocsParser = (documentable) => {
const { docs } = documentable; const { docs } = documentable;
if (!docs) { if (!docs) {
return []; return [];
@@ -9,6 +9,12 @@ export function parseDocs(documentable: DocumentableData): readonly string[] {
let result = new DocumentationContainer(); let result = new DocumentationContainer();
result = addDocs(docs, result); result = addDocs(docs, result);
return result.getAll(); return result.getAll();
};
export interface DocsParser {
(
documentable: DocumentableData,
): readonly string[];
} }
function addDocs( function addDocs(

View File

@@ -1,34 +0,0 @@
import { CustomError } from '@/application/Common/CustomError';
import { NodeType } from './NodeType';
import type { NodeData } from './NodeData';
export class NodeDataError extends CustomError {
constructor(message: string, public readonly context: INodeDataErrorContext) {
super(createMessage(message, context));
}
}
export interface INodeDataErrorContext {
readonly type?: NodeType;
readonly selfNode: NodeData;
readonly parentNode?: NodeData;
}
function createMessage(errorMessage: string, context: INodeDataErrorContext) {
let message = '';
if (context.type !== undefined) {
message += `${NodeType[context.type]}: `;
}
message += errorMessage;
message += `\n${dump(context)}`;
return message;
}
function dump(context: INodeDataErrorContext): string {
const printJson = (obj: unknown) => JSON.stringify(obj, undefined, 2);
let output = `Self: ${printJson(context.selfNode)}`;
if (context.parentNode) {
output += `\nParent: ${printJson(context.parentNode)}`;
}
return output;
}

View File

@@ -0,0 +1,25 @@
import type { CategoryData, ScriptData } from '@/application/collections/';
import { NodeDataType } from './NodeDataType';
import type { NodeData } from './NodeData';
export type NodeDataErrorContext = {
readonly parentNode?: CategoryData;
} & (CategoryNodeErrorContext | ScriptNodeErrorContext | UnknownNodeErrorContext);
export type CategoryNodeErrorContext = {
readonly type: NodeDataType.Category;
readonly selfNode: CategoryData;
readonly parentNode?: CategoryData;
};
export type ScriptNodeErrorContext = {
readonly type: NodeDataType.Script;
readonly selfNode: ScriptData;
readonly parentNode?: CategoryData;
};
export type UnknownNodeErrorContext = {
readonly type?: undefined;
readonly selfNode: NodeData;
readonly parentNode?: CategoryData;
};

View File

@@ -0,0 +1,35 @@
import { NodeDataType } from './NodeDataType';
import type { NodeDataErrorContext } from './NodeDataErrorContext';
import type { NodeData } from './NodeData';
export interface NodeContextErrorMessageCreator {
(
errorMessage: string,
context: NodeDataErrorContext,
): string;
}
export const createNodeContextErrorMessage: NodeContextErrorMessageCreator = (
errorMessage,
context,
) => {
let message = '';
if (context.type !== undefined) {
message += `${NodeDataType[context.type]}: `;
}
message += errorMessage;
message += `\n${getErrorContextDetails(context)}`;
return message;
};
function getErrorContextDetails(context: NodeDataErrorContext): string {
let output = `Self: ${printNodeDataAsJson(context.selfNode)}`;
if (context.parentNode) {
output += `\nParent: ${printNodeDataAsJson(context.parentNode)}`;
}
return output;
}
function printNodeDataAsJson(node: NodeData): string {
return JSON.stringify(node, undefined, 2);
}

View File

@@ -0,0 +1,4 @@
export enum NodeDataType {
Script,
Category,
}

View File

@@ -0,0 +1,69 @@
import { isString } from '@/TypeHelpers';
import { type NodeDataErrorContext } from './NodeDataErrorContext';
import { createNodeContextErrorMessage, type NodeContextErrorMessageCreator } from './NodeDataErrorContextMessage';
import type { NodeData } from './NodeData';
export interface NodeDataValidatorFactory {
(context: NodeDataErrorContext): NodeDataValidator;
}
export interface NodeDataValidator {
assertValidName(nameValue: string): void;
assertDefined(
node: NodeData | undefined,
): asserts node is NonNullable<NodeData> & void;
assert(
validationPredicate: () => boolean,
errorMessage: string,
): asserts validationPredicate is (() => true);
createContextualErrorMessage(errorMessage: string): string;
}
export const createNodeDataValidator
: NodeDataValidatorFactory = (context) => new ContextualNodeDataValidator(context);
export class ContextualNodeDataValidator implements NodeDataValidator {
constructor(
private readonly context: NodeDataErrorContext,
private readonly createErrorMessage
: NodeContextErrorMessageCreator = createNodeContextErrorMessage,
) {
}
public assertValidName(nameValue: string): void {
this.assert(() => Boolean(nameValue), 'missing name');
this.assert(
() => isString(nameValue),
`Name (${JSON.stringify(nameValue)}) is not a string but ${typeof nameValue}.`,
);
}
public assertDefined(
node: NodeData,
): asserts node is NonNullable<NodeData> {
this.assert(
() => node !== undefined && node !== null && Object.keys(node).length > 0,
'missing node data',
);
}
public assert(
validationPredicate: () => boolean,
errorMessage: string,
): asserts validationPredicate is (() => true) {
if (!validationPredicate()) {
this.throw(errorMessage);
}
}
public createContextualErrorMessage(errorMessage: string): string {
return this.createErrorMessage(errorMessage, this.context);
}
private throw(errorMessage: string): never {
throw new Error(
this.createContextualErrorMessage(errorMessage),
);
}
}

View File

@@ -1,4 +0,0 @@
export enum NodeType {
Script,
Category,
}

View File

@@ -1,39 +0,0 @@
import { isString } from '@/TypeHelpers';
import { type INodeDataErrorContext, NodeDataError } from './NodeDataError';
import type { NodeData } from './NodeData';
export class NodeValidator {
constructor(private readonly context: INodeDataErrorContext) {
}
public assertValidName(nameValue: string) {
return this
.assert(
() => Boolean(nameValue),
'missing name',
)
.assert(
() => isString(nameValue),
`Name (${JSON.stringify(nameValue)}) is not a string but ${typeof nameValue}.`,
);
}
public assertDefined(node: NodeData) {
return this.assert(
() => node !== undefined && node !== null && Object.keys(node).length > 0,
'missing node data',
);
}
public assert(validationPredicate: () => boolean, errorMessage: string) {
if (!validationPredicate()) {
this.throw(errorMessage);
}
return this;
}
public throw(errorMessage: string): never {
throw new NodeDataError(errorMessage, this.context);
}
}

View File

@@ -7,15 +7,18 @@ import type { IReadOnlyFunctionParameterCollection } from '../../Function/Parame
import type { IExpression } from './IExpression'; import type { IExpression } from './IExpression';
export type ExpressionEvaluator = (context: IExpressionEvaluationContext) => string; export type ExpressionEvaluator = (context: IExpressionEvaluationContext) => string;
export class Expression implements IExpression { export class Expression implements IExpression {
public readonly parameters: IReadOnlyFunctionParameterCollection; public readonly parameters: IReadOnlyFunctionParameterCollection;
constructor( public readonly position: ExpressionPosition;
public readonly position: ExpressionPosition,
public readonly evaluator: ExpressionEvaluator, public readonly evaluator: ExpressionEvaluator;
parameters?: IReadOnlyFunctionParameterCollection,
) { constructor(parameters: ExpressionInitParameters) {
this.parameters = parameters ?? new FunctionParameterCollection(); this.parameters = parameters.parameters ?? new FunctionParameterCollection();
this.evaluator = parameters.evaluator;
this.position = parameters.position;
} }
public evaluate(context: IExpressionEvaluationContext): string { public evaluate(context: IExpressionEvaluationContext): string {
@@ -26,6 +29,12 @@ export class Expression implements IExpression {
} }
} }
export interface ExpressionInitParameters {
readonly position: ExpressionPosition,
readonly evaluator: ExpressionEvaluator,
readonly parameters?: IReadOnlyFunctionParameterCollection,
}
function validateThatAllRequiredParametersAreSatisfied( function validateThatAllRequiredParametersAreSatisfied(
parameters: IReadOnlyFunctionParameterCollection, parameters: IReadOnlyFunctionParameterCollection,
args: IReadOnlyFunctionCallArgumentCollection, args: IReadOnlyFunctionCallArgumentCollection,

View File

@@ -1,8 +1,13 @@
import { ExpressionPosition } from './ExpressionPosition'; import { ExpressionPosition } from './ExpressionPosition';
export function createPositionFromRegexFullMatch( export interface ExpressionPositionFactory {
match: RegExpMatchArray, (
): ExpressionPosition { match: RegExpMatchArray,
): ExpressionPosition
}
export const createPositionFromRegexFullMatch
: ExpressionPositionFactory = (match) => {
const startPos = match.index; const startPos = match.index;
if (startPos === undefined) { if (startPos === undefined) {
throw new Error(`Regex match did not yield any results: ${JSON.stringify(match)}`); throw new Error(`Regex match did not yield any results: ${JSON.stringify(match)}`);
@@ -13,4 +18,4 @@ export function createPositionFromRegexFullMatch(
} }
const endPos = startPos + fullMatch.length; const endPos = startPos + fullMatch.length;
return new ExpressionPosition(startPos, endPos); return new ExpressionPosition(startPos, endPos);
} };

View File

@@ -3,10 +3,10 @@ import { WithParser } from '../SyntaxParsers/WithParser';
import type { IExpression } from '../Expression/IExpression'; import type { IExpression } from '../Expression/IExpression';
import type { IExpressionParser } from './IExpressionParser'; import type { IExpressionParser } from './IExpressionParser';
const Parsers = [ const Parsers: readonly IExpressionParser[] = [
new ParameterSubstitutionParser(), new ParameterSubstitutionParser(),
new WithParser(), new WithParser(),
]; ] as const;
export class CompositeExpressionParser implements IExpressionParser { export class CompositeExpressionParser implements IExpressionParser {
public constructor(private readonly leafs: readonly IExpressionParser[] = Parsers) { public constructor(private readonly leafs: readonly IExpressionParser[] = Parsers) {

View File

@@ -1,53 +1,127 @@
import { wrapErrorWithAdditionalContext, type ErrorWithContextWrapper } from '@/application/Parser/ContextualError';
import { Expression, type ExpressionEvaluator } from '../../Expression/Expression'; import { Expression, type ExpressionEvaluator } from '../../Expression/Expression';
import { FunctionParameterCollection } from '../../../Function/Parameter/FunctionParameterCollection'; import { createPositionFromRegexFullMatch, type ExpressionPositionFactory } from '../../Expression/ExpressionPositionFactory';
import { createPositionFromRegexFullMatch } from '../../Expression/ExpressionPositionFactory'; import { createFunctionParameterCollection, type FunctionParameterCollectionFactory } from '../../../Function/Parameter/FunctionParameterCollectionFactory';
import type { IExpressionParser } from '../IExpressionParser'; import type { IExpressionParser } from '../IExpressionParser';
import type { IExpression } from '../../Expression/IExpression'; import type { IExpression } from '../../Expression/IExpression';
import type { IFunctionParameter } from '../../../Function/Parameter/IFunctionParameter'; import type { IFunctionParameter } from '../../../Function/Parameter/IFunctionParameter';
import type { IFunctionParameterCollection, IReadOnlyFunctionParameterCollection } from '../../../Function/Parameter/IFunctionParameterCollection';
export interface RegexParserUtilities {
readonly wrapError: ErrorWithContextWrapper;
readonly createPosition: ExpressionPositionFactory;
readonly createExpression: ExpressionFactory;
readonly createParameterCollection: FunctionParameterCollectionFactory;
}
export abstract class RegexParser implements IExpressionParser { export abstract class RegexParser implements IExpressionParser {
protected abstract readonly regex: RegExp; protected abstract readonly regex: RegExp;
public constructor(
private readonly utilities: RegexParserUtilities = DefaultRegexParserUtilities,
) {
}
public findExpressions(code: string): IExpression[] { public findExpressions(code: string): IExpression[] {
return Array.from(this.findRegexExpressions(code)); return Array.from(this.findRegexExpressions(code));
} }
protected abstract buildExpression(match: RegExpMatchArray): IPrimitiveExpression; protected abstract buildExpression(match: RegExpMatchArray): PrimitiveExpression;
private* findRegexExpressions(code: string): Iterable<IExpression> { private* findRegexExpressions(code: string): Iterable<IExpression> {
if (!code) { if (!code) {
throw new Error('missing code'); throw new Error(
this.buildErrorMessageWithContext({ errorMessage: 'missing code', code: 'EMPTY' }),
);
} }
const matches = code.matchAll(this.regex); const createErrorContext = (message: string): ErrorContext => ({ code, errorMessage: message });
const matches = this.doOrRethrow(
() => code.matchAll(this.regex),
createErrorContext('Failed to match regex.'),
);
for (const match of matches) { for (const match of matches) {
const primitiveExpression = this.buildExpression(match); const primitiveExpression = this.doOrRethrow(
const position = this.doOrRethrow(() => createPositionFromRegexFullMatch(match), 'invalid script position', code); () => this.buildExpression(match),
const parameters = createParameters(primitiveExpression); createErrorContext('Failed to build expression.'),
const expression = new Expression(position, primitiveExpression.evaluator, parameters); );
const position = this.doOrRethrow(
() => this.utilities.createPosition(match),
createErrorContext('Failed to create position.'),
);
const parameters = this.doOrRethrow(
() => createParameters(
primitiveExpression,
this.utilities.createParameterCollection(),
),
createErrorContext('Failed to create parameters.'),
);
const expression = this.doOrRethrow(
() => this.utilities.createExpression({
position,
evaluator: primitiveExpression.evaluator,
parameters,
}),
createErrorContext('Failed to create expression.'),
);
yield expression; yield expression;
} }
} }
private doOrRethrow<T>(action: () => T, errorText: string, code: string): T { private doOrRethrow<T>(
action: () => T,
context: ErrorContext,
): T {
try { try {
return action(); return action();
} catch (error) { } catch (error) {
throw new Error(`[${this.constructor.name}] ${errorText}: ${error.message}\nRegex: ${this.regex}\nCode: ${code}`); throw this.utilities.wrapError(
error,
this.buildErrorMessageWithContext(context),
);
} }
} }
private buildErrorMessageWithContext(context: ErrorContext): string {
return [
context.errorMessage,
`Class name: ${this.constructor.name}`,
`Regex pattern used: ${this.regex}`,
`Code: ${context.code}`,
].join('\n');
}
}
interface ErrorContext {
readonly errorMessage: string,
readonly code: string,
} }
function createParameters( function createParameters(
expression: IPrimitiveExpression, expression: PrimitiveExpression,
): FunctionParameterCollection { parameterCollection: IFunctionParameterCollection,
): IReadOnlyFunctionParameterCollection {
return (expression.parameters || []) return (expression.parameters || [])
.reduce((parameters, parameter) => { .reduce((parameters, parameter) => {
parameters.addParameter(parameter); parameters.addParameter(parameter);
return parameters; return parameters;
}, new FunctionParameterCollection()); }, parameterCollection);
} }
export interface IPrimitiveExpression { export interface PrimitiveExpression {
evaluator: ExpressionEvaluator; readonly evaluator: ExpressionEvaluator;
parameters?: readonly IFunctionParameter[]; readonly parameters?: readonly IFunctionParameter[];
} }
export interface ExpressionFactory {
(
...args: ConstructorParameters<typeof Expression>
): IExpression;
}
const DefaultRegexParserUtilities: RegexParserUtilities = {
wrapError: wrapErrorWithAdditionalContext,
createPosition: createPositionFromRegexFullMatch,
createExpression: (...args) => new Expression(...args),
createParameterCollection: createFunctionParameterCollection,
};

View File

@@ -1,5 +1,5 @@
import { FunctionParameter } from '@/application/Parser/Script/Compiler/Function/Parameter/FunctionParameter'; import { FunctionParameter } from '@/application/Parser/Script/Compiler/Function/Parameter/FunctionParameter';
import { RegexParser, type IPrimitiveExpression } from '../Parser/Regex/RegexParser'; import { RegexParser, type PrimitiveExpression } from '../Parser/Regex/RegexParser';
import { ExpressionRegexBuilder } from '../Parser/Regex/ExpressionRegexBuilder'; import { ExpressionRegexBuilder } from '../Parser/Regex/ExpressionRegexBuilder';
export class ParameterSubstitutionParser extends RegexParser { export class ParameterSubstitutionParser extends RegexParser {
@@ -12,7 +12,7 @@ export class ParameterSubstitutionParser extends RegexParser {
.expectExpressionEnd() .expectExpressionEnd()
.buildRegExp(); .buildRegExp();
protected buildExpression(match: RegExpMatchArray): IPrimitiveExpression { protected buildExpression(match: RegExpMatchArray): PrimitiveExpression {
const parameterName = match[1]; const parameterName = match[1];
const pipeline = match[2]; const pipeline = match[2];
return { return {

View File

@@ -8,7 +8,7 @@ export class FunctionCallArgument implements IFunctionCallArgument {
) { ) {
ensureValidParameterName(parameterName); ensureValidParameterName(parameterName);
if (!argumentValue) { if (!argumentValue) {
throw new Error(`missing argument value for "${parameterName}"`); throw new Error(`Missing argument value for the parameter "${parameterName}".`);
} }
} }
} }

View File

@@ -72,7 +72,7 @@ function throwIfUnexpectedParametersExist(
// eslint-disable-next-line prefer-template // eslint-disable-next-line prefer-template
`Function "${functionName}" has unexpected parameter(s) provided: ` `Function "${functionName}" has unexpected parameter(s) provided: `
+ `"${unexpectedParameters.join('", "')}"` + `"${unexpectedParameters.join('", "')}"`
+ '. Expected parameter(s): ' + '.\nExpected parameter(s): '
+ (expectedParameters.length ? `"${expectedParameters.join('", "')}"` : 'none'), + (expectedParameters.length ? `"${expectedParameters.join('", "')}".` : 'none'),
); );
} }

View File

@@ -6,11 +6,14 @@ import type { IExpressionsCompiler } from '@/application/Parser/Script/Compiler/
import type { FunctionCall } from '@/application/Parser/Script/Compiler/Function/Call/FunctionCall'; import type { FunctionCall } from '@/application/Parser/Script/Compiler/Function/Call/FunctionCall';
import type { FunctionCallCompilationContext } from '@/application/Parser/Script/Compiler/Function/Call/Compiler/FunctionCallCompilationContext'; import type { FunctionCallCompilationContext } from '@/application/Parser/Script/Compiler/Function/Call/Compiler/FunctionCallCompilationContext';
import { ParsedFunctionCall } from '@/application/Parser/Script/Compiler/Function/Call/ParsedFunctionCall'; import { ParsedFunctionCall } from '@/application/Parser/Script/Compiler/Function/Call/ParsedFunctionCall';
import { wrapErrorWithAdditionalContext, type ErrorWithContextWrapper } from '@/application/Parser/ContextualError';
import type { ArgumentCompiler } from './ArgumentCompiler'; import type { ArgumentCompiler } from './ArgumentCompiler';
export class NestedFunctionArgumentCompiler implements ArgumentCompiler { export class NestedFunctionArgumentCompiler implements ArgumentCompiler {
constructor( constructor(
private readonly expressionsCompiler: IExpressionsCompiler = new ExpressionsCompiler(), private readonly expressionsCompiler: IExpressionsCompiler = new ExpressionsCompiler(),
private readonly wrapError: ErrorWithContextWrapper
= wrapErrorWithAdditionalContext,
) { } ) { }
public createCompiledNestedCall( public createCompiledNestedCall(
@@ -22,18 +25,26 @@ export class NestedFunctionArgumentCompiler implements ArgumentCompiler {
nestedFunction, nestedFunction,
parentFunction.args, parentFunction.args,
context, context,
this.expressionsCompiler, {
expressionsCompiler: this.expressionsCompiler,
wrapError: this.wrapError,
},
); );
const compiledCall = new ParsedFunctionCall(nestedFunction.functionName, compiledArgs); const compiledCall = new ParsedFunctionCall(nestedFunction.functionName, compiledArgs);
return compiledCall; return compiledCall;
} }
} }
interface ArgumentCompilationUtilities {
readonly expressionsCompiler: IExpressionsCompiler,
readonly wrapError: ErrorWithContextWrapper;
}
function compileNestedFunctionArguments( function compileNestedFunctionArguments(
nestedFunction: FunctionCall, nestedFunction: FunctionCall,
parentFunctionArgs: IReadOnlyFunctionCallArgumentCollection, parentFunctionArgs: IReadOnlyFunctionCallArgumentCollection,
context: FunctionCallCompilationContext, context: FunctionCallCompilationContext,
expressionsCompiler: IExpressionsCompiler, utilities: ArgumentCompilationUtilities,
): IReadOnlyFunctionCallArgumentCollection { ): IReadOnlyFunctionCallArgumentCollection {
const requiredParameterNames = context const requiredParameterNames = context
.allFunctions .allFunctions
@@ -47,7 +58,7 @@ function compileNestedFunctionArguments(
paramName, paramName,
nestedFunction, nestedFunction,
parentFunctionArgs, parentFunctionArgs,
expressionsCompiler, utilities,
), ),
})) }))
// Filter out arguments with absent values // Filter out arguments with absent values
@@ -89,13 +100,13 @@ function compileArgument(
parameterName: string, parameterName: string,
nestedFunction: FunctionCall, nestedFunction: FunctionCall,
parentFunctionArgs: IReadOnlyFunctionCallArgumentCollection, parentFunctionArgs: IReadOnlyFunctionCallArgumentCollection,
expressionsCompiler: IExpressionsCompiler, utilities: ArgumentCompilationUtilities,
): string { ): string {
try { try {
const { argumentValue: codeInArgument } = nestedFunction.args.getArgument(parameterName); const { argumentValue: codeInArgument } = nestedFunction.args.getArgument(parameterName);
return expressionsCompiler.compileExpressions(codeInArgument, parentFunctionArgs); return utilities.expressionsCompiler.compileExpressions(codeInArgument, parentFunctionArgs);
} catch (err) { } catch (error) {
throw new AggregateError([err], `Error when compiling argument for "${parameterName}"`); throw utilities.wrapError(error, `Error when compiling argument for "${parameterName}"`);
} }
} }

View File

@@ -1,14 +1,21 @@
import { type CallFunctionBody, FunctionBodyType, type ISharedFunction } from '@/application/Parser/Script/Compiler/Function/ISharedFunction'; import {
type CallFunctionBody, FunctionBodyType,
type ISharedFunction,
} from '@/application/Parser/Script/Compiler/Function/ISharedFunction';
import type { FunctionCall } from '@/application/Parser/Script/Compiler/Function/Call/FunctionCall'; import type { FunctionCall } from '@/application/Parser/Script/Compiler/Function/Call/FunctionCall';
import type { FunctionCallCompilationContext } from '@/application/Parser/Script/Compiler/Function/Call/Compiler/FunctionCallCompilationContext'; import type { FunctionCallCompilationContext } from '@/application/Parser/Script/Compiler/Function/Call/Compiler/FunctionCallCompilationContext';
import type { CompiledCode } from '@/application/Parser/Script/Compiler/Function/Call/Compiler/CompiledCode'; import type { CompiledCode } from '@/application/Parser/Script/Compiler/Function/Call/Compiler/CompiledCode';
import { wrapErrorWithAdditionalContext, type ErrorWithContextWrapper } from '@/application/Parser/ContextualError';
import { NestedFunctionArgumentCompiler } from './Argument/NestedFunctionArgumentCompiler'; import { NestedFunctionArgumentCompiler } from './Argument/NestedFunctionArgumentCompiler';
import type { SingleCallCompilerStrategy } from '../SingleCallCompilerStrategy'; import type { SingleCallCompilerStrategy } from '../SingleCallCompilerStrategy';
import type { ArgumentCompiler } from './Argument/ArgumentCompiler'; import type { ArgumentCompiler } from './Argument/ArgumentCompiler';
export class NestedFunctionCallCompiler implements SingleCallCompilerStrategy { export class NestedFunctionCallCompiler implements SingleCallCompilerStrategy {
public constructor( public constructor(
private readonly argumentCompiler: ArgumentCompiler = new NestedFunctionArgumentCompiler(), private readonly argumentCompiler: ArgumentCompiler
= new NestedFunctionArgumentCompiler(),
private readonly wrapError: ErrorWithContextWrapper
= wrapErrorWithAdditionalContext,
) { ) {
} }
@@ -29,8 +36,11 @@ export class NestedFunctionCallCompiler implements SingleCallCompilerStrategy {
const compiledNestedCall = context.singleCallCompiler const compiledNestedCall = context.singleCallCompiler
.compileSingleCall(compiledParentCall, context); .compileSingleCall(compiledParentCall, context);
return compiledNestedCall; return compiledNestedCall;
} catch (err) { } catch (error) {
throw new AggregateError([err], `Error with call to "${nestedCall.functionName}" function from "${callToFunction.functionName}" function`); throw this.wrapError(
error,
`Failed to call '${nestedCall.functionName}' (callee function) from '${callToFunction.functionName}' (caller function).`,
);
} }
}).flat(); }).flat();
} }

View File

@@ -0,0 +1,12 @@
import { FunctionParameterCollection } from './FunctionParameterCollection';
import type { IFunctionParameterCollection } from './IFunctionParameterCollection';
export interface FunctionParameterCollectionFactory {
(
...args: ConstructorParameters<typeof FunctionParameterCollection>
): IFunctionParameterCollection;
}
export const createFunctionParameterCollection: FunctionParameterCollectionFactory = (...args) => {
return new FunctionParameterCollection(...args);
};

View File

@@ -15,7 +15,7 @@ export class SharedFunctionCollection implements ISharedFunctionCollection {
if (!name) { throw Error('missing function name'); } if (!name) { throw Error('missing function name'); }
const func = this.functionsByName.get(name); const func = this.functionsByName.get(name);
if (!func) { if (!func) {
throw new Error(`called function is not defined "${name}"`); throw new Error(`Called function is not defined: "${name}"`);
} }
return func; return func;
} }

View File

@@ -1,5 +1,6 @@
import type { import type {
FunctionData, CodeInstruction, CodeFunctionData, CallFunctionData, CallInstruction, FunctionData, CodeInstruction, CodeFunctionData, CallFunctionData,
CallInstruction, ParameterDefinitionData,
} from '@/application/collections/'; } from '@/application/collections/';
import type { ILanguageSyntax } from '@/application/Parser/Script/Validation/Syntax/ILanguageSyntax'; import type { ILanguageSyntax } from '@/application/Parser/Script/Validation/Syntax/ILanguageSyntax';
import { CodeValidator } from '@/application/Parser/Script/Validation/CodeValidator'; import { CodeValidator } from '@/application/Parser/Script/Validation/CodeValidator';
@@ -7,20 +8,30 @@ import { NoEmptyLines } from '@/application/Parser/Script/Validation/Rules/NoEmp
import { NoDuplicatedLines } from '@/application/Parser/Script/Validation/Rules/NoDuplicatedLines'; import { NoDuplicatedLines } from '@/application/Parser/Script/Validation/Rules/NoDuplicatedLines';
import type { ICodeValidator } from '@/application/Parser/Script/Validation/ICodeValidator'; import type { ICodeValidator } from '@/application/Parser/Script/Validation/ICodeValidator';
import { isArray, isNullOrUndefined, isPlainObject } from '@/TypeHelpers'; import { isArray, isNullOrUndefined, isPlainObject } from '@/TypeHelpers';
import { wrapErrorWithAdditionalContext, type ErrorWithContextWrapper } from '@/application/Parser/ContextualError';
import { createFunctionWithInlineCode, createCallerFunction } from './SharedFunction'; import { createFunctionWithInlineCode, createCallerFunction } from './SharedFunction';
import { SharedFunctionCollection } from './SharedFunctionCollection'; import { SharedFunctionCollection } from './SharedFunctionCollection';
import { FunctionParameter } from './Parameter/FunctionParameter'; import { FunctionParameter } from './Parameter/FunctionParameter';
import { FunctionParameterCollection } from './Parameter/FunctionParameterCollection';
import { parseFunctionCalls } from './Call/FunctionCallParser'; import { parseFunctionCalls } from './Call/FunctionCallParser';
import { createFunctionParameterCollection, type FunctionParameterCollectionFactory } from './Parameter/FunctionParameterCollectionFactory';
import type { ISharedFunctionCollection } from './ISharedFunctionCollection'; import type { ISharedFunctionCollection } from './ISharedFunctionCollection';
import type { ISharedFunctionsParser } from './ISharedFunctionsParser'; import type { ISharedFunctionsParser } from './ISharedFunctionsParser';
import type { IReadOnlyFunctionParameterCollection } from './Parameter/IFunctionParameterCollection'; import type { IReadOnlyFunctionParameterCollection } from './Parameter/IFunctionParameterCollection';
import type { ISharedFunction } from './ISharedFunction'; import type { ISharedFunction } from './ISharedFunction';
const DefaultSharedFunctionsParsingUtilities: SharedFunctionsParsingUtilities = {
wrapError: wrapErrorWithAdditionalContext,
createParameter: (...args) => new FunctionParameter(...args),
codeValidator: CodeValidator.instance,
createParameterCollection: createFunctionParameterCollection,
};
export class SharedFunctionsParser implements ISharedFunctionsParser { export class SharedFunctionsParser implements ISharedFunctionsParser {
public static readonly instance: ISharedFunctionsParser = new SharedFunctionsParser(); public static readonly instance: ISharedFunctionsParser = new SharedFunctionsParser();
constructor(private readonly codeValidator: ICodeValidator = CodeValidator.instance) { } constructor(
private readonly utilities = DefaultSharedFunctionsParsingUtilities,
) { }
public parseFunctions( public parseFunctions(
functions: readonly FunctionData[], functions: readonly FunctionData[],
@@ -32,7 +43,7 @@ export class SharedFunctionsParser implements ISharedFunctionsParser {
} }
ensureValidFunctions(functions); ensureValidFunctions(functions);
return functions return functions
.map((func) => parseFunction(func, syntax, this.codeValidator)) .map((func) => parseFunction(func, syntax, this.utilities))
.reduce((acc, func) => { .reduce((acc, func) => {
acc.addFunction(func); acc.addFunction(func);
return acc; return acc;
@@ -40,15 +51,26 @@ export class SharedFunctionsParser implements ISharedFunctionsParser {
} }
} }
interface SharedFunctionsParsingUtilities {
readonly wrapError: ErrorWithContextWrapper;
readonly createParameter: FunctionParameterFactory;
readonly codeValidator: ICodeValidator;
readonly createParameterCollection: FunctionParameterCollectionFactory;
}
export type FunctionParameterFactory = (
...args: ConstructorParameters<typeof FunctionParameter>
) => FunctionParameter;
function parseFunction( function parseFunction(
data: FunctionData, data: FunctionData,
syntax: ILanguageSyntax, syntax: ILanguageSyntax,
validator: ICodeValidator, utilities: SharedFunctionsParsingUtilities,
): ISharedFunction { ): ISharedFunction {
const { name } = data; const { name } = data;
const parameters = parseParameters(data); const parameters = parseParameters(data, utilities);
if (hasCode(data)) { if (hasCode(data)) {
validateCode(data, syntax, validator); validateCode(data, syntax, utilities.codeValidator);
return createFunctionWithInlineCode(name, parameters, data.code, data.revertCode); return createFunctionWithInlineCode(name, parameters, data.code, data.revertCode);
} }
// Has call // Has call
@@ -71,22 +93,38 @@ function validateCode(
); );
} }
function parseParameters(data: FunctionData): IReadOnlyFunctionParameterCollection { function parseParameters(
data: FunctionData,
utilities: SharedFunctionsParsingUtilities,
): IReadOnlyFunctionParameterCollection {
return (data.parameters || []) return (data.parameters || [])
.map((parameter) => { .map((parameter) => createFunctionParameter(
try { data.name,
return new FunctionParameter( parameter,
parameter.name, utilities,
parameter.optional || false, ))
);
} catch (err) {
throw new Error(`"${data.name}": ${err.message}`);
}
})
.reduce((parameters, parameter) => { .reduce((parameters, parameter) => {
parameters.addParameter(parameter); parameters.addParameter(parameter);
return parameters; return parameters;
}, new FunctionParameterCollection()); }, utilities.createParameterCollection());
}
function createFunctionParameter(
functionName: string,
parameterData: ParameterDefinitionData,
utilities: SharedFunctionsParsingUtilities,
): FunctionParameter {
try {
return utilities.createParameter(
parameterData.name,
parameterData.optional || false,
);
} catch (err) {
throw utilities.wrapError(
err,
`Failed to create parameter: ${parameterData.name} for function "${functionName}"`,
);
}
} }
function hasCode(data: FunctionData): data is CodeFunctionData { function hasCode(data: FunctionData): data is CodeFunctionData {
@@ -98,6 +136,7 @@ function hasCall(data: FunctionData): data is CallFunctionData {
} }
function ensureValidFunctions(functions: readonly FunctionData[]) { function ensureValidFunctions(functions: readonly FunctionData[]) {
ensureNoUnnamedFunctions(functions);
ensureNoDuplicatesInFunctionNames(functions); ensureNoDuplicatesInFunctionNames(functions);
ensureEitherCallOrCodeIsDefined(functions); ensureEitherCallOrCodeIsDefined(functions);
ensureNoDuplicateCode(functions); ensureNoDuplicateCode(functions);
@@ -108,6 +147,16 @@ function printList(list: readonly string[]): string {
return `"${list.join('","')}"`; return `"${list.join('","')}"`;
} }
function ensureNoUnnamedFunctions(functions: readonly FunctionData[]) {
const functionsWithoutNames = functions.filter(
(func) => !func.name || func.name.trim().length === 0,
);
if (functionsWithoutNames.length) {
const invalidFunctions = functionsWithoutNames.map((f) => JSON.stringify(f));
throw new Error(`Some function(s) have no names:\n${invalidFunctions.join('\n')}`);
}
}
function ensureEitherCallOrCodeIsDefined(holders: readonly FunctionData[]) { function ensureEitherCallOrCodeIsDefined(holders: readonly FunctionData[]) {
// Ensure functions do not define both call and code // Ensure functions do not define both call and code
const withBothCallAndCode = holders.filter((holder) => hasCode(holder) && hasCall(holder)); const withBothCallAndCode = holders.filter((holder) => hasCode(holder) && hasCall(holder));

View File

@@ -1,10 +1,11 @@
import type { FunctionData, ScriptData, CallInstruction } from '@/application/collections/'; import type { FunctionData, ScriptData, CallInstruction } from '@/application/collections/';
import type { IScriptCode } from '@/domain/IScriptCode'; import type { IScriptCode } from '@/domain/IScriptCode';
import { ScriptCode } from '@/domain/ScriptCode';
import type { ILanguageSyntax } from '@/application/Parser/Script/Validation/Syntax/ILanguageSyntax'; import type { ILanguageSyntax } from '@/application/Parser/Script/Validation/Syntax/ILanguageSyntax';
import { CodeValidator } from '@/application/Parser/Script/Validation/CodeValidator'; import { CodeValidator } from '@/application/Parser/Script/Validation/CodeValidator';
import { NoEmptyLines } from '@/application/Parser/Script/Validation/Rules/NoEmptyLines'; import { NoEmptyLines } from '@/application/Parser/Script/Validation/Rules/NoEmptyLines';
import type { ICodeValidator } from '@/application/Parser/Script/Validation/ICodeValidator'; import type { ICodeValidator } from '@/application/Parser/Script/Validation/ICodeValidator';
import { wrapErrorWithAdditionalContext, type ErrorWithContextWrapper } from '@/application/Parser/ContextualError';
import { createScriptCode, type ScriptCodeFactory } from '@/domain/ScriptCodeFactory';
import { SharedFunctionsParser } from './Function/SharedFunctionsParser'; import { SharedFunctionsParser } from './Function/SharedFunctionsParser';
import { FunctionCallSequenceCompiler } from './Function/Call/Compiler/FunctionCallSequenceCompiler'; import { FunctionCallSequenceCompiler } from './Function/Call/Compiler/FunctionCallSequenceCompiler';
import { parseFunctionCalls } from './Function/Call/FunctionCallParser'; import { parseFunctionCalls } from './Function/Call/FunctionCallParser';
@@ -23,6 +24,8 @@ export class ScriptCompiler implements IScriptCompiler {
sharedFunctionsParser: ISharedFunctionsParser = SharedFunctionsParser.instance, sharedFunctionsParser: ISharedFunctionsParser = SharedFunctionsParser.instance,
private readonly callCompiler: FunctionCallCompiler = FunctionCallSequenceCompiler.instance, private readonly callCompiler: FunctionCallCompiler = FunctionCallSequenceCompiler.instance,
private readonly codeValidator: ICodeValidator = CodeValidator.instance, private readonly codeValidator: ICodeValidator = CodeValidator.instance,
private readonly wrapError: ErrorWithContextWrapper = wrapErrorWithAdditionalContext,
private readonly scriptCodeFactory: ScriptCodeFactory = createScriptCode,
) { ) {
this.functions = sharedFunctionsParser.parseFunctions(functions, syntax); this.functions = sharedFunctionsParser.parseFunctions(functions, syntax);
} }
@@ -39,12 +42,12 @@ export class ScriptCompiler implements IScriptCompiler {
const calls = parseFunctionCalls(script.call); const calls = parseFunctionCalls(script.call);
const compiledCode = this.callCompiler.compileFunctionCalls(calls, this.functions); const compiledCode = this.callCompiler.compileFunctionCalls(calls, this.functions);
validateCompiledCode(compiledCode, this.codeValidator); validateCompiledCode(compiledCode, this.codeValidator);
return new ScriptCode( return this.scriptCodeFactory(
compiledCode.code, compiledCode.code,
compiledCode.revertCode, compiledCode.revertCode,
); );
} catch (error) { } catch (error) {
throw Error(`Script "${script.name}" ${error.message}`); throw this.wrapError(error, `Failed to compile script: ${script.name}`);
} }
} }
} }

View File

@@ -4,37 +4,52 @@ import type { ILanguageSyntax } from '@/application/Parser/Script/Validation/Syn
import { Script } from '@/domain/Script'; import { Script } from '@/domain/Script';
import { RecommendationLevel } from '@/domain/RecommendationLevel'; import { RecommendationLevel } from '@/domain/RecommendationLevel';
import type { IScriptCode } from '@/domain/IScriptCode'; import type { IScriptCode } from '@/domain/IScriptCode';
import { ScriptCode } from '@/domain/ScriptCode';
import type { ICodeValidator } from '@/application/Parser/Script/Validation/ICodeValidator'; import type { ICodeValidator } from '@/application/Parser/Script/Validation/ICodeValidator';
import { parseDocs } from '../DocumentationParser'; import { wrapErrorWithAdditionalContext, type ErrorWithContextWrapper } from '@/application/Parser/ContextualError';
import type { ScriptCodeFactory } from '@/domain/ScriptCodeFactory';
import { createScriptCode } from '@/domain/ScriptCodeFactory';
import type { IScript } from '@/domain/IScript';
import { parseDocs, type DocsParser } from '../DocumentationParser';
import { createEnumParser, type IEnumParser } from '../../Common/Enum'; import { createEnumParser, type IEnumParser } from '../../Common/Enum';
import { NodeType } from '../NodeValidation/NodeType'; import { NodeDataType } from '../NodeValidation/NodeDataType';
import { NodeValidator } from '../NodeValidation/NodeValidator'; import { createNodeDataValidator, type NodeDataValidator, type NodeDataValidatorFactory } from '../NodeValidation/NodeDataValidator';
import { CodeValidator } from './Validation/CodeValidator'; import { CodeValidator } from './Validation/CodeValidator';
import { NoDuplicatedLines } from './Validation/Rules/NoDuplicatedLines'; import { NoDuplicatedLines } from './Validation/Rules/NoDuplicatedLines';
import type { ICategoryCollectionParseContext } from './ICategoryCollectionParseContext'; import type { ICategoryCollectionParseContext } from './ICategoryCollectionParseContext';
export function parseScript( export interface ScriptParser {
data: ScriptData, (
context: ICategoryCollectionParseContext, data: ScriptData,
levelParser = createEnumParser(RecommendationLevel), context: ICategoryCollectionParseContext,
scriptFactory: ScriptFactoryType = ScriptFactory, utilities?: ScriptParserUtilities,
codeValidator: ICodeValidator = CodeValidator.instance, ): IScript;
): Script { }
const validator = new NodeValidator({ type: NodeType.Script, selfNode: data });
export const parseScript: ScriptParser = (
data,
context,
utilities = DefaultScriptParserUtilities,
) => {
const validator = utilities.createValidator({
type: NodeDataType.Script,
selfNode: data,
});
validateScript(data, validator); validateScript(data, validator);
try { try {
const script = scriptFactory( const script = utilities.createScript({
/* name: */ data.name, name: data.name,
/* code: */ parseCode(data, context, codeValidator), code: parseCode(data, context, utilities.codeValidator, utilities.createCode),
/* docs: */ parseDocs(data), docs: utilities.parseDocs(data),
/* level: */ parseLevel(data.recommend, levelParser), level: parseLevel(data.recommend, utilities.levelParser),
); });
return script; return script;
} catch (err) { } catch (error) {
return validator.throw(err.message); throw utilities.wrapError(
error,
validator.createContextualErrorMessage('Failed to parse script.'),
);
} }
} };
function parseLevel( function parseLevel(
level: string | undefined, level: string | undefined,
@@ -50,18 +65,19 @@ function parseCode(
script: ScriptData, script: ScriptData,
context: ICategoryCollectionParseContext, context: ICategoryCollectionParseContext,
codeValidator: ICodeValidator, codeValidator: ICodeValidator,
createCode: ScriptCodeFactory,
): IScriptCode { ): IScriptCode {
if (context.compiler.canCompile(script)) { if (context.compiler.canCompile(script)) {
return context.compiler.compile(script); return context.compiler.compile(script);
} }
const codeScript = script as CodeScriptData; // Must be inline code if it cannot be compiled const codeScript = script as CodeScriptData; // Must be inline code if it cannot be compiled
const code = new ScriptCode(codeScript.code, codeScript.revertCode); const code = createCode(codeScript.code, codeScript.revertCode);
validateHardcodedCodeWithoutCalls(code, codeValidator, context.syntax); validateHardcodedCodeWithoutCalls(code, codeValidator, context.syntax);
return code; return code;
} }
function validateHardcodedCodeWithoutCalls( function validateHardcodedCodeWithoutCalls(
scriptCode: ScriptCode, scriptCode: IScriptCode,
validator: ICodeValidator, validator: ICodeValidator,
syntax: ILanguageSyntax, syntax: ILanguageSyntax,
) { ) {
@@ -77,25 +93,48 @@ function validateHardcodedCodeWithoutCalls(
function validateScript( function validateScript(
script: ScriptData, script: ScriptData,
validator: NodeValidator, validator: NodeDataValidator,
): asserts script is NonNullable<ScriptData> { ): asserts script is NonNullable<ScriptData> {
validator validator.assertDefined(script);
.assertDefined(script) validator.assertValidName(script.name);
.assertValidName(script.name) validator.assert(
.assert( () => Boolean((script as CodeScriptData).code || (script as CallScriptData).call),
() => Boolean((script as CodeScriptData).code || (script as CallScriptData).call), 'Neither "call" or "code" is defined.',
'Neither "call" or "code" is defined.', );
) validator.assert(
.assert( () => !((script as CodeScriptData).code && (script as CallScriptData).call),
() => !((script as CodeScriptData).code && (script as CallScriptData).call), 'Both "call" and "code" are defined.',
'Both "call" and "code" are defined.', );
) validator.assert(
.assert( () => !((script as CodeScriptData).revertCode && (script as CallScriptData).call),
() => !((script as CodeScriptData).revertCode && (script as CallScriptData).call), 'Both "call" and "revertCode" are defined.',
'Both "call" and "revertCode" are defined.', );
);
} }
export type ScriptFactoryType = (...parameters: ConstructorParameters<typeof Script>) => Script; interface ScriptParserUtilities {
readonly levelParser: IEnumParser<RecommendationLevel>;
readonly createScript: ScriptFactory;
readonly codeValidator: ICodeValidator;
readonly wrapError: ErrorWithContextWrapper;
readonly createValidator: NodeDataValidatorFactory;
readonly createCode: ScriptCodeFactory;
readonly parseDocs: DocsParser;
}
const ScriptFactory: ScriptFactoryType = (...parameters) => new Script(...parameters); export type ScriptFactory = (
...parameters: ConstructorParameters<typeof Script>
) => IScript;
const createScript: ScriptFactory = (...parameters) => {
return new Script(...parameters);
};
const DefaultScriptParserUtilities: ScriptParserUtilities = {
levelParser: createEnumParser(RecommendationLevel),
createScript,
codeValidator: CodeValidator.instance,
wrapError: wrapErrorWithAdditionalContext,
createValidator: createNodeDataValidator,
createCode: createScriptCode,
parseDocs,
};

View File

@@ -5,6 +5,7 @@ import { ExpressionsCompiler } from '@/application/Parser/Script/Compiler/Expres
import type { ProjectDetails } from '@/domain/Project/ProjectDetails'; import type { ProjectDetails } from '@/domain/Project/ProjectDetails';
import { FunctionCallArgumentCollection } from '@/application/Parser/Script/Compiler/Function/Call/Argument/FunctionCallArgumentCollection'; import { FunctionCallArgumentCollection } from '@/application/Parser/Script/Compiler/Function/Call/Argument/FunctionCallArgumentCollection';
import { FunctionCallArgument } from '@/application/Parser/Script/Compiler/Function/Call/Argument/FunctionCallArgument'; import { FunctionCallArgument } from '@/application/Parser/Script/Compiler/Function/Call/Argument/FunctionCallArgument';
import type { IExpressionParser } from '@/application/Parser/Script/Compiler/Expressions/Parser/IExpressionParser';
import type { ICodeSubstituter } from './ICodeSubstituter'; import type { ICodeSubstituter } from './ICodeSubstituter';
export class CodeSubstituter implements ICodeSubstituter { export class CodeSubstituter implements ICodeSubstituter {
@@ -29,7 +30,9 @@ export class CodeSubstituter implements ICodeSubstituter {
} }
function createSubstituteCompiler(): IExpressionsCompiler { function createSubstituteCompiler(): IExpressionsCompiler {
const parsers = [new ParameterSubstitutionParser()]; const parsers: readonly IExpressionParser[] = [
new ParameterSubstitutionParser(),
] as const;
const parser = new CompositeExpressionParser(parsers); const parser = new CompositeExpressionParser(parsers);
const expressionCompiler = new ExpressionsCompiler(parser); const expressionCompiler = new ExpressionsCompiler(parser);
return expressionCompiler; return expressionCompiler;

View File

@@ -184,7 +184,7 @@ actions:
> - Logs are valuable for diagnosing issues and understanding past actions [1]. > - Logs are valuable for diagnosing issues and understanding past actions [1].
> - Script files can help review changes made to the system and aid in reverting those changes if needed. > - Script files can help review changes made to the system and aid in reverting those changes if needed.
[1]: https://github.com/undergroundwires/privacy.sexy/blob/master/docs/desktop-vs-web-features.md "Desktop vs. Web Features | privacy.sexy | github.com" [1]: https://github.com/undergroundwires/privacy.sexy/blob/master/docs/desktop/desktop-vs-web-features.md "Desktop vs. Web Features | privacy.sexy | github.com"
[2]: https://github.com/undergroundwires/privacy.sexy/blob/master/SECURITY.md "SECURITY.md | privacy.sexy | github.com" [2]: https://github.com/undergroundwires/privacy.sexy/blob/master/SECURITY.md "SECURITY.md | privacy.sexy | github.com"
children: children:
- -
@@ -202,7 +202,7 @@ actions:
> - This action is irreversible. Deleted script files cannot be retrieved. > - This action is irreversible. Deleted script files cannot be retrieved.
> - These files might be necessary for troubleshooting if you experience issues after using privacy.sexy scripts. > - These files might be necessary for troubleshooting if you experience issues after using privacy.sexy scripts.
[1]: https://github.com/undergroundwires/privacy.sexy/blob/master/docs/desktop-vs-web-features.md "Desktop vs. Web Features | privacy.sexy | github.com" [1]: https://github.com/undergroundwires/privacy.sexy/blob/master/docs/desktop/desktop-vs-web-features.md "Desktop vs. Web Features | privacy.sexy | github.com"
[2]: https://github.com/undergroundwires/privacy.sexy/blob/master/SECURITY.md "SECURITY.md | privacy.sexy | github.com" [2]: https://github.com/undergroundwires/privacy.sexy/blob/master/SECURITY.md "SECURITY.md | privacy.sexy | github.com"
call: call:
function: ClearDirectoryContents function: ClearDirectoryContents
@@ -223,7 +223,7 @@ actions:
> - Removing logs will prevent you from reviewing the application's activities, which could be helpful in diagnosing issues. > - Removing logs will prevent you from reviewing the application's activities, which could be helpful in diagnosing issues.
> - Logs can contain valuable information for technical support should you need assistance. > - Logs can contain valuable information for technical support should you need assistance.
[1]: https://github.com/undergroundwires/privacy.sexy/blob/master/docs/desktop-vs-web-features.md "Desktop vs. Web Features | privacy.sexy | github.com" [1]: https://github.com/undergroundwires/privacy.sexy/blob/master/docs/desktop/desktop-vs-web-features.md "Desktop vs. Web Features | privacy.sexy | github.com"
[2]: https://github.com/undergroundwires/privacy.sexy/blob/master/SECURITY.md "SECURITY.md | privacy.sexy | github.com" [2]: https://github.com/undergroundwires/privacy.sexy/blob/master/SECURITY.md "SECURITY.md | privacy.sexy | github.com"
call: call:
function: ClearDirectoryContents function: ClearDirectoryContents
@@ -2072,8 +2072,8 @@ actions:
[1]: https://web.archive.org/web/20221029165307/https://packages.fedoraproject.org/pkgs/zeitgeist/zeitgeist/index.html "zeitgeist - Fedora Packages | packages.fedoraproject.org" [1]: https://web.archive.org/web/20221029165307/https://packages.fedoraproject.org/pkgs/zeitgeist/zeitgeist/index.html "zeitgeist - Fedora Packages | packages.fedoraproject.org"
[2]: https://web.archive.org/web/20221029165603/https://archlinux.org/packages/extra/x86_64/zeitgeist/ "Arch Linux - zeitgeist 1.0.4-1 (x86_64) | archlinux.org" [2]: https://web.archive.org/web/20221029165603/https://archlinux.org/packages/extra/x86_64/zeitgeist/ "Arch Linux - zeitgeist 1.0.4-1 (x86_64) | archlinux.org"
[3]: https://web.archive.org/web/20221029165609/https://packages.debian.org/search?keywords=zeitgeist-core "Debian -- Package Search Results -- zeitgeist-core | packages.debian.org" [3]: https://web.archive.org/web/20221029165609/https://packages.debian.org/search?keywords=zeitgeist-core "Debian -- Package Search Results -- zeitgeist-core | packages.debian.org"
[4]: https://web.archive.org/web/20221029165714/https://releases.ubuntu.com/xenial/ubuntu-16.04.6-desktop-i386.manifest "List of sofware packags shipped with Ubuntu 16.04.6 | releases.ubuntu.com" [4]: https://web.archive.org/web/20221029165714/https://releases.ubuntu.com/xenial/ubuntu-16.04.6-desktop-i386.manifest "List of software packages shipped with Ubuntu 16.04.6 | releases.ubuntu.com"
[5]: https://web.archive.org/web/20221029165726/https://releases.ubuntu.com/18.04/ubuntu-18.04.6-desktop-amd64.manifest "List of sofware packags shipped with Ubuntu 18.04.6 | releases.ubuntu.com" [5]: https://web.archive.org/web/20221029165726/https://releases.ubuntu.com/18.04/ubuntu-18.04.6-desktop-amd64.manifest "List of software packages shipped with Ubuntu 18.04.6 | releases.ubuntu.com"
[6]: https://web.archive.org/web/20221029165821/https://bugs.archlinux.org/task/52326 "FS#52326 : [midori-gtk2] Please remove the zeitgeist dependency! | archlinux.org" [6]: https://web.archive.org/web/20221029165821/https://bugs.archlinux.org/task/52326 "FS#52326 : [midori-gtk2] Please remove the zeitgeist dependency! | archlinux.org"
[7]: https://web.archive.org/web/20221029165914/https://forum.artixlinux.org/index.php/topic,1432.0.html "Remove Unmaintained Zeitgeist (Spyware/Telemetry) from Default MATE installation | artixlinux.org" [7]: https://web.archive.org/web/20221029165914/https://forum.artixlinux.org/index.php/topic,1432.0.html "Remove Unmaintained Zeitgeist (Spyware/Telemetry) from Default MATE installation | artixlinux.org"
[8]: https://web.archive.org/web/20221029165902/https://askubuntu.com/questions/45548/disabling-zeitgeist/57487 "Disabling Zeitgeist - Ask Ubuntu | askubuntu.com" [8]: https://web.archive.org/web/20221029165902/https://askubuntu.com/questions/45548/disabling-zeitgeist/57487 "Disabling Zeitgeist - Ask Ubuntu | askubuntu.com"
@@ -2761,7 +2761,7 @@ actions:
docs: |- docs: |-
Firefox provides an option for Enhanced Tracking Protection [1], which blocks trackers that Firefox provides an option for Enhanced Tracking Protection [1], which blocks trackers that
gather information about your browsing behavior without disrupting site functionality [1]. gather information about your browsing behavior without disrupting site functionality [1].
This feature also includes protections against harmful scripts such as malware that drains This feature also includes protections against harmful scripts such as malware that drain
your battery [1]. your battery [1].
This script enables the `privacy.resistFingerprinting` preference, This script enables the `privacy.resistFingerprinting` preference,
@@ -2791,7 +2791,7 @@ actions:
This script enables the `privacy.resistFingerprinting` preference, activating This script enables the `privacy.resistFingerprinting` preference, activating
anti-fingerprinting [1][2]. anti-fingerprinting [1][2].
As an experimental feature, it might cause some website breakage [2], such as impacting web As an experimental feature, it might cause some website breakages [2], such as impacting web
speech functionality [3] and favicons [4]. speech functionality [3] and favicons [4].
[1]: https://web.archive.org/web/20221025201025/https://support.mozilla.org/en-US/kb/firefox-protection-against-fingerprinting "Firefox's protection against fingerprinting | Firefox Help | support.mozilla.org" [1]: https://web.archive.org/web/20221025201025/https://support.mozilla.org/en-US/kb/firefox-protection-against-fingerprinting "Firefox's protection against fingerprinting | Firefox Help | support.mozilla.org"
@@ -2876,7 +2876,7 @@ actions:
It's configured to be enabled in nightly, aurora, beta, or default (developer) builds. It's configured to be enabled in nightly, aurora, beta, or default (developer) builds.
In release builds, however, it's set to false [1]. This setting is hard-coded into the C++ In release builds, however, it's set to false [1]. This setting is hard-coded into the C++
code to prevent easy disabling [2]. Developers have been approached about this issue but code to prevent easy disabling [2]. Developers have been approached about this issue, but
have rejected proposals to unlock it [3]. have rejected proposals to unlock it [3].
Mozilla's plan is to deprecate this setting eventually, followed by removal [1]. Mozilla's plan is to deprecate this setting eventually, followed by removal [1].
@@ -3012,7 +3012,7 @@ actions:
recommend: standard recommend: standard
docs: |- docs: |-
This script sets `toolkit.telemetry.server` to be empty. This script sets `toolkit.telemetry.server` to be empty.
This preference defines the server to which Telemetry pings are sent [1]. This preference defines the server to which telemetry pings are sent [1].
[1]: https://web.archive.org/web/20221015102124/https://firefox-source-docs.mozilla.org/toolkit/components/telemetry/internals/preferences.html "Preferences and Defines — Firefox Source Docs documentation | firefox-source-docs.mozilla.org" [1]: https://web.archive.org/web/20221015102124/https://firefox-source-docs.mozilla.org/toolkit/components/telemetry/internals/preferences.html "Preferences and Defines — Firefox Source Docs documentation | firefox-source-docs.mozilla.org"
call: call:
@@ -3133,7 +3133,7 @@ actions:
name: Disable Firefox Pioneer study monitoring name: Disable Firefox Pioneer study monitoring
recommend: standard recommend: standard
docs: |- docs: |-
This script configures `toolkit.telemetry.pioneer-new-studies-available` to be disabled to opt out. This script configures `toolkit.telemetry.pioneer-new-studies-available` to be disabled to opt out
Firefox Pioneer program. Firefox Pioneer program.
This setting disables availability check for Firefox Pioneer studies [1]. This setting disables availability check for Firefox Pioneer studies [1].
@@ -3711,7 +3711,7 @@ functions:
# User-specific: # User-specific:
# [~/.profile] # [~/.profile]
# User-specific shell initialization scripts. # User-specific shell initialization scripts.
# ✅ Recomended by Debian to edit for user-specific environment variables. # ✅ Recommended by Debian to edit for user-specific environment variables.
# [~/.bashrc] # [~/.bashrc]
# User-based configuration file to set environment variables for Bash shell. # User-based configuration file to set environment variables for Bash shell.
# ❌ Bash-specific. # ❌ Bash-specific.
@@ -3783,7 +3783,7 @@ functions:
if [[ -f "$cronjob_path" ]]; then if [[ -f "$cronjob_path" ]]; then
if [[ -x "$cronjob_path" ]]; then if [[ -x "$cronjob_path" ]]; then
sudo chmod -x "$cronjob_path" sudo chmod -x "$cronjob_path"
echo "Succesfully disabled cronjob \"$job_name\"." echo "Successfully disabled cronjob \"$job_name\"."
else else
echo "Skipping, cronjob \"$job_name\" is already disabled." echo "Skipping, cronjob \"$job_name\" is already disabled."
fi fi
@@ -3797,7 +3797,7 @@ functions:
echo "Skipping, cronjob \"$job_name\" is already enabled." echo "Skipping, cronjob \"$job_name\" is already enabled."
else else
sudo chmod +x "$cronjob_path" sudo chmod +x "$cronjob_path"
echo "Succesfully enabled cronjob \"$job_name\"." echo "Successfully enabled cronjob \"$job_name\"."
fi fi
else else
>&2 echo "Failed to enable cronjob \"$job_name\" because it's missing." >&2 echo "Failed to enable cronjob \"$job_name\" because it's missing."
@@ -3939,7 +3939,7 @@ functions:
echo "Backup file exists: $file." echo "Backup file exists: $file."
sudo mv "$backup_file" "$file" sudo mv "$backup_file" "$file"
echo "Moved to: $file." echo "Moved to: $file."
echo "Succesfully restored." echo "Successfully restored."
else else
>&2 echo "Failed to restore, backup file could not be found at $backup_file." >&2 echo "Failed to restore, backup file could not be found at $backup_file."
>&2 echo "Was the change initially applied by privacy.sexy?" >&2 echo "Was the change initially applied by privacy.sexy?"

View File

@@ -300,7 +300,7 @@ actions:
> - Logs are valuable for diagnosing issues and understanding past actions [1]. > - Logs are valuable for diagnosing issues and understanding past actions [1].
> - Script files can help review changes made to the system and aid in reverting those changes if needed. > - Script files can help review changes made to the system and aid in reverting those changes if needed.
[1]: https://github.com/undergroundwires/privacy.sexy/blob/master/docs/desktop-vs-web-features.md "Desktop vs. Web Features | privacy.sexy | github.com" [1]: https://github.com/undergroundwires/privacy.sexy/blob/master/docs/desktop/desktop-vs-web-features.md "Desktop vs. Web Features | privacy.sexy | github.com"
[2]: https://github.com/undergroundwires/privacy.sexy/blob/master/SECURITY.md "SECURITY.md | privacy.sexy | github.com" [2]: https://github.com/undergroundwires/privacy.sexy/blob/master/SECURITY.md "SECURITY.md | privacy.sexy | github.com"
children: children:
- -
@@ -318,7 +318,7 @@ actions:
> - This action is irreversible. Deleted script files cannot be retrieved. > - This action is irreversible. Deleted script files cannot be retrieved.
> - These files might be necessary for troubleshooting if you experience issues after using privacy.sexy scripts. > - These files might be necessary for troubleshooting if you experience issues after using privacy.sexy scripts.
[1]: https://github.com/undergroundwires/privacy.sexy/blob/master/docs/desktop-vs-web-features.md "Desktop vs. Web Features | privacy.sexy | github.com" [1]: https://github.com/undergroundwires/privacy.sexy/blob/master/docs/desktop/desktop-vs-web-features.md "Desktop vs. Web Features | privacy.sexy | github.com"
[2]: https://github.com/undergroundwires/privacy.sexy/blob/master/SECURITY.md "SECURITY.md | privacy.sexy | github.com" [2]: https://github.com/undergroundwires/privacy.sexy/blob/master/SECURITY.md "SECURITY.md | privacy.sexy | github.com"
call: call:
function: ClearDirectoryContents function: ClearDirectoryContents
@@ -339,7 +339,7 @@ actions:
> - Removing logs will prevent you from reviewing the application's activities, which could be helpful in diagnosing issues. > - Removing logs will prevent you from reviewing the application's activities, which could be helpful in diagnosing issues.
> - Logs can contain valuable information for technical support should you need assistance. > - Logs can contain valuable information for technical support should you need assistance.
[1]: https://github.com/undergroundwires/privacy.sexy/blob/master/docs/desktop-vs-web-features.md "Desktop vs. Web Features | privacy.sexy | github.com" [1]: https://github.com/undergroundwires/privacy.sexy/blob/master/docs/desktop/desktop-vs-web-features.md "Desktop vs. Web Features | privacy.sexy | github.com"
[2]: https://github.com/undergroundwires/privacy.sexy/blob/master/SECURITY.md "SECURITY.md | privacy.sexy | github.com" [2]: https://github.com/undergroundwires/privacy.sexy/blob/master/SECURITY.md "SECURITY.md | privacy.sexy | github.com"
call: call:
function: ClearDirectoryContents function: ClearDirectoryContents
@@ -1408,7 +1408,7 @@ actions:
name: Disable Gatekeeper name: Disable Gatekeeper
docs: docs:
# References for spctl --master-disable # References for spctl --master-disable
- https://www.manpagez.com/man/8/spctl/ - https://web.archive.org/web/20240523173608/https://www.manpagez.com/man/8/spctl/
# References for /var/db/SystemPolicy-prefs.plist # References for /var/db/SystemPolicy-prefs.plist
- https://krypted.com/mac-security/manage-gatekeeper-from-the-command-line-in-mountain-lion/ - https://krypted.com/mac-security/manage-gatekeeper-from-the-command-line-in-mountain-lion/
- https://community.jamf.com/t5/jamf-pro/users-can-t-change-password-greyed-out/m-p/54228 - https://community.jamf.com/t5/jamf-pro/users-can-t-change-password-greyed-out/m-p/54228
@@ -1468,7 +1468,7 @@ actions:
> **Caution**: > **Caution**:
> Disabling automatic updates can leave your system vulnerable to unpatched exploits. > Disabling automatic updates can leave your system vulnerable to unpatched exploits.
> Manually check and and apply updates to stay protected. > Manually check and apply updates to stay protected.
children: children:
- -
name: Disable automatic checks for updates name: Disable automatic checks for updates

File diff suppressed because it is too large Load Diff

View File

@@ -5,15 +5,21 @@ import type { IScript } from './IScript';
export class Category extends BaseEntity<number> implements ICategory { export class Category extends BaseEntity<number> implements ICategory {
private allSubScripts?: ReadonlyArray<IScript> = undefined; private allSubScripts?: ReadonlyArray<IScript> = undefined;
constructor( public readonly name: string;
id: number,
public readonly name: string, public readonly docs: ReadonlyArray<string>;
public readonly docs: ReadonlyArray<string>,
public readonly subCategories: ReadonlyArray<ICategory>, public readonly subCategories: ReadonlyArray<ICategory>;
public readonly scripts: ReadonlyArray<IScript>,
) { public readonly scripts: ReadonlyArray<IScript>;
super(id);
validateCategory(this); constructor(parameters: CategoryInitParameters) {
super(parameters.id);
validateParameters(parameters);
this.name = parameters.name;
this.docs = parameters.docs;
this.subCategories = parameters.subcategories;
this.scripts = parameters.scripts;
} }
public includes(script: IScript): boolean { public includes(script: IScript): boolean {
@@ -28,6 +34,14 @@ export class Category extends BaseEntity<number> implements ICategory {
} }
} }
export interface CategoryInitParameters {
readonly id: number;
readonly name: string;
readonly docs: ReadonlyArray<string>;
readonly subcategories: ReadonlyArray<ICategory>;
readonly scripts: ReadonlyArray<IScript>;
}
function parseScriptsRecursively(category: ICategory): ReadonlyArray<IScript> { function parseScriptsRecursively(category: ICategory): ReadonlyArray<IScript> {
return [ return [
...category.scripts, ...category.scripts,
@@ -35,11 +49,11 @@ function parseScriptsRecursively(category: ICategory): ReadonlyArray<IScript> {
]; ];
} }
function validateCategory(category: ICategory) { function validateParameters(parameters: CategoryInitParameters) {
if (!category.name) { if (!parameters.name) {
throw new Error('missing name'); throw new Error('missing name');
} }
if (category.subCategories.length === 0 && category.scripts.length === 0) { if (parameters.subcategories.length === 0 && parameters.scripts.length === 0) {
throw new Error('A category must have at least one sub-category or script'); throw new Error('A category must have at least one sub-category or script');
} }
} }

View File

@@ -4,14 +4,21 @@ import type { IScript } from './IScript';
import type { IScriptCode } from './IScriptCode'; import type { IScriptCode } from './IScriptCode';
export class Script extends BaseEntity<string> implements IScript { export class Script extends BaseEntity<string> implements IScript {
constructor( public readonly name: string;
public readonly name: string,
public readonly code: IScriptCode, public readonly code: IScriptCode;
public readonly docs: ReadonlyArray<string>,
public readonly level?: RecommendationLevel, public readonly docs: ReadonlyArray<string>;
) {
super(name); public readonly level?: RecommendationLevel;
validateLevel(level);
constructor(parameters: ScriptInitParameters) {
super(parameters.name);
this.name = parameters.name;
this.code = parameters.code;
this.docs = parameters.docs;
this.level = parameters.level;
validateLevel(parameters.level);
} }
public canRevert(): boolean { public canRevert(): boolean {
@@ -19,6 +26,13 @@ export class Script extends BaseEntity<string> implements IScript {
} }
} }
export interface ScriptInitParameters {
readonly name: string;
readonly code: IScriptCode;
readonly docs: ReadonlyArray<string>;
readonly level?: RecommendationLevel;
}
function validateLevel(level?: RecommendationLevel) { function validateLevel(level?: RecommendationLevel) {
if (level !== undefined && !(level in RecommendationLevel)) { if (level !== undefined && !(level in RecommendationLevel)) {
throw new Error(`invalid level: ${level}`); throw new Error(`invalid level: ${level}`);

View File

@@ -0,0 +1,10 @@
import { ScriptCode } from './ScriptCode';
import type { IScriptCode } from './IScriptCode';
export interface ScriptCodeFactory {
(
...args: ConstructorParameters<typeof ScriptCode>
): IScriptCode;
}
export const createScriptCode: ScriptCodeFactory = (...args) => new ScriptCode(...args);

View File

@@ -0,0 +1,5 @@
export interface CommandDefinition {
buildShellCommand(filePath: string): string;
isExecutionTerminatedExternally(exitCode: number): boolean;
isExecutablePermissionsRequiredOnFile(): boolean;
}

View File

@@ -0,0 +1,61 @@
import { PosixShellArgumentEscaper } from './ShellArgument/PosixShellArgumentEscaper';
import type { CommandDefinition } from '../CommandDefinition';
import type { ShellArgumentEscaper } from './ShellArgument/ShellArgumentEscaper';
export const LinuxTerminalEmulator = 'x-terminal-emulator';
export class LinuxVisibleTerminalCommand implements CommandDefinition {
constructor(
private readonly escaper: ShellArgumentEscaper = new PosixShellArgumentEscaper(),
) { }
public buildShellCommand(filePath: string): string {
return `${LinuxTerminalEmulator} -e ${this.escaper.escapePathArgument(filePath)}`;
/*
🤔 Potential improvements:
Use user-friendly GUI sudo prompt (not terminal-based).
If `pkexec` exists, we could do `x-terminal-emulator -e pkexec 'path'`, which always
prompts with user-friendly GUI sudo prompt.
📝 Options:
`x-terminal-emulator -e 'path'`:
✅ Visible terminal window
❌ Terminal-based (not GUI) sudo prompt.
`x-terminal-emulator -e pkexec 'path'
✅ Visible terminal window
✅ Always prompts with user-friendly GUI sudo prompt.
🤔 Not using `pkexec` as it is not in all Linux distributions. It should have smarter
logic to handle if it does not exist.
`electron.shell.openPath`:
❌ Opens the script in the default text editor, verified on
Debian/Ubuntu-based distributions.
`child_process.execFile()`:
❌ Script execution in the background without a visible terminal.
*/
}
public isExecutionTerminatedExternally(exitCode: number): boolean {
return exitCode === 137;
/*
`x-terminal-emulator` may return exit code `137` under specific circumstances like when the
user closes the terminal (observed with `gnome-terminal` on Pop!_OS). This exit code (128 +
Unix signal 9) indicates the process was terminated by a SIGKILL signal, which can occur due
to user action (cancelling the progress) or the system (e.g., due to memory shortages).
Additional exit codes noted for future consideration (currently not handled as they have not
been reproduced):
- 130 (130 = 128 + Unix signal 2): Indicates the script was terminated by the user
(Control-C), corresponding to a SIGINT signal.
- 143 (128 + Unix signal 15): Indicates termination by a SIGTERM signal, suggesting a request
to gracefully terminate the process.
*/
}
public isExecutablePermissionsRequiredOnFile(): boolean {
/*
On Linux, a script file without executable permissions cannot be run directly by its path
without specifying a shell explicitly.
*/
return true;
}
}

View File

@@ -0,0 +1,46 @@
import { PosixShellArgumentEscaper } from './ShellArgument/PosixShellArgumentEscaper';
import type { CommandDefinition } from '../CommandDefinition';
import type { ShellArgumentEscaper } from './ShellArgument/ShellArgumentEscaper';
export class MacOsVisibleTerminalCommand implements CommandDefinition {
constructor(
private readonly escaper: ShellArgumentEscaper = new PosixShellArgumentEscaper(),
) { }
public buildShellCommand(filePath: string): string {
return `open -a Terminal.app ${this.escaper.escapePathArgument(filePath)}`;
/*
📝 Options:
`child_process.execFile()`
"path", `cmd.exe /c "path"`
❌ Script execution in the background without a visible terminal.
This occurs only when the user runs the application as administrator, as seen
in Windows Pro VMs on Azure.
`PowerShell Start -Verb RunAs "path"`
✅ Visible terminal window
✅ GUI sudo prompt (through `RunAs` option)
`PowerShell Start "path"`
`explorer.exe "path"`
`electron.shell.openPath`
`start cmd.exe /c "$path"`
✅ Visible terminal window
✅ GUI sudo prompt (through `RunAs` option)
👍 Among all options `start` command is the most explicit one, being the most resilient
against the potential changes in Windows or Electron framework (e.g. https://github.com/electron/electron/issues/36765).
`%COMSPEC%` environment variable should be checked before defaulting to `cmd.exe.
Related docs: https://web.archive.org/web/20240106002357/https://nodejs.org/api/child_process.html#spawning-bat-and-cmd-files-on-windows
*/
}
public isExecutionTerminatedExternally(): boolean {
return false;
}
public isExecutablePermissionsRequiredOnFile(): boolean {
/*
On macOS, a script file without executable permissions cannot be run directly by its path
without specifying a shell explicitly.
*/
return true;
}
}

View File

@@ -0,0 +1,32 @@
import type { PowerShellInvokeShellCommandCreator } from './PowerShellInvokeShellCommandCreator';
/**
Encoding PowerShell commands resolve issues with quote handling.
There are known problems with PowerShell's handling of double quotes in command line arguments:
- Quote stripping in PowerShell command line arguments: https://web.archive.org/web/20240507102706/https://stackoverflow.com/questions/6714165/powershell-stripping-double-quotes-from-command-line-arguments
- privacy.sexy double quotes issue when calling PowerShell from command line: https://web.archive.org/web/20240507102841/https://github.com/undergroundwires/privacy.sexy/issues/351
- Challenges with single quotes in PowerShell command line: https://web.archive.org/web/20240507102047/https://stackoverflow.com/questions/20958388/command-line-escaping-single-quote-for-powershell
Using the `EncodedCommand` parameter is recommended by Microsoft for handling
complex quoting scenarios. This approach helps avoid issues by encoding the entire
command as a Base64 string:
- Microsoft's documentation on using the `EncodedCommand` parameter: https://web.archive.org/web/20240507102733/https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1#-encodedcommand-base64encodedcommand
*/
export class EncodedPowerShellInvokeCmdCommandCreator
implements PowerShellInvokeShellCommandCreator {
public createCommandToInvokePowerShell(powerShellScript: string): string {
return generateEncodedPowershellCommand(powerShellScript);
}
}
function generateEncodedPowershellCommand(powerShellScript: string): string {
const encodedCommand = encodeForPowershellExecution(powerShellScript);
return `PowerShell -EncodedCommand ${encodedCommand}`;
}
function encodeForPowershellExecution(script: string): string {
// The string must be formatted using UTF-16LE character encoding, see: https://web.archive.org/web/20240507102733/https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1#-encodedcommand-base64encodedcommand
const buffer = Buffer.from(script, 'utf16le');
return buffer.toString('base64');
}

View File

@@ -0,0 +1,3 @@
export interface PowerShellInvokeShellCommandCreator {
createCommandToInvokePowerShell(powerShellCommand: string): string;
}

View File

@@ -0,0 +1,18 @@
import type { ShellArgumentEscaper } from './ShellArgumentEscaper';
export class PosixShellArgumentEscaper implements ShellArgumentEscaper {
public escapePathArgument(pathArgument: string): string {
return posixShellPathArgumentEscape(pathArgument);
}
}
function posixShellPathArgumentEscape(pathArgument: string): string {
/*
- Wraps the path in single quotes, which is a standard practice in POSIX shells
(like bash and zsh) found on macOS/Linux to ensure that characters like spaces, '*', and
'?' are treated as literals, not as special characters.
- Escapes any single quotes within the path itself. This allows paths containing single
quotes to be correctly interpreted in POSIX-compliant systems, such as Linux and macOS.
*/
return `'${pathArgument.replaceAll('\'', '\'\\\'\'')}'`;
}

View File

@@ -0,0 +1,15 @@
import type { ShellArgumentEscaper } from './ShellArgumentEscaper';
export class PowerShellArgumentEscaper implements ShellArgumentEscaper {
public escapePathArgument(pathArgument: string): string {
return powerShellPathArgumentEscape(pathArgument);
}
}
function powerShellPathArgumentEscape(pathArgument: string): string {
// - Encloses the path in single quotes to handle spaces and most special characters.
// - Single quotes are used in PowerShell to ensure the string is treated as a literal string.
// - Paths in Windows can include single quotes ('), so any internal single quotes are escaped
// using double quotes.
return `'${pathArgument.replace(/'/g, "''")}'`;
}

View File

@@ -0,0 +1,3 @@
export interface ShellArgumentEscaper {
escapePathArgument(pathArgument: string): string;
}

View File

@@ -0,0 +1,61 @@
import type { Logger } from '@/application/Common/Log/Logger';
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
import { PowerShellArgumentEscaper } from './ShellArgument/PowerShellArgumentEscaper';
import { EncodedPowerShellInvokeCmdCommandCreator } from './PowerShellInvoke/EncodedPowerShellInvokeCmdCommandCreator';
import type { ShellArgumentEscaper } from './ShellArgument/ShellArgumentEscaper';
import type { CommandDefinition } from '../CommandDefinition';
import type { PowerShellInvokeShellCommandCreator } from './PowerShellInvoke/PowerShellInvokeShellCommandCreator';
export class WindowsVisibleTerminalCommand implements CommandDefinition {
constructor(
private readonly escaper: ShellArgumentEscaper = new PowerShellArgumentEscaper(),
private readonly powershellCommandCreator: PowerShellInvokeShellCommandCreator
= new EncodedPowerShellInvokeCmdCommandCreator(),
private readonly logger: Logger = ElectronLogger,
) { }
public buildShellCommand(filePath: string): string {
const powershellCommand = [
'Start-Process',
'-Verb RunAs', // Run as administrator with GUI sudo prompt
`-FilePath ${this.escaper.escapePathArgument(filePath)}`,
].join(' ');
/*
Running PowerShell command is preferred due to its flexibility and the way it provides
GUI sudo prompt through `RunAs` argument.
Other options considered:
`child_process.execFile()`
"path", `cmd.exe /c "path"`
❌ Script execution in the background without a visible terminal.
This occurs only when the user runs the application as administrator, as seen
in Windows Pro VMs on Azure.
`PowerShell Start -Verb RunAs "path"`
✅ Visible terminal window
✅ GUI sudo prompt (through `RunAs` option)
`PowerShell Start "path"`
`explorer.exe "path"`
`electron.shell.openPath`
`start cmd.exe /c "$path"`
✅ Visible terminal window
✅ GUI sudo prompt (through `RunAs` option)
👍 Among all options `start` command is the most explicit one, being the most resilient
against the potential changes in Windows or Electron framework (e.g. https://github.com/electron/electron/issues/36765).
`%COMSPEC%` environment variable should be checked before defaulting to `cmd.exe.
Related docs: https://web.archive.org/web/20240106002357/https://nodejs.org/api/child_process.html#spawning-bat-and-cmd-files-on-windows
*/
this.logger.info(`Building command for PowerShell execution:\n\tCommand: ${powershellCommand}`);
return this.powershellCommandCreator.createCommandToInvokePowerShell(powershellCommand);
}
public isExecutionTerminatedExternally(): boolean {
return false;
}
public isExecutablePermissionsRequiredOnFile(): boolean {
/*
In Windows, whether a file can be executed is determined by its file extension
(.exe, .bat, .cmd, etc.) rather than executable permissions set on the file.
*/
return false;
}
}

View File

@@ -0,0 +1,5 @@
import type { CommandDefinition } from '../CommandDefinition';
export interface CommandDefinitionFactory {
provideCommandDefinition(): CommandDefinition;
}

View File

@@ -0,0 +1,40 @@
import { OperatingSystem } from '@/domain/OperatingSystem';
import { CurrentEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory';
import type { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
import { WindowsVisibleTerminalCommand } from '../Commands/WindowsVisibleTerminalCommand';
import { LinuxVisibleTerminalCommand } from '../Commands/LinuxVisibleTerminalCommand';
import { MacOsVisibleTerminalCommand } from '../Commands/MacOsVisibleTerminalCommand';
import type { CommandDefinitionFactory } from './CommandDefinitionFactory';
import type { CommandDefinition } from '../CommandDefinition';
export class OsSpecificTerminalLaunchCommandFactory implements CommandDefinitionFactory {
constructor(
private readonly environment: RuntimeEnvironment = CurrentEnvironment,
) { }
public provideCommandDefinition(): CommandDefinition {
const { os } = this.environment;
if (os === undefined) {
throw new Error('Operating system could not be identified from environment.');
}
return getOperatingSystemCommandDefinition(os);
}
}
function getOperatingSystemCommandDefinition(
operatingSystem: OperatingSystem,
): CommandDefinition {
const definition = SupportedDesktopCommandDefinitions[operatingSystem];
if (!definition) {
throw new Error(`Unsupported operating system: ${OperatingSystem[operatingSystem]}`);
}
return definition;
}
const SupportedDesktopCommandDefinitions: Readonly<Partial<Record<
OperatingSystem,
CommandDefinition>>> = {
[OperatingSystem.Windows]: new WindowsVisibleTerminalCommand(),
[OperatingSystem.Linux]: new LinuxVisibleTerminalCommand(),
[OperatingSystem.macOS]: new MacOsVisibleTerminalCommand(),
} as const;

View File

@@ -0,0 +1,9 @@
import type { ScriptFileExecutionOutcome } from '../../ScriptFileExecutor';
import type { CommandDefinition } from '../CommandDefinition';
export interface CommandDefinitionRunner {
runCommandDefinition(
commandDefinition: CommandDefinition,
filePath: string,
): Promise<ScriptFileExecutionOutcome>;
}

View File

@@ -0,0 +1,80 @@
import type { CodeRunErrorType } from '@/application/CodeRunner/CodeRunner';
import { FileSystemExecutablePermissionSetter } from './PermissionSetter/FileSystemExecutablePermissionSetter';
import { LoggingNodeShellCommandRunner } from './ShellRunner/LoggingNodeShellCommandRunner';
import type { FailedScriptFileExecution, ScriptFileExecutionOutcome } from '../../ScriptFileExecutor';
import type { CommandDefinition } from '../CommandDefinition';
import type { CommandDefinitionRunner } from './CommandDefinitionRunner';
import type { ExecutablePermissionSetter } from './PermissionSetter/ExecutablePermissionSetter';
import type { ShellCommandOutcome, ShellCommandRunner } from './ShellRunner/ShellCommandRunner';
export class ExecutableFileShellCommandDefinitionRunner implements CommandDefinitionRunner {
constructor(
private readonly executablePermissionSetter: ExecutablePermissionSetter
= new FileSystemExecutablePermissionSetter(),
private readonly shellCommandRunner: ShellCommandRunner
= new LoggingNodeShellCommandRunner(),
) { }
public async runCommandDefinition(
commandDefinition: CommandDefinition,
filePath: string,
): Promise<ScriptFileExecutionOutcome> {
if (commandDefinition.isExecutablePermissionsRequiredOnFile()) {
const filePermissionsResult = await this.executablePermissionSetter
.makeFileExecutable(filePath);
if (!filePermissionsResult.success) {
return filePermissionsResult;
}
}
const command = commandDefinition.buildShellCommand(filePath);
const shellOutcome = await this.shellCommandRunner.runShellCommand(command);
return interpretShellOutcome(shellOutcome, commandDefinition);
}
}
function interpretShellOutcome(
outcome: ShellCommandOutcome,
commandDefinition: CommandDefinition,
): ScriptFileExecutionOutcome {
switch (outcome.type) {
case 'RegularProcessExit':
if (outcome.exitCode === 0) {
return { success: true };
}
if (commandDefinition.isExecutionTerminatedExternally(outcome.exitCode)) {
return createFailureOutcome(
'ExternalProcessTermination',
`Process terminated externally: Exit code ${outcome.exitCode}.`,
);
}
return createFailureOutcome(
'FileExecutionError',
`Unexpected exit code: ${outcome.exitCode}.`,
);
case 'ExternallyTerminated':
return createFailureOutcome(
'ExternalProcessTermination',
`Process terminated by signal ${outcome.terminationSignal}.`,
);
case 'ExecutionError':
return createFailureOutcome(
'FileExecutionError',
`Execution error: ${outcome.error.message}.`,
);
default:
throw new Error(`Unknown outcome type: ${outcome}`);
}
}
function createFailureOutcome(
type: CodeRunErrorType,
errorMessage: string,
): FailedScriptFileExecution {
return {
success: false,
error: {
type,
message: `Error during command execution: ${errorMessage}`,
},
};
}

View File

@@ -0,0 +1,5 @@
import type { ScriptFileExecutionOutcome } from '@/infrastructure/CodeRunner/Execution/ScriptFileExecutor';
export interface ExecutablePermissionSetter {
makeFileExecutable(filePath: string): Promise<ScriptFileExecutionOutcome>;
}

View File

@@ -0,0 +1,35 @@
import { NodeElectronSystemOperations } from '@/infrastructure/CodeRunner/System/NodeElectronSystemOperations';
import type { Logger } from '@/application/Common/Log/Logger';
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
import type { SystemOperations } from '@/infrastructure/CodeRunner/System/SystemOperations';
import type { ScriptFileExecutionOutcome } from '@/infrastructure/CodeRunner/Execution/ScriptFileExecutor';
import type { ExecutablePermissionSetter } from './ExecutablePermissionSetter';
export class FileSystemExecutablePermissionSetter implements ExecutablePermissionSetter {
constructor(
private readonly system: SystemOperations = new NodeElectronSystemOperations(),
private readonly logger: Logger = ElectronLogger,
) { }
public async makeFileExecutable(filePath: string): Promise<ScriptFileExecutionOutcome> {
/*
This is required on macOS and Linux otherwise the terminal emulators will refuse to
execute the script. It's not needed on Windows.
*/
try {
this.logger.info(`Setting execution permissions for file at ${filePath}`);
await this.system.fileSystem.setFilePermissions(filePath, '755');
this.logger.info(`Execution permissions set successfully for ${filePath}`);
return { success: true };
} catch (error) {
this.logger.error(error);
return {
success: false,
error: {
type: 'FilePermissionChangeError',
message: `Error setting script file permission: ${error.message}`,
},
};
}
}
}

View File

@@ -0,0 +1,47 @@
import type { Logger } from '@/application/Common/Log/Logger';
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
import type { SystemOperations } from '@/infrastructure/CodeRunner/System/SystemOperations';
import { NodeElectronSystemOperations } from '@/infrastructure/CodeRunner/System/NodeElectronSystemOperations';
import type { ShellCommandOutcome, ShellCommandRunner } from './ShellCommandRunner';
export class LoggingNodeShellCommandRunner implements ShellCommandRunner {
constructor(
private readonly logger: Logger = ElectronLogger,
private readonly systemOps: SystemOperations = new NodeElectronSystemOperations(),
) {
}
public runShellCommand(command: string): Promise<ShellCommandOutcome> {
this.logger.info(`Executing command: ${command}`);
return new Promise((resolve) => {
this.systemOps.command.exec(command)
// https://archive.today/2024.01.19-004011/https://nodejs.org/api/child_process.html#child_process_event_exit
.on('exit', (
code, // The exit code if the child exited on its own.
signal, // The signal by which the child process was terminated.
) => {
// One of `code` or `signal` will always be non-null.
// If the process exited, code is the final exit code of the process, otherwise null.
if (code !== null) {
this.logger.info(`Command completed with exit code ${code}.`);
resolve({ type: 'RegularProcessExit', exitCode: code });
return; // Prevent further execution to avoid multiple promise resolutions and logs.
}
// If the process terminated due to receipt of a signal, signal is the string name of
// the signal, otherwise null.
resolve({ type: 'ExternallyTerminated', terminationSignal: signal as NodeJS.Signals });
this.logger.warn(`Command terminated by signal: ${signal}`);
})
.on('error', (error) => {
// https://archive.ph/20200912193803/https://nodejs.org/api/child_process.html#child_process_event_error
// The 'error' event is emitted whenever:
// - The process could not be spawned, or
// - The process could not be killed, or
// - Sending a message to the child process failed.
// The 'exit' event may or may not fire after an error has occurred.
this.logger.error('Command execution failed:', error);
resolve({ type: 'ExecutionError', error });
});
});
}
}

View File

@@ -0,0 +1,23 @@
export interface ShellCommandRunner {
runShellCommand(command: string): Promise<ShellCommandOutcome>;
}
export type ShellCommandOutcome = ProcessStatus & ({
readonly type: 'RegularProcessExit',
readonly exitCode: number;
} | {
readonly type: 'ExternallyTerminated';
readonly terminationSignal: NodeJS.Signals;
} | {
readonly type: 'ExecutionError';
readonly error: Error;
});
type ProcessOutcomeType = 'RegularProcessExit' | 'ExternallyTerminated' | 'ExecutionError';
interface ProcessStatus {
readonly type: ProcessOutcomeType;
readonly error?: Error;
readonly terminationSignal?: NodeJS.Signals;
readonly exitCode?: number;
}

View File

@@ -0,0 +1,71 @@
import type { Logger } from '@/application/Common/Log/Logger';
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
import { OsSpecificTerminalLaunchCommandFactory } from './CommandDefinition/Factory/OsSpecificTerminalLaunchCommandFactory';
import { ExecutableFileShellCommandDefinitionRunner } from './CommandDefinition/Runner/ExecutableFileShellCommandDefinitionRunner';
import type { ScriptFileExecutionOutcome, ScriptFileExecutor } from './ScriptFileExecutor';
import type { CommandDefinitionFactory } from './CommandDefinition/Factory/CommandDefinitionFactory';
import type { CommandDefinitionRunner } from './CommandDefinition/Runner/CommandDefinitionRunner';
import type { CommandDefinition } from './CommandDefinition/CommandDefinition';
export class VisibleTerminalFileRunner implements ScriptFileExecutor {
constructor(
private readonly logger: Logger = ElectronLogger,
private readonly commandFactory: CommandDefinitionFactory
= new OsSpecificTerminalLaunchCommandFactory(),
private readonly commandRunner: CommandDefinitionRunner
= new ExecutableFileShellCommandDefinitionRunner(),
) { }
public async executeScriptFile(
filePath: string,
): Promise<ScriptFileExecutionOutcome> {
this.logger.info(`Executing script file: ${filePath}.`);
const outcome = await this.findAndExecuteCommand(filePath);
this.logOutcome(outcome);
return outcome;
}
private async findAndExecuteCommand(
filePath: string,
): Promise<ScriptFileExecutionOutcome> {
try {
let commandDefinition: CommandDefinition;
try {
commandDefinition = this.commandFactory.provideCommandDefinition();
} catch (error) {
return {
success: false,
error: {
type: 'UnsupportedPlatform',
message: `Error finding command: ${error.message}`,
},
};
}
const runOutcome = await this.commandRunner.runCommandDefinition(
commandDefinition,
filePath,
);
return runOutcome;
} catch (error) {
return {
success: false,
error: {
type: 'FileExecutionError',
message: `Unexpected error: ${error.message}`,
},
};
}
}
private logOutcome(outcome: ScriptFileExecutionOutcome) {
if (outcome.success) {
this.logger.info('Executed script file in terminal successfully.');
return;
}
this.logger.error(
'Failed to execute the script file in terminal.',
outcome.error.type,
outcome.error.message,
);
}
}

View File

@@ -1,214 +0,0 @@
import { OperatingSystem } from '@/domain/OperatingSystem';
import type { CommandOps, SystemOperations } from '@/infrastructure/CodeRunner/System/SystemOperations';
import type { Logger } from '@/application/Common/Log/Logger';
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
import type { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
import { NodeElectronSystemOperations } from '@/infrastructure/CodeRunner/System/NodeElectronSystemOperations';
import { CurrentEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory';
import type { CodeRunErrorType } from '@/application/CodeRunner/CodeRunner';
import { isString } from '@/TypeHelpers';
import type { FailedScriptFileExecution, ScriptFileExecutionOutcome, ScriptFileExecutor } from './ScriptFileExecutor';
export class VisibleTerminalScriptExecutor implements ScriptFileExecutor {
constructor(
private readonly system: SystemOperations = new NodeElectronSystemOperations(),
private readonly logger: Logger = ElectronLogger,
private readonly environment: RuntimeEnvironment = CurrentEnvironment,
) { }
public async executeScriptFile(filePath: string): Promise<ScriptFileExecutionOutcome> {
const { os } = this.environment;
if (os === undefined) {
return this.handleError('UnsupportedOperatingSystem', 'Operating system could not be identified from environment.');
}
const filePermissionsResult = await this.setFileExecutablePermissions(filePath);
if (!filePermissionsResult.success) {
return filePermissionsResult;
}
const scriptExecutionResult = await this.runFileWithRunner(filePath, os);
if (!scriptExecutionResult.success) {
return scriptExecutionResult;
}
return {
success: true,
};
}
private async setFileExecutablePermissions(
filePath: string,
): Promise<ScriptFileExecutionOutcome> {
/*
This is required on macOS and Linux otherwise the terminal emulators will refuse to
execute the script. It's not needed on Windows.
*/
try {
this.logger.info(`Setting execution permissions for file at ${filePath}`);
await this.system.fileSystem.setFilePermissions(filePath, '755');
this.logger.info(`Execution permissions set successfully for ${filePath}`);
return { success: true };
} catch (error) {
return this.handleError('FileExecutionError', error);
}
}
private async runFileWithRunner(
filePath: string,
os: OperatingSystem,
): Promise<ScriptFileExecutionOutcome> {
this.logger.info(`Executing script file: ${filePath} on ${OperatingSystem[os]}.`);
const runner = TerminalRunners[os];
if (!runner) {
return this.handleError('UnsupportedOperatingSystem', `Unsupported operating system: ${OperatingSystem[os]}`);
}
const context: TerminalExecutionContext = {
scriptFilePath: filePath,
commandOps: this.system.command,
logger: this.logger,
};
try {
await runner(context);
this.logger.info('Command script file successfully.');
return { success: true };
} catch (error) {
return this.handleError('FileExecutionError', error);
}
}
private handleError(
type: CodeRunErrorType,
error: Error | string,
): FailedScriptFileExecution {
const errorMessage = 'Error during script file execution';
this.logger.error([type, errorMessage, ...(error ? [error] : [])]);
return {
success: false,
error: {
type,
message: `${errorMessage}: ${isString(error) ? error : errorMessage}`,
},
};
}
}
interface TerminalExecutionContext {
readonly scriptFilePath: string;
readonly commandOps: CommandOps;
readonly logger: Logger;
}
type TerminalRunner = (context: TerminalExecutionContext) => Promise<void>;
export const LinuxTerminalEmulator = 'x-terminal-emulator';
const TerminalRunners: Partial<Record<OperatingSystem, TerminalRunner>> = {
[OperatingSystem.Windows]: async (context) => {
const command = [
'PowerShell',
'Start-Process',
'-Verb RunAs', // Run as administrator with GUI sudo prompt
`-FilePath ${cmdShellPathArgumentEscape(context.scriptFilePath)}`,
].join(' ');
/*
📝 Options:
`child_process.execFile()`
"path", `cmd.exe /c "path"`
❌ Script execution in the background without a visible terminal.
This occurs only when the user runs the application as administrator, as seen
in Windows Pro VMs on Azure.
`PowerShell Start -Verb RunAs "path"`
✅ Visible terminal window
✅ GUI sudo prompt (through `RunAs` option)
`PowerShell Start "path"`
`explorer.exe "path"`
`electron.shell.openPath`
`start cmd.exe /c "$path"`
✅ Visible terminal window
✅ GUI sudo prompt (through `RunAs` option)
👍 Among all options `start` command is the most explicit one, being the most resilient
against the potential changes in Windows or Electron framework (e.g. https://github.com/electron/electron/issues/36765).
`%COMSPEC%` environment variable should be checked before defaulting to `cmd.exe.
Related docs: https://web.archive.org/web/20240106002357/https://nodejs.org/api/child_process.html#spawning-bat-and-cmd-files-on-windows
*/
await runCommand(command, context);
},
[OperatingSystem.Linux]: async (context) => {
const command = `${LinuxTerminalEmulator} -e ${posixShellPathArgumentEscape(context.scriptFilePath)}`;
/*
🤔 Potential improvements:
Use user-friendly GUI sudo prompt (not terminal-based).
If `pkexec` exists, we could do `x-terminal-emulator -e pkexec 'path'`, which always
prompts with user-friendly GUI sudo prompt.
📝 Options:
`x-terminal-emulator -e 'path'`:
✅ Visible terminal window
❌ Terminal-based (not GUI) sudo prompt.
`x-terminal-emulator -e pkexec 'path'
✅ Visible terminal window
✅ Always prompts with user-friendly GUI sudo prompt.
🤔 Not using `pkexec` as it is not in all Linux distributions. It should have smarter
logic to handle if it does not exist.
`electron.shell.openPath`:
❌ Opens the script in the default text editor, verified on
Debian/Ubuntu-based distributions.
`child_process.execFile()`:
❌ Script execution in the background without a visible terminal.
*/
await runCommand(command, context);
},
[OperatingSystem.macOS]: async (context) => {
const command = `open -a Terminal.app ${posixShellPathArgumentEscape(context.scriptFilePath)}`;
// -a Specifies the application to use for opening the file
/* eslint-disable vue/max-len */
/*
🤔 Potential improvements:
Use user-friendly GUI sudo prompt for running the script.
📝 Options:
`open -a Terminal.app 'path'`
✅ Visible terminal window
❌ Terminal-based (not GUI) sudo prompt.
❌ Terminal app requires many privileges to execute the script, this prompts user
to grant privileges to the Terminal app.
`osascript -e 'do shell script "'/tmp/test.sh'" with administrator privileges'`
✅ Script as root
✅ GUI sudo prompt.
❌ Script execution in the background without a visible terminal.
`osascript -e 'do shell script "open -a 'Terminal.app' '/tmp/test.sh'" with administrator privileges'`
❌ Script as user, not root
✅ GUI sudo prompt.
✅ Visible terminal window
`osascript -e 'do shell script "/System/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal '/tmp/test.sh'" with administrator privileges'`
✅ Script as root
✅ GUI sudo prompt.
✅ Visible terminal window
Useful resources about `do shell script .. with administrator privileges`:
- Change "osascript wants to make changes" prompt: https://web.archive.org/web/20240109191128/https://apple.stackexchange.com/questions/283353/how-to-rename-osascript-in-the-administrator-privileges-dialog
- More about `do shell script`: https://web.archive.org/web/20100906222226/http://developer.apple.com/mac/library/technotes/tn2002/tn2065.html
*/
/* eslint-enable vue/max-len */
await runCommand(command, context);
},
} as const;
async function runCommand(command: string, context: TerminalExecutionContext): Promise<void> {
context.logger.info(`Executing command:\n${command}`);
await context.commandOps.exec(command);
context.logger.info('Executed command successfully.');
}
function posixShellPathArgumentEscape(pathArgument: string): string {
/*
- Wraps the path in single quotes, which is a standard practice in POSIX shells
(like bash and zsh) found on macOS/Linux to ensure that characters like spaces, '*', and
'?' are treated as literals, not as special characters.
- Escapes any single quotes within the path itself. This allows paths containing single
quotes to be correctly interpreted in POSIX-compliant systems, such as Linux and macOS.
*/
return `'${pathArgument.replaceAll('\'', '\'\\\'\'')}'`;
}
function cmdShellPathArgumentEscape(pathArgument: string): string {
// - Encloses the path in double quotes, which is necessary for Windows command line (cmd.exe)
// to correctly handle paths containing spaces.
// - Paths in Windows cannot include double quotes `"` themselves, so these are not escaped.
return `"${pathArgument}"`;
}

View File

@@ -4,15 +4,15 @@ import type {
CodeRunError, CodeRunOutcome, CodeRunner, FailedCodeRun, CodeRunError, CodeRunOutcome, CodeRunner, FailedCodeRun,
} from '@/application/CodeRunner/CodeRunner'; } from '@/application/CodeRunner/CodeRunner';
import { ElectronLogger } from '../Log/ElectronLogger'; import { ElectronLogger } from '../Log/ElectronLogger';
import { VisibleTerminalScriptExecutor } from './Execution/VisibleTerminalScriptFileExecutor';
import { ScriptFileCreationOrchestrator } from './Creation/ScriptFileCreationOrchestrator'; import { ScriptFileCreationOrchestrator } from './Creation/ScriptFileCreationOrchestrator';
import { VisibleTerminalFileRunner } from './Execution/VisibleTerminalFileRunner';
import type { ScriptFileExecutor } from './Execution/ScriptFileExecutor'; import type { ScriptFileExecutor } from './Execution/ScriptFileExecutor';
import type { ScriptFileCreator } from './Creation/ScriptFileCreator'; import type { ScriptFileCreator } from './Creation/ScriptFileCreator';
export class ScriptFileCodeRunner implements CodeRunner { export class ScriptFileCodeRunner implements CodeRunner {
constructor( constructor(
private readonly scriptFileExecutor private readonly scriptFileExecutor
: ScriptFileExecutor = new VisibleTerminalScriptExecutor(), : ScriptFileExecutor = new VisibleTerminalFileRunner(),
private readonly scriptFileCreator: ScriptFileCreator = new ScriptFileCreationOrchestrator(), private readonly scriptFileCreator: ScriptFileCreator = new ScriptFileCreationOrchestrator(),
private readonly logger: Logger = ElectronLogger, private readonly logger: Logger = ElectronLogger,
) { } ) { }

View File

@@ -6,6 +6,9 @@ import type {
CommandOps, FileSystemOps, LocationOps, OperatingSystemOps, SystemOperations, CommandOps, FileSystemOps, LocationOps, OperatingSystemOps, SystemOperations,
} from './SystemOperations'; } from './SystemOperations';
/**
* Thin wrapper for Node and Electron APIs.
*/
export class NodeElectronSystemOperations implements SystemOperations { export class NodeElectronSystemOperations implements SystemOperations {
public readonly operatingSystem: OperatingSystemOps = { public readonly operatingSystem: OperatingSystemOps = {
/* /*
@@ -49,13 +52,6 @@ export class NodeElectronSystemOperations implements SystemOperations {
}; };
public readonly command: CommandOps = { public readonly command: CommandOps = {
exec: (command) => new Promise((resolve, reject) => { exec,
exec(command, (error) => {
if (error) {
reject(error);
}
resolve();
});
}),
}; };
} }

View File

@@ -1,3 +1,5 @@
import type { exec } from 'node:child_process';
export interface SystemOperations { export interface SystemOperations {
readonly operatingSystem: OperatingSystemOps; readonly operatingSystem: OperatingSystemOps;
readonly location: LocationOps; readonly location: LocationOps;
@@ -14,7 +16,7 @@ export interface LocationOps {
} }
export interface CommandOps { export interface CommandOps {
exec(command: string): Promise<void>; exec(command: string): ReturnType<typeof exec>;
} }
export interface FileSystemOps { export interface FileSystemOps {

View File

@@ -13,11 +13,16 @@
@use "_code-styling" as *; @use "_code-styling" as *;
@use "_margin-padding" as *; @use "_margin-padding" as *;
@use "_link-styling" as *; @use "_link-styling" as *;
@use "_prevent-scrollbar-layout-shift" as *;
* { * {
box-sizing: border-box; box-sizing: border-box;
} }
html {
@include prevent-scrollbar-layout-shift;
}
body { body {
background: $color-background; background: $color-background;
@include base-font-style; @include base-font-style;

View File

@@ -0,0 +1,19 @@
// This mixin prevents layout shifts caused by the appearance of a vertical scrollbar
// in Chromium-based browsers on Linux and Windows.
// It creates a reserved space for the scrollbar, ensuring content remains stable and does
// not shift horizontally when the scrollbar appears.
@mixin prevent-scrollbar-layout-shift {
scrollbar-gutter: stable;
@supports not (scrollbar-gutter: stable) { // https://caniuse.com/mdn-css_properties_scrollbar-gutter
// Safari workaround: Shift content to accommodate non-overlay scrollbar.
// An issue: On small screens, the appearance of the scrollbar can shift content, due to limited space for
// both content and scrollbar.
$full-width-including-scrollbar: 100vw;
$full-width-excluding-scrollbar: 100%;
$scrollbar-width: calc($full-width-including-scrollbar - $full-width-excluding-scrollbar);
padding-inline-start: $scrollbar-width; // Allows both right-to-left (RTL) and left-to-right (LTR) text direction support
}
// More details: https://web.archive.org/web/20240509122237/https://stackoverflow.com/questions/1417934/how-to-prevent-scrollbar-from-repositioning-web-page
}

View File

@@ -16,6 +16,7 @@ import { useCodeRunner } from '@/presentation/components/Shared/Hooks/UseCodeRun
import { CurrentEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory'; import { CurrentEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory';
import { useDialog } from '@/presentation/components/Shared/Hooks/Dialog/UseDialog'; import { useDialog } from '@/presentation/components/Shared/Hooks/Dialog/UseDialog';
import { useScriptDiagnosticsCollector } from '@/presentation/components/Shared/Hooks/UseScriptDiagnosticsCollector'; import { useScriptDiagnosticsCollector } from '@/presentation/components/Shared/Hooks/UseScriptDiagnosticsCollector';
import { useAutoUnsubscribedEventListener } from '@/presentation/components/Shared/Hooks/UseAutoUnsubscribedEventListener';
export function provideDependencies( export function provideDependencies(
context: IApplicationContext, context: IApplicationContext,
@@ -77,6 +78,10 @@ export function provideDependencies(
InjectionKeys.useScriptDiagnosticsCollector, InjectionKeys.useScriptDiagnosticsCollector,
useScriptDiagnosticsCollector, useScriptDiagnosticsCollector,
), ),
useAutoUnsubscribedEventListener: (di) => di.provide(
InjectionKeys.useAutoUnsubscribedEventListener,
useAutoUnsubscribedEventListener,
),
}; };
registerAll(Object.values(resolvers), api); registerAll(Object.values(resolvers), api);
} }

View File

@@ -11,6 +11,7 @@
import { defineComponent, computed } from 'vue'; import { defineComponent, computed } from 'vue';
import { injectKey } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
import { OperatingSystem } from '@/domain/OperatingSystem'; import { OperatingSystem } from '@/domain/OperatingSystem';
import type { CodeRunError } from '@/application/CodeRunner/CodeRunner';
import IconButton from './IconButton.vue'; import IconButton from './IconButton.vue';
import { createScriptErrorDialog } from './ScriptErrorDialog'; import { createScriptErrorDialog } from './ScriptErrorDialog';
@@ -38,15 +39,19 @@ export default defineComponent({
currentContext.state.collection.scripting.fileExtension, currentContext.state.collection.scripting.fileExtension,
); );
if (!success) { if (!success) {
dialog.showError(...(await createScriptErrorDialog({ await handleCodeRunFailure(error);
errorContext: 'run',
errorType: error.type,
errorMessage: error.message,
isFileReadbackError: error.type === 'FileReadbackVerificationError',
}, scriptDiagnosticsCollector)));
} }
} }
async function handleCodeRunFailure(error: CodeRunError) {
dialog.showError(...(await createScriptErrorDialog({
errorContext: 'run',
errorType: error.type,
errorMessage: error.message,
isFileReadbackError: error.type === 'FileReadbackVerificationError',
}, scriptDiagnosticsCollector)));
}
return { return {
canRun, canRun,
runCode, runCode,

View File

@@ -1,5 +1,7 @@
<template> <template>
<span class="info-container"> <span
class="info-container"
>
<TooltipWrapper> <TooltipWrapper>
<AppIcon icon="circle-info" /> <AppIcon icon="circle-info" />
<template #tooltip> <template #tooltip>
@@ -19,27 +21,17 @@ export default defineComponent({
TooltipWrapper, TooltipWrapper,
AppIcon, AppIcon,
}, },
props: {
hasLeftMargin: {
type: Boolean,
default: false,
},
},
}); });
</script> </script>
<style scoped lang="scss"> <style lang="scss">
@use "@/presentation/assets/styles/main" as *;
@mixin apply-style-when-placed-after-non-text {
* + & {
@content;
}
}
.info-container { .info-container {
vertical-align: text-top; vertical-align: text-top;
* + & { // If it's followed by any other element
vertical-align: middle;
@include set-property-ch-value-with-fallback(
$property: margin-left,
$value-in-ch: 0.5,
)
}
} }
</style> </style>

View File

@@ -0,0 +1,36 @@
<template>
<span class="info-tooltip-wrapper">
<span>
<slot />
</span>
<span>
<InfoTooltipInline>
<slot name="info" />
</InfoTooltipInline>
</span>
</span>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import InfoTooltipInline from './InfoTooltipInline.vue';
export default defineComponent({
components: {
InfoTooltipInline,
},
});
</script>
<style lang="scss">
@use "@/presentation/assets/styles/main" as *;
.info-tooltip-wrapper {
display: flex;
align-items: center;
@include set-property-ch-value-with-fallback(
$property: gap,
$value-in-ch: 0.5,
)
}
</style>

View File

@@ -17,7 +17,7 @@
<p> <p>
This requires you to do additional manual This requires you to do additional manual
steps. If you are unsure how to follow the instructions, tap or hover on information steps. If you are unsure how to follow the instructions, tap or hover on information
<InfoTooltip>Engage with icons like this for extra wisdom!</InfoTooltip> <InfoTooltipInline>Engage with icons like this for extra wisdom!</InfoTooltipInline>
icons near the steps, or follow the easy alternative described above. icons near the steps, or follow the easy alternative described above.
</p> </p>
<p> <p>
@@ -32,12 +32,12 @@ import { defineComponent, computed } from 'vue';
import { injectKey } from '@/presentation/injectionSymbols'; import { injectKey } from '@/presentation/injectionSymbols';
import { OperatingSystem } from '@/domain/OperatingSystem'; import { OperatingSystem } from '@/domain/OperatingSystem';
import { getOperatingSystemDisplayName } from '@/presentation/components/Shared/OperatingSystemNames'; import { getOperatingSystemDisplayName } from '@/presentation/components/Shared/OperatingSystemNames';
import InfoTooltip from './InfoTooltip.vue'; import InfoTooltipInline from './Help/InfoTooltipInline.vue';
import PlatformInstructionSteps from './Steps/PlatformInstructionSteps.vue'; import PlatformInstructionSteps from './Steps/PlatformInstructionSteps.vue';
export default defineComponent({ export default defineComponent({
components: { components: {
InfoTooltip, InfoTooltipInline,
PlatformInstructionSteps, PlatformInstructionSteps,
}, },
props: { props: {

Some files were not shown because too many files have changed in this diff Show More