From 8a2910c5ac7f41e833a793f54024ecfbfaa6e4cf Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Tue, 10 Nov 2026 09:01:53 -0700 Subject: [PATCH 01/30] Add repository hygiene files .editorconfig, .gitattributes (line-ending normalization), PSScriptAnalyzer settings, GitHub community files and issue/PR templates, expanded .gitignore. Co-Authored-By: Claude Opus 5.5 --- .PSScriptAnalyzerSettings.psd1 | 139 ++++++++++++++++++++++ .editorconfig | 48 ++++++++ .gitattributes | 94 +++++++++++++++ .github/CODE_OF_CONDUCT.md | 101 ++++++++++++++++ .github/CONTRIBUTING.md | 130 ++++++++++++++++++++ .github/ISSUE_TEMPLATE/ai_task.md | 58 +++++++++ .github/ISSUE_TEMPLATE/bug_report.md | 54 +++++++++ .github/ISSUE_TEMPLATE/config.yml | 11 ++ .github/ISSUE_TEMPLATE/feature_request.md | 52 ++++++++ .github/PULL_REQUEST_TEMPLATE.md | 50 ++++++++ .github/SECURITY.md | 98 +++++++++++++++ .gitignore | 100 +++++++++++++++- 12 files changed, 933 insertions(+), 2 deletions(-) create mode 100644 .PSScriptAnalyzerSettings.psd1 create mode 100644 .editorconfig create mode 100644 .gitattributes create mode 100644 .github/CODE_OF_CONDUCT.md create mode 100644 .github/CONTRIBUTING.md create mode 100644 .github/ISSUE_TEMPLATE/ai_task.md create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/SECURITY.md diff --git a/.PSScriptAnalyzerSettings.psd1 b/.PSScriptAnalyzerSettings.psd1 new file mode 100644 index 0000000..b9d8253 --- /dev/null +++ b/.PSScriptAnalyzerSettings.psd1 @@ -0,0 +1,139 @@ +@{ + # Severity levels: Error, Warning, Information + Severity = @('Error', 'Warning') + + IncludeRules = @( + # Code Style + 'PSAvoidDefaultValueForMandatoryParameter', + 'PSAvoidDefaultValueSwitchParameter', + 'PSAvoidGlobalVars', + 'PSAvoidUsingCmdletAliases', + 'PSAvoidUsingComputerNameHardcoded', + 'PSAvoidUsingConvertToSecureStringWithPlainText', + 'PSAvoidUsingDeprecatedManifestFields', + 'PSAvoidUsingEmptyCatchBlock', + 'PSAvoidUsingInvokeExpression', + 'PSAvoidUsingPlainTextForPassword', + 'PSAvoidUsingPositionalParameters', + 'PSAvoidUsingUsernameAndPasswordParams', + 'PSAvoidUsingWMICmdlet', + 'PSAvoidUsingWriteHost', + + # Best Practices + 'PSAlignAssignmentStatement', + 'PSAvoidAssignmentToAutomaticVariable', + 'PSAvoidLongLines', + 'PSAvoidOverwritingBuiltInCmdlets', + 'PSAvoidShouldContinueWithoutForce', + 'PSAvoidTrailingWhitespace', + 'PSAvoidUsingBrokenHashAlgorithms', + 'PSAvoidUsingDoubleQuotesForConstantString', + + # Functions + 'PSAvoidMultipleTypeAttributes', + 'PSMisleadingBacktick', + 'PSMissingModuleManifestField', + 'PSPlaceCloseBrace', + 'PSPlaceOpenBrace', + 'PSProvideCommentHelp', + 'PSReservedCmdletChar', + 'PSReservedParams', + 'PSReviewUnusedParameter', + 'PSShouldProcess', + 'PSUseApprovedVerbs', + 'PSUseBOMForUnicodeEncodedFile', + 'PSUseCmdletCorrectly', + 'PSUseCompatibleCmdlets', + 'PSUseCompatibleSyntax', + 'PSUseCompatibleTypes', + 'PSUseConsistentIndentation', + 'PSUseConsistentWhitespace', + 'PSUseCorrectCasing', + 'PSUseDeclaredVarsMoreThanAssignments', + 'PSUseLiteralInitializerForHashtable', + 'PSUseOutputTypeCorrectly', + 'PSUsePSCredentialType', + 'PSUseProcessBlockForPipelineCommand', + 'PSUseShouldProcessForStateChangingFunctions', + 'PSUseSingularNouns', + 'PSUseSupportsShouldProcess', + 'PSUseToExportFieldsInManifest', + 'PSUseUTF8EncodingForHelpFile', + 'PSUseUsingScopeModifierInNewRunspaces' + ) + + Rules = @{ + PSPlaceOpenBrace = @{ + Enable = $true + OnSameLine = $true + NewLineAfter = $true + IgnoreOneLineBlock = $true + } + + PSPlaceCloseBrace = @{ + Enable = $true + NewLineAfter = $false + IgnoreOneLineBlock = $true + NoEmptyLineBefore = $false + } + + PSUseConsistentIndentation = @{ + Enable = $true + Kind = 'space' + PipelineIndentation = 'IncreaseIndentationForFirstPipeline' + IndentationSize = 4 + } + + PSUseConsistentWhitespace = @{ + Enable = $true + CheckInnerBrace = $true + CheckOpenBrace = $true + CheckOpenParen = $true + CheckOperator = $true + CheckPipe = $true + CheckPipeForRedundantWhitespace = $false + CheckSeparator = $true + CheckParameter = $false + } + + PSAlignAssignmentStatement = @{ + Enable = $true + CheckHashtable = $true + } + + PSUseCorrectCasing = @{ + Enable = $true + } + + PSAvoidLongLines = @{ + Enable = $true + MaximumLineLength = 120 + } + + # Module targets PS 5.1+ for MSP audience compatibility + # Dev environment runs PS 7+ but published module must work on 5.1 + PSUseCompatibleSyntax = @{ + Enable = $true + TargetVersions = @( + '5.1', + '7.2', + '7.4' + ) + } + + # PSUseCompatibleCommands is disabled because the PSSA compatibility + # profile catalog is often outdated. + # PSUseCompatibleCommands = @{ + # Enable = $true + # TargetProfiles = @() + # } + + PSProvideCommentHelp = @{ + Enable = $true + ExportedOnly = $true + BlockComment = $true + VSCodeSnippetCorrection = $false + Placement = 'before' + } + } +} diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..4b31bec --- /dev/null +++ b/.editorconfig @@ -0,0 +1,48 @@ +# EditorConfig is awesome: https://EditorConfig.org + +# Top-most EditorConfig file +root = true + +# Default settings for all files +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 4 + +# Markdown files +[*.md] +trim_trailing_whitespace = false # Markdown uses trailing spaces for line breaks +max_line_length = off + +# YAML files (GitHub workflows, config files) +[*.{yml,yaml}] +indent_size = 2 + +# JSON files +[*.json] +indent_size = 2 + +# XML files (MAML help, config) +[*.xml] +indent_size = 2 + +# PowerShell files +[*.{ps1,psm1,psd1}] +charset = utf-8-bom # PowerShell prefers BOM for UTF-8 +indent_size = 4 +end_of_line = crlf # Windows line endings for PowerShell + +# Batch files (Windows) +[*.{bat,cmd}] +end_of_line = crlf + +# Documentation files +[*.{txt,rst}] +max_line_length = off + +# License and changelog files +[{LICENSE,CHANGELOG,CONTRIBUTING,CODE_OF_CONDUCT,SECURITY}] +max_line_length = off diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..19e0f9b --- /dev/null +++ b/.gitattributes @@ -0,0 +1,94 @@ +# Git Attributes Configuration +# https://git-scm.com/docs/gitattributes + +# Set default behavior to automatically normalize line endings +* text=auto + +############################### +# Text Files (Auto-normalize) # +############################### + +# PowerShell +*.ps1 text eol=crlf diff=powershell +*.psm1 text eol=crlf diff=powershell +*.psd1 text eol=crlf +*.ps1xml text eol=crlf +*.pssc text eol=crlf +*.psrc text eol=crlf +*.cdxml text eol=crlf + +# Scripts +*.bash text eol=lf +*.sh text eol=lf +*.bat text eol=crlf +*.cmd text eol=crlf + +# Documentation +*.md text diff=markdown +*.txt text + +# Config files +*.json text +*.yaml text +*.yml text +*.xml text +.editorconfig text +.gitattributes text +.gitconfig text +.gitignore text + +# Special files +AUTHORS text +CHANGELOG text +CONTRIBUTING text +LICENSE text +README text + +############################### +# Binary Files # +############################### + +# Graphics +*.gif binary +*.ico binary +*.jpg binary +*.jpeg binary +*.png binary +*.webp binary +*.svg text + +# Archives +*.7z binary +*.gz binary +*.tar binary +*.zip binary + +# Executables +*.exe binary +*.dll binary + +#################### +# Merge Strategies # +#################### + +# For changelog files, prefer union merge +CHANGELOG* merge=union + +#################### +# Linguist # +#################### + +# Documentation +Docs/** linguist-documentation +*.md linguist-documentation + +#################### +# Export Ignore # +#################### +# Files to exclude from export archives (git archive) + +.gitattributes export-ignore +.gitignore export-ignore +.editorconfig export-ignore +.github export-ignore +Tests export-ignore diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..0473ac6 --- /dev/null +++ b/.github/CODE_OF_CONDUCT.md @@ -0,0 +1,101 @@ +# Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall community +* Using welcoming and inclusive language +* Being patient with newcomers and those learning +* Recognizing and respecting different skill levels and contributions + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, without their explicit permission +* Spamming, excessive self-promotion, or off-topic posts +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. + +This includes: + +- GitHub repositories (issues, pull requests, discussions, code reviews) +- Community Slack channels +- Project-related social media +- Community events and meetups +- Email communications + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at: + +- **Email:** conduct@christaylor.codes +- **Slack:** @CTaylor on [MSPGeek Slack](https://join.mspgeek.com/) +- **GitHub:** Open a confidential issue via the Security Advisory feature + +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact:** Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. + +**Consequence:** A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact:** A violation through a single incident or series of actions. + +**Consequence:** A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. + +### 3. Temporary Ban + +**Community Impact:** A serious violation of community standards, including sustained inappropriate behavior. + +**Consequence:** A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact:** Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. + +**Consequence:** A permanent ban from any sort of public interaction within the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md new file mode 100644 index 0000000..507d304 --- /dev/null +++ b/.github/CONTRIBUTING.md @@ -0,0 +1,130 @@ +# Contributing to ConnectWiseControlAPI + +:+1::tada: First off, thanks for taking the time to contribute! :tada::+1: + +The following is a set of guidelines for contributing. These are mostly guidelines, not rules. Use your best judgment, and feel free to propose changes to this document, or anything else in a pull request. + +## Table Of Contents + +[I don't want to read this whole thing, I just have a question!!!](#i-don't-want-to-read-this-whole-thing-i-just-have-a-question) + +[How Can I Contribute?](#how-can-i-contribute) + +- [Reporting Bugs](#reporting-bugs) +- [Suggesting Enhancements](#suggesting-enhancements) +- [Your First Code Contribution](#your-first-code-contribution) +- [Pull Requests](#pull-requests) + +[AI Contributors](#ai-contributors) + +[Styleguides](#styleguides) + +- [Git Commit Messages](#git-commit-messages) +- [Powershell Styleguide](#powershell-styleguide) +- [Documentation Styleguide](#documentation-styleguide) + +## I don't want to read this whole thing I just have a question + +> **Note:** *Please don't file an issue to ask a question.* You'll get faster results by using the resources below. + +Join a community Slack team: + +- [Join the MSPGeek Slack Team](https://join.mspgeek.com/) +- [Join the PowerShell Slack Team](https://powershell.slack.com/join/shared_invite/zt-eodd93as-RHYl6s~9XH8FNyE09M7zmA#/) + + - Even though Slack is a chat service, sometimes it takes several hours for community members to respond — please be patient! + - Use a channel that looks appropriate for general questions or discussion + - There are many other channels available, check the channel list + - Send me a DM if you want, @CTaylor + +## How Can I Contribute + +### Reporting Bugs + +This section guides you through submitting a bug report. Following these guidelines helps maintainers and the community understand your report :pencil:, reproduce the behavior :computer: :computer:, and find related reports :mag_right:. + +Before creating bug reports, please check existing issues as you might find out that you don't need to create one. When you are creating a bug report, please include as many details as possible. Fill out template, the information it asks for helps us resolve issues faster. + +> **Note:** If you find a **Closed** issue that seems like it is the same thing that you're experiencing, open a new issue and include a link to the original issue in the body of your new one. + +#### Before Submitting A Bug Report + +- **Check the Wiki.** You might be able to find the cause of the problem and fix things yourself. +- **Check the [MSPGeek Slack Team](https://join.mspgeek.com/)** for help from the community. + +#### How Do I Submit A (Good) Bug Report + +Bugs are tracked as [GitHub issues](https://guides.github.com/features/issues/). After you've determined which repository your bug is related to, create an issue on that repository and provide the following information by filling in the template. + +Explain the problem and include additional details to help maintainers reproduce the problem: + +- **Use a clear and descriptive title** for the issue to identify the problem. +- **Describe the exact steps which reproduce the problem** in as many details as possible. +- **Provide specific examples to demonstrate the steps**. Include links to files or GitHub projects, or copy/pasteable snippets, which you use in those examples. If you're providing snippets in the issue, use [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines). +- **Describe the behavior you observed after following the steps** and point out what exactly is the problem with that behavior. +- **Explain which behavior you expected to see instead and why.** + +Provide more context by answering these questions: + +- **Did the problem start happening recently** (e.g. after updating to a new version) or was this always a problem? +- **Can you reliably reproduce the issue?** If not, provide details about how often the problem happens and under which conditions it normally happens. + +### Suggesting Enhancements + +This section guides you through submitting an enhancement suggestion, including completely new features and minor improvements to existing functionality. Following these guidelines helps maintainers and the community understand your suggestion :pencil: and find related suggestions :mag_right:. + +Before creating enhancement suggestions, please check existing suggestions as you might find out that you don't need to create one. When you are creating an enhancement suggestion, please include as many details as possible. Fill in the template, including the steps that you imagine you would take if the feature you're requesting existed. + +#### How Do I Submit A (Good) Enhancement Suggestion + +Enhancement suggestions are tracked as [GitHub issues](https://guides.github.com/features/issues/). Create an issue and provide the following information: + +- **Use a clear and descriptive title** for the issue to identify the suggestion. +- **Provide a step-by-step description of the suggested enhancement** in as many details as possible. +- **Provide specific examples to demonstrate the steps**. Include copy/pasteable snippets which you use in those examples, as [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines). +- **Describe the current behavior** and **explain which behavior you expected to see instead** and why. +- **Explain why this enhancement would be useful** to most users and isn't something that can or should be implemented as a [community package](<>). +- **List some other text examples where this enhancement exists.** +- **Specify which version of the module you're using.** +- **Specify the name and version of the OS you're using.** + +## AI Contributors + +This project welcomes contributions from AI coding agents. AI agents follow the same quality standards as human contributors. See [CLAUDE.md](../CLAUDE.md) for development instructions and conventions. + +## Styleguides + +### Git Commit Messages + +- Use the present tense ("Add feature" not "Added feature") + +- Use the imperative mood ("Move cursor to..." not "Moves cursor to...") + +- Limit the first line to 72 characters or less + +- Reference issues and pull requests liberally after the first line + +- When only changing documentation, include `[ci skip]` in the commit title + +- Consider starting the commit message with an applicable emoji: + - :art: `:art:` when improving the format/structure of the code + - :racehorse: `:racehorse:` when improving performance + - :non-potable_water: `:non-potable_water:` when plugging memory leaks + - :memo: `:memo:` when writing docs + - :checkered_flag: `:checkered_flag:` when fixing something on Windows + - :bug: `:bug:` when fixing a bug + - :fire: `:fire:` when removing code or files + - :green_heart: `:green_heart:` when fixing the CI build + - :white_check_mark: `:white_check_mark:` when adding tests + - :lock: `:lock:` when dealing with security + - :arrow_up: `:arrow_up:` when upgrading dependencies + - :arrow_down: `:arrow_down:` when downgrading dependencies + - :shirt: `:shirt:` when removing linter warnings + +### PowerShell Styleguide + +- Refer to the [unofficial guide](https://github.com/PoshCode/PowerShellPracticeAndStyle). + +### Documentation Styleguide + +- Documentation is built with [platyPS](https://github.com/PowerShell/platyPS). diff --git a/.github/ISSUE_TEMPLATE/ai_task.md b/.github/ISSUE_TEMPLATE/ai_task.md new file mode 100644 index 0000000..546db32 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/ai_task.md @@ -0,0 +1,58 @@ +--- +name: AI Task +about: Create a structured task for AI coding agents +title: '[AI] ' +labels: 'ai-task, ai-ready' +assignees: '' +--- + +## Objective + + + +## Context + + + + +## Requirements + + + +- [ ] +- [ ] +- [ ] + +## Acceptance Criteria + + + +- [ ] All existing tests pass (`Invoke-Pester`) +- [ ] PSScriptAnalyzer reports zero errors +- [ ] New/changed functionality has test coverage +- [ ] + +## Files to Modify + + + + +- +- + +## Out of Scope + + + +- + +## Technical Notes + + + + +## Related Issues + + + +- Related to # diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..e8e2d6d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,54 @@ +--- +name: Bug Report +about: Create a report to help us improve +title: '[BUG] ' +labels: 'bug' +assignees: '' +--- + +## Bug Description + + + +## Steps to Reproduce + + + +1. +2. +3. +4. + +## Expected Behavior + + + +## Actual Behavior + + + +## Screenshots + + + +## Environment + + + +- **OS**: [e.g., Windows 11, Windows Server 2022] +- **Module Version**: [e.g., 0.3.5.0] +- **PowerShell Version**: [e.g., 5.1, 7.4.0] +- **Control Server Version**: [e.g., 24.1] + +## Additional Context + + + +## Possible Solution + + + +## Checklist + +- [ ] I have searched existing issues to ensure this is not a duplicate +- [ ] I have tested with the latest version diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..1e97046 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,11 @@ +blank_issues_enabled: true +contact_links: + - name: Community Support + url: https://join.mspgeek.com/ + about: Ask questions and discuss with the MSPGeek community on Slack + - name: Documentation + url: https://github.com/christaylorcodes/ConnectWiseControlAPI/blob/master/README.md + about: Check out our documentation + - name: Contributing Guide + url: https://github.com/christaylorcodes/ConnectWiseControlAPI/blob/master/.github/CONTRIBUTING.md + about: Learn how to contribute to this project diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..21426fd --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,52 @@ +--- +name: Feature Request +about: Suggest an idea for this project +title: '[FEATURE] ' +labels: 'enhancement' +assignees: '' +--- + +## Feature Description + + + +## Problem Statement + + + + +## Proposed Solution + + + +## Alternative Solutions + + + +## Use Cases + + + +1. +2. +3. + +## Benefits + + + +- +- +- + +## Additional Context + + + +## Would you be willing to contribute this feature? + + + +- [ ] Yes, I'd like to contribute +- [ ] No, but I'm happy to help test +- [ ] No, but I can provide more details diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..96a9045 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,50 @@ +# Pull Request + +## Description + + + +## Related Issue + + + +## Type of Change + +- [ ] Bug fix +- [ ] New feature +- [ ] Breaking change +- [ ] Documentation +- [ ] Refactoring / tests + +## Changes Made + + + +- +- + +## Testing + + + +- [ ] `Invoke-Pester` passes +- [ ] Tested against a live Control server (if applicable) + +## Checklist + +- [ ] Code follows project conventions ([CLAUDE.md](../CLAUDE.md)) +- [ ] Tests cover new/changed behavior +- [ ] PSScriptAnalyzer reports zero errors +- [ ] CHANGELOG.md updated (if applicable) +- [ ] Documentation updated (if applicable) +- [ ] Function added to `FunctionsToExport` in `.psd1` (if new public function) + +## Screenshots + + + +## AI Contribution + + + +- [ ] AI-assisted (tool: ___, issue: #___) diff --git a/.github/SECURITY.md b/.github/SECURITY.md new file mode 100644 index 0000000..5136b9e --- /dev/null +++ b/.github/SECURITY.md @@ -0,0 +1,98 @@ +# Security Policy + +## Supported Versions + +We actively support the following versions of this project with security updates: + +| Version | Supported | +| ------- | ------------------ | +| Latest | :white_check_mark: | +| < 1.0 | :x: | + +## Reporting a Vulnerability + +We take the security of ConnectWiseControlAPI seriously. If you believe you have found a security vulnerability, please report it to us as described below. + +### Where to Report + +**Please do NOT report security vulnerabilities through public GitHub issues.** + +Instead, please report them via one of the following methods: + +1. **GitHub Security Advisories** (Preferred) + - Navigate to the repository's Security tab + - Click "Report a vulnerability" + - Fill out the security advisory form with details + +2. **Direct Email** + - Send an email to: **security@christaylor.codes** + - Use the subject line: `[SECURITY] ConnectWiseControlAPI - Brief Description` + +3. **Private Message on Slack** + - Contact **@CTaylor** on [MSPGeek Slack](https://join.mspgeek.com/) + - Clearly mark the message as security-related + +### What to Include + +Please include the following information in your report to help us better understand and resolve the issue: + +- **Type of issue** (e.g., credential exposure, injection, privilege escalation) +- **Full paths of source file(s)** related to the manifestation of the issue +- **Location of the affected source code** (tag/branch/commit or direct URL) +- **Step-by-step instructions to reproduce the issue** +- **Proof-of-concept or exploit code** (if possible) +- **Impact of the issue**, including how an attacker might exploit it +- **Your assessment of severity** (Critical, High, Medium, Low) + +### What to Expect + +After you submit a vulnerability report: + +1. **Acknowledgment** - We will acknowledge receipt of your vulnerability report within **48 hours** +2. **Initial Assessment** - We will provide an initial assessment of the vulnerability within **5 business days** +3. **Updates** - We will keep you informed of the progress toward a fix and full announcement +4. **Verification** - We may ask you to verify that our fix resolves the vulnerability +5. **Public Disclosure** - We will coordinate with you on the timing of public disclosure +6. **Credit** - We will credit you in the security advisory (unless you prefer to remain anonymous) + +### Severity Levels + +We use the [CVSS v3.1](https://www.first.org/cvss/calculator/3.1) scoring system to assess vulnerability severity: + +- **Critical (9.0-10.0)** - Fix within 24-48 hours +- **High (7.0-8.9)** - Fix within 1 week +- **Medium (4.0-6.9)** - Fix within 2-4 weeks +- **Low (0.1-3.9)** - Fix in next regular release + +## Security Best Practices for Users + +When using this module, please: + +1. **Secure Your Credentials** + - Never commit API credentials or passwords to source control + - Use PowerShell `[PSCredential]` objects, not plaintext passwords + - The module requires a non-MFA account; use a complex username and password + +2. **Use HTTPS** + - The module requires your Control server to use HTTPS + - TLS 1.2 is enforced by the module + +3. **Keep Updated** + - Regularly update the module from the PowerShell Gallery + - Review the CHANGELOG for security-related fixes + +4. **PowerShell Execution Policy** + - Be cautious when using `-ExecutionPolicy Bypass` + - Prefer signed scripts in production environments + +## Security Hall of Fame + +We appreciate security researchers who responsibly disclose vulnerabilities. Contributors will be listed here (with permission): + +_No vulnerabilities reported yet._ + +## Additional Resources + +- [GitHub Security Best Practices](https://docs.github.com/en/code-security) +- [OWASP Top 10](https://owasp.org/www-project-top-ten/) +- [PowerShell Security Best Practices](https://docs.microsoft.com/en-us/powershell/scripting/security/overview) diff --git a/.gitignore b/.gitignore index f999d21..2392713 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,98 @@ -/Scratch.ps1 -.vscode \ No newline at end of file +# ============================================ +# .gitignore - ConnectWiseControlAPI +# ============================================ + +# ---- Project-Specific ---- +Scratch*.ps1 +output/ +coverage.xml +testResults.xml +nul +*-help.xml + +# ---- Operating Systems ---- + +# Windows +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +Desktop.ini +$RECYCLE.BIN/ + +# macOS +.DS_Store +.AppleDouble +.LSOverride +._* +.Spotlight-V100 +.Trashes + +# Linux +*~ +.fuse_hidden* +.nfs* + +# ---- IDEs and Editors ---- + +# VS Code +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Visual Studio +.vs/ +*.suo +*.user +*.userosscache +*.sln.docuser + +# JetBrains (Rider, IntelliJ) +.idea/ +*.iml + +# Vim +[._]*.s[a-v][a-z] +[._]*.sw[a-p] +Session.vim +Sessionx.vim +.netrwhist +tags + +# ---- PowerShell ---- +modules/ +*.dll +*.pdb + +# ---- Build Artifacts ---- +bin/ +obj/ +artifacts/ +publish/ +*.nupkg + +# ---- Security & Secrets ---- +.env +.env.* +*.pfx +*.key +*.pem +*.p12 +*credentials* +*secret* +!.github/SECURITY.md + +# ---- Claude Code ---- +.claude/settings.local.json +.claude/plan.md + +# ---- Logs & Temp ---- +*.log +logs/ +temp/ +tmp/ +*.tmp +*.bak +*.swp From feb11db48cdaee9c95090f3a00c9f58d0f1e1657 Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Tue, 10 Nov 2026 09:26:05 -0700 Subject: [PATCH 02/30] Route API calls through one request helper; fix cookies, logging and retries - Invoke-CWCServiceMethod builds the endpoint (built-in service, RESTful API Manager, or another extension), serializes arguments consistently and logs one redacted line. Replaces the hand-built request blocks in every function. - HTTP 500 retries are opt-in (-Idempotent): a 500 after the server acted could repeat a command, wake, delete or user creation. - Credentials connections keep a WebRequestSession so server cookies are sent back (they were sent as a Set-Cookie request header). Likely fix for #22. - Debug/verbose output redacts auth headers, cookies and secret-bearing bodies. - Connect-CWC validates with GetEligibleHosts (any permission, #14), matches the anti-forgery token by shape, keeps the old connection on a failed -Force, adds -ApiSecret (RESTful API Manager), and explains failed logins. - Session event types in one table, verified live; Remove-CWCSession confirms per session with ConfirmImpact High (#30 equivalent). Co-Authored-By: Claude Opus 5.5 # Conflicts: # ConnectWiseControlAPI/Public/PageService/Remove-CWCSession.ps1 --- .../ConnectWiseControlAPI.psm1 | 31 +++- .../Private/ConvertFrom-CWCEventTime.ps1 | 19 ++ .../Private/ConvertFrom-CWCSecureString.ps1 | 17 ++ .../Private/Invoke-CWCServiceMethod.ps1 | 73 ++++++++ .../Private/Invoke-CWCWebRequest.ps1 | 171 ++++++++++++------ .../Public/AuditService/Get-CWCAuditInfo.ps1 | 9 +- .../Public/AuditService/Get-CWCAuditLog.ps1 | 26 +-- .../Public/Authentication/Connect-CWC.ps1 | 164 +++++++++++++++-- .../Public/PageService/Get-CWCLastContact.ps1 | 30 +-- .../Public/PageService/Get-CWCSession.ps1 | 38 +--- .../PageService/Get-CWCSessionDetail.ps1 | 34 +++- .../Public/PageService/Invoke-CWCCommand.ps1 | 109 ++++++----- .../Public/PageService/Invoke-CWCWake.ps1 | 33 ++-- .../Public/PageService/New-CWCAccessToken.ps1 | 18 +- .../PageService/Remove-CWCHostFromSession.ps1 | 74 ++++---- .../Public/PageService/Remove-CWCSession.ps1 | 59 +++--- .../PageService/Update-CWCCustomProperty.ps1 | 18 +- .../PageService/Update-CWCSessionName.ps1 | 20 +- .../Get-CWCSecurityConfigurationInfo.ps1 | 10 +- .../Public/SecurityService/New-CWCUser.ps1 | 13 +- .../Public/SecurityService/Remove-CWCUser.ps1 | 18 +- .../Public/SecurityService/Update-CWCUser.ps1 | 22 +-- .../Get-CWCSessionGroup.ps1 | 10 +- 23 files changed, 629 insertions(+), 387 deletions(-) create mode 100644 ConnectWiseControlAPI/Private/ConvertFrom-CWCEventTime.ps1 create mode 100644 ConnectWiseControlAPI/Private/ConvertFrom-CWCSecureString.ps1 create mode 100644 ConnectWiseControlAPI/Private/Invoke-CWCServiceMethod.ps1 diff --git a/ConnectWiseControlAPI/ConnectWiseControlAPI.psm1 b/ConnectWiseControlAPI/ConnectWiseControlAPI.psm1 index 4afa76d..8c6b63e 100644 --- a/ConnectWiseControlAPI/ConnectWiseControlAPI.psm1 +++ b/ConnectWiseControlAPI/ConnectWiseControlAPI.psm1 @@ -11,12 +11,37 @@ Foreach($import in @($Public + $Private)) { } } -# Set Security Protocol -if([Net.SecurityProtocolType]::Tls) { - [Net.ServicePointManager]::SecurityProtocol=[Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls +# Set Security Protocol to TLS 1.2+ +if([Net.SecurityProtocolType]::Tls12) { + [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 } $script:InternalUserSource = 'InternalMembershipProvider' +# ScreenConnect.SessionType values (verified against ScreenConnect.Core.dll) +$script:CWCSessionType = @{ Support = 0; Meeting = 1; Access = 2 } + +# ScreenConnect.SessionEventType values used by this module (verified live from the web client's +# SC.types.SessionEventType, 2026-11-10) +$script:CWCSessionEventType = @{ + Connected = 10 + Disconnected = 11 + DeletedSession = 21 + AddedNote = 32 + QueuedWake = 43 + QueuedCommand = 44 + QueuedMessage = 45 + QueuedTool = 47 + QueuedForceDisconnect = 48 + RanCommand = 70 + QueuedUninstallAndDelete = 100 +} + +# Remote Workforce extension ID (App_Extensions//Service.ashx) +$script:CWCRemoteWorkforceExtensionID = '2c4f522f-b39a-413a-8807-dc52a2fce13e' + +# RESTful API Manager extension ID, used by Connect-CWC -ApiSecret +$script:CWCRestApiExtensionID = '2d558935-686a-4bd0-9991-07539f5fe749' + # Export Public functions ($Public.BaseName) for WIP modules Export-ModuleMember -Function $Public.Basename \ No newline at end of file diff --git a/ConnectWiseControlAPI/Private/ConvertFrom-CWCEventTime.ps1 b/ConnectWiseControlAPI/Private/ConvertFrom-CWCEventTime.ps1 new file mode 100644 index 0000000..cd357ac --- /dev/null +++ b/ConnectWiseControlAPI/Private/ConvertFrom-CWCEventTime.ps1 @@ -0,0 +1,19 @@ +function ConvertFrom-CWCEventTime { + <# + .SYNOPSIS + Converts a PageService session event's Time to an absolute UTC DateTime. + + .DESCRIPTION + PageService.GetSessionDetails reports each event's Time as the milliseconds elapsed before the + response (not an epoch). Converting to an absolute time lets callers compare events across + separate polls. + #> + [CmdletBinding()] + [OutputType([datetime])] + param( + [Parameter(Mandatory = $True)] + $SessionEvent + ) + + [DateTime]::UtcNow.AddMilliseconds(-[double]$SessionEvent.Time) +} diff --git a/ConnectWiseControlAPI/Private/ConvertFrom-CWCSecureString.ps1 b/ConnectWiseControlAPI/Private/ConvertFrom-CWCSecureString.ps1 new file mode 100644 index 0000000..1f0a8bb --- /dev/null +++ b/ConnectWiseControlAPI/Private/ConvertFrom-CWCSecureString.ps1 @@ -0,0 +1,17 @@ +function ConvertFrom-CWCSecureString { + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory = $True)] + [securestring]$SecureString + ) + + # Convert to plain text for API request bodies, zeroing the unmanaged copy afterwards + $bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString) + try { + [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr) + } + finally { + [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr) + } +} diff --git a/ConnectWiseControlAPI/Private/Invoke-CWCServiceMethod.ps1 b/ConnectWiseControlAPI/Private/Invoke-CWCServiceMethod.ps1 new file mode 100644 index 0000000..af7c1ea --- /dev/null +++ b/ConnectWiseControlAPI/Private/Invoke-CWCServiceMethod.ps1 @@ -0,0 +1,73 @@ +function Invoke-CWCServiceMethod { + <# + .SYNOPSIS + Calls one Control web service method. Every public function's API call goes through here. + + .DESCRIPTION + Builds the endpoint, serializes the method arguments as a JSON array and passes the request to + Invoke-CWCWebRequest (transport: auth headers, cookies, retry, error handling). + + -Service built-in service: Services/.ashx/ (credentials connections) + -RestApi RESTful API Manager: App_Extensions//Service.ashx/ (API secret connections) + -ExtensionID any other extension: App_Extensions//Service.ashx/ (credentials connections) + + .PARAMETER Arguments + The server method's arguments, in order. Omit for methods without arguments (no body is sent). + + .PARAMETER Idempotent + The call is safe to repeat (reads, "set to value" updates). Only idempotent calls are retried on + HTTP 500: a 500 after the server acted would otherwise repeat the action (a second command, note, + wake or delete). + + .PARAMETER Sensitive + The arguments contain a secret (password). The body is left out of verbose and debug output. + #> + [CmdletBinding(DefaultParameterSetName = 'Service')] + param( + [Parameter(Mandatory = $True, ParameterSetName = 'Service')] + [ValidateSet('PageService', 'SecurityService', 'AuditService', 'SessionGroupService')] + [string]$Service, + + [Parameter(Mandatory = $True, ParameterSetName = 'RestApi')] + [switch]$RestApi, + + [Parameter(Mandatory = $True, ParameterSetName = 'Extension')] + [guid]$ExtensionID, + + [Parameter(Mandatory = $True)] + [ValidateNotNullOrEmpty()] + [string]$Method, + + [object[]]$Arguments, + + [switch]$Idempotent, + + [switch]$Sensitive + ) + + switch ($PSCmdlet.ParameterSetName) { + 'Service' { $Endpoint = "Services/$Service.ashx/$Method" } + 'RestApi' { $Endpoint = "App_Extensions/$($script:CWCRestApiExtensionID)/Service.ashx/$Method" } + 'Extension' { $Endpoint = "App_Extensions/$ExtensionID/Service.ashx/$Method" } + } + + $WebRequestArguments = @{ + Endpoint = $Endpoint + Method = 'Post' + } + + if ($PSBoundParameters.ContainsKey('Arguments')) { + # -InputObject keeps a one-element list as a JSON array; -Depth keeps nested event entries intact. + # PS 5.1 serializes an empty array as an empty string, so send '[]' explicitly. + if (@($Arguments).Count -eq 0) { $WebRequestArguments.Body = '[]' } + else { $WebRequestArguments.Body = ConvertTo-Json -InputObject @($Arguments) -Depth 10 } + } + + if ($Sensitive) { Write-Verbose "POST $Endpoint (arguments redacted)" } + else { Write-Verbose "POST $Endpoint $($WebRequestArguments.Body)" } + + $MaxRetry = 0 + if ($Idempotent) { $MaxRetry = 5 } + + Invoke-CWCWebRequest -Arguments $WebRequestArguments -MaxRetry $MaxRetry -SensitiveBody:$Sensitive +} diff --git a/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 b/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 index 22a2675..2f213a4 100644 --- a/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 +++ b/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 @@ -2,7 +2,11 @@ [CmdletBinding()] param( $Arguments, - [int]$MaxRetry = 5 + # Retries on HTTP 500. Off by default: only the caller knows whether a request is safe to repeat + # (Invoke-CWCServiceMethod -Idempotent). + [int]$MaxRetry = 0, + # Body holds a secret: keep it out of debug output. + [switch]$SensitiveBody ) # Check that we have cached connection info @@ -14,81 +18,130 @@ return Write-Error ($ErrorMessage | Out-String) } + # The two auth methods reach different endpoints: an API secret is only accepted by the + # RESTful API Manager extension, and that extension ignores Basic auth sessions. + $IsApiSecretConnection = Test-CWCApiSecretConnection + $IsRestApiEndpoint = $Arguments.Endpoint -like "App_Extensions/$($script:CWCRestApiExtensionID)/*" + if ($IsApiSecretConnection -ne $IsRestApiEndpoint) { + # Name the public function the user called, not the private request helpers. + $Caller = Get-PSCallStack | Select-Object -Skip 1 -ExpandProperty Command | + Where-Object { $_ -notin 'Invoke-CWCServiceMethod', 'Invoke-CWCWebRequest' } | Select-Object -First 1 + if (-not $Caller -or $Caller -eq '') { $Caller = 'This command' } + if ($IsApiSecretConnection) { + return Write-Error "$Caller is not available when connected with -ApiSecret (RESTful API Manager). Connect with 'Connect-CWC -Credentials' to use it." + } + return Write-Error "$Caller requires the RESTful API Manager extension. Connect with 'Connect-CWC -ApiSecret' to use it." + } + $BaseURI = "https://$($script:CWCServerConnection.Server)" $Arguments.URI = Join-Url $BaseURI $Arguments.Endpoint $Arguments.remove('Endpoint') - $Arguments.Headers = $script:CWCServerConnection.Headers $Arguments.UseBasicParsing = $true - Write-Debug "Arguments: $($Arguments | ConvertTo-Json)" - # Issue request - try { $Result = Invoke-WebRequest @Arguments } - catch { - # Start error message - $ErrorMessage = @() + # Copy so per-request headers (the API secret) never persist in the connection state + $Headers = @{} + $script:CWCServerConnection.Headers + if ($IsApiSecretConnection) { + $Headers.CTRLAuthHeader = ConvertFrom-CWCSecureString $script:CWCServerConnection.ApiSecret + } + $Arguments.Headers = $Headers - if ($_.Exception.Response -and $PSVersionTable.PSVersion.Major -lt 6) { - # Read exception response - $ErrorStream = $_.Exception.Response.GetResponseStream() - $Reader = New-Object System.IO.StreamReader($ErrorStream) - $script:ErrBody = $Reader.ReadToEnd() | ConvertFrom-Json + # Credentials connections send back the cookies the server set (via the WebRequestSession from + # Connect-CWC); Invoke-WebRequest stores new Set-Cookie values in it automatically. + # API-secret connections are stateless and never carry cookies. + if (-not $IsApiSecretConnection -and $script:CWCServerConnection.WebSession) { + $Arguments.WebSession = $script:CWCServerConnection.WebSession + } - if ($ErrBody.code) { - $ErrorMessage += 'An exception has been thrown.' - $ErrorMessage += "--> $($ErrBody.code)" - if ($ErrBody.code -eq 'Unauthorized') { - $ErrorMessage += "-----> $($ErrBody.message)" - $ErrorMessage += "-----> Use 'Disconnect-CWC' or 'Connect-CWC -Force' to set new authentication." - } - else { - $ErrorMessage += "-----> $($ErrBody.code): $($ErrBody.message)" - $ErrorMessage += '-----> ^ Error has not been documented please report. ^' + # Only build the redacted copy when debug output is on: this runs on every request. + if ($DebugPreference -ne 'SilentlyContinue') { + $RedactedHeaderNames = @('authorization', 'ctrlauthheader', 'x-anti-forgery-token', 'cookie', 'set-cookie') + $DebugArguments = @{} + $Arguments + if ($DebugArguments.WebSession) { $DebugArguments.WebSession = '' } + if ($SensitiveBody -and $DebugArguments.Body) { $DebugArguments.Body = '' } + $DebugArguments.Headers = @{} + foreach ($HeaderName in $Headers.Keys) { + $DebugArguments.Headers[$HeaderName] = if ($RedactedHeaderNames -contains $HeaderName.ToLower()) { '' } else { $Headers[$HeaderName] } + } + Write-Debug "Arguments: $($DebugArguments | ConvertTo-Json)" + } + + # Issue request with retry on HTTP 500 + $Retry = 0 + while ($true) { + try { + $Result = Invoke-WebRequest @Arguments + break + } + catch { + # PS 6+ puts the HttpRequestMessage (with auth headers) on the error record, which stays in + # $Error. Strip the secrets from it. + # Type-name check: a [System.Net.Http.HttpRequestMessage] literal fails on PS 5.1 when the assembly isn't loaded. + if ($_.TargetObject -and $_.TargetObject.GetType().FullName -eq 'System.Net.Http.HttpRequestMessage') { + foreach ($SecretHeader in 'Authorization', 'CTRLAuthHeader', 'x-anti-forgery-token') { + $null = $_.TargetObject.Headers.Remove($SecretHeader) } } - elseif ($_.Exception.message) { - $ErrorMessage += 'An exception has been thrown.' - $ErrorMessage += "--> $($_.Exception.message)" - } - } - if ($_.ErrorDetails) { - $ErrorMessage += 'An error has been thrown.' - $script:ErrDetails = $_.ErrorDetails - $ErrorMessage += "--> $($ErrDetails.code)" - $ErrorMessage += "--> $($ErrDetails.message)" - if ($ErrDetails.errors.message) { - $ErrorMessage += "-----> $($ErrDetails.errors.message)" + # Retry on HTTP 500 (no response yields 0) + $StatusCode = [int]$_.Exception.Response.StatusCode + if ($StatusCode -eq 500) { + if ($Retry -ge $MaxRetry) { + return Write-Error "Max retries hit. Status: 500" + } + $Retry++ + # ConnectWise Manage recommended wait time + $Wait = [math]::pow(2, $Retry) + Write-Warning "Issue with request, status: 500" + Write-Warning "$($Retry)/$($MaxRetry) retries, waiting $($Wait)ms." + Start-Sleep -Milliseconds $Wait + continue } - } - if ($ErrorMessage.Length -lt 1) { $ErrorMessage = $_ } - else { $ErrorMessage += $_.ScriptStackTrace } + # Build error message for non-retryable errors + $ErrorMessage = @() - return Write-Error ($ErrorMessage | Out-String) - } + if ($_.Exception.Response -and $PSVersionTable.PSVersion.Major -lt 6) { + $ErrorStream = $_.Exception.Response.GetResponseStream() + $Reader = New-Object System.IO.StreamReader($ErrorStream) + # Error bodies are not always JSON (IIS 401/404 pages); don't let the parse mask the status. + $ErrBody = $null + try { $ErrBody = $Reader.ReadToEnd() | ConvertFrom-Json } catch { $ErrBody = $null } - # Not sure this will be hit with current iwr error handling - # May need to move to catch block need to find test - # TODO Find test for retry - # Retry the request - $Retry = 0 - while ($Retry -lt $MaxRetry -and $Result.StatusCode -eq 500) { - $Retry++ - # ConnectWise Manage recommended wait time - $Wait = $([math]::pow( 2, $Retry)) - Write-Warning "Issue with request, status: $($Result.StatusCode) $($Result.StatusDescription)" - Write-Warning "$($Retry)/$($MaxRetry) retries, waiting $($Wait)ms." - Start-Sleep -Milliseconds $Wait - $Result = Invoke-WebRequest @Arguments -UseBasicParsing - } - if ($Retry -ge $MaxRetry) { - return Write-Error "Max retries hit. Status: $($Result.StatusCode) $($Result.StatusDescription)" - } + if ($ErrBody.code) { + $ErrorMessage += 'An exception has been thrown.' + $ErrorMessage += "--> $($ErrBody.code)" + if ($ErrBody.code -eq 'Unauthorized') { + $ErrorMessage += "-----> $($ErrBody.message)" + $ErrorMessage += "-----> Use 'Disconnect-CWC' or 'Connect-CWC -Force' to set new authentication." + } + else { + $ErrorMessage += "-----> $($ErrBody.code): $($ErrBody.message)" + $ErrorMessage += '-----> ^ Error has not been documented please report. ^' + } + } + elseif ($_.Exception.message) { + $ErrorMessage += 'An exception has been thrown.' + $ErrorMessage += "--> $($_.Exception.message)" + } + } - if ($script:CWCServerConnection -and $script:CWCServerConnection.Headers) { - $script:CWCServerConnection.Headers.'Set-Cookie' = $Result.Headers['Set-Cookie'] + if ($_.ErrorDetails) { + $ErrorMessage += 'An error has been thrown.' + $ErrorMessage += "--> $($_.ErrorDetails.code)" + $ErrorMessage += "--> $($_.ErrorDetails.message)" + if ($_.ErrorDetails.errors.message) { + $ErrorMessage += "-----> $($_.ErrorDetails.errors.message)" + } + } + + if ($ErrorMessage.Length -lt 1) { $ErrorMessage = $_ } + else { $ErrorMessage += $_.ScriptStackTrace } + + return Write-Error ($ErrorMessage | Out-String) + } } + # OutFile: the response body was saved to disk (used by WIP/Invoke-CWCSession) if ($Arguments.OutFile) { return $Result } diff --git a/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditInfo.ps1 b/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditInfo.ps1 index c1fa36e..1fd4a2d 100644 --- a/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditInfo.ps1 +++ b/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditInfo.ps1 @@ -2,12 +2,5 @@ function Get-CWCAuditInfo { [CmdletBinding()] param () - $Endpoint = 'Services/AuditService.ashx/GetAuditInfo' - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Method = 'Post' - } - - Invoke-CWCWebRequest -Arguments $WebRequestArguments + Invoke-CWCServiceMethod -Service AuditService -Method GetAuditInfo -Idempotent } diff --git a/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditLog.ps1 b/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditLog.ps1 index 26275b2..cfc8028 100644 --- a/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditLog.ps1 +++ b/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditLog.ps1 @@ -1,31 +1,25 @@ function Get-CWCAuditLog { [CmdletBinding()] param ( - [datetime]$StartDate, - [datetime]$EndDate, + [datetime]$StartDate = (Get-Date).AddDays(-1), + [datetime]$EndDate = (Get-Date), [string]$SessionName, + # Deprecated: QueryAuditLog no longer accepts this argument. Kept so existing scripts don't break. [switch]$IncludeSessionCaptures, [int[]]$EventTypes, [int[]]$SecurityTypes ) - $Endpoint = 'Services/AuditService.ashx/QueryAuditLog' + if ($IncludeSessionCaptures) { + Write-Warning '-IncludeSessionCaptures is no longer supported by the Control server and is ignored.' + } - $Body = ConvertTo-Json @( - $(Get-Date $StartDate -Format 'yyyy-MM-ddTHH:mm:ss.ffffZ'), - $(Get-Date $EndDate -Format 'yyyy-MM-ddTHH:mm:ss.ffffZ'), + # Server signature: QueryAuditLog(minTime, maxTime, sessionName, sessionEventTypes[], securityEventTypes[]) + Invoke-CWCServiceMethod -Service AuditService -Method QueryAuditLog -Idempotent -Arguments @( + $StartDate.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ'), + $EndDate.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ'), $SessionName, - $IncludeSessionCaptures.IsPresent $EventTypes, $SecurityTypes ) - Write-Verbose $Body - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - - Invoke-CWCWebRequest -Arguments $WebRequestArguments } diff --git a/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 b/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 index a26b501..5b14853 100644 --- a/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 +++ b/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 @@ -1,19 +1,134 @@ function Connect-CWC { - [CmdletBinding()] + <# + .SYNOPSIS + Connects to a ConnectWise Control server. + + .DESCRIPTION + Two authentication methods are supported: + + -Credentials (default): Basic auth with a Control user account that does not use MFA. Gives + access to every function in the module, limited by that user's permissions. + + -ApiSecret: the authentication secret configured in the RESTful API Manager extension's + RESTfulAuthenticationSecret setting, sent as the CTRLAuthHeader header. Works when every user + account requires MFA. Only functions backed by that extension are available (see NOTES); other + functions return an error telling you to connect with -Credentials. + + The connection is validated before it is cached. Without -Force an existing connection is reused. + + .PARAMETER Server + Control server hostname, e.g. control.example.com. A leading http(s):// is removed. HTTPS is always used. + + .PARAMETER Credentials + Credentials for a Control user account without MFA. + + .PARAMETER ApiSecret + The RESTful API Manager extension's RESTfulAuthenticationSecret value. + + .PARAMETER Origin + Origin header sent with -ApiSecret requests. Defaults to https://. Set it to match the + extension's RESTfulAllowedOrigin setting if that setting is configured. + + .PARAMETER Force + Replace an existing cached connection. If the new connection fails validation, the previous + connection is kept. + + .EXAMPLE + Connect-CWC -Server 'control.example.com' -Credentials (Get-Credential) + + .EXAMPLE + $Secret = Read-Host -AsSecureString -Prompt 'RESTful API secret' + Connect-CWC -Server 'control.example.com' -ApiSecret $Secret + + .NOTES + Functions available with -ApiSecret: Get-CWCSessionDetail, Update-CWCSessionName, + Invoke-CWCCommand (queues the command; output is not retrieved), Find-CWCSession, + New-CWCSession, Add-CWCSessionNote, Send-CWCSessionMessage, Send-CWCToolboxItem. + Only calls that are safe to repeat (reads, "set to value" updates) are retried on HTTP 500. + + The API secret is not tied to a Control user: the extension does not apply role permissions or + session group scoping, so it can act on every session. Treat it like an administrator password. + Requires the RESTful API Manager extension (2d558935-686a-4bd0-9991-07539f5fe749). + + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> + [CmdletBinding(DefaultParameterSetName = 'Credentials')] param( - [Parameter(Mandatory=$true)] - [string]$Server, [Parameter(Mandatory = $True)] + [ValidateNotNullOrEmpty()] + [string]$Server, + + [Parameter(Mandatory = $True, ParameterSetName = 'Credentials')] [pscredential]$Credentials, + + [Parameter(Mandatory = $True, ParameterSetName = 'ApiSecret')] + [securestring]$ApiSecret, + + [Parameter(ParameterSetName = 'ApiSecret')] + [ValidateNotNullOrEmpty()] + [string]$Origin, + [switch]$Force ) + $Server = $Server -replace("http.*:\/\/",'') + $RequestedAuthType = $PSCmdlet.ParameterSetName + if ($script:CWCServerConnection -and !$Force) { - Write-Verbose "Using cached Authentication information." + $Cached = $script:CWCServerConnection + $CachedAuthType = if ($Cached.AuthType) { $Cached.AuthType } else { 'Credentials' } + if ($Cached.Server -ne $Server -or $CachedAuthType -ne $RequestedAuthType) { + Write-Warning "Already connected to '$($Cached.Server)' with $CachedAuthType. Keeping that connection; use -Force to connect to '$Server' with $RequestedAuthType." + } + else { + Write-Verbose "Using cached Authentication information." + } + return + } + + # Kept so a failed -Force reconnect leaves the previous working connection in place + $PreviousConnection = $script:CWCServerConnection + + if ($RequestedAuthType -eq 'ApiSecret') { + if ($ApiSecret.Length -eq 0) { + throw 'ApiSecret cannot be empty.' + } + if (-not $Origin) { $Origin = "https://$Server" } + + # Own copy, so the caller disposing their SecureString doesn't break later requests + $StoredSecret = $ApiSecret.Copy() + $StoredSecret.MakeReadOnly() + + # No Basic auth, anti-forgery token or cookies: the extension only checks CTRLAuthHeader, + # which Invoke-CWCWebRequest adds per request from the stored SecureString. + $script:CWCServerConnection = @{ + Server = $Server + AuthType = 'ApiSecret' + ApiSecret = $StoredSecret + Headers = @{ + 'content-type' = "application/json; charset=utf-8" + 'origin' = $Origin + } + } + + try { + # Lookup of an all-zero session ID: returns an empty list when the secret is valid. + $null = Invoke-CWCServiceMethod -RestApi -Method GetSessionBySessionID -Arguments ([guid]::Empty.ToString()) -Idempotent -ErrorAction Stop + Write-Verbose "Connected to Control server with API secret: https://$Server" + } + catch { + $script:CWCServerConnection = $PreviousConnection + Write-Verbose 'Authentication failed.' + Write-Error ("API secret authentication to 'https://$Server' failed. Check that the RESTful API Manager " + + "extension is installed, its RESTfulAuthenticationSecret matches, and RESTfulAllowedOrigin is empty " + + "or equals '$Origin' (see -Origin). $_") + } return } - $Server = $Server -replace("http.*:\/\/",'') $EncodedCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("$($Credentials.UserName):$($Credentials.GetNetworkCredential().Password)")) $Headers = @{ 'authorization' = "Basic $EncodedCredentials" @@ -21,25 +136,44 @@ function Connect-CWC { 'origin' = "https://$Server" } - $FrontPage = Invoke-WebRequest -Uri $Headers.origin -Headers $Headers -UseBasicParsing - $Regex = [Regex]'(?<=antiForgeryToken":")(.*)(?=","isUserAdministrator)' + # The WebRequestSession keeps the cookies the server sets (e.g. .ASPXAUTH) and sends them back on + # every later request, the way a browser does. The anti-forgery token is issued alongside them. + $WebSession = $null + try { + $FrontPage = Invoke-WebRequest -Uri $Headers.origin -Headers $Headers -UseBasicParsing -SessionVariable 'WebSession' + } + catch { + Write-Error "Failed to connect to Control server 'https://$Server': $_" + return + } + + # Match only a token-shaped value, so a change in the page's JSON key order can't break the + # capture (the old pattern required "isUserAdministrator" to follow) and no other page content is taken. + $Regex = [Regex]'antiForgeryToken":"([A-Za-z0-9+/=_-]{16,512})"' $Match = $Regex.Match($FrontPage.content) - if($Match.Success){ $Headers.'x-anti-forgery-token' = $Match.Value.ToString() } - else{ Write-Verbose 'Unable to find anti forgery token. Some commands may not work.' } + if ($Match.Success) { $Headers.'x-anti-forgery-token' = $Match.Groups[1].Value } + else { Write-Warning 'Unable to find the anti-forgery token on the server front page. Commands that change sessions may fail with "Invalid anti-forgery token".' } $script:CWCServerConnection = @{ - Server = $Server - Headers = $Headers + Server = $Server + AuthType = 'Credentials' + Headers = $Headers + WebSession = $WebSession } - Write-Verbose ($script:CWCServerConnection | Out-String) + Write-Verbose "Connected to Control server: https://$Server" try{ - $null = Get-CWCSessionGroup -ErrorAction Stop + # GetEligibleHosts requires any permission, so it validates auth for non-admin accounts too + # (Get-CWCSessionGroup requires ManageSessionGroups). + $null = Invoke-CWCServiceMethod -Service PageService -Method GetEligibleHosts -Idempotent -ErrorAction Stop Write-Verbose '$CWCServerConnection, variable initialized.' } catch{ - Remove-Variable CWCServerConnection -Scope script + $script:CWCServerConnection = $PreviousConnection Write-Verbose 'Authentication failed.' - Write-Error $_ + # Bad credentials are not rejected with a 401: the request runs as an anonymous user and fails + # with "Needs permission", so name the likely causes. + Write-Error ("Authentication to 'https://$Server' failed. Check the username and password, that the " + + "account does not require MFA, and that its role grants at least one permission. $_") } } diff --git a/ConnectWiseControlAPI/Public/PageService/Get-CWCLastContact.ps1 b/ConnectWiseControlAPI/Public/PageService/Get-CWCLastContact.ps1 index f3d7845..4b1ec7f 100644 --- a/ConnectWiseControlAPI/Public/PageService/Get-CWCLastContact.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Get-CWCLastContact.ps1 @@ -11,12 +11,16 @@ [string]$Group = 'All Machines' ) - # Time conversion - $origin = New-Object -Type DateTime -ArgumentList 1970, 1, 1, 0, 0, 0, 0 - $epoch = $((New-TimeSpan -Start $(Get-Date -Date '01/01/1970') -End $(Get-Date)).TotalSeconds) + # Relies on PageService's elapsed-milliseconds event times; the RESTful API Manager returns raw DateTimes. + if (Test-CWCApiSecretConnection) { + return Write-Error "Get-CWCLastContact is not available when connected with -ApiSecret (RESTful API Manager). Connect with 'Connect-CWC -Credentials' to use it." + } - try { $SessionDetails = Get-CWCSessionDetail -Group $Group -GUID $GUID } - catch { return $_ } + try { $SessionDetails = Get-CWCSessionDetail -Group $Group -GUID $GUID -Include 'Events', 'Connections' -ErrorAction Stop } + catch { + Write-Error $_ + return + } if ($SessionDetails -eq 'null' -or !$SessionDetails) { Write-Warning 'Machine not found.' @@ -30,20 +34,20 @@ # Get connection events $LatestEvent = $GuestSessionEvents | Where-Object { - $_.EventType -in (10, 11) -and + $_.EventType -in ($script:CWCSessionEventType.Connected, $script:CWCSessionEventType.Disconnected) -and $_.ConnectionID -NotIn $GuestSessionConnections.ConnectionID - } | Sort-Object time | Select-Object -First 1 - if ($LatestEvent.EventType -eq 10) { + } | Sort-Object { [double]$_.Time } | Select-Object -First 1 + if (-not $LatestEvent) { return Write-Error 'Unable to determine last contact.' } + if ($LatestEvent.EventType -eq $script:CWCSessionEventType.Connected) { # Currently connected if ($Quiet) { return $True } else { return Get-Date } } else { - # Time conversion hell :( - $TimeDiff = $epoch - ($LatestEvent.Time / 1000) - $OfflineTime = $origin.AddSeconds($TimeDiff) - $Difference = New-TimeSpan -Start $OfflineTime -End $(Get-Date) - if ($Quiet -and $Difference.TotalSeconds -lt $Seconds) { return $True } + $LastContactUtc = ConvertFrom-CWCEventTime -SessionEvent $LatestEvent + $SecondsSinceContact = ([DateTime]::UtcNow - $LastContactUtc).TotalSeconds + $OfflineTime = $LastContactUtc.ToLocalTime() + if ($Quiet -and $SecondsSinceContact -lt $Seconds) { return $True } elseif ($Quiet) { return $False } else { return $OfflineTime } } diff --git a/ConnectWiseControlAPI/Public/PageService/Get-CWCSession.ps1 b/ConnectWiseControlAPI/Public/PageService/Get-CWCSession.ps1 index 28271b4..c121693 100644 --- a/ConnectWiseControlAPI/Public/PageService/Get-CWCSession.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Get-CWCSession.ps1 @@ -10,36 +10,18 @@ function Get-CWCSession { [int]$Limit ) - $Endpoint = 'Services/PageService.ashx/GetLiveData' - - switch ($Type) { - 'Support' { $Number = 0 } - 'Meeting' { $Number = 1 } - 'Access' { $Number = 2 } - default { return Write-Error "Unknown Type, $Type" } - } - - $Body = ConvertTo-Json @( - @{ - HostSessionInfo = @{ - 'sessionType' = $Number - 'sessionGroupPathParts' = @($Group) - 'filter' = $Search - 'findSessionID' = $FindSessionID - 'sessionLimit' = $Limit - } - ActionCenterInfo = @{} + # GetLiveData(requestInfoMap, version) + $RequestInfoMap = @{ + HostSessionInfo = @{ + 'sessionType' = $script:CWCSessionType[$Type] + 'sessionGroupPathParts' = @($Group) + 'filter' = $Search + 'findSessionID' = $FindSessionID + 'sessionLimit' = $Limit } - 0 - ) -Depth 5 - Write-Verbose $Body - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' + ActionCenterInfo = @{} } - $Data = Invoke-CWCWebRequest -Arguments $WebRequestArguments + $Data = Invoke-CWCServiceMethod -Service PageService -Method GetLiveData -Arguments @($RequestInfoMap, 0) -Idempotent $Data.ResponseInfoMap.HostSessionInfo.Sessions } diff --git a/ConnectWiseControlAPI/Public/PageService/Get-CWCSessionDetail.ps1 b/ConnectWiseControlAPI/Public/PageService/Get-CWCSessionDetail.ps1 index c9bdecc..a7d389b 100644 --- a/ConnectWiseControlAPI/Public/PageService/Get-CWCSessionDetail.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Get-CWCSessionDetail.ps1 @@ -3,19 +3,35 @@ function Get-CWCSessionDetail { param ( [string]$Group = 'All Machines', [Parameter(Mandatory=$True)] - [guid]$GUID + [guid]$GUID, + # Parts of the session details to return (server SessionDetailsItems flags). Omit for everything. + # Polling callers should request only what they need: GetSessionDetails is rate limited and + # 'All' includes the guest screenshot. + [ValidateSet('SessionInfo', 'GuestScreenshotContent', 'Events', 'Connections')] + [string[]]$Include ) - $Endpoint = 'Services/PageService.ashx/GetSessionDetails' + # SessionDetailsItems flag values, read from SC.types.SessionDetailsItems in the web client. + $SessionDetailsItemFlags = @{ + SessionInfo = 1 + GuestScreenshotContent = 4 + Events = 8 + Connections = 16 + } - $Body = ConvertTo-Json @($Group,$GUID) - Write-Verbose $Body + if (Test-CWCApiSecretConnection) { + # RESTful API Manager: GetSessionDetailsBySessionID(Guid). Not scoped by group, so -Group and + # -Include are ignored. + return Invoke-CWCServiceMethod -RestApi -Method GetSessionDetailsBySessionID -Arguments $GUID.ToString() -Idempotent + } - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' + # GetSessionDetails(group, sessionID[, items]). Without items the server returns All. + $DetailArguments = @($Group, $GUID) + if ($Include) { + $Items = 0 + foreach ($Item in ($Include | Select-Object -Unique)) { $Items = $Items -bor $SessionDetailsItemFlags[$Item] } + $DetailArguments += $Items } - Invoke-CWCWebRequest -Arguments $WebRequestArguments + Invoke-CWCServiceMethod -Service PageService -Method GetSessionDetails -Arguments $DetailArguments -Idempotent } \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/PageService/Invoke-CWCCommand.ps1 b/ConnectWiseControlAPI/Public/PageService/Invoke-CWCCommand.ps1 index 08f7537..c560732 100644 --- a/ConnectWiseControlAPI/Public/PageService/Invoke-CWCCommand.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Invoke-CWCCommand.ps1 @@ -11,74 +11,71 @@ [switch]$NoWait ) - $Endpoint = 'Services/PageService.ashx/AddSessionEvents' + $QueuedCommandEventType = $script:CWCSessionEventType.QueuedCommand + $RanCommandEventType = $script:CWCSessionEventType.RanCommand - $origin = New-Object -Type DateTime -ArgumentList 1970, 1, 1, 0, 0, 0, 0 - $SessionEventType = 44 + # Format command: directives, then the command; the server expects LF line endings + $CommandLines = @() + if ($PowerShell) { $CommandLines += '#!ps' } + $CommandLines += "#timeout=$TimeOut" + $CommandLines += "#maxlength=$MaxLength" + $CommandLines += $Command + $FormattedCommand = ($CommandLines | Out-String) -replace "`r`n", "`n" - # Format command - $FormattedCommand = @() - if ($Powershell) { $FormattedCommand += '#!ps' } - $FormattedCommand += "#timeout=$TimeOut" - $FormattedCommand += "#maxlength=$MaxLength" - $FormattedCommand += $Command - $FormattedCommand = $FormattedCommand | Out-String - $CommandObject = @{ - SessionID = $GUID - EventType = $SessionEventType - Data = $FormattedCommand + # Queueing a command is not idempotent, so it is never retried + if (Test-CWCApiSecretConnection) { + # RESTful API Manager: SendCommandToSession(Guid sessionID, string command) queues the same + # QueuedCommand event. Not scoped by group, so -Group is ignored. + $null = Invoke-CWCServiceMethod -RestApi -Method SendCommandToSession -Arguments @($GUID.ToString(), $FormattedCommand) } - $Body = (ConvertTo-Json @(@($Group), @($CommandObject))).Replace('\r\n', '\n') - Write-Verbose $Body - - # Issue command - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' + else { + $CommandEvent = @{ + SessionID = $GUID + EventType = $QueuedCommandEventType + Data = $FormattedCommand + } + $null = Invoke-CWCServiceMethod -Service PageService -Method AddSessionEvents -Arguments @(@($Group), @($CommandEvent)) } - $null = Invoke-CWCWebRequest -Arguments $WebRequestArguments if ($NoWait) { return } - # Get Session - try { $SessionDetails = Get-CWCSessionDetail -Group $Group -GUID $GUID } - catch { return $_ } - - #Get time command was executed - $epoch = $((New-TimeSpan -Start $(Get-Date -Date '01/01/1970') -End $(Get-Date)).TotalSeconds) - $ExecuteTime = $epoch - ((($SessionDetails.events | Where-Object { $_.EventType -eq 44 })[-1]).Time / 1000) - $ExecuteDate = $origin.AddSeconds($ExecuteTime) + # The extension's GetSessionDetailsBySessionID returns raw SessionDetails (event Time is a DateTime), + # not PageService's elapsed-milliseconds shape the output polling below depends on. + if (Test-CWCApiSecretConnection) { + Write-Warning 'Command queued. Output is not retrieved when connected with -ApiSecret; use -NoWait to suppress this warning.' + return + } - # Look for results of command - $Looking = $True - $TimeOutDateTime = (Get-Date).AddMilliseconds($TimeOut) - $Body = ConvertTo-Json @($Group, $GUID) - while ($Looking) { - try { $SessionDetails = Get-CWCSessionDetail -Group $Group -GUID $GUID } - catch { return $_ } + # Poll for the command's output: the first RanCommand event newer than the queued command. + $TimeOutDateTime = (Get-Date).AddMilliseconds($TimeOut).AddSeconds(1) + $QueuedAtUtc = $null + do { + # Events only: this polls every second against a rate-limited endpoint. + try { $SessionDetails = Get-CWCSessionDetail -Group $Group -GUID $GUID -Include 'Events' -ErrorAction Stop } + catch { + Write-Error $_ + return + } - $ConnectionsWithData = @() - Foreach ($Connection in $SessionDetails.Events) { - $ConnectionsWithData += $Connection | Where-Object { $_.EventType -eq 70 } + if (-not $QueuedAtUtc) { + # The most recent queued command (smallest elapsed time) is the one just sent + $QueuedEvent = $SessionDetails.Events | Where-Object { $_.EventType -eq $QueuedCommandEventType } | + Sort-Object { [double]$_.Time } | Select-Object -First 1 + if ($QueuedEvent) { $QueuedAtUtc = ConvertFrom-CWCEventTime -SessionEvent $QueuedEvent } } - $Events = ($ConnectionsWithData | Where-Object { $_.EventType -eq 70 -and $_.Time }) - foreach ($Event in $Events) { - $epoch = $((New-TimeSpan -Start $(Get-Date -Date '01/01/1970') -End $(Get-Date)).TotalSeconds) - $CheckTime = $epoch - ($Event.Time / 1000) - $CheckDate = $origin.AddSeconds($CheckTime) - if ($CheckDate -gt $ExecuteDate) { - $Looking = $False - $Output = $Event.Data -split '[\r\n]' | Where-Object { $_ -and $_ -ne "C:\WINDOWS\system32>$Command" } - Write-Verbose $Event.Data - return $Output + if ($QueuedAtUtc) { + $OutputEvent = $SessionDetails.Events | Where-Object { + $_.EventType -eq $RanCommandEventType -and $_.Time -and + (ConvertFrom-CWCEventTime -SessionEvent $_) -gt $QueuedAtUtc + } | Select-Object -First 1 + if ($OutputEvent) { + Write-Verbose $OutputEvent.Data + return $OutputEvent.Data -split '[\r\n]' | Where-Object { $_ -and $_ -ne "C:\WINDOWS\system32>$Command" } } } Start-Sleep -Seconds 1 - if ($(Get-Date) -gt $TimeOutDateTime.AddSeconds(1)) { - $Looking = $False - Write-Warning 'Command timed out.' - } - } + } while ((Get-Date) -le $TimeOutDateTime) + + Write-Warning 'Command timed out.' } \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/PageService/Invoke-CWCWake.ps1 b/ConnectWiseControlAPI/Public/PageService/Invoke-CWCWake.ps1 index 1023bef..5235a28 100644 --- a/ConnectWiseControlAPI/Public/PageService/Invoke-CWCWake.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Invoke-CWCWake.ps1 @@ -8,25 +8,20 @@ function Invoke-CWCWake { [string]$Type ) - $Endpoint = 'Services/PageService.ashx/AddEventToSessions' + # PageService.AddEventToSessions no longer exists on the server; wake is queued as a session event. + $SessionEventType = $script:CWCSessionEventType.QueuedWake - $SessionEventType = 43 + if ($Type -eq 'Support') { $Group = 'All Sessions' } + else { $Group = 'All Machines' } - switch($Type){ - 'Support' { $Group = 'All Sessions' } - 'Access' { $Group = 'All Machines' } - default { return Write-Error "Unknown Type, $Type" } - } - - $Body = ConvertTo-Json @($Group,@($GUID),$SessionEventType,'') - Write-Verbose $Body - - # Issue command - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } + $EventEntries = @( + foreach ($SessionID in $GUID) { + @{ + SessionID = $SessionID + EventType = $SessionEventType + } + } + ) - Invoke-CWCWebRequest -Arguments $WebRequestArguments -} \ No newline at end of file + Invoke-CWCServiceMethod -Service PageService -Method AddSessionEvents -Arguments @(@($Group), $EventEntries) +} diff --git a/ConnectWiseControlAPI/Public/PageService/New-CWCAccessToken.ps1 b/ConnectWiseControlAPI/Public/PageService/New-CWCAccessToken.ps1 index 9464dbb..0b96ae0 100644 --- a/ConnectWiseControlAPI/Public/PageService/New-CWCAccessToken.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/New-CWCAccessToken.ps1 @@ -1,22 +1,10 @@ function New-CWCAccessToken { [CmdletBinding()] param ( - [String[]]$Group = 'All Machines', + [string]$Group = 'All Machines', [Parameter(Mandatory = $True)] [guid]$GUID ) - $Endpoint = 'Services/PageService.ashx/GetAccessToken' - - $Body = @" -[["$($Group -join '","')"],"$GUID"] -"@ - Write-Verbose $Body - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Method = 'Post' - Body = $Body - } - Invoke-CWCWebRequest -Arguments $WebRequestArguments -} \ No newline at end of file + Invoke-CWCServiceMethod -Service PageService -Method GetAccessToken -Arguments @(@($Group), "$GUID") -Idempotent +} diff --git a/ConnectWiseControlAPI/Public/PageService/Remove-CWCHostFromSession.ps1 b/ConnectWiseControlAPI/Public/PageService/Remove-CWCHostFromSession.ps1 index b4d48d9..d50da55 100644 --- a/ConnectWiseControlAPI/Public/PageService/Remove-CWCHostFromSession.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Remove-CWCHostFromSession.ps1 @@ -1,38 +1,38 @@ -function Remove-CWCHostFromSession -{ - [CmdletBinding(SupportsShouldProcess)] - param ( - [Parameter(Mandatory = $True)] - [guid[]]$SessionID, - [Parameter(Mandatory = $True)] - [guid[]]$ConnectionID, - [Parameter(Mandatory = $True)] - [string]$Group - ) - - $Endpoint = 'Services/PageService.ashx/AddSessionEvents' - - $SessionEventType = 48 - $Body = ConvertTo-Json @( - @( - $Group - ), - @( - @{ - SessionID = $SessionID - EventType = $SessionEventType - ConnectionID = $ConnectionID - } - ) - ) - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - if ($PSCmdlet.ShouldProcess($WebRequestArguments.Body, 'Remove-CWCHostFromSession')) - { - Invoke-CWCWebRequest -Arguments $WebRequestArguments - } +function Remove-CWCHostFromSession +{ + [CmdletBinding(SupportsShouldProcess)] + param ( + [Parameter(Mandatory = $True)] + [guid[]]$SessionID, + [Parameter(Mandatory = $True)] + [guid[]]$ConnectionID, + [Parameter(Mandatory = $True)] + [string]$Group + ) + + $Endpoint = 'Services/PageService.ashx/AddSessionEvents' + + $SessionEventType = 48 + $Body = ConvertTo-Json @( + @( + $Group + ), + @( + @{ + SessionID = $SessionID + EventType = $SessionEventType + ConnectionID = $ConnectionID + } + ) + ) + + $WebRequestArguments = @{ + Endpoint = $Endpoint + Body = $Body + Method = 'Post' + } + if ($PSCmdlet.ShouldProcess($WebRequestArguments.Body, 'Remove-CWCHostFromSession')) + { + Invoke-CWCWebRequest -Arguments $WebRequestArguments + } } \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/PageService/Remove-CWCSession.ps1 b/ConnectWiseControlAPI/Public/PageService/Remove-CWCSession.ps1 index 89ec864..d87f0f8 100644 --- a/ConnectWiseControlAPI/Public/PageService/Remove-CWCSession.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Remove-CWCSession.ps1 @@ -1,40 +1,43 @@ function Remove-CWCSession { - [CmdletBinding(SupportsShouldProcess)] + # ConfirmImpact High: deleting (or uninstalling) sessions is irreversible, and -GUID accepts + # many IDs at once, so prompt by default. + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] param ( [Parameter(Mandatory = $True)] + [ValidateScript({ $_ -ne [guid]::Empty })] [guid[]]$GUID, [Parameter(Mandatory = $True)] - [string]$Group + [string]$Group, + # Queue an uninstall of the Access client and delete the session (QueuedUninstallAndDelete), + # instead of only deleting the session record (DeletedSession). + [switch]$Uninstall ) - $Endpoint = 'Services/PageService.ashx/AddSessionEvents' - - $SessionEventType = 21 - - $GuidList = @() - foreach ($SessionID in $GUID) - { - $GuidList += @{ - SessionID = $SessionID - EventType = $SessionEventType - } + if ($Uninstall) { + $SessionEventType = $script:CWCSessionEventType.QueuedUninstallAndDelete + $Action = 'Uninstall client and delete session' + } + else { + $SessionEventType = $script:CWCSessionEventType.DeletedSession + $Action = 'Delete session' } - $Body = ConvertTo-Json -Compress -InputObject @( - @( - $Group - ), - $GuidList + # Confirm each session individually (readable -WhatIf/-Confirm target), then send one + # SessionEventEntry per approved session in a single request. + $EventEntries = @( + foreach ($SessionID in $GUID) { + if ($PSCmdlet.ShouldProcess("Session $SessionID (group '$Group')", $Action)) { + @{ + SessionID = $SessionID + EventType = $SessionEventType + } + } + } ) - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - if ($PSCmdlet.ShouldProcess($WebRequestArguments.Body, 'Remove-CWCSession')) - { - Invoke-CWCWebRequest -Arguments $WebRequestArguments - } -} \ No newline at end of file + if ($EventEntries.Count -eq 0) { return } + + # Not idempotent: never retried + Invoke-CWCServiceMethod -Service PageService -Method AddSessionEvents -Arguments @(@($Group), $EventEntries) +} diff --git a/ConnectWiseControlAPI/Public/PageService/Update-CWCCustomProperty.ps1 b/ConnectWiseControlAPI/Public/PageService/Update-CWCCustomProperty.ps1 index 08447c2..a4d765e 100644 --- a/ConnectWiseControlAPI/Public/PageService/Update-CWCCustomProperty.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Update-CWCCustomProperty.ps1 @@ -6,19 +6,11 @@ function Update-CWCCustomProperty { [Parameter(Mandatory=$True)] [int]$Property, [string]$Value, - [string[]]$Group = 'All Machines' + [string]$Group = 'All Machines' ) - $Endpoint = 'Services/PageService.ashx/UpdateSessionCustomPropertyValue' - - $Body = ConvertTo-Json @($Group,$GUID,$Property,$Value) - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - if ($PSCmdlet.ShouldProcess($WebRequestArguments.Body, "Update-CWCCustomProperty")) { - Invoke-CWCWebRequest -Arguments $WebRequestArguments + if ($PSCmdlet.ShouldProcess("$GUID", "Set custom property $Property to '$Value'")) { + # Sets a value, so it is safe to retry + Invoke-CWCServiceMethod -Service PageService -Method UpdateSessionCustomPropertyValue -Arguments @($Group, $GUID, $Property, $Value) -Idempotent } -} \ No newline at end of file +} diff --git a/ConnectWiseControlAPI/Public/PageService/Update-CWCSessionName.ps1 b/ConnectWiseControlAPI/Public/PageService/Update-CWCSessionName.ps1 index 8d71ecb..4f6ae12 100644 --- a/ConnectWiseControlAPI/Public/PageService/Update-CWCSessionName.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Update-CWCSessionName.ps1 @@ -8,16 +8,14 @@ function Update-CWCSessionName { [string]$Group = 'All Machines' ) - $Endpoint = 'Services/PageService.ashx/UpdateSessionName' - - $Body = ConvertTo-Json @($Group,$GUID,$NewName) - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - if ($PSCmdlet.ShouldProcess($WebRequestArguments.Body, "Update-CWCSessionName")) { - Invoke-CWCWebRequest -Arguments $WebRequestArguments + if ($PSCmdlet.ShouldProcess("$GUID", "Rename to '$NewName'")) { + # Sets a value, so it is safe to retry + if (Test-CWCApiSecretConnection) { + # RESTful API Manager: UpdateSessionName(Guid sessionID, string newName). -Group is ignored. + Invoke-CWCServiceMethod -RestApi -Method UpdateSessionName -Arguments @($GUID.ToString(), $NewName) -Idempotent + } + else { + Invoke-CWCServiceMethod -Service PageService -Method UpdateSessionName -Arguments @($Group, $GUID, $NewName) -Idempotent + } } } \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/SecurityService/Get-CWCSecurityConfigurationInfo.ps1 b/ConnectWiseControlAPI/Public/SecurityService/Get-CWCSecurityConfigurationInfo.ps1 index daeaff0..1280de5 100644 --- a/ConnectWiseControlAPI/Public/SecurityService/Get-CWCSecurityConfigurationInfo.ps1 +++ b/ConnectWiseControlAPI/Public/SecurityService/Get-CWCSecurityConfigurationInfo.ps1 @@ -2,11 +2,5 @@ function Get-CWCSecurityConfigurationInfo { [CmdletBinding()] param () - $Endpoint = 'Services/SecurityService.ashx/GetSecurityConfigurationInfo' - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Method = 'Post' - } - Invoke-CWCWebRequest -Arguments $WebRequestArguments -} \ No newline at end of file + Invoke-CWCServiceMethod -Service SecurityService -Method GetSecurityConfigurationInfo -Idempotent +} diff --git a/ConnectWiseControlAPI/Public/SecurityService/New-CWCUser.ps1 b/ConnectWiseControlAPI/Public/SecurityService/New-CWCUser.ps1 index def3a90..f0de653 100644 --- a/ConnectWiseControlAPI/Public/SecurityService/New-CWCUser.ps1 +++ b/ConnectWiseControlAPI/Public/SecurityService/New-CWCUser.ps1 @@ -11,9 +11,7 @@ [boolean]$ForcePassChange = $true ) - $Endpoint = 'Services/SecurityService.ashx/SaveUser' - - $Body = ConvertTo-Json @( + $SaveUserArguments = @( $script:InternalUserSource, $null, $Credentials.UserName, @@ -27,12 +25,7 @@ $ForcePassChange ) - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - if ($PSCmdlet.ShouldProcess($WebRequestArguments.Body, "New-CWCUser")) { - Invoke-CWCWebRequest -Arguments $WebRequestArguments + if ($PSCmdlet.ShouldProcess($Credentials.UserName, "New-CWCUser")) { + Invoke-CWCServiceMethod -Service SecurityService -Method SaveUser -Arguments $SaveUserArguments -Sensitive } } \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/SecurityService/Remove-CWCUser.ps1 b/ConnectWiseControlAPI/Public/SecurityService/Remove-CWCUser.ps1 index b76bf29..886faa0 100644 --- a/ConnectWiseControlAPI/Public/SecurityService/Remove-CWCUser.ps1 +++ b/ConnectWiseControlAPI/Public/SecurityService/Remove-CWCUser.ps1 @@ -5,19 +5,7 @@ [string]$User ) - $Endpoint = 'Services/SecurityService.ashx/DeleteUser' - - $Body = ConvertTo-Json @( - $script:InternalUserSource, - $User - ) - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - if ($PSCmdlet.ShouldProcess($WebRequestArguments.Body, "Remove-CWCUser")) { - Invoke-CWCWebRequest -Arguments $WebRequestArguments + if ($PSCmdlet.ShouldProcess($User, 'Delete user')) { + Invoke-CWCServiceMethod -Service SecurityService -Method DeleteUser -Arguments @($script:InternalUserSource, $User) } -} \ No newline at end of file +} diff --git a/ConnectWiseControlAPI/Public/SecurityService/Update-CWCUser.ps1 b/ConnectWiseControlAPI/Public/SecurityService/Update-CWCUser.ps1 index 5a37e54..9079848 100644 --- a/ConnectWiseControlAPI/Public/SecurityService/Update-CWCUser.ps1 +++ b/ConnectWiseControlAPI/Public/SecurityService/Update-CWCUser.ps1 @@ -12,8 +12,6 @@ [boolean]$ForcePassChange = $False ) - $Endpoint = 'Services/SecurityService.ashx/SaveUser' - $Security = Get-CWCSecurityConfigurationInfo -ErrorAction Stop $Internal = $Security.UserSources | Where-Object { $_.ResourceKey -eq $script:InternalUserSource } $User = $Internal.Users | Where-Object { $_.Name -eq $UserToUpdate } @@ -27,7 +25,7 @@ $null, $User.PasswordQuestion, $User.DisplayName, - '', + $User.Comment, $User.Email, $User.RoleNames, $False @@ -35,10 +33,9 @@ if($NewUserName){ $Update[2] = $NewUserName } if($Password){ - $bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password) - $Update[3] = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr) - $Update[4] = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr) - Remove-Variable bstr + $PasswordPlain = ConvertFrom-CWCSecureString $Password + $Update[3] = $PasswordPlain + $Update[4] = $PasswordPlain } if($OTP){ $Update[5] = $OTP } if($DisplayName){ $Update[6] = $DisplayName } @@ -46,14 +43,7 @@ if($SecurityGroups){ $Update[9] = $SecurityGroups } if($ForcePassChange){ $Update[10] = $True } - $Body = ConvertTo-Json $Update - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - if ($PSCmdlet.ShouldProcess($WebRequestArguments.Body, "Update-CWCUser")) { - Invoke-CWCWebRequest -Arguments $WebRequestArguments + if ($PSCmdlet.ShouldProcess($UserToUpdate, "Update-CWCUser")) { + Invoke-CWCServiceMethod -Service SecurityService -Method SaveUser -Arguments $Update -Sensitive } } \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/SessionGroupService/Get-CWCSessionGroup.ps1 b/ConnectWiseControlAPI/Public/SessionGroupService/Get-CWCSessionGroup.ps1 index 27de46f..ae77b26 100644 --- a/ConnectWiseControlAPI/Public/SessionGroupService/Get-CWCSessionGroup.ps1 +++ b/ConnectWiseControlAPI/Public/SessionGroupService/Get-CWCSessionGroup.ps1 @@ -2,12 +2,6 @@ function Get-CWCSessionGroup { [CmdletBinding()] param () - $Endpoint = 'Services/SessionGroupService.ashx/session-groups' - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Method = 'Get' - } - - Invoke-CWCWebRequest -Arguments $WebRequestArguments + # Requires the ManageSessionGroups permission on the server. + Invoke-CWCServiceMethod -Service SessionGroupService -Method GetSessionGroups -Idempotent } From 44f7d18ed861c9803d2ca6125350d784a527b873 Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Tue, 10 Nov 2026 09:03:23 -0700 Subject: [PATCH 03/30] Add session functions that work on both connection types Find-CWCSession (API secret only), New-CWCSession, Add-CWCSessionNote, Send-CWCSessionMessage and Send-CWCToolboxItem. On credentials connections the last three queue AddedNote (32), QueuedMessage (45) and QueuedTool (47) events through PageService.AddSessionEvents; New-CWCSession uses PageService.CreateSession. Co-Authored-By: Claude Opus 5.5 --- .../Public/RestApi/Add-CWCSessionNote.ps1 | 64 +++++++++++++++ .../Public/RestApi/Find-CWCSession.ps1 | 59 ++++++++++++++ .../Public/RestApi/New-CWCSession.ps1 | 77 +++++++++++++++++++ .../Public/RestApi/Send-CWCSessionMessage.ps1 | 75 ++++++++++++++++++ .../Public/RestApi/Send-CWCToolboxItem.ps1 | 63 +++++++++++++++ 5 files changed, 338 insertions(+) create mode 100644 ConnectWiseControlAPI/Public/RestApi/Add-CWCSessionNote.ps1 create mode 100644 ConnectWiseControlAPI/Public/RestApi/Find-CWCSession.ps1 create mode 100644 ConnectWiseControlAPI/Public/RestApi/New-CWCSession.ps1 create mode 100644 ConnectWiseControlAPI/Public/RestApi/Send-CWCSessionMessage.ps1 create mode 100644 ConnectWiseControlAPI/Public/RestApi/Send-CWCToolboxItem.ps1 diff --git a/ConnectWiseControlAPI/Public/RestApi/Add-CWCSessionNote.ps1 b/ConnectWiseControlAPI/Public/RestApi/Add-CWCSessionNote.ps1 new file mode 100644 index 0000000..1e8c143 --- /dev/null +++ b/ConnectWiseControlAPI/Public/RestApi/Add-CWCSessionNote.ps1 @@ -0,0 +1,64 @@ +function Add-CWCSessionNote { + <# + .SYNOPSIS + Adds a note to a session. + + .DESCRIPTION + Queues an AddedNote session event. + + Credentials connections: PageService.AddSessionEvents. The note is attributed to the connected + user and needs the AddNote permission in -Group. + + API secret connections: the RESTful API Manager extension's AddNoteToSession. The note is + attributed to the extension's RESTfulUserName setting ("RESTful API" by default); -Group is ignored. + + .PARAMETER GUID + Session ID. + + .PARAMETER Note + Note text. + + .PARAMETER Group + Session group containing the session (credentials connections only). Defaults to 'All Machines'. + + .EXAMPLE + Add-CWCSessionNote -GUID $SessionID -Note 'Rebooted for patching' + + .NOTES + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> + [CmdletBinding(SupportsShouldProcess)] + param( + [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] + [Alias('SessionID')] + [guid]$GUID, + + [Parameter(Mandatory = $True)] + [ValidateNotNullOrEmpty()] + [string]$Note, + + [ValidateNotNullOrEmpty()] + [string]$Group = 'All Machines' + ) + + process { + if (-not $PSCmdlet.ShouldProcess("$GUID", 'Add note')) { return } + + # Adding an event is not idempotent: never retried + if (Test-CWCApiSecretConnection) { + # AddNoteToSession(Guid sessionID, string noteBody) + Invoke-CWCServiceMethod -RestApi -Method AddNoteToSession -Arguments @($GUID.ToString(), $Note) + } + else { + $NoteEvent = @{ + SessionID = $GUID + EventType = $script:CWCSessionEventType.AddedNote + Data = $Note + } + Invoke-CWCServiceMethod -Service PageService -Method AddSessionEvents -Arguments @(@($Group), @($NoteEvent)) + } + } +} diff --git a/ConnectWiseControlAPI/Public/RestApi/Find-CWCSession.ps1 b/ConnectWiseControlAPI/Public/RestApi/Find-CWCSession.ps1 new file mode 100644 index 0000000..7dd1d27 --- /dev/null +++ b/ConnectWiseControlAPI/Public/RestApi/Find-CWCSession.ps1 @@ -0,0 +1,59 @@ +function Find-CWCSession { + <# + .SYNOPSIS + Finds sessions by session filter expression, name or ID (API secret connections). + + .DESCRIPTION + Calls the RESTful API Manager extension. Searches all sessions of every type; results are not + limited by role permissions or session groups. + + -Filter uses Control's session filter syntax, the same syntax as session group filters, + e.g. "Name LIKE 'DESKTOP-*'" or "CustomProperty1 = 'Acme'". + + .PARAMETER Filter + A session filter expression (GetSessionsByFilter). + + .PARAMETER Name + Exact session name (GetSessionsByName). Single quotes are not allowed because the extension + inserts the name into a filter expression without escaping. + + .PARAMETER GUID + Session ID (GetSessionBySessionID). + + .EXAMPLE + Find-CWCSession -Filter "GuestOperatingSystemName LIKE '*Server*'" + + .EXAMPLE + Find-CWCSession -Name 'DESKTOP-01' + + .NOTES + Requires Connect-CWC -ApiSecret and the RESTful API Manager extension. + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> + [CmdletBinding(DefaultParameterSetName = 'Filter')] + param( + [Parameter(Mandatory = $True, ParameterSetName = 'Filter')] + [ValidateNotNullOrEmpty()] + [string]$Filter, + + [Parameter(Mandatory = $True, ParameterSetName = 'Name')] + [ValidateNotNullOrEmpty()] + [ValidatePattern("^[^']*$")] + [string]$Name, + + [Parameter(Mandatory = $True, ParameterSetName = 'GUID')] + [guid]$GUID + ) + + switch ($PSCmdlet.ParameterSetName) { + 'Filter' { $ServerMethod = 'GetSessionsByFilter'; $Argument = $Filter } + 'Name' { $ServerMethod = 'GetSessionsByName'; $Argument = $Name } + 'GUID' { $ServerMethod = 'GetSessionBySessionID'; $Argument = $GUID.ToString() } + } + + # Unroll the returned array so each session goes down the pipeline + Invoke-CWCServiceMethod -RestApi -Method $ServerMethod -Arguments $Argument -Idempotent | ForEach-Object { $_ } +} diff --git a/ConnectWiseControlAPI/Public/RestApi/New-CWCSession.ps1 b/ConnectWiseControlAPI/Public/RestApi/New-CWCSession.ps1 new file mode 100644 index 0000000..ace6db0 --- /dev/null +++ b/ConnectWiseControlAPI/Public/RestApi/New-CWCSession.ps1 @@ -0,0 +1,77 @@ +function New-CWCSession { + <# + .SYNOPSIS + Creates a session. + + .DESCRIPTION + Creates a session and returns the new session ID. Works with both connection types: + + -Credentials: PageService.CreateSession. Requires the create permission for the session type; + the session host is the connected user. + + -ApiSecret: the RESTful API Manager extension's CreateSession. The session host is the + extension's RESTfulUserName setting ("RESTful API" by default). + + .PARAMETER Type + Support, Meeting or Access. + + .PARAMETER Name + Session name. + + .PARAMETER IsPublic + Make the session publicly listed on the guest page. + + .PARAMETER Code + Session join code. + + .PARAMETER CustomPropertyValues + Custom property values in order (CustomProperty1, CustomProperty2, ...). + + .EXAMPLE + New-CWCSession -Type Support -Name 'Ticket 12345' -Code '12345' + + .NOTES + Not retried on HTTP 500: a retry after the server created the session would create a second one. + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> + [CmdletBinding(SupportsShouldProcess)] + [OutputType([guid])] + param( + [Parameter(Mandatory = $True)] + [ValidateSet('Support', 'Meeting', 'Access')] + [string]$Type, + + [Parameter(Mandatory = $True)] + [ValidateNotNullOrEmpty()] + [string]$Name, + + [switch]$IsPublic, + + [string]$Code = '', + + [string[]]$CustomPropertyValues = @() + ) + + # Same signature on both services: + # CreateSession(SessionType sessionType, string name, bool isPublic, string code, string[] customPropertyValues) + $CreateSessionArguments = @( + $script:CWCSessionType[$Type], + $Name, + [bool]$IsPublic, + $Code, + @($CustomPropertyValues) + ) + + if ($PSCmdlet.ShouldProcess($Name, "Create $Type session")) { + if (Test-CWCApiSecretConnection) { + $Result = Invoke-CWCServiceMethod -RestApi -Method CreateSession -Arguments $CreateSessionArguments + } + else { + $Result = Invoke-CWCServiceMethod -Service PageService -Method CreateSession -Arguments $CreateSessionArguments + } + if ($Result) { [guid]$Result } + } +} diff --git a/ConnectWiseControlAPI/Public/RestApi/Send-CWCSessionMessage.ps1 b/ConnectWiseControlAPI/Public/RestApi/Send-CWCSessionMessage.ps1 new file mode 100644 index 0000000..d34ffd8 --- /dev/null +++ b/ConnectWiseControlAPI/Public/RestApi/Send-CWCSessionMessage.ps1 @@ -0,0 +1,75 @@ +function Send-CWCSessionMessage { + <# + .SYNOPSIS + Sends a chat message to a session's guest. + + .DESCRIPTION + Queues a QueuedMessage session event. + + Credentials connections: PageService.AddSessionEvents. The guest sees the connected user's + display name as the sender (-From is not supported) and the user needs the matching permission + in -Group. + + API secret connections: the RESTful API Manager extension's SendMessageToSession. The guest sees + -From as the sender; -Group is ignored. + + .PARAMETER GUID + Session ID. + + .PARAMETER Message + Message text. + + .PARAMETER From + Sender name shown to the guest (API secret connections only). + + .PARAMETER Group + Session group containing the session (credentials connections only). Defaults to 'All Machines'. + + .EXAMPLE + Send-CWCSessionMessage -GUID $SessionID -Message 'Your computer will restart in 5 minutes.' + + .NOTES + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> + [CmdletBinding(SupportsShouldProcess)] + param( + [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] + [Alias('SessionID')] + [guid]$GUID, + + [Parameter(Mandatory = $True)] + [ValidateNotNullOrEmpty()] + [string]$Message, + + [ValidateNotNullOrEmpty()] + [string]$From = 'RESTful API', + + [ValidateNotNullOrEmpty()] + [string]$Group = 'All Machines' + ) + + process { + if (-not $PSCmdlet.ShouldProcess("$GUID", 'Send message')) { return } + + # Adding an event is not idempotent: never retried + if (Test-CWCApiSecretConnection) { + # SendMessageToSession(Guid sessionID, string byHost, string message) + Invoke-CWCServiceMethod -RestApi -Method SendMessageToSession -Arguments @($GUID.ToString(), $From, $Message) + } + else { + # The server sets the sender to the connected user's display name. + if ($PSBoundParameters.ContainsKey('From')) { + Write-Warning '-From is only used with -ApiSecret connections; the guest sees the connected user as the sender.' + } + $MessageEvent = @{ + SessionID = $GUID + EventType = $script:CWCSessionEventType.QueuedMessage + Data = $Message + } + Invoke-CWCServiceMethod -Service PageService -Method AddSessionEvents -Arguments @(@($Group), @($MessageEvent)) + } + } +} diff --git a/ConnectWiseControlAPI/Public/RestApi/Send-CWCToolboxItem.ps1 b/ConnectWiseControlAPI/Public/RestApi/Send-CWCToolboxItem.ps1 new file mode 100644 index 0000000..5e56249 --- /dev/null +++ b/ConnectWiseControlAPI/Public/RestApi/Send-CWCToolboxItem.ps1 @@ -0,0 +1,63 @@ +function Send-CWCToolboxItem { + <# + .SYNOPSIS + Queues a Toolbox item to run on a session. + + .DESCRIPTION + Queues a QueuedTool session event naming the Toolbox item. + + Credentials connections: PageService.AddSessionEvents; the user needs the RunSharedTool + permission in -Group. + + API secret connections: the RESTful API Manager extension's SendToolboxItemToSession; -Group is ignored. + + .PARAMETER GUID + Session ID. + + .PARAMETER Name + Toolbox item name as shown in the Control Toolbox. + + .PARAMETER Group + Session group containing the session (credentials connections only). Defaults to 'All Machines'. + + .EXAMPLE + Send-CWCToolboxItem -GUID $SessionID -Name 'Cleanup.ps1' + + .NOTES + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> + [CmdletBinding(SupportsShouldProcess)] + param( + [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] + [Alias('SessionID')] + [guid]$GUID, + + [Parameter(Mandatory = $True)] + [ValidateNotNullOrEmpty()] + [string]$Name, + + [ValidateNotNullOrEmpty()] + [string]$Group = 'All Machines' + ) + + process { + if (-not $PSCmdlet.ShouldProcess("$GUID", "Run toolbox item '$Name'")) { return } + + # Adding an event is not idempotent: never retried + if (Test-CWCApiSecretConnection) { + # SendToolboxItemToSession(Guid sessionID, string toolboxItemName) + Invoke-CWCServiceMethod -RestApi -Method SendToolboxItemToSession -Arguments @($GUID.ToString(), $Name) + } + else { + $ToolEvent = @{ + SessionID = $GUID + EventType = $script:CWCSessionEventType.QueuedTool + Data = $Name + } + Invoke-CWCServiceMethod -Service PageService -Method AddSessionEvents -Arguments @(@($Group), @($ToolEvent)) + } + } +} From a8a22a5d1ec222f5beabd0a2cbf807fe7d9734e4 Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Tue, 10 Nov 2026 09:03:23 -0700 Subject: [PATCH 04/30] Fix Remote Workforce functions against the extension source Get-CWCLauncURL moves under Remote Workforce and forwards to the new Get-CWCRemoteWorkforceLaunchURL (it sent 6 arguments to a 1-argument method, including an unused plaintext password). Adds Get-CWCRemoteWorkforceSession and Initialize-CWCRemoteWorkforceSessionGroup; Add-CWCRemoteWorkforceRequiredRole uses the extension's idempotent EnsureRemoteWorkforceSecurityRoleExists. Co-Authored-By: Claude Opus 5.5 --- .../Extensions/Launcher/Get-CWCLauncURL.ps1 | 28 -------- .../Add-CWCRemoteWorkforceRequiredRole.ps1 | 65 +++++++---------- .../Remote Workforce/Get-CWCLauncURL.ps1 | 62 +++++++++++++++++ .../Get-CWCRemoteWorkforceLaunchURL.ps1 | 69 +++++++++++++++++++ .../Get-CWCRemoteWorkforceSession.ps1 | 36 ++++++++++ ...tialize-CWCRemoteWorkforceSessionGroup.ps1 | 31 +++++++++ .../New-CWCRemoteWorkforceAssignment.ps1 | 23 ++----- 7 files changed, 230 insertions(+), 84 deletions(-) delete mode 100644 ConnectWiseControlAPI/Public/Extensions/Launcher/Get-CWCLauncURL.ps1 create mode 100644 ConnectWiseControlAPI/Public/Extensions/Remote Workforce/Get-CWCLauncURL.ps1 create mode 100644 ConnectWiseControlAPI/Public/Extensions/Remote Workforce/Get-CWCRemoteWorkforceLaunchURL.ps1 create mode 100644 ConnectWiseControlAPI/Public/Extensions/Remote Workforce/Get-CWCRemoteWorkforceSession.ps1 create mode 100644 ConnectWiseControlAPI/Public/Extensions/Remote Workforce/Initialize-CWCRemoteWorkforceSessionGroup.ps1 diff --git a/ConnectWiseControlAPI/Public/Extensions/Launcher/Get-CWCLauncURL.ps1 b/ConnectWiseControlAPI/Public/Extensions/Launcher/Get-CWCLauncURL.ps1 deleted file mode 100644 index c21fc3e..0000000 --- a/ConnectWiseControlAPI/Public/Extensions/Launcher/Get-CWCLauncURL.ps1 +++ /dev/null @@ -1,28 +0,0 @@ -function Get-CWCLauncURL { - [CmdletBinding(SupportsShouldProcess)] - param( - [Parameter(Mandatory = $True)] - [guid[]]$GUID - ) - - $Endpoint = 'App_Extensions/2c4f522f-b39a-413a-8807-dc52a2fce13e/Service.ashx/GetLaunchUrlForSessionId' - - $Body = ConvertTo-Json @( - @($GUID) - $onSuccess - $onFailure - $userContext - $userNameOverride - $passwordOverride - ) - Write-Verbose $Body - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - if ($PSCmdlet.ShouldProcess($WebRequestArguments.Body, 'New-CWCRemoteWorkforceAssignment')) { - Invoke-CWCWebRequest -Arguments $WebRequestArguments - } -} \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/Add-CWCRemoteWorkforceRequiredRole.ps1 b/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/Add-CWCRemoteWorkforceRequiredRole.ps1 index 69f64aa..1c33d64 100644 --- a/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/Add-CWCRemoteWorkforceRequiredRole.ps1 +++ b/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/Add-CWCRemoteWorkforceRequiredRole.ps1 @@ -1,46 +1,31 @@ function Add-CWCRemoteWorkforceRequiredRole { - [CmdletBinding()] - param() + <# + .SYNOPSIS + Creates the security role required by the Remote Workforce extension. + + .DESCRIPTION + Calls the Remote Workforce extension's EnsureRemoteWorkforceSecurityRoleExists endpoint. + The extension creates its role (name from the extension's RoleName setting, "Remote Workforce" + by default) with View Session Group, Join Session and Host Session Without Consent scoped to the + extension's session group, then marks the role as created in the extension settings. - $Endpoint = 'Services/SecurityService.ashx/SaveRole' + Idempotent: if the role already exists nothing is changed. Requires the Administer permission. - $SessionGroups = @('My Assigned Machines') - $RoleName = 'Remote Workforce' + .EXAMPLE + Add-CWCRemoteWorkforceRequiredRole - $Body = ConvertTo-Json -Depth 10 @( - "", - $RoleName, - @(), - @( - @{ - "AccessControlType" = 0 - "Name" = "ViewSessionGroup" - "SessionGroupFilter" = 7 - "SessionGroupPath" = $SessionGroups - "OwnershipFilter" = 0 - }, - @{ - "AccessControlType" = 0 - "Name" = "JoinSession" - "SessionGroupFilter" = 7 - "SessionGroupPath" = $SessionGroups - "OwnershipFilter" = 0 - }, - @{ - "AccessControlType" = 0 - "Name" = "HostSessionWithoutConsent" - "SessionGroupFilter" = 7 - "SessionGroupPath" = $SessionGroups - "OwnershipFilter" = 0 - } - ) - ) - Write-Verbose $Body + .NOTES + Requires the Remote Workforce extension (2c4f522f-b39a-413a-8807-dc52a2fce13e), Control 23.6+. + Pair with Initialize-CWCRemoteWorkforceSessionGroup. + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> + [CmdletBinding(SupportsShouldProcess)] + param() - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' + if ($PSCmdlet.ShouldProcess('Remote Workforce security role', 'Add-CWCRemoteWorkforceRequiredRole')) { + Invoke-CWCServiceMethod -ExtensionID $script:CWCRemoteWorkforceExtensionID -Method EnsureRemoteWorkforceSecurityRoleExists -Arguments @() -Idempotent } - Invoke-CWCWebRequest -Arguments $WebRequestArguments -} \ No newline at end of file +} diff --git a/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/Get-CWCLauncURL.ps1 b/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/Get-CWCLauncURL.ps1 new file mode 100644 index 0000000..9dd685a --- /dev/null +++ b/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/Get-CWCLauncURL.ps1 @@ -0,0 +1,62 @@ +function Get-CWCLauncURL { + <# + .SYNOPSIS + DEPRECATED. Use Get-CWCRemoteWorkforceLaunchURL. + + .DESCRIPTION + Retained for backwards compatibility. Forwards -GUID to Get-CWCRemoteWorkforceLaunchURL. + The Remote Workforce GetLaunchUrlForSessionId endpoint takes only a session ID, so the + OnSuccess, OnFailure, UserContext, UserNameOverride and PasswordOverride parameters are + ignored. This function will be removed in v1.0. + + .PARAMETER GUID + One or more session IDs. + + .PARAMETER OnSuccess + Ignored. Not accepted by the server. + + .PARAMETER OnFailure + Ignored. Not accepted by the server. + + .PARAMETER UserContext + Ignored. Not accepted by the server. + + .PARAMETER UserNameOverride + Ignored. Not accepted by the server. + + .PARAMETER PasswordOverride + Ignored. Not accepted by the server. + + .EXAMPLE + Get-CWCRemoteWorkforceLaunchURL -GUID $SessionID + + .NOTES + Deprecated in favor of Get-CWCRemoteWorkforceLaunchURL. + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> + [CmdletBinding(SupportsShouldProcess)] + param( + [Parameter(Mandatory = $True)] + [guid[]]$GUID, + [string]$OnSuccess, + [string]$OnFailure, + [string]$UserContext, + [string]$UserNameOverride, + [securestring]$PasswordOverride + ) + + Write-Warning 'Get-CWCLauncURL is deprecated and will be removed in v1.0. Use Get-CWCRemoteWorkforceLaunchURL.' + + $IgnoredParameters = @('OnSuccess', 'OnFailure', 'UserContext', 'UserNameOverride', 'PasswordOverride') | + Where-Object { $PSBoundParameters.ContainsKey($_) } + if ($IgnoredParameters) { + Write-Warning "Ignoring parameter(s) not accepted by the server: $($IgnoredParameters -join ', ')" + } + + if ($PSCmdlet.ShouldProcess("$GUID", 'Get-CWCLauncURL')) { + Get-CWCRemoteWorkforceLaunchURL -GUID $GUID + } +} diff --git a/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/Get-CWCRemoteWorkforceLaunchURL.ps1 b/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/Get-CWCRemoteWorkforceLaunchURL.ps1 new file mode 100644 index 0000000..7364496 --- /dev/null +++ b/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/Get-CWCRemoteWorkforceLaunchURL.ps1 @@ -0,0 +1,69 @@ +function Get-CWCRemoteWorkforceLaunchURL { + <# + .SYNOPSIS + Gets a Remote Workforce host launch URL for an assigned machine. + + .DESCRIPTION + Calls the Remote Workforce extension's GetLaunchUrlForSessionId (by session GUID) or + GetLaunchUrl (by session name) endpoint and returns a ClickOnce launch URL. + + The extension only returns a URL when the CALLING user is the user the machine is assigned to + (the session is in their Remote Workforce session group, "My Assigned Machines" by default) + and has View and Join permissions on that group. Otherwise the server returns null and this + function writes a warning. An administrator cannot get launch URLs for other users' machines. + + .PARAMETER GUID + One or more session IDs. Each is requested separately. + + .PARAMETER SessionName + The session name to look up within the caller's Remote Workforce sessions. + + .EXAMPLE + Get-CWCRemoteWorkforceLaunchURL -GUID 'd2b6f0a1-1111-2222-3333-444455556666' + + .EXAMPLE + Get-CWCRemoteWorkforceSession | Get-CWCRemoteWorkforceLaunchURL + + .EXAMPLE + Get-CWCRemoteWorkforceLaunchURL -SessionName 'DESKTOP-01' + + .NOTES + Requires the Remote Workforce extension (2c4f522f-b39a-413a-8807-dc52a2fce13e), Control 23.6+. + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> + [CmdletBinding(DefaultParameterSetName = 'GUID')] + param( + [Parameter(Mandatory = $True, ParameterSetName = 'GUID', ValueFromPipelineByPropertyName = $True)] + [Alias('SessionID')] + [guid[]]$GUID, + + [Parameter(Mandatory = $True, ParameterSetName = 'SessionName')] + [ValidateNotNullOrEmpty()] + [string]$SessionName + ) + + process { + if ($PSCmdlet.ParameterSetName -eq 'SessionName') { + $ServerMethod = 'GetLaunchUrl' + $Values = @($SessionName) + } + else { + $ServerMethod = 'GetLaunchUrlForSessionId' + $Values = @($GUID | ForEach-Object { $_.ToString() }) + } + + foreach ($Value in $Values) { + # The server method takes exactly one argument + $Result = Invoke-CWCServiceMethod -ExtensionID $script:CWCRemoteWorkforceExtensionID -Method $ServerMethod -Arguments $Value -Idempotent + + if ($null -eq $Result -or $Result -eq '') { + Write-Warning "No launch URL returned for '$Value'. Remote Workforce only returns URLs for machines assigned to the calling user." + continue + } + $Result + } + } +} diff --git a/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/Get-CWCRemoteWorkforceSession.ps1 b/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/Get-CWCRemoteWorkforceSession.ps1 new file mode 100644 index 0000000..ab9384d --- /dev/null +++ b/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/Get-CWCRemoteWorkforceSession.ps1 @@ -0,0 +1,36 @@ +function Get-CWCRemoteWorkforceSession { + <# + .SYNOPSIS + Lists the Remote Workforce machines assigned to the calling user. + + .DESCRIPTION + Calls the Remote Workforce extension's GetRemoteWorkforceSessions endpoint, which returns the + sessions in the extension's session group for the CALLING user that they can view and join. + The server's name-to-ID map is returned as objects with Name and SessionID properties. + + .EXAMPLE + Get-CWCRemoteWorkforceSession + + .EXAMPLE + Get-CWCRemoteWorkforceSession | Get-CWCRemoteWorkforceLaunchURL + + .NOTES + Requires the Remote Workforce extension (2c4f522f-b39a-413a-8807-dc52a2fce13e), Control 23.6+. + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> + [CmdletBinding()] + param() + + $Result = Invoke-CWCServiceMethod -ExtensionID $script:CWCRemoteWorkforceExtensionID -Method GetRemoteWorkforceSessions -Arguments @() -Idempotent + if ($null -eq $Result) { return } + + foreach ($Property in $Result.PSObject.Properties) { + [PSCustomObject]@{ + Name = $Property.Name + SessionID = [guid]$Property.Value + } + } +} diff --git a/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/Initialize-CWCRemoteWorkforceSessionGroup.ps1 b/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/Initialize-CWCRemoteWorkforceSessionGroup.ps1 new file mode 100644 index 0000000..bc9a7f6 --- /dev/null +++ b/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/Initialize-CWCRemoteWorkforceSessionGroup.ps1 @@ -0,0 +1,31 @@ +function Initialize-CWCRemoteWorkforceSessionGroup { + <# + .SYNOPSIS + Creates or repairs the session group used by the Remote Workforce extension. + + .DESCRIPTION + Calls the Remote Workforce extension's EnsureCorrectSessionGroupExists endpoint. The extension + creates its Access session group (name from the SessionGroupName setting, "My Assigned Machines" + by default) with the filter Notes LIKE '*|UserName:' + $USERLOGINNAME + ',*', or repairs an + older group whose filter was missing the trailing comma. Without this group, assignments made + with New-CWCRemoteWorkforceAssignment are not visible to users. + + Idempotent. Requires the Administer permission. + + .EXAMPLE + Initialize-CWCRemoteWorkforceSessionGroup + + .NOTES + Requires the Remote Workforce extension (2c4f522f-b39a-413a-8807-dc52a2fce13e), Control 23.6+. + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> + [CmdletBinding(SupportsShouldProcess)] + param() + + if ($PSCmdlet.ShouldProcess('Remote Workforce session group', 'Initialize-CWCRemoteWorkforceSessionGroup')) { + Invoke-CWCServiceMethod -ExtensionID $script:CWCRemoteWorkforceExtensionID -Method EnsureCorrectSessionGroupExists -Arguments @() -Idempotent + } +} diff --git a/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/New-CWCRemoteWorkforceAssignment.ps1 b/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/New-CWCRemoteWorkforceAssignment.ps1 index 0bba3b9..8035400 100644 --- a/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/New-CWCRemoteWorkforceAssignment.ps1 +++ b/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/New-CWCRemoteWorkforceAssignment.ps1 @@ -9,21 +9,12 @@ function New-CWCRemoteWorkforceAssignment { [string]$Group = 'All Machines' ) - $Endpoint = 'App_Extensions/2c4f522f-b39a-413a-8807-dc52a2fce13e/Service.ashx/AddAssignmentNoteToSession' - - $Body = ConvertTo-Json @( - @($Group), - $GUID, - "UserName:$($Username),UserDisplayName:$($DisplayName)" - ) - Write-Verbose $Body - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - if ($PSCmdlet.ShouldProcess($WebRequestArguments.Body, 'New-CWCRemoteWorkforceAssignment')) { - Invoke-CWCWebRequest -Arguments $WebRequestArguments + if ($PSCmdlet.ShouldProcess("$GUID", "Assign to $Username")) { + # Adds an assignment note: not idempotent, so not retried + Invoke-CWCServiceMethod -ExtensionID $script:CWCRemoteWorkforceExtensionID -Method AddAssignmentNoteToSession -Arguments @( + @($Group), + $GUID, + "UserName:$($Username),UserDisplayName:$($DisplayName)" + ) } } From 6e1d32e2aeae1e0ff6b0af69440683c53dc993d9 Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Tue, 10 Nov 2026 09:03:23 -0700 Subject: [PATCH 05/30] Add unit tests and a live smoke test Pester suites for the module, private helpers and public functions (all HTTP mocked; pass on PS 7 and 5.1), an opt-in live read-only suite, and Tests/Live/Invoke-CWCLiveSmokeTest.ps1 for checks against a real server (event types, write paths, MFA login probe, note cleanup). Co-Authored-By: Claude Opus 5.5 --- Tests/ConnectWiseControlAPI.Live.Tests.ps1 | 295 +++ Tests/ConnectWiseControlAPI.Module.Tests.ps1 | 361 ++++ Tests/ConnectWiseControlAPI.Private.Tests.ps1 | 478 +++++ Tests/ConnectWiseControlAPI.Public.Tests.ps1 | 1717 +++++++++++++++++ Tests/ConnectWiseControlAPI.Tests.ps1 | 15 - Tests/Live/Invoke-CWCLiveSmokeTest.ps1 | 340 ++++ 6 files changed, 3191 insertions(+), 15 deletions(-) create mode 100644 Tests/ConnectWiseControlAPI.Live.Tests.ps1 create mode 100644 Tests/ConnectWiseControlAPI.Module.Tests.ps1 create mode 100644 Tests/ConnectWiseControlAPI.Private.Tests.ps1 create mode 100644 Tests/ConnectWiseControlAPI.Public.Tests.ps1 delete mode 100644 Tests/ConnectWiseControlAPI.Tests.ps1 create mode 100644 Tests/Live/Invoke-CWCLiveSmokeTest.ps1 diff --git a/Tests/ConnectWiseControlAPI.Live.Tests.ps1 b/Tests/ConnectWiseControlAPI.Live.Tests.ps1 new file mode 100644 index 0000000..39fd5d3 --- /dev/null +++ b/Tests/ConnectWiseControlAPI.Live.Tests.ps1 @@ -0,0 +1,295 @@ +#Requires -Module Pester + +<# +.SYNOPSIS + Live integration tests against a real ConnectWise Control server. + +.DESCRIPTION + Read-only tests that verify actual API connectivity, authentication, + and response parsing against a live CWC instance. No data is modified. + + Requires environment variables: + $env:CWC_SERVER - CWC server hostname (e.g. 'control.example.com') + $env:CWC_USER - Username for Basic auth + $env:CWC_PASSWORD - Password for Basic auth + + All tests are skipped when environment variables are not set. + + The module connects once in the top-level BeforeAll and shared read-only + data (Access sessions) is fetched once there. Per-endpoint data is fetched + once in each Describe's BeforeAll and the It blocks assert on the cached + results, keeping the number of network calls to a minimum. + +.NOTES + Run with: + Invoke-Pester Tests\ConnectWiseControlAPI.Live.Tests.ps1 -Output Detailed + + Set environment variables first: + $env:CWC_SERVER = 'control.example.com' + $env:CWC_USER = 'apiuser' + $env:CWC_PASSWORD = 'password' +#> + +BeforeDiscovery { + $script:HasCredentials = [bool]($env:CWC_SERVER -and $env:CWC_USER -and $env:CWC_PASSWORD) +} + +BeforeAll { + $ModuleRoot = Split-Path -Parent $PSScriptRoot + Import-Module "$ModuleRoot\ConnectWiseControlAPI\ConnectWiseControlAPI.psd1" -Force + + # Variables set in BeforeDiscovery do not survive into the Run phase (Pester 5), + # so the credential check must be re-evaluated here for the run-time code paths. + $script:HasCredentials = [bool]($env:CWC_SERVER -and $env:CWC_USER -and $env:CWC_PASSWORD) + if ($script:HasCredentials) { + $script:TestServer = $env:CWC_SERVER + $script:TestCredentials = [PSCredential]::new( + $env:CWC_USER, + ($env:CWC_PASSWORD | ConvertTo-SecureString -AsPlainText -Force) + ) + + # Single connection shared by every Describe + Connect-CWC -Server $script:TestServer -Credentials $script:TestCredentials -Force + + # Access sessions are used by the Session, Session Detail and Last Contact tests + $script:AccessSessionsError = $null + try { + $script:AccessSessions = Get-CWCSession -Type 'Access' + } + catch { + $script:AccessSessionsError = $_ + } + $script:HasSessions = @($script:AccessSessions | Where-Object { $null -ne $_ }).Count -gt 0 + if ($script:HasSessions) { + $script:TestSessionGuid = @($script:AccessSessions)[0].SessionID + } + } +} + +AfterAll { + # Runs once, after every Describe in this file has finished + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection = $null + } + Get-Module 'ConnectWiseControlAPI' -ErrorAction SilentlyContinue | Remove-Module -Force +} + +# ============================================================================= +# Authentication +# ============================================================================= +Describe 'Live: Connect-CWC' -Skip:(-not $script:HasCredentials) { + + BeforeAll { + # Connection state established by the top-level BeforeAll - read once + $module = Get-Module 'ConnectWiseControlAPI' + $script:Connection = & $module { $script:CWCServerConnection } + } + + AfterAll { + # 'rejects invalid credentials' clears the connection - restore it for later Describes + Connect-CWC -Server $script:TestServer -Credentials $script:TestCredentials -Force + } + + It 'authenticates successfully' { + { Connect-CWC -Server $script:TestServer -Credentials $script:TestCredentials -Force } | Should -Not -Throw + } + + It 'sets CWCServerConnection after auth' { + $script:Connection | Should -Not -BeNullOrEmpty + $script:Connection.Server | Should -Not -BeNullOrEmpty + $script:Connection.Headers | Should -Not -BeNullOrEmpty + } + + It 'stores the correct server name' { + $cleanServer = $script:TestServer -replace 'http.*://', '' + $script:Connection.Server | Should -Be $cleanServer + } + + It 'extracts an anti-forgery token' { + $script:Connection.Headers.'x-anti-forgery-token' | Should -Not -BeNullOrEmpty + } + + It 'skips reconnect when already connected' { + # Already connected - call should return quickly without error + { Connect-CWC -Server $script:TestServer -Credentials $script:TestCredentials } | Should -Not -Throw + } + + It 'rejects invalid credentials' { + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection = $null + } + $badCred = [PSCredential]::new('baduser', ('badpass' | ConvertTo-SecureString -AsPlainText -Force)) + $result = Connect-CWC -Server $script:TestServer -Credentials $badCred 2>&1 + $hasError = $result | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] } + $hasError | Should -Not -BeNullOrEmpty + } +} + +# ============================================================================= +# Session Groups (simplest read-only call) +# ============================================================================= +Describe 'Live: Get-CWCSessionGroup' -Skip:(-not $script:HasCredentials) { + + BeforeAll { + $script:Groups = Get-CWCSessionGroup + } + + It 'returns session groups' { + $script:Groups | Should -Not -BeNullOrEmpty + } + + It 'returns an array or collection' { + @($script:Groups).Count | Should -BeGreaterThan 0 + } +} + +# ============================================================================= +# Sessions +# ============================================================================= +Describe 'Live: Get-CWCSession' -Skip:(-not $script:HasCredentials) { + + It 'returns Access sessions without error' { + # Fetched once in the top-level BeforeAll + $script:AccessSessionsError | Should -BeNullOrEmpty + } + + It 'returns Support sessions without error' { + { Get-CWCSession -Type 'Support' } | Should -Not -Throw + } + + It 'returns Meeting sessions without error' { + { Get-CWCSession -Type 'Meeting' } | Should -Not -Throw + } + + It 'accepts a Group parameter' { + { Get-CWCSession -Type 'Access' -Group 'All Machines' } | Should -Not -Throw + } + + It 'accepts a Search parameter' { + { Get-CWCSession -Type 'Access' -Search 'nonexistent-machine-xyz' } | Should -Not -Throw + } + + It 'returns session objects with expected properties' { + if (-not $script:HasSessions) { + Set-ItResult -Inconclusive -Because 'No Access sessions found on server' + return + } + $first = @($script:AccessSessions)[0] + # Sessions should have at minimum a SessionID and Name + $first.PSObject.Properties.Name | Should -Contain 'SessionID' + $first.PSObject.Properties.Name | Should -Contain 'Name' + } +} + +# ============================================================================= +# Session Detail +# ============================================================================= +Describe 'Live: Get-CWCSessionDetail' -Skip:(-not $script:HasCredentials) { + + BeforeAll { + if ($script:HasSessions) { + $script:SessionDetail = Get-CWCSessionDetail -GUID $script:TestSessionGuid + } + } + + # HasSessions is only known at run time, so skip inside each It rather than via -Skip + It 'returns detail for a real session' { + if (-not $script:HasSessions) { Set-ItResult -Skipped -Because 'no sessions'; return } + $script:SessionDetail | Should -Not -BeNullOrEmpty + } + + It 'detail contains Events property' { + if (-not $script:HasSessions) { Set-ItResult -Skipped -Because 'no sessions'; return } + $script:SessionDetail.PSObject.Properties.Name | Should -Contain 'Events' + } + + It 'detail contains Connections property' { + if (-not $script:HasSessions) { Set-ItResult -Skipped -Because 'no sessions'; return } + $script:SessionDetail.PSObject.Properties.Name | Should -Contain 'Connections' + } +} + +# ============================================================================= +# Last Contact +# ============================================================================= +Describe 'Live: Get-CWCLastContact' -Skip:(-not $script:HasCredentials) { + + It 'returns a datetime or null for a real session' { + if (-not $script:HasSessions) { Set-ItResult -Skipped -Because 'no sessions'; return } + $result = Get-CWCLastContact -GUID $script:TestSessionGuid -ErrorAction SilentlyContinue + if ($null -ne $result) { + $result | Should -BeOfType [datetime] + } + } + + It 'returns boolean with Quiet switch' { + if (-not $script:HasSessions) { Set-ItResult -Skipped -Because 'no sessions'; return } + $result = Get-CWCLastContact -GUID $script:TestSessionGuid -Quiet -Seconds 86400 -ErrorAction SilentlyContinue + if ($null -ne $result) { + $result | Should -BeOfType [bool] + } + } +} + +# ============================================================================= +# Audit Service +# ============================================================================= +Describe 'Live: Get-CWCAuditInfo' -Skip:(-not $script:HasCredentials) { + + BeforeAll { + $script:AuditInfoError = $null + try { + $script:AuditInfo = Get-CWCAuditInfo + } + catch { + $script:AuditInfoError = $_ + } + } + + It 'returns audit info without error' { + $script:AuditInfoError | Should -BeNullOrEmpty + } + + It 'returns data' { + $script:AuditInfo | Should -Not -BeNullOrEmpty + } +} + +Describe 'Live: Get-CWCAuditLog' -Skip:(-not $script:HasCredentials) { + + It 'returns audit log for date range without error' { + $end = Get-Date + $start = $end.AddDays(-1) + { Get-CWCAuditLog -StartDate $start -EndDate $end } | Should -Not -Throw + } +} + +# ============================================================================= +# Security Service +# ============================================================================= +Describe 'Live: Get-CWCSecurityConfigurationInfo' -Skip:(-not $script:HasCredentials) { + + BeforeAll { + $script:SecurityConfigError = $null + try { + $script:SecurityConfig = Get-CWCSecurityConfigurationInfo + } + catch { + $script:SecurityConfigError = $_ + } + } + + It 'returns security configuration without error' { + $script:SecurityConfigError | Should -BeNullOrEmpty + } + + It 'contains UserSources' { + $script:SecurityConfig | Should -Not -BeNullOrEmpty + $script:SecurityConfig.PSObject.Properties.Name | Should -Contain 'UserSources' + } + + It 'contains InternalMembershipProvider source' { + $internal = $script:SecurityConfig.UserSources | Where-Object { $_.ResourceKey -eq 'InternalMembershipProvider' } + $internal | Should -Not -BeNullOrEmpty + } +} diff --git a/Tests/ConnectWiseControlAPI.Module.Tests.ps1 b/Tests/ConnectWiseControlAPI.Module.Tests.ps1 new file mode 100644 index 0000000..d0fcaa3 --- /dev/null +++ b/Tests/ConnectWiseControlAPI.Module.Tests.ps1 @@ -0,0 +1,361 @@ +#Requires -Module Pester + +<# +.SYNOPSIS + Module structure, quality, and function validation tests. + +.DESCRIPTION + Tests module manifest, import, exports, function structure, + parameter validation, and ShouldProcess declarations. + +.NOTES + Run with: + Invoke-Pester Tests\ConnectWiseControlAPI.Module.Tests.ps1 -Output Detailed +#> + +BeforeDiscovery { + $ExpectedFunctions = @( + 'Connect-CWC' + 'Get-CWCAuditInfo' + 'Get-CWCAuditLog' + 'Get-CWCSession' + 'Get-CWCSessionDetail' + 'Get-CWCLastContact' + 'Invoke-CWCCommand' + 'Invoke-CWCWake' + 'New-CWCAccessToken' + 'Remove-CWCSession' + 'Update-CWCCustomProperty' + 'Update-CWCSessionName' + 'Get-CWCSecurityConfigurationInfo' + 'New-CWCUser' + 'Remove-CWCUser' + 'Update-CWCUser' + 'Get-CWCSessionGroup' + 'Get-CWCLauncURL' + 'Add-CWCRemoteWorkforceRequiredRole' + 'New-CWCRemoteWorkforceAssignment' + 'Get-CWCRemoteWorkforceLaunchURL' + 'Get-CWCRemoteWorkforceSession' + 'Initialize-CWCRemoteWorkforceSessionGroup' + 'Find-CWCSession' + 'New-CWCSession' + 'Add-CWCSessionNote' + 'Send-CWCSessionMessage' + 'Send-CWCToolboxItem' + 'New-CWCMFA' + ) +} + +BeforeAll { + $ModuleRoot = Split-Path -Parent $PSScriptRoot + $ManifestPath = Join-Path $ModuleRoot 'ConnectWiseControlAPI\ConnectWiseControlAPI.psd1' + Import-Module $ManifestPath -Force +} + +AfterAll { + Get-Module 'ConnectWiseControlAPI' -ErrorAction SilentlyContinue | Remove-Module -Force +} + +# ============================================================================= +# Module Quality Tests +# ============================================================================= +Describe 'Module: ConnectWiseControlAPI' { + + Context 'Module Manifest' { + BeforeAll { + $Manifest = Test-ModuleManifest -Path $ManifestPath -ErrorAction Stop + } + + It 'has a valid module manifest' { + $Manifest | Should -Not -BeNullOrEmpty + } + + It 'has a valid root module' { + $Manifest.RootModule | Should -Be 'ConnectWiseControlAPI.psm1' + } + + It 'has a valid GUID' { + $Manifest.GUID.ToString() | Should -Be 'f94fa996-0f01-4c5c-9cd9-3227728ebacb' + } + + It 'requires PowerShell 3.0 or higher' { + $Manifest.PowerShellVersion | Should -Be '3.0' + } + + It 'has a project URI' { + $Manifest.PrivateData.PSData.ProjectUri | Should -Not -BeNullOrEmpty + } + + It 'exports no cmdlets' { + $Manifest.ExportedCmdlets.Keys | Should -HaveCount 0 + } + } + + Context 'Module Import' { + It 'is loaded in the session' { + $module = Get-Module 'ConnectWiseControlAPI' + $module | Should -Not -BeNullOrEmpty + $module.Name | Should -Be 'ConnectWiseControlAPI' + } + } + + Context 'Exported Functions' { + BeforeAll { + $ExportedFunctions = (Get-Module 'ConnectWiseControlAPI').ExportedFunctions.Keys + } + + It 'exports the expected number of functions' -ForEach @(@{ Expected = $ExpectedFunctions }) { + $ExportedFunctions | Should -HaveCount $Expected.Count + } + + It 'exports <_>' -ForEach $ExpectedFunctions { + $_ | Should -BeIn $ExportedFunctions + } + } + + Context 'Function-to-File Mapping' { + BeforeAll { + $PublicPath = Join-Path $ModuleRoot 'ConnectWiseControlAPI\Public' + $PublicFiles = Get-ChildItem -Path $PublicPath -Filter '*.ps1' -Recurse | + Select-Object -ExpandProperty BaseName + $ExportedFunctions = (Get-Module 'ConnectWiseControlAPI').ExportedFunctions.Keys + } + + It 'has a .ps1 file for each exported function' { + foreach ($function in $ExportedFunctions) { + $function | Should -BeIn $PublicFiles -Because "$function should have a matching .ps1 file" + } + } + + It 'every public .ps1 file corresponds to an exported function' { + foreach ($file in $PublicFiles) { + $file | Should -BeIn $ExportedFunctions -Because "$file.ps1 should be exported" + } + } + } + + Context 'Script-Scope Variables' { + It 'has InternalUserSource set to InternalMembershipProvider' { + $module = Get-Module 'ConnectWiseControlAPI' + $value = & $module { $script:InternalUserSource } + $value | Should -Be 'InternalMembershipProvider' + } + } +} + +# ============================================================================= +# Function Structure Tests +# ============================================================================= +Describe 'Function Structure' { + + Context '<_> has proper structure' -ForEach $ExpectedFunctions { + BeforeAll { + $cmd = Get-Command $_ -Module 'ConnectWiseControlAPI' + } + + It 'is a recognized command' { + $cmd | Should -Not -BeNullOrEmpty + } + + It 'has CmdletBinding attribute' { + $cmd.CmdletBinding | Should -BeTrue + } + } + + Context 'ShouldProcess on destructive functions' { + It '<_> supports ShouldProcess' -ForEach @( + 'Remove-CWCSession' + 'Update-CWCCustomProperty' + 'Update-CWCSessionName' + 'New-CWCUser' + 'Remove-CWCUser' + 'Update-CWCUser' + 'Get-CWCLauncURL' + 'Add-CWCRemoteWorkforceRequiredRole' + 'New-CWCRemoteWorkforceAssignment' + 'Initialize-CWCRemoteWorkforceSessionGroup' + 'New-CWCSession' + 'Add-CWCSessionNote' + 'Send-CWCSessionMessage' + 'Send-CWCToolboxItem' + 'New-CWCMFA' + ) { + $cmd = Get-Command $_ -Module 'ConnectWiseControlAPI' + $cmd.Parameters.Keys | Should -Contain 'WhatIf' -Because "$_ should support -WhatIf" + } + } +} + +# ============================================================================= +# Parameter Validation Tests +# ============================================================================= +Describe 'Parameter Validation' { + + Context 'Connect-CWC parameters' { + BeforeAll { + $cmd = Get-Command Connect-CWC -Module 'ConnectWiseControlAPI' + } + + It 'has mandatory Server parameter' { + $cmd.Parameters['Server'].Attributes.Mandatory | Should -Contain $True + } + + It 'has mandatory Credentials parameter' { + $cmd.Parameters['Credentials'].Attributes.Mandatory | Should -Contain $True + } + + It 'Credentials is type PSCredential' { + $cmd.Parameters['Credentials'].ParameterType.Name | Should -Be 'PSCredential' + } + + It 'has optional Force switch' { + $cmd.Parameters.Keys | Should -Contain 'Force' + $cmd.Parameters['Force'].SwitchParameter | Should -BeTrue + } + } + + Context 'Get-CWCSession parameters' { + BeforeAll { + $cmd = Get-Command Get-CWCSession -Module 'ConnectWiseControlAPI' + } + + It 'has mandatory Type parameter' { + $cmd.Parameters['Type'].Attributes.Mandatory | Should -Contain $True + } + + It 'Type validates to Support, Access, Meeting' { + $validateSet = $cmd.Parameters['Type'].Attributes | Where-Object { $_ -is [System.Management.Automation.ValidateSetAttribute] } + $validateSet.ValidValues | Should -Contain 'Support' + $validateSet.ValidValues | Should -Contain 'Access' + $validateSet.ValidValues | Should -Contain 'Meeting' + $validateSet.ValidValues | Should -HaveCount 3 + } + + It 'has optional Group parameter' { + $cmd.Parameters.Keys | Should -Contain 'Group' + } + } + + Context 'Invoke-CWCCommand parameters' { + BeforeAll { + $cmd = Get-Command Invoke-CWCCommand -Module 'ConnectWiseControlAPI' + } + + It 'has mandatory GUID parameter' { + $cmd.Parameters['GUID'].Attributes.Mandatory | Should -Contain $True + } + + It 'GUID is type guid' { + $cmd.Parameters['GUID'].ParameterType.Name | Should -Be 'Guid' + } + + It 'has optional TimeOut parameter' { + $cmd.Parameters.Keys | Should -Contain 'TimeOut' + $cmd.Parameters['TimeOut'].ParameterType.Name | Should -Be 'Int32' + } + + It 'has optional MaxLength parameter' { + $cmd.Parameters.Keys | Should -Contain 'MaxLength' + $cmd.Parameters['MaxLength'].ParameterType.Name | Should -Be 'Int32' + } + + It 'has PowerShell switch' { + $cmd.Parameters['PowerShell'].SwitchParameter | Should -BeTrue + } + + It 'has NoWait switch' { + $cmd.Parameters['NoWait'].SwitchParameter | Should -BeTrue + } + } + + Context 'Invoke-CWCWake parameters' { + BeforeAll { + $cmd = Get-Command Invoke-CWCWake -Module 'ConnectWiseControlAPI' + } + + It 'has mandatory Type parameter' { + $cmd.Parameters['Type'].Attributes.Mandatory | Should -Contain $True + } + + It 'Type validates to Support, Access only' { + $validateSet = $cmd.Parameters['Type'].Attributes | Where-Object { $_ -is [System.Management.Automation.ValidateSetAttribute] } + $validateSet.ValidValues | Should -Contain 'Support' + $validateSet.ValidValues | Should -Contain 'Access' + $validateSet.ValidValues | Should -HaveCount 2 + } + + It 'GUID accepts array' { + $cmd.Parameters['GUID'].ParameterType.Name | Should -Be 'Guid[]' + } + } + + Context 'New-CWCUser parameters' { + BeforeAll { + $cmd = Get-Command New-CWCUser -Module 'ConnectWiseControlAPI' + } + + It 'has mandatory Credentials parameter' { + $cmd.Parameters['Credentials'].Attributes.Mandatory | Should -Contain $True + } + + It 'has mandatory Email parameter' { + $cmd.Parameters['Email'].Attributes.Mandatory | Should -Contain $True + } + + It 'has optional ForcePassChange parameter' { + $cmd.Parameters.Keys | Should -Contain 'ForcePassChange' + $cmd.Parameters['ForcePassChange'].ParameterType.Name | Should -Be 'Boolean' + } + } + + Context 'Remove-CWCSession parameters' { + BeforeAll { + $cmd = Get-Command Remove-CWCSession -Module 'ConnectWiseControlAPI' + } + + It 'has mandatory GUID parameter' { + $cmd.Parameters['GUID'].Attributes.Mandatory | Should -Contain $True + } + + It 'GUID accepts array' { + $cmd.Parameters['GUID'].ParameterType.Name | Should -Be 'Guid[]' + } + + It 'has mandatory Group parameter' { + $cmd.Parameters['Group'].Attributes.Mandatory | Should -Contain $True + } + } + + Context 'Get-CWCLastContact parameters' { + BeforeAll { + $cmd = Get-Command Get-CWCLastContact -Module 'ConnectWiseControlAPI' + } + + It 'has mandatory GUID parameter' { + $cmd.Parameters['GUID'].Attributes.Mandatory | Should -Contain $True + } + + It 'has Quiet switch' { + $cmd.Parameters['Quiet'].SwitchParameter | Should -BeTrue + } + + It 'Quiet is in parameter set Quiet' { + $cmd.Parameters['Quiet'].ParameterSets.Keys | Should -Contain 'Quiet' + } + } + + Context 'Update-CWCUser parameters' { + BeforeAll { + $cmd = Get-Command Update-CWCUser -Module 'ConnectWiseControlAPI' + } + + It 'has mandatory UserToUpdate parameter' { + $cmd.Parameters['UserToUpdate'].Attributes.Mandatory | Should -Contain $True + } + + It 'Password is type SecureString' { + $cmd.Parameters['Password'].ParameterType.Name | Should -Be 'SecureString' + } + } +} diff --git a/Tests/ConnectWiseControlAPI.Private.Tests.ps1 b/Tests/ConnectWiseControlAPI.Private.Tests.ps1 new file mode 100644 index 0000000..dce04e8 --- /dev/null +++ b/Tests/ConnectWiseControlAPI.Private.Tests.ps1 @@ -0,0 +1,478 @@ +#Requires -Module Pester + +<# +.SYNOPSIS + Mocked tests for private helper functions. + +.DESCRIPTION + Tests Join-Url and Invoke-CWCWebRequest private functions using + InModuleScope and mocked dependencies. + +.NOTES + Run with: + Invoke-Pester Tests\ConnectWiseControlAPI.Private.Tests.ps1 -Output Detailed +#> + +BeforeAll { + $ModuleRoot = Split-Path -Parent $PSScriptRoot + $ManifestPath = Join-Path $ModuleRoot 'ConnectWiseControlAPI\ConnectWiseControlAPI.psd1' + Import-Module $ManifestPath -Force +} + +AfterAll { + Get-Module 'ConnectWiseControlAPI' -ErrorAction SilentlyContinue | Remove-Module -Force +} + +# ============================================================================= +# Join-Url +# ============================================================================= +Describe 'Join-Url' { + + It 'joins base and child path' { + InModuleScope 'ConnectWiseControlAPI' { + $result = Join-Url -Path 'https://server.com' -ChildPath 'Services/Test.ashx' + $result | Should -Be 'https://server.com/Services/Test.ashx' + } + } + + It 'trims trailing slash from Path' { + InModuleScope 'ConnectWiseControlAPI' { + $result = Join-Url -Path 'https://server.com/' -ChildPath 'endpoint' + $result | Should -Be 'https://server.com/endpoint' + } + } + + It 'trims leading slash from ChildPath' { + InModuleScope 'ConnectWiseControlAPI' { + $result = Join-Url -Path 'https://server.com' -ChildPath '/endpoint' + $result | Should -Be 'https://server.com/endpoint' + } + } + + It 'handles both trailing and leading slashes' { + InModuleScope 'ConnectWiseControlAPI' { + $result = Join-Url -Path 'https://server.com/' -ChildPath '/endpoint' + $result | Should -Be 'https://server.com/endpoint' + } + } + + It 'handles multi-segment child paths' { + InModuleScope 'ConnectWiseControlAPI' { + $result = Join-Url -Path 'https://server.com' -ChildPath 'Services/PageService.ashx/GetLiveData' + $result | Should -Be 'https://server.com/Services/PageService.ashx/GetLiveData' + } + } +} + +# ============================================================================= +# Invoke-CWCWebRequest +# ============================================================================= +Describe 'Invoke-CWCWebRequest' { + + BeforeEach { + # Default fake connection in module script scope. Tests that need a + # different state (no connection, custom headers) override it inline. + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection = @{ + Server = 'test.example.com' + Headers = @{ 'Authorization' = 'Basic dGVzdDp0ZXN0' } + } + } + } + + Context 'Connection Check' { + It 'returns error when not connected' { + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection = $null + $result = Invoke-CWCWebRequest -Arguments @{ Endpoint = 'test' } 2>&1 + $result | Should -Match 'Not connected' + } + } + } + + Context 'URI Construction' { + BeforeEach { + Mock Invoke-WebRequest -ModuleName 'ConnectWiseControlAPI' { + [PSCustomObject]@{ + Content = '{"result":"ok"}' + Headers = @{} + } + } + } + + It 'constructs full URI from server and endpoint' { + InModuleScope 'ConnectWiseControlAPI' { + $arguments = @{ Endpoint = 'Services/PageService.ashx/GetLiveData'; Method = 'Post' } + Invoke-CWCWebRequest -Arguments $arguments + Should -Invoke Invoke-WebRequest -Times 1 + $arguments.URI | Should -Be 'https://test.example.com/Services/PageService.ashx/GetLiveData' + } + } + + It 'removes Endpoint key from arguments after constructing URI' { + InModuleScope 'ConnectWiseControlAPI' { + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + Invoke-CWCWebRequest -Arguments $arguments + $arguments.Keys | Should -Not -Contain 'Endpoint' + } + } + + It 'sets UseBasicParsing to true' { + InModuleScope 'ConnectWiseControlAPI' { + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + Invoke-CWCWebRequest -Arguments $arguments + $arguments.UseBasicParsing | Should -BeTrue + } + } + + It 'passes headers from connection state' { + InModuleScope 'ConnectWiseControlAPI' { + $testHeaders = @{ + 'Authorization' = 'Basic dGVzdDp0ZXN0' + 'x-anti-forgery-token' = 'abc123' + } + $script:CWCServerConnection = @{ + Server = 'test.example.com' + Headers = $testHeaders + } + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + Invoke-CWCWebRequest -Arguments $arguments + $arguments.Headers.Authorization | Should -Be 'Basic dGVzdDp0ZXN0' + $arguments.Headers.'x-anti-forgery-token' | Should -Be 'abc123' + } + } + + It 'passes a copy of the headers, not the connection state hashtable' { + InModuleScope 'ConnectWiseControlAPI' { + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + Invoke-CWCWebRequest -Arguments $arguments + [object]::ReferenceEquals($arguments.Headers, $script:CWCServerConnection.Headers) | Should -BeFalse + } + } + } + + Context 'Debug output' { + It 'redacts auth headers in debug output' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest { [PSCustomObject]@{ Content = '{}'; Headers = @{} } } + $script:CWCServerConnection.Headers.'x-anti-forgery-token' = 'antiforgerysecret' + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + $DebugPreference = 'Continue' # not -Debug: PS 5.1 -Debug prompts (Inquire), which fails without a console + $debugOutput = Invoke-CWCWebRequest -Arguments $arguments 5>&1 | Out-String + $debugOutput | Should -Not -Match 'dGVzdDp0ZXN0' + $debugOutput | Should -Not -Match 'antiforgerysecret' + $debugOutput | Should -Match 'redacted' + } + } + } + + Context 'API secret connection' { + BeforeEach { + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection = @{ + Server = 'test.example.com' + AuthType = 'ApiSecret' + ApiSecret = ('topsecretvalue' | ConvertTo-SecureString -AsPlainText -Force) + Headers = @{ 'origin' = 'https://test.example.com' } + } + Mock Invoke-WebRequest { + [PSCustomObject]@{ Content = '[]'; Headers = @{ 'Set-Cookie' = 'x=1' } } + } + } + } + + It 'sends the secret as CTRLAuthHeader on RESTful API Manager endpoints' { + InModuleScope 'ConnectWiseControlAPI' { + $arguments = @{ Endpoint = "App_Extensions/$($script:CWCRestApiExtensionID)/Service.ashx/GetSessionsByFilter"; Method = 'Post' } + Invoke-CWCWebRequest -Arguments $arguments + Should -Invoke Invoke-WebRequest -Times 1 + $arguments.Headers.CTRLAuthHeader | Should -Be 'topsecretvalue' + $arguments.Headers.Keys | Should -Not -Contain 'authorization' + } + } + + It 'never sends a WebSession on API-secret connections' { + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection.WebSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession + $arguments = @{ Endpoint = "App_Extensions/$($script:CWCRestApiExtensionID)/Service.ashx/GetSessionsByFilter"; Method = 'Post' } + Invoke-CWCWebRequest -Arguments $arguments + Should -Invoke Invoke-WebRequest -Times 1 -ParameterFilter { $null -eq $WebSession } + } + } + + It 'does not persist the plaintext secret or cookies in connection state' { + InModuleScope 'ConnectWiseControlAPI' { + $arguments = @{ Endpoint = "App_Extensions/$($script:CWCRestApiExtensionID)/Service.ashx/GetSessionsByFilter"; Method = 'Post' } + Invoke-CWCWebRequest -Arguments $arguments + $script:CWCServerConnection.Headers.Keys | Should -Not -Contain 'CTRLAuthHeader' + $script:CWCServerConnection.Headers.Keys | Should -Not -Contain 'Set-Cookie' + } + } + + It 'redacts the secret in debug output' { + InModuleScope 'ConnectWiseControlAPI' { + $arguments = @{ Endpoint = "App_Extensions/$($script:CWCRestApiExtensionID)/Service.ashx/GetSessionsByFilter"; Method = 'Post' } + $DebugPreference = 'Continue' # not -Debug: PS 5.1 -Debug prompts (Inquire), which fails without a console + $debugOutput = Invoke-CWCWebRequest -Arguments $arguments 5>&1 | Out-String + $debugOutput | Should -Not -Match 'topsecretvalue' + } + } + + It 'does not retry extension calls on HTTP 500 (they are not idempotent)' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Start-Sleep {} + Mock Invoke-WebRequest { + $response = [PSCustomObject]@{ StatusCode = 500 } + $exception = [System.Exception]::new('500') + $exception | Add-Member -NotePropertyName Response -NotePropertyValue $response -Force + throw [System.Management.Automation.ErrorRecord]::new($exception, 'x', 'NotSpecified', $null) + } + $arguments = @{ Endpoint = "App_Extensions/$($script:CWCRestApiExtensionID)/Service.ashx/CreateSession"; Method = 'Post' } + $null = Invoke-CWCWebRequest -Arguments $arguments -WarningAction SilentlyContinue 2>&1 + Should -Invoke Invoke-WebRequest -Times 1 -Exactly + } + } + + It 'refuses non-extension endpoints without calling the server' { + InModuleScope 'ConnectWiseControlAPI' { + $arguments = @{ Endpoint = 'Services/PageService.ashx/GetLiveData'; Method = 'Post' } + $result = Invoke-CWCWebRequest -Arguments $arguments 2>&1 + $result.Exception.Message | Should -Match 'Connect-CWC -Credentials' + Should -Invoke Invoke-WebRequest -Times 0 + } + } + + It 'refuses RESTful API Manager endpoints on a credentials connection' { + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection = @{ + Server = 'test.example.com' + Headers = @{ 'Authorization' = 'Basic dGVzdDp0ZXN0' } + } + $arguments = @{ Endpoint = "App_Extensions/$($script:CWCRestApiExtensionID)/Service.ashx/GetSessionsByFilter"; Method = 'Post' } + $result = Invoke-CWCWebRequest -Arguments $arguments 2>&1 + $result.Exception.Message | Should -Match 'Connect-CWC -ApiSecret' + Should -Invoke Invoke-WebRequest -Times 0 + } + } + } + + Context 'Successful Request' { + It 'returns parsed JSON from response content' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest { + [PSCustomObject]@{ + Content = '{"name":"TestSession","id":42}' + Headers = @{} + } + } + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + $result = Invoke-CWCWebRequest -Arguments $arguments + $result.name | Should -Be 'TestSession' + $result.id | Should -Be 42 + } + } + + It 'returns raw result when OutFile is specified' { + InModuleScope 'ConnectWiseControlAPI' { + $mockResponse = [PSCustomObject]@{ + Content = 'binary-data' + Headers = @{} + } + Mock Invoke-WebRequest { $mockResponse } + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get'; OutFile = 'C:\temp\test.bin' } + $result = Invoke-CWCWebRequest -Arguments $arguments + $result | Should -Be $mockResponse + } + } + + It 'does not store response Set-Cookie as a request header (issue #22)' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest { + [PSCustomObject]@{ + Content = '{"ok":true}' + Headers = @{ 'Set-Cookie' = 'session=abc123; Path=/' } + } + } + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + Invoke-CWCWebRequest -Arguments $arguments + $script:CWCServerConnection.Headers.Keys | Should -Not -Contain 'Set-Cookie' + } + } + + It 'sends the connection WebSession so server cookies go back to the server (issue #22)' { + InModuleScope 'ConnectWiseControlAPI' { + $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession + $script:CWCServerConnection.WebSession = $session + Mock Invoke-WebRequest { [PSCustomObject]@{ Content = '{}'; Headers = @{} } } + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + Invoke-CWCWebRequest -Arguments $arguments + Should -Invoke Invoke-WebRequest -Times 1 -ParameterFilter { [object]::ReferenceEquals($WebSession, $session) } + } + } + + It 'redacts the WebSession in debug output' { + InModuleScope 'ConnectWiseControlAPI' { + $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession + $session.Cookies.Add([System.Net.Cookie]::new('.ASPXAUTH', 'cookiesecretvalue', '/', 'test.example.com')) + $script:CWCServerConnection.WebSession = $session + Mock Invoke-WebRequest { [PSCustomObject]@{ Content = '{}'; Headers = @{} } } + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + $DebugPreference = 'Continue' + $debugOutput = Invoke-CWCWebRequest -Arguments $arguments 5>&1 | Out-String + $debugOutput | Should -Not -Match 'cookiesecretvalue' + } + } + } + + Context 'Retry on HTTP 500' { + BeforeAll { + # Single factory for the fake HTTP 500 error so both retry tests + # exercise the same catch path: [int]$_.Exception.Response.StatusCode -eq 500. + # Stored in module script scope so mock bodies (which run in module scope) can see it. + InModuleScope 'ConnectWiseControlAPI' { + $script:NewHttp500ErrorRecord = { + $exception = [System.Net.WebException]::new('Server Error') + $exception | Add-Member -NotePropertyName Response -NotePropertyValue ([PSCustomObject]@{ StatusCode = 500 }) -Force + [System.Management.Automation.ErrorRecord]::new( + $exception, 'WebError', 'ConnectionError', $null + ) + } + } + } + + AfterAll { + InModuleScope 'ConnectWiseControlAPI' { + Remove-Variable -Name NewHttp500ErrorRecord -Scope Script -ErrorAction SilentlyContinue + } + } + + BeforeEach { + Mock Start-Sleep -ModuleName 'ConnectWiseControlAPI' {} + } + + It 'retries on HTTP 500 and succeeds' { + InModuleScope 'ConnectWiseControlAPI' { + $script:RetryCallCount = 0 + Mock Invoke-WebRequest { + $script:RetryCallCount++ + if ($script:RetryCallCount -lt 3) { + throw (& $script:NewHttp500ErrorRecord) + } + [PSCustomObject]@{ + Content = '{"ok":true}' + Headers = @{} + } + } + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + $result = Invoke-CWCWebRequest -Arguments $arguments -MaxRetry 5 + $result.ok | Should -BeTrue + Should -Invoke Start-Sleep -Times 2 + } + } + + It 'fails after max retries' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest { + throw (& $script:NewHttp500ErrorRecord) + } + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + $result = Invoke-CWCWebRequest -Arguments $arguments -MaxRetry 3 2>&1 + $result | Should -Match 'Max retries hit' + } + } + + It 'does not retry by default (the caller must opt in)' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest { throw (& $script:NewHttp500ErrorRecord) } + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Post' } + $null = Invoke-CWCWebRequest -Arguments $arguments 2>&1 + Should -Invoke Invoke-WebRequest -Times 1 -Exactly + } + } + } +} + +# ============================================================================= +# Invoke-CWCServiceMethod +# ============================================================================= +Describe 'Invoke-CWCServiceMethod' { + + BeforeEach { + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection = @{ + Server = 'test.example.com' + Headers = @{ 'Authorization' = 'Basic dGVzdDp0ZXN0' } + } + $script:ServiceMethodCall = $null + Mock Invoke-CWCWebRequest { + param($Arguments, $MaxRetry, [switch]$SensitiveBody) + $script:ServiceMethodCall = @{ Arguments = $Arguments; MaxRetry = $MaxRetry; SensitiveBody = [bool]$SensitiveBody } + } + } + } + + It 'builds built-in service endpoints' { + InModuleScope 'ConnectWiseControlAPI' { + Invoke-CWCServiceMethod -Service PageService -Method GetEligibleHosts + $script:ServiceMethodCall.Arguments.Endpoint | Should -Be 'Services/PageService.ashx/GetEligibleHosts' + $script:ServiceMethodCall.Arguments.Keys | Should -Not -Contain 'Body' + } + } + + It 'builds RESTful API Manager and other extension endpoints' { + InModuleScope 'ConnectWiseControlAPI' { + Invoke-CWCServiceMethod -RestApi -Method CreateSession -Arguments 1 + $script:ServiceMethodCall.Arguments.Endpoint | Should -Be "App_Extensions/$($script:CWCRestApiExtensionID)/Service.ashx/CreateSession" + Invoke-CWCServiceMethod -ExtensionID $script:CWCRemoteWorkforceExtensionID -Method GetRemoteWorkforceSessions -Arguments @() + $script:ServiceMethodCall.Arguments.Endpoint | Should -Be "App_Extensions/$($script:CWCRemoteWorkforceExtensionID)/Service.ashx/GetRemoteWorkforceSessions" + } + } + + It 'serializes arguments as a JSON array ()' -TestCases @( + @{ Name = 'single value'; Value = (, 'only'); Expected = '["only"]' } + @{ Name = 'empty list'; Value = (, @()); Expected = '[]' } + @{ Name = 'nested group'; Value = (, @(@('Machines'), 'x')); Expected = '[["Machines"],"x"]' } + ) { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ Value = $Value[0]; Expected = $Expected } { + param($Value, $Expected) + Invoke-CWCServiceMethod -Service PageService -Method Test -Arguments $Value + ($script:ServiceMethodCall.Arguments.Body -replace '\s', '') | Should -Be $Expected + } + } + + It 'retries only idempotent calls' { + InModuleScope 'ConnectWiseControlAPI' { + Invoke-CWCServiceMethod -Service PageService -Method AddSessionEvents -Arguments 1 + $script:ServiceMethodCall.MaxRetry | Should -Be 0 + Invoke-CWCServiceMethod -Service PageService -Method GetSessionDetails -Arguments 1 -Idempotent + $script:ServiceMethodCall.MaxRetry | Should -BeGreaterThan 0 + } + } + + It 'keeps sensitive arguments out of verbose output and marks the body sensitive' { + InModuleScope 'ConnectWiseControlAPI' { + $verbose = Invoke-CWCServiceMethod -Service SecurityService -Method SaveUser -Arguments @('user', 'hunter2secret') -Sensitive -Verbose 4>&1 | Out-String + $verbose | Should -Not -Match 'hunter2secret' + $script:ServiceMethodCall.SensitiveBody | Should -BeTrue + } + } + +} + +Describe 'Connection-type mismatch through Invoke-CWCServiceMethod' { + + It 'names the public function the user called, not the private helpers' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest {} + $script:CWCServerConnection = @{ + Server = 'test.example.com' + AuthType = 'ApiSecret' + ApiSecret = ('s' | ConvertTo-SecureString -AsPlainText -Force) + Headers = @{} + } + $result = Get-CWCSessionGroup 2>&1 + ($result | Out-String) | Should -Match 'Get-CWCSessionGroup is not available' + Should -Invoke Invoke-WebRequest -Times 0 + } + } +} diff --git a/Tests/ConnectWiseControlAPI.Public.Tests.ps1 b/Tests/ConnectWiseControlAPI.Public.Tests.ps1 new file mode 100644 index 0000000..3cb22ee --- /dev/null +++ b/Tests/ConnectWiseControlAPI.Public.Tests.ps1 @@ -0,0 +1,1717 @@ +#Requires -Module Pester + +<# +.SYNOPSIS + Mocked behavioral tests for all public functions. + +.DESCRIPTION + Tests all public functions using mocked Invoke-CWCWebRequest + (or Invoke-WebRequest for Connect-CWC) to verify endpoint construction, + body formatting, parameter handling, and ShouldProcess behavior. + +.NOTES + Run with: + Invoke-Pester Tests\ConnectWiseControlAPI.Public.Tests.ps1 -Output Detailed +#> + +BeforeAll { + $ModuleRoot = Split-Path -Parent $PSScriptRoot + $ManifestPath = Join-Path $ModuleRoot 'ConnectWiseControlAPI\ConnectWiseControlAPI.psd1' + Import-Module $ManifestPath -Force + + # Sets a fake, already-connected module state so API functions pass their + # connection check. Called from each API Describe's BeforeEach. + function Set-CWCTestConnection { + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection = @{ + Server = 'test.example.com' + Headers = @{ 'Authorization' = 'Basic dGVzdDp0ZXN0' } + } + } + } + + # Fake RESTful API Manager (Connect-CWC -ApiSecret) connection. + function Set-CWCTestApiSecretConnection { + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection = @{ + Server = 'test.example.com' + AuthType = 'ApiSecret' + ApiSecret = ('secret' | ConvertTo-SecureString -AsPlainText -Force) + Headers = @{ 'origin' = 'https://test.example.com' } + } + } + } +} + +AfterAll { + Get-Module 'ConnectWiseControlAPI' -ErrorAction SilentlyContinue | Remove-Module -Force +} + + +# ============================================================================= +# Authentication +# ============================================================================= +Describe 'Connect-CWC' { + + BeforeEach { + $cred = [PSCredential]::new('user', ('pass' | ConvertTo-SecureString -AsPlainText -Force)) + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection = $null + Mock Invoke-WebRequest { + [PSCustomObject]@{ + Content = 'antiForgeryToken":"testtoken123testtoken123","isUserAdministrator' + } + } + Mock Invoke-CWCWebRequest {} + } + } + + Context 'Validation call' { + It 'validates with GetEligibleHosts (works for non-admin accounts)' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { + param($cred) + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be 'Services/PageService.ashx/GetEligibleHosts' + $Arguments.Method | Should -Be 'Post' + } + Connect-CWC -Server 'server.example.com' -Credentials $cred + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + } + + Context 'Server URL cleanup' { + It 'strips https:// prefix from server' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { + param($cred) + Connect-CWC -Server 'https://server.example.com' -Credentials $cred + $script:CWCServerConnection.Server | Should -Be 'server.example.com' + } + } + + It 'strips http:// prefix from server' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { + param($cred) + Connect-CWC -Server 'http://server.example.com' -Credentials $cred + $script:CWCServerConnection.Server | Should -Be 'server.example.com' + } + } + } + + Context 'Authentication header' { + It 'creates Basic auth header from credentials' { + InModuleScope 'ConnectWiseControlAPI' { + # Distinct credentials so the encoded header is verifiably derived from them + $cred = [PSCredential]::new('testuser', ('testpass' | ConvertTo-SecureString -AsPlainText -Force)) + Connect-CWC -Server 'server.example.com' -Credentials $cred + $expected = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes('testuser:testpass')) + $script:CWCServerConnection.Headers.'authorization' | Should -Be "Basic $expected" + } + } + + It 'sets content-type header' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { + param($cred) + Connect-CWC -Server 'server.example.com' -Credentials $cred + $script:CWCServerConnection.Headers.'content-type' | Should -Be 'application/json; charset=utf-8' + } + } + + It 'sets origin header' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { + param($cred) + Connect-CWC -Server 'server.example.com' -Credentials $cred + $script:CWCServerConnection.Headers.'origin' | Should -Be 'https://server.example.com' + } + } + } + + Context 'Anti-forgery token' { + It 'extracts anti-forgery token from page content' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { + param($cred) + Mock Invoke-WebRequest { + [PSCustomObject]@{ + Content = 'someprefix antiForgeryToken":"mytoken456mytoken456+/=","isUserAdministrator":true' + } + } + Connect-CWC -Server 'server.example.com' -Credentials $cred + $script:CWCServerConnection.Headers.'x-anti-forgery-token' | Should -Be 'mytoken456mytoken456+/=' + } + } + + It 'extracts the token when isUserAdministrator does not follow it (issue #22)' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { + param($cred) + Mock Invoke-WebRequest { + [PSCustomObject]@{ Content = '{"antiForgeryToken":"abcdefghijklmnop1234","userDisplayName":"x"}' } + } + Connect-CWC -Server 'server.example.com' -Credentials $cred + $script:CWCServerConnection.Headers.'x-anti-forgery-token' | Should -Be 'abcdefghijklmnop1234' + } + } + + It 'warns, without echoing page content, when no token is found' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { + param($cred) + Mock Invoke-WebRequest { [PSCustomObject]@{ Content = 'pagesecretcontent' } } + $warnings = Connect-CWC -Server 'server.example.com' -Credentials $cred 3>&1 + ($warnings | Out-String) | Should -Match 'anti-forgery token' + ($warnings | Out-String) | Should -Not -Match 'pagesecretcontent' + $script:CWCServerConnection.Headers.Keys | Should -Not -Contain 'x-anti-forgery-token' + } + } + } + + Context 'Cookies (issue #22)' { + It 'requests the front page with a session variable and stores the WebSession' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { + param($cred) + Connect-CWC -Server 'server.example.com' -Credentials $cred + Should -Invoke Invoke-WebRequest -Times 1 -ParameterFilter { $SessionVariable -eq 'WebSession' } + $script:CWCServerConnection.Keys | Should -Contain 'WebSession' + } + } + } + + Context 'Connection caching' { + + BeforeEach { + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection = @{ + Server = 'existing.server.com' + Headers = @{ 'Authorization' = 'Basic existing' } + } + } + } + + It 'returns early if already connected and Force not set' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { + param($cred) + Connect-CWC -Server 'new.server.com' -Credentials $cred + Should -Invoke Invoke-WebRequest -Times 0 + $script:CWCServerConnection.Server | Should -Be 'existing.server.com' + } + } + + It 'reconnects when Force is set' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { + param($cred) + Connect-CWC -Server 'new.server.com' -Credentials $cred -Force + Should -Invoke Invoke-WebRequest -Times 1 + $script:CWCServerConnection.Server | Should -Be 'new.server.com' + } + } + } + + Context 'Validation failure' { + It 'clears connection state on validation failure' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { + param($cred) + Mock Invoke-CWCWebRequest { throw 'Unauthorized' } + Connect-CWC -Server 'server.example.com' -Credentials $cred -ErrorAction SilentlyContinue + $script:CWCServerConnection | Should -BeNullOrEmpty + } + } + } + + Context 'Connection failure' { + It 'writes error when Invoke-WebRequest fails' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { + param($cred) + Mock Invoke-WebRequest { throw 'Connection refused' } + $result = Connect-CWC -Server 'bad.server.com' -Credentials $cred 2>&1 + $result | Should -Match 'Failed to connect' + } + } + } +} + +# ============================================================================= +# PageService +# ============================================================================= +Describe 'Connect-CWC -ApiSecret' { + + BeforeEach { + $secret = 'topsecretvalue' | ConvertTo-SecureString -AsPlainText -Force + InModuleScope 'ConnectWiseControlAPI' { $script:CWCServerConnection = $null } + } + + It 'validates with the RESTful API Manager and stores an ApiSecret connection' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ secret = $secret } { + param($secret) + Mock Invoke-WebRequest {} + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be 'App_Extensions/2d558935-686a-4bd0-9991-07539f5fe749/Service.ashx/GetSessionBySessionID' + @($Arguments.Body | ConvertFrom-Json) | Should -HaveCount 1 + } + Connect-CWC -Server 'https://server.example.com' -ApiSecret $secret + Should -Invoke Invoke-CWCWebRequest -Times 1 + Should -Invoke Invoke-WebRequest -Times 0 + $script:CWCServerConnection.AuthType | Should -Be 'ApiSecret' + $script:CWCServerConnection.Server | Should -Be 'server.example.com' + $script:CWCServerConnection.ApiSecret | Should -BeOfType [securestring] + $script:CWCServerConnection.Headers.Keys | Should -Not -Contain 'authorization' + $script:CWCServerConnection.Headers.Keys | Should -Not -Contain 'CTRLAuthHeader' + } + } + + It 'clears the connection and errors when validation fails' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ secret = $secret } { + param($secret) + Mock Invoke-CWCWebRequest { throw 'Unauthorized' } + { Connect-CWC -Server 'server.example.com' -ApiSecret $secret -ErrorAction Stop } | Should -Throw '*RESTful API Manager*' + $script:CWCServerConnection | Should -BeNullOrEmpty + } + } + + It 'rejects an empty secret' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest {} + { Connect-CWC -Server 'server.example.com' -ApiSecret (New-Object securestring) } | Should -Throw '*empty*' + Should -Invoke Invoke-CWCWebRequest -Times 0 + } + } + + It 'keeps the previous connection when a -Force reconnect fails' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ secret = $secret } { + param($secret) + $previous = @{ Server = 'old.example.com'; AuthType = 'Credentials'; Headers = @{} } + $script:CWCServerConnection = $previous + Mock Invoke-CWCWebRequest { throw 'Unauthorized' } + Connect-CWC -Server 'new.example.com' -ApiSecret $secret -Force -ErrorAction SilentlyContinue + $script:CWCServerConnection.Server | Should -Be 'old.example.com' + } + } + + It 'warns instead of silently reusing a cached connection of another mode or server' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ secret = $secret } { + param($secret) + $script:CWCServerConnection = @{ Server = 'server.example.com'; Headers = @{} } + Mock Invoke-CWCWebRequest {} + Connect-CWC -Server 'server.example.com' -ApiSecret $secret -WarningVariable warn -WarningAction SilentlyContinue + ($warn -join ' ') | Should -Match '-Force' + Should -Invoke Invoke-CWCWebRequest -Times 0 + } + } + + It 'stores its own copy of the secret and honors -Origin' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ secret = $secret } { + param($secret) + Mock Invoke-CWCWebRequest {} + $callerSecret = $secret.Copy() + Connect-CWC -Server 'server.example.com' -ApiSecret $callerSecret -Origin 'https://app.example.com' + $callerSecret.Dispose() + ConvertFrom-CWCSecureString $script:CWCServerConnection.ApiSecret | Should -Be 'topsecretvalue' + $script:CWCServerConnection.Headers.origin | Should -Be 'https://app.example.com' + } + } + + It 'cannot combine -Credentials and -ApiSecret' { + $cred = [PSCredential]::new('user', ('pass' | ConvertTo-SecureString -AsPlainText -Force)) + { Connect-CWC -Server 's' -Credentials $cred -ApiSecret $secret } | Should -Throw + } +} + +Describe 'Get-CWCSession' { + + BeforeEach { Set-CWCTestConnection } + + It 'calls correct endpoint' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be 'Services/PageService.ashx/GetLiveData' + @{ ResponseInfoMap = @{ HostSessionInfo = @{ Sessions = @() } } } + } + Get-CWCSession -Type 'Access' + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'maps type to session type ' -ForEach @( + @{ Type = 'Support'; Code = 0 } + @{ Type = 'Meeting'; Code = 1 } + @{ Type = 'Access'; Code = 2 } + ) { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ Type = $Type; Code = $Code } { + param($Type, $Code) + Mock Invoke-CWCWebRequest { + param($Arguments) + $body = $Arguments.Body | ConvertFrom-Json + $body[0].HostSessionInfo.sessionType | Should -Be $Code + @{ ResponseInfoMap = @{ HostSessionInfo = @{ Sessions = @() } } } + } + Get-CWCSession -Type $Type + } + } + + It 'passes Group in body' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $body = $Arguments.Body | ConvertFrom-Json + $body[0].HostSessionInfo.sessionGroupPathParts[0] | Should -Be 'Custom Group' + @{ ResponseInfoMap = @{ HostSessionInfo = @{ Sessions = @() } } } + } + Get-CWCSession -Type 'Access' -Group 'Custom Group' + } + } + + It 'passes Search as filter' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $body = $Arguments.Body | ConvertFrom-Json + $body[0].HostSessionInfo.filter | Should -Be 'TestPC' + @{ ResponseInfoMap = @{ HostSessionInfo = @{ Sessions = @() } } } + } + Get-CWCSession -Type 'Access' -Search 'TestPC' + } + } + + It 'returns sessions from response' { + InModuleScope 'ConnectWiseControlAPI' { + $mockSessions = @( + @{ SessionID = 'guid1'; Name = 'PC1' } + @{ SessionID = 'guid2'; Name = 'PC2' } + ) + Mock Invoke-CWCWebRequest { + @{ ResponseInfoMap = @{ HostSessionInfo = @{ Sessions = $mockSessions } } } + } + $result = Get-CWCSession -Type 'Access' + $result | Should -HaveCount 2 + } + } + + It 'uses POST method' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Method | Should -Be 'Post' + @{ ResponseInfoMap = @{ HostSessionInfo = @{ Sessions = @() } } } + } + Get-CWCSession -Type 'Access' + } + } +} + +Describe 'Get-CWCSessionDetail' { + + BeforeEach { Set-CWCTestConnection } + + It 'calls correct endpoint' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be 'Services/PageService.ashx/GetSessionDetails' + @{ Events = @(); Connections = @() } + } + Get-CWCSessionDetail -GUID ([guid]::NewGuid()) + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'passes Group and GUID in body' { + InModuleScope 'ConnectWiseControlAPI' { + $testGuid = [guid]'12345678-1234-1234-1234-123456789abc' + Mock Invoke-CWCWebRequest { + param($Arguments) + $body = $Arguments.Body | ConvertFrom-Json + $body[0] | Should -Be 'Test Group' + $body[1] | Should -Be '12345678-1234-1234-1234-123456789abc' + @{ Events = @(); Connections = @() } + } + Get-CWCSessionDetail -Group 'Test Group' -GUID $testGuid + } + } + + It 'omits the items argument when -Include is not used (server returns All)' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $body = $Arguments.Body | ConvertFrom-Json + $body | Should -HaveCount 2 + } + Get-CWCSessionDetail -GUID ([guid]::NewGuid()) + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'sends SessionDetailsItems flags for -Include ( = )' -TestCases @( + @{ Include = @('Events'); Expected = 8 } + @{ Include = @('Events', 'Connections'); Expected = 24 } + @{ Include = @('SessionInfo', 'GuestScreenshotContent'); Expected = 5 } + @{ Include = @('Events', 'Events'); Expected = 8 } + ) { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ Include = $Include; Expected = $Expected } { + param($Include, $Expected) + $script:ExpectedItems = $Expected + Mock Invoke-CWCWebRequest { + param($Arguments) + $body = $Arguments.Body | ConvertFrom-Json + $body | Should -HaveCount 3 + $body[2] | Should -Be $script:ExpectedItems + } + Get-CWCSessionDetail -GUID ([guid]::NewGuid()) -Include $Include + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } +} + +Describe 'Session detail polling callers' { + + BeforeEach { Set-CWCTestConnection } + + It 'Get-CWCLastContact requests only Events and Connections' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Get-CWCSessionDetail { @{ Events = @(@{ EventType = 10; Time = 0 }); Connections = @() } } + $null = Get-CWCLastContact -GUID ([guid]::NewGuid()) -Quiet + Should -Invoke Get-CWCSessionDetail -Times 1 -ParameterFilter { + ($Include | Sort-Object) -join ',' -eq 'Connections,Events' + } + } + } + + It 'Invoke-CWCCommand polls with Events only' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest {} + Mock Start-Sleep {} + Mock Get-CWCSessionDetail { + @{ Events = @( + @{ EventType = 44; Time = 5000 } + @{ EventType = 70; Time = 1000; Data = 'output' } + ) } + } + $null = Invoke-CWCCommand -GUID ([guid]::NewGuid()) -Command 'hostname' -TimeOut 1000 + Should -Invoke Get-CWCSessionDetail -ParameterFilter { $Include -eq 'Events' } + Should -Invoke Get-CWCSessionDetail -Times 0 -ParameterFilter { -not $Include } + } + } +} + +Describe 'Get-CWCLastContact' { + + BeforeEach { Set-CWCTestConnection } + + It 'returns null and warns when machine not found' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Get-CWCSessionDetail { return $null } + $result = Get-CWCLastContact -GUID ([guid]::NewGuid()) 3>&1 + # The function returns $null for the machine not found case + } + } + + It 'returns true with Quiet when machine is connected' { + InModuleScope 'ConnectWiseControlAPI' { + $epoch = [math]::Floor(((Get-Date).ToUniversalTime() - [datetime]'1970-01-01').TotalSeconds) + Mock Get-CWCSessionDetail { + @{ + Events = @( + @{ EventType = 10; Time = $epoch * 1000; ConnectionID = 'conn1' } + ) + Connections = @() + } + } + $result = Get-CWCLastContact -GUID ([guid]::NewGuid()) -Quiet + $result | Should -BeTrue + } + } + + Context 'Offline machine (event Time = milliseconds since the event)' { + BeforeEach { + InModuleScope 'ConnectWiseControlAPI' { + Mock Get-CWCSessionDetail { + @{ + Events = @( + @{ EventType = 11; Time = 120000; ConnectionID = 'conn1' } + ) + Connections = @() + } + } + } + } + + It 'returns true with Quiet when last contact is within Seconds' { + InModuleScope 'ConnectWiseControlAPI' { + Get-CWCLastContact -GUID ([guid]::NewGuid()) -Quiet -Seconds 300 | Should -BeTrue + } + } + + It 'returns false with Quiet when last contact is older than Seconds' { + InModuleScope 'ConnectWiseControlAPI' { + Get-CWCLastContact -GUID ([guid]::NewGuid()) -Quiet -Seconds 60 | Should -BeFalse + } + } + + It 'returns a local time about two minutes ago' { + InModuleScope 'ConnectWiseControlAPI' { + $result = Get-CWCLastContact -GUID ([guid]::NewGuid()) + $result.Kind | Should -Not -Be ([System.DateTimeKind]::Utc) + ((Get-Date) - $result).TotalSeconds | Should -BeGreaterThan 115 + ((Get-Date) - $result).TotalSeconds | Should -BeLessThan 130 + } + } + } +} + +Describe 'Invoke-CWCCommand' { + + BeforeEach { Set-CWCTestConnection } + + It 'calls AddSessionEvents endpoint' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + if ($Arguments.Endpoint -eq 'Services/PageService.ashx/AddSessionEvents') { + $Arguments.Endpoint | Should -Be 'Services/PageService.ashx/AddSessionEvents' + return $null + } + @{ Events = @(); Connections = @() } + } + Mock Get-CWCSessionDetail { + @{ Events = @(); Connections = @() } + } + Mock Start-Sleep {} + Invoke-CWCCommand -GUID ([guid]::NewGuid()) -Command 'hostname' -NoWait + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'includes #!ps directive when PowerShell switch is used' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + if ($Arguments.Body) { + $Arguments.Body | Should -Match '#!ps' + } + return $null + } + Invoke-CWCCommand -GUID ([guid]::NewGuid()) -Command 'Get-Process' -PowerShell -NoWait + } + } + + It 'includes timeout and maxlength directives' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + if ($Arguments.Body) { + $Arguments.Body | Should -Match '#timeout=5000' + $Arguments.Body | Should -Match '#maxlength=2000' + } + return $null + } + Invoke-CWCCommand -GUID ([guid]::NewGuid()) -Command 'test' -TimeOut 5000 -MaxLength 2000 -NoWait + } + } + + It 'uses EventType 44 for commands' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + if ($Arguments.Body) { + $body = $Arguments.Body | ConvertFrom-Json + $body[1][0].EventType | Should -Be 44 + } + return $null + } + Invoke-CWCCommand -GUID ([guid]::NewGuid()) -Command 'test' -NoWait + } + } + + It 'returns immediately with NoWait' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { return $null } + Mock Get-CWCSessionDetail {} + Invoke-CWCCommand -GUID ([guid]::NewGuid()) -Command 'test' -NoWait + Should -Invoke Get-CWCSessionDetail -Times 0 + } + } +} + +Describe 'Invoke-CWCWake' { + + BeforeEach { Set-CWCTestConnection } + + It 'calls correct endpoint' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be 'Services/PageService.ashx/AddSessionEvents' + } + Invoke-CWCWake -GUID ([guid]::NewGuid()) -Type 'Access' + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'sends one EventType 43 entry per session' { + InModuleScope 'ConnectWiseControlAPI' { + $script:WakeGuids = @([guid]::NewGuid(), [guid]::NewGuid()) + Mock Invoke-CWCWebRequest { + param($Arguments) + $body = $Arguments.Body | ConvertFrom-Json + $body | Should -HaveCount 2 + $body[1] | Should -HaveCount 2 + $body[1].EventType | Should -Be @(43, 43) + $body[1].SessionID | Should -Be ($script:WakeGuids | ForEach-Object { "$_" }) + } + Invoke-CWCWake -GUID $script:WakeGuids -Type 'Access' + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'maps Support to All Sessions group' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $body = $Arguments.Body | ConvertFrom-Json + $body[0] | Should -Be 'All Sessions' + } + Invoke-CWCWake -GUID ([guid]::NewGuid()) -Type 'Support' + } + } + + It 'maps Access to All Machines group' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $body = $Arguments.Body | ConvertFrom-Json + $body[0] | Should -Be 'All Machines' + } + Invoke-CWCWake -GUID ([guid]::NewGuid()) -Type 'Access' + } + } +} + +Describe 'New-CWCAccessToken' { + + BeforeEach { Set-CWCTestConnection } + + It 'calls correct endpoint' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be 'Services/PageService.ashx/GetAccessToken' + 'token123' + } + New-CWCAccessToken -GUID ([guid]::NewGuid()) + } + } + + It 'uses POST method' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Method | Should -Be 'Post' + 'token123' + } + New-CWCAccessToken -GUID ([guid]::NewGuid()) + } + } +} + +Describe 'Remove-CWCSession' { + + BeforeEach { Set-CWCTestConnection } + + It 'calls correct endpoint' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be 'Services/PageService.ashx/AddSessionEvents' + } + Remove-CWCSession -GUID ([guid]::NewGuid()) -Group 'All Machines' -Confirm:$false + } + } + + It 'uses EventType 21' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $body = $Arguments.Body | ConvertFrom-Json + $body[1][0].EventType | Should -Be 21 + } + Remove-CWCSession -GUID ([guid]::NewGuid()) -Group 'All Machines' -Confirm:$false + } + } + + It 'uses EventType 100 (QueuedUninstallAndDelete) with -Uninstall' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $body = $Arguments.Body | ConvertFrom-Json + $body[1][0].EventType | Should -Be 100 + } + Remove-CWCSession -GUID ([guid]::NewGuid()) -Group 'All Machines' -Uninstall -Confirm:$false + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'sends one event entry per session' { + InModuleScope 'ConnectWiseControlAPI' { + $script:RemoveGuids = @([guid]::NewGuid(), [guid]::NewGuid()) + Mock Invoke-CWCWebRequest { + param($Arguments) + $body = $Arguments.Body | ConvertFrom-Json + $body[1] | Should -HaveCount 2 + $body[1].SessionID | Should -Be ($script:RemoveGuids | ForEach-Object { "$_" }) + } + Remove-CWCSession -GUID $script:RemoveGuids -Group 'All Machines' -Confirm:$false + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'does not call API with WhatIf' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest {} + Remove-CWCSession -GUID ([guid]::NewGuid()) -Group 'All Machines' -WhatIf + Should -Invoke Invoke-CWCWebRequest -Times 0 + } + } + + It 'is ConfirmImpact High (prompts by default)' { + $cmd = Get-Command Remove-CWCSession -Module 'ConnectWiseControlAPI' + $binding = $cmd.ScriptBlock.Attributes | Where-Object { $_ -is [System.Management.Automation.CmdletBindingAttribute] } + $binding.ConfirmImpact | Should -Be 'High' + } + + It 'rejects an empty GUID' { + { Remove-CWCSession -GUID ([guid]::Empty) -Group 'All Machines' -Confirm:$false } | Should -Throw + } + + It 'sends a single session as one event entry' { + InModuleScope 'ConnectWiseControlAPI' { + $script:RemoveSessionBody = $null + Mock Invoke-CWCWebRequest { param($Arguments) $script:RemoveSessionBody = $Arguments.Body } + $id = [guid]'11111111-1111-1111-1111-111111111111' + Remove-CWCSession -GUID $id -Group 'All Machines' -Confirm:$false + $parsed = $script:RemoveSessionBody | ConvertFrom-Json + @($parsed[1]).Count | Should -Be 1 + @($parsed[1])[0].SessionID | Should -Be $id.ToString() + @($parsed[1])[0].EventType | Should -Be 21 + } + } +} + +Describe 'Update-CWCCustomProperty' { + + BeforeEach { Set-CWCTestConnection } + + It 'calls correct endpoint' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be 'Services/PageService.ashx/UpdateSessionCustomPropertyValue' + } + Update-CWCCustomProperty -GUID ([guid]::NewGuid()) -Property 1 -Value 'test' -Confirm:$false + } + } + + It 'passes property and value in body' { + InModuleScope 'ConnectWiseControlAPI' { + $testGuid = [guid]'12345678-1234-1234-1234-123456789abc' + Mock Invoke-CWCWebRequest { + param($Arguments) + $body = $Arguments.Body | ConvertFrom-Json + $body[0] | Should -Be 'All Machines' + $body[2] | Should -Be 3 + $body[3] | Should -Be 'custom value' + } + Update-CWCCustomProperty -GUID $testGuid -Property 3 -Value 'custom value' -Confirm:$false + } + } + + It 'does not call API with WhatIf' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest {} + Update-CWCCustomProperty -GUID ([guid]::NewGuid()) -Property 1 -Value 'test' -WhatIf + Should -Invoke Invoke-CWCWebRequest -Times 0 + } + } +} + +Describe 'Update-CWCSessionName' { + + BeforeEach { Set-CWCTestConnection } + + It 'calls correct endpoint' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be 'Services/PageService.ashx/UpdateSessionName' + } + Update-CWCSessionName -GUID ([guid]::NewGuid()) -NewName 'NewPC' -Confirm:$false + } + } + + It 'passes new name in body' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $body = $Arguments.Body | ConvertFrom-Json + $body[2] | Should -Be 'RenamedPC' + } + Update-CWCSessionName -GUID ([guid]::NewGuid()) -NewName 'RenamedPC' -Confirm:$false + } + } + + It 'does not call API with WhatIf' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest {} + Update-CWCSessionName -GUID ([guid]::NewGuid()) -NewName 'test' -WhatIf + Should -Invoke Invoke-CWCWebRequest -Times 0 + } + } +} + +# ============================================================================= +# AuditService +# ============================================================================= +Describe 'Get-CWCAuditInfo' { + + BeforeEach { Set-CWCTestConnection } + + It 'calls correct endpoint' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be 'Services/AuditService.ashx/GetAuditInfo' + @{ AuditTypes = @() } + } + Get-CWCAuditInfo + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'uses POST method' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Method | Should -Be 'Post' + @{} + } + Get-CWCAuditInfo + } + } +} + +Describe 'Get-CWCAuditLog' { + + BeforeEach { Set-CWCTestConnection } + + It 'calls correct endpoint' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be 'Services/AuditService.ashx/QueryAuditLog' + @() + } + Get-CWCAuditLog -StartDate '2024-01-01' -EndDate '2024-01-31' + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'formats dates in body' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Body | Should -Match '2024-01-01' + $Arguments.Body | Should -Match '2024-01-31' + @() + } + Get-CWCAuditLog -StartDate '2024-01-01' -EndDate '2024-01-31' + } + } + + It 'sends the 5 arguments QueryAuditLog expects' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $body = $Arguments.Body | ConvertFrom-Json + $body | Should -HaveCount 5 + @() + } + Get-CWCAuditLog -StartDate '2024-01-01' -EndDate '2024-01-31' -EventTypes 10, 11 -SecurityTypes 1 + } + } + + It 'converts dates to UTC before adding the Z suffix' { + InModuleScope 'ConnectWiseControlAPI' { + $script:AuditStart = Get-Date '2024-01-01T12:00:00' + Mock Invoke-CWCWebRequest { + param($Arguments) + $expected = $script:AuditStart.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ') + $Arguments.Body | Should -Match ([regex]::Escape($expected)) + @() + } + Get-CWCAuditLog -StartDate $script:AuditStart -EndDate $script:AuditStart.AddDays(1) + } + } + + It 'warns that IncludeSessionCaptures is ignored' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { @() } + $warnings = Get-CWCAuditLog -IncludeSessionCaptures 3>&1 + $warnings | Should -Match 'IncludeSessionCaptures' + } + } +} + +# ============================================================================= +# SecurityService +# ============================================================================= +Describe 'Get-CWCSecurityConfigurationInfo' { + + BeforeEach { Set-CWCTestConnection } + + It 'calls correct endpoint' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be 'Services/SecurityService.ashx/GetSecurityConfigurationInfo' + @{ UserSources = @() } + } + Get-CWCSecurityConfigurationInfo + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } +} + +Describe 'New-CWCUser' { + + BeforeEach { Set-CWCTestConnection } + + BeforeEach { + $cred = [PSCredential]::new('newuser', ('pass123' | ConvertTo-SecureString -AsPlainText -Force)) + } + + It 'calls correct endpoint' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { + param($cred) + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be 'Services/SecurityService.ashx/SaveUser' + } + New-CWCUser -Credentials $cred -Email 'test@example.com' -Confirm:$false + } + } + + It 'includes InternalUserSource in body' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { + param($cred) + Mock Invoke-CWCWebRequest { + param($Arguments) + $body = $Arguments.Body | ConvertFrom-Json + $body[0] | Should -Be 'InternalMembershipProvider' + } + New-CWCUser -Credentials $cred -Email 'test@example.com' -Confirm:$false + } + } + + It 'includes username in body' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { + param($cred) + Mock Invoke-CWCWebRequest { + param($Arguments) + $body = $Arguments.Body | ConvertFrom-Json + $body[2] | Should -Be 'newuser' + } + New-CWCUser -Credentials $cred -Email 'test@example.com' -Confirm:$false + } + } + + It 'does not call API with WhatIf' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { + param($cred) + Mock Invoke-CWCWebRequest {} + New-CWCUser -Credentials $cred -Email 'test@example.com' -WhatIf + Should -Invoke Invoke-CWCWebRequest -Times 0 + } + } +} + +Describe 'Remove-CWCUser' { + + BeforeEach { Set-CWCTestConnection } + + It 'calls correct endpoint' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be 'Services/SecurityService.ashx/DeleteUser' + } + Remove-CWCUser -User 'testuser' -Confirm:$false + } + } + + It 'includes InternalUserSource and username in body' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $body = $Arguments.Body | ConvertFrom-Json + $body[0] | Should -Be 'InternalMembershipProvider' + $body[1] | Should -Be 'deleteuser' + } + Remove-CWCUser -User 'deleteuser' -Confirm:$false + } + } + + It 'does not call API with WhatIf' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest {} + Remove-CWCUser -User 'testuser' -WhatIf + Should -Invoke Invoke-CWCWebRequest -Times 0 + } + } +} + +Describe 'Update-CWCUser' { + + BeforeEach { Set-CWCTestConnection } + + It 'fetches current user before updating' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Get-CWCSecurityConfigurationInfo { + @{ + UserSources = @( + @{ + ResourceKey = 'InternalMembershipProvider' + Users = @( + @{ + Name = 'existinguser' + DisplayName = 'Existing' + Email = 'existing@test.com' + PasswordQuestion = '' + RoleNames = @('admin') + } + ) + } + ) + } + } + Mock Invoke-CWCWebRequest {} + Update-CWCUser -UserToUpdate 'existinguser' -Email 'new@test.com' -Confirm:$false + Should -Invoke Get-CWCSecurityConfigurationInfo -Times 1 + } + } + + It 'errors when user not found' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Get-CWCSecurityConfigurationInfo { + @{ + UserSources = @( + @{ + ResourceKey = 'InternalMembershipProvider' + Users = @() + } + ) + } + } + $result = Update-CWCUser -UserToUpdate 'nonexistent' -Confirm:$false 2>&1 + $result | Should -Match 'Unable to find user' + } + } + + It 'does not call API with WhatIf' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Get-CWCSecurityConfigurationInfo { + @{ + UserSources = @( + @{ + ResourceKey = 'InternalMembershipProvider' + Users = @( + @{ + Name = 'testuser' + DisplayName = 'Test' + Email = 'test@test.com' + PasswordQuestion = '' + RoleNames = @() + } + ) + } + ) + } + } + Mock Invoke-CWCWebRequest {} + Update-CWCUser -UserToUpdate 'testuser' -Email 'new@test.com' -WhatIf + Should -Invoke Invoke-CWCWebRequest -Times 0 + } + } + + It 'preserves the existing user comment' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Get-CWCSecurityConfigurationInfo { + @{ + UserSources = @( + @{ + ResourceKey = 'InternalMembershipProvider' + Users = @( + @{ + Name = 'testuser' + DisplayName = 'Test' + Comment = 'keep me' + Email = 'test@test.com' + PasswordQuestion = '' + RoleNames = @() + } + ) + } + ) + } + } + Mock Invoke-CWCWebRequest { + param($Arguments) + $body = $Arguments.Body | ConvertFrom-Json + $body | Should -HaveCount 11 + $body[7] | Should -Be 'keep me' + } + Update-CWCUser -UserToUpdate 'testuser' -Email 'new@test.com' -Confirm:$false + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } +} + +# ============================================================================= +# SessionGroupService +# ============================================================================= +Describe 'Get-CWCSessionGroup' { + + BeforeEach { Set-CWCTestConnection } + + It 'calls correct endpoint' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be 'Services/SessionGroupService.ashx/GetSessionGroups' + @() + } + Get-CWCSessionGroup + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'uses POST method' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Method | Should -Be 'Post' + @() + } + Get-CWCSessionGroup + } + } +} + +# ============================================================================= +# Extensions - Remote Workforce +# Signatures from Remote Workforce 1.3.16 App_Extensions/2c4f522f.../Service.ashx +# ============================================================================= +Describe 'Get-CWCRemoteWorkforceLaunchURL' { + + BeforeEach { Set-CWCTestConnection } + + It 'calls GetLaunchUrlForSessionId with exactly one argument (the session ID)' { + InModuleScope 'ConnectWiseControlAPI' { + $id = [guid]::NewGuid() + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be 'App_Extensions/2c4f522f-b39a-413a-8807-dc52a2fce13e/Service.ashx/GetLaunchUrlForSessionId' + $Arguments.Body.Trim() | Should -Match '^\[' + $body = @($Arguments.Body | ConvertFrom-Json) + $body | Should -HaveCount 1 + 'https://launch.url' + } + Get-CWCRemoteWorkforceLaunchURL -GUID $id | Should -Be 'https://launch.url' + } + } + + It 'makes one request per GUID' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { 'https://launch.url' } + Get-CWCRemoteWorkforceLaunchURL -GUID ([guid]::NewGuid()), ([guid]::NewGuid()) + Should -Invoke Invoke-CWCWebRequest -Times 2 + } + } + + It 'accepts SessionID from the pipeline by property name' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { 'https://launch.url' } + [PSCustomObject]@{ Name = 'PC'; SessionID = [guid]::NewGuid() } | Get-CWCRemoteWorkforceLaunchURL + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'calls GetLaunchUrl with -SessionName' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Match '/GetLaunchUrl$' + @($Arguments.Body | ConvertFrom-Json)[0] | Should -Be 'DESKTOP-01' + 'https://launch.url' + } + Get-CWCRemoteWorkforceLaunchURL -SessionName 'DESKTOP-01' + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'warns and returns nothing when the server returns null' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { $null } + $result = Get-CWCRemoteWorkforceLaunchURL -GUID ([guid]::NewGuid()) -WarningVariable warn -WarningAction SilentlyContinue + $result | Should -BeNullOrEmpty + $warn | Should -Not -BeNullOrEmpty + } + } +} + +Describe 'Get-CWCLauncURL (deprecated)' { + + BeforeEach { Set-CWCTestConnection } + + It 'forwards to GetLaunchUrlForSessionId with one argument and warns' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Match '/GetLaunchUrlForSessionId$' + @($Arguments.Body | ConvertFrom-Json) | Should -HaveCount 1 + 'https://launch.url' + } + $result = Get-CWCLauncURL -GUID ([guid]::NewGuid()) -OnSuccess 'x' -Confirm:$false -WarningVariable warn -WarningAction SilentlyContinue + $result | Should -Be 'https://launch.url' + ($warn -join ' ') | Should -Match 'deprecated' + ($warn -join ' ') | Should -Match 'OnSuccess' + } + } + + It 'does not call API with WhatIf' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest {} + Get-CWCLauncURL -GUID ([guid]::NewGuid()) -WhatIf -WarningAction SilentlyContinue + Should -Invoke Invoke-CWCWebRequest -Times 0 + } + } +} + +Describe 'Get-CWCRemoteWorkforceSession' { + + BeforeEach { Set-CWCTestConnection } + + It 'calls GetRemoteWorkforceSessions and maps the name/ID dictionary to objects' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Match '/GetRemoteWorkforceSessions$' + $Arguments.Body | Should -Be '[]' + '{"PC-1":"11111111-1111-1111-1111-111111111111","PC-2":"22222222-2222-2222-2222-222222222222"}' | ConvertFrom-Json + } + $result = @(Get-CWCRemoteWorkforceSession) + $result | Should -HaveCount 2 + $result[0].Name | Should -Be 'PC-1' + $result[0].SessionID | Should -BeOfType [guid] + } + } +} + +Describe 'Initialize-CWCRemoteWorkforceSessionGroup' { + + BeforeEach { Set-CWCTestConnection } + + It 'calls EnsureCorrectSessionGroupExists with no arguments' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be 'App_Extensions/2c4f522f-b39a-413a-8807-dc52a2fce13e/Service.ashx/EnsureCorrectSessionGroupExists' + $Arguments.Body | Should -Be '[]' + } + Initialize-CWCRemoteWorkforceSessionGroup -Confirm:$false + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'does not call API with WhatIf' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest {} + Initialize-CWCRemoteWorkforceSessionGroup -WhatIf + Should -Invoke Invoke-CWCWebRequest -Times 0 + } + } +} + +Describe 'Add-CWCRemoteWorkforceRequiredRole' { + + BeforeEach { Set-CWCTestConnection } + + It 'calls the extension EnsureRemoteWorkforceSecurityRoleExists endpoint with no arguments' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be 'App_Extensions/2c4f522f-b39a-413a-8807-dc52a2fce13e/Service.ashx/EnsureRemoteWorkforceSecurityRoleExists' + $Arguments.Body | Should -Be '[]' + } + Add-CWCRemoteWorkforceRequiredRole -Confirm:$false + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'does not call API with WhatIf' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest {} + Add-CWCRemoteWorkforceRequiredRole -WhatIf + Should -Invoke Invoke-CWCWebRequest -Times 0 + } + } +} + +Describe 'New-CWCRemoteWorkforceAssignment' { + + BeforeEach { Set-CWCTestConnection } + + It 'calls correct extension endpoint' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be 'App_Extensions/2c4f522f-b39a-413a-8807-dc52a2fce13e/Service.ashx/AddAssignmentNoteToSession' + } + New-CWCRemoteWorkforceAssignment -GUID ([guid]::NewGuid()) -Username 'testuser' -Confirm:$false + } + } + + It 'includes username in assignment data' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Body | Should -Match 'UserName:jdoe' + } + New-CWCRemoteWorkforceAssignment -GUID ([guid]::NewGuid()) -Username 'jdoe' -DisplayName 'John Doe' -Confirm:$false + } + } + + It 'sends AddAssignmentNoteToSession(string[] groupPath, Guid[] sessionIDs, string note)' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $body = $Arguments.Body | ConvertFrom-Json + $body | Should -HaveCount 3 + @($body[0]) | Should -Be @('All Machines') + @($body[1]) | Should -HaveCount 1 + $body[2] | Should -Be 'UserName:jdoe,UserDisplayName:John Doe' + } + New-CWCRemoteWorkforceAssignment -GUID ([guid]::NewGuid()) -Username 'jdoe' -DisplayName 'John Doe' -Confirm:$false + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'does not call API with WhatIf' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest {} + New-CWCRemoteWorkforceAssignment -GUID ([guid]::NewGuid()) -Username 'test' -WhatIf + Should -Invoke Invoke-CWCWebRequest -Times 0 + } + } +} + +# ============================================================================= +# RESTful API Manager (Connect-CWC -ApiSecret) +# Signatures from RESTful API Manager 1.0.9 App_Extensions/2d558935.../Service.ashx +# ============================================================================= +Describe 'API secret routing of existing functions' { + + BeforeEach { Set-CWCTestApiSecretConnection } + + It 'Get-CWCSessionDetail calls GetSessionDetailsBySessionID(Guid)' { + InModuleScope 'ConnectWiseControlAPI' { + $id = [guid]::NewGuid() + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be "App_Extensions/$($script:CWCRestApiExtensionID)/Service.ashx/GetSessionDetailsBySessionID" + $body = @($Arguments.Body | ConvertFrom-Json) + $body | Should -HaveCount 1 + $body[0] | Should -Be $id.ToString() + } + Get-CWCSessionDetail -GUID $id + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'Update-CWCSessionName calls UpdateSessionName(Guid, string)' { + InModuleScope 'ConnectWiseControlAPI' { + $id = [guid]::NewGuid() + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be "App_Extensions/$($script:CWCRestApiExtensionID)/Service.ashx/UpdateSessionName" + $body = $Arguments.Body | ConvertFrom-Json + $body | Should -HaveCount 2 + $body[0] | Should -Be $id.ToString() + $body[1] | Should -Be 'NewName' + } + Update-CWCSessionName -GUID $id -NewName 'NewName' -Confirm:$false + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'Invoke-CWCCommand calls SendCommandToSession(Guid, string)' { + InModuleScope 'ConnectWiseControlAPI' { + $id = [guid]::NewGuid() + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be "App_Extensions/$($script:CWCRestApiExtensionID)/Service.ashx/SendCommandToSession" + $body = $Arguments.Body | ConvertFrom-Json + $body | Should -HaveCount 2 + $body[0] | Should -Be $id.ToString() + $body[1] | Should -Match '#timeout=10000' + $body[1] | Should -Match 'hostname' + } + Invoke-CWCCommand -GUID $id -Command 'hostname' -NoWait + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'Invoke-CWCCommand without -NoWait queues once, warns, and does not poll' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest {} + Mock Get-CWCSessionDetail {} + Invoke-CWCCommand -GUID ([guid]::NewGuid()) -Command 'hostname' -WarningVariable warn -WarningAction SilentlyContinue + Should -Invoke Invoke-CWCWebRequest -Times 1 + Should -Invoke Get-CWCSessionDetail -Times 0 + ($warn -join ' ') | Should -Match 'not retrieved' + } + } + + It 'Get-CWCLastContact fails clearly instead of misreading raw event times' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest {} + { Get-CWCLastContact -GUID ([guid]::NewGuid()) -ErrorAction Stop } | Should -Throw '*Connect-CWC -Credentials*' + Should -Invoke Invoke-CWCWebRequest -Times 0 + } + } + + It 'functions without an extension equivalent fail with a clear error' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest {} + { Get-CWCSession -Type Access -ErrorAction Stop } | Should -Throw '*Connect-CWC -Credentials*' + Should -Invoke Invoke-WebRequest -Times 0 + } + } +} + +Describe 'Find-CWCSession' { + + BeforeEach { Set-CWCTestApiSecretConnection } + + It 'calls GetSessionsByFilter with the filter as the only argument' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be "App_Extensions/$($script:CWCRestApiExtensionID)/Service.ashx/GetSessionsByFilter" + $body = @($Arguments.Body | ConvertFrom-Json) + $body | Should -HaveCount 1 + $body[0] | Should -Be "Name LIKE 'PC*'" + , @([PSCustomObject]@{ Name = 'PC1' }, [PSCustomObject]@{ Name = 'PC2' }) + } + $result = @(Find-CWCSession -Filter "Name LIKE 'PC*'") + $result | Should -HaveCount 2 + } + } + + It 'calls GetSessionsByName with -Name' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be "App_Extensions/$($script:CWCRestApiExtensionID)/Service.ashx/GetSessionsByName" + } + Find-CWCSession -Name 'DESKTOP-01' + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'rejects single quotes in -Name (server does not escape them)' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest {} + { Find-CWCSession -Name "x' OR Name LIKE '*" } | Should -Throw + Should -Invoke Invoke-CWCWebRequest -Times 0 + } + } + + It 'calls GetSessionBySessionID with -GUID' { + InModuleScope 'ConnectWiseControlAPI' { + $id = [guid]::NewGuid() + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be "App_Extensions/$($script:CWCRestApiExtensionID)/Service.ashx/GetSessionBySessionID" + @($Arguments.Body | ConvertFrom-Json)[0] | Should -Be $id.ToString() + } + Find-CWCSession -GUID $id + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } +} + +Describe 'New-CWCSession' { + + BeforeEach { Set-CWCTestApiSecretConnection } + + It 'sends CreateSession(sessionType, name, isPublic, code, customPropertyValues[]) and returns a guid' { + InModuleScope 'ConnectWiseControlAPI' { + $newId = [guid]::NewGuid() + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be "App_Extensions/$($script:CWCRestApiExtensionID)/Service.ashx/CreateSession" + $body = $Arguments.Body | ConvertFrom-Json + $body | Should -HaveCount 5 + $body[0] | Should -Be 2 + $body[1] | Should -Be 'Server01' + $body[2] | Should -BeFalse + $body[3] | Should -Be '' + @($body[4]) | Should -Be @('Acme') + $newId.ToString() + } + New-CWCSession -Type Access -Name 'Server01' -CustomPropertyValues 'Acme' -Confirm:$false | Should -Be $newId + } + } + + It 'sends an empty array when no custom properties are given' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Body | Should -Match '\[\s*\]' + } + New-CWCSession -Type Support -Name 'T1' -Confirm:$false + } + } + + It 'does not call API with WhatIf' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest {} + New-CWCSession -Type Support -Name 'T1' -WhatIf + Should -Invoke Invoke-CWCWebRequest -Times 0 + } + } +} + +Describe 'Session event functions (API secret)' { + + BeforeEach { Set-CWCTestApiSecretConnection } + + It ' sends ()' -ForEach @( + @{ Command = 'Add-CWCSessionNote'; Method = 'AddNoteToSession'; Params = @{ Note = 'hello' }; Expected = @('hello') } + @{ Command = 'Send-CWCSessionMessage'; Method = 'SendMessageToSession'; Params = @{ Message = 'hi'; From = 'IT' }; Expected = @('IT', 'hi') } + @{ Command = 'Send-CWCToolboxItem'; Method = 'SendToolboxItemToSession'; Params = @{ Name = 'Tool.ps1' }; Expected = @('Tool.ps1') } + ) { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ Command = $Command; Method = $Method; Params = $Params; Expected = $Expected } { + param($Command, $Method, $Params, $Expected) + $id = [guid]::NewGuid() + Mock Invoke-CWCWebRequest { + param($Arguments) + $Arguments.Endpoint | Should -Be "App_Extensions/$($script:CWCRestApiExtensionID)/Service.ashx/$Method" + $body = $Arguments.Body | ConvertFrom-Json + $body[0] | Should -Be $id.ToString() + @($body | Select-Object -Skip 1) | Should -Be $Expected + } + & $Command -GUID $id @Params -Confirm:$false + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It '<_> does not call API with WhatIf' -ForEach @('Add-CWCSessionNote', 'Send-CWCSessionMessage', 'Send-CWCToolboxItem') { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ Command = $_ } { + param($Command) + Mock Invoke-CWCWebRequest {} + $params = @{ GUID = [guid]::NewGuid(); WhatIf = $true } + switch ($Command) { + 'Add-CWCSessionNote' { $params.Note = 'n' } + 'Send-CWCSessionMessage' { $params.Message = 'm' } + 'Send-CWCToolboxItem' { $params.Name = 't' } + } + & $Command @params + Should -Invoke Invoke-CWCWebRequest -Times 0 + } + } + +} + +Describe 'Session event functions (credentials)' { + + BeforeEach { Set-CWCTestConnection } + + It ' queues event through PageService.AddSessionEvents' -ForEach @( + @{ Command = 'Add-CWCSessionNote'; Params = @{ Note = 'hello' }; EventType = 32; Data = 'hello' } + @{ Command = 'Send-CWCSessionMessage'; Params = @{ Message = 'hi' }; EventType = 45; Data = 'hi' } + @{ Command = 'Send-CWCToolboxItem'; Params = @{ Name = 'Tool.ps1' }; EventType = 47; Data = 'Tool.ps1' } + ) { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ Command = $Command; Params = $Params; EventType = $EventType; Data = $Data } { + param($Command, $Params, $EventType, $Data) + $id = [guid]::NewGuid() + Mock Invoke-CWCWebRequest { + param($Arguments, $MaxRetry) + $Arguments.Endpoint | Should -Be 'Services/PageService.ashx/AddSessionEvents' + $MaxRetry | Should -Be 0 + $body = $Arguments.Body | ConvertFrom-Json + @($body[0]) | Should -Be @('Servers') + @($body[1]).Count | Should -Be 1 + $body[1][0].SessionID | Should -Be $id.ToString() + $body[1][0].EventType | Should -Be $EventType + $body[1][0].Data | Should -Be $Data + } + & $Command -GUID $id -Group 'Servers' @Params -Confirm:$false + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'Send-CWCSessionMessage warns that -From is ignored' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest {} + Mock Write-Warning {} + Send-CWCSessionMessage -GUID ([guid]::NewGuid()) -Message 'hi' -From 'IT' -Confirm:$false + Should -Invoke Write-Warning -Times 1 -ParameterFilter { $Message -like '*-From*' } + } + } +} + +# ============================================================================= +# Helpers +# ============================================================================= +Describe 'New-CWCMFA' { + + It 'returns object with QR and OTP properties' { + $result = New-CWCMFA -Confirm:$false + $result.PSObject.Properties.Name | Should -Contain 'QR' + $result.PSObject.Properties.Name | Should -Contain 'OTP' + } + + It 'OTP starts with ms: prefix' { + $result = New-CWCMFA -Confirm:$false + $result.OTP | Should -Match '^ms:' + } + + It 'OTP key is 16 characters from Base32 alphabet' { + $result = New-CWCMFA -Confirm:$false + $key = $result.OTP -replace '^ms:', '' + $key.Length | Should -Be 16 + $key | Should -Match '^[A-Z2-7]+$' + } + + It 'QR URL points to quickchart.io' { + $result = New-CWCMFA -Confirm:$false + $result.QR | Should -Match 'quickchart\.io' + } + + It 'QR URL contains otpauth data' { + $result = New-CWCMFA -Confirm:$false + $result.QR | Should -Match 'otpauth' + } + + It 'uses custom DisplayName' { + $result = New-CWCMFA -DisplayName 'MyApp' -Confirm:$false + $result.QR | Should -Match 'MyApp' + } + + It 'does not require server connection' { + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection = $null + } + $result = New-CWCMFA -Confirm:$false + $result | Should -Not -BeNullOrEmpty + } +} diff --git a/Tests/ConnectWiseControlAPI.Tests.ps1 b/Tests/ConnectWiseControlAPI.Tests.ps1 deleted file mode 100644 index 5d681ca..0000000 --- a/Tests/ConnectWiseControlAPI.Tests.ps1 +++ /dev/null @@ -1,15 +0,0 @@ -$ModuleName = 'ConnectWiseControlAPI' -$Verbose = @{} -if($env:APPVEYOR_REPO_BRANCH -and $env:APPVEYOR_REPO_BRANCH -notlike "master") { - $Verbose.add("Verbose",$True) -} - -$PSVersion = $PSVersionTable.PSVersion.Major -Import-Module $PSScriptRoot\..\ConnectWiseControlAPI\$($ModuleName).psm1 -Force - -#Integration test example -Describe "Basic Pester Tests for PS version $PSVersion" { - It 'Do you need to write tests?' { - $true | Should -Be $true - } - } diff --git a/Tests/Live/Invoke-CWCLiveSmokeTest.ps1 b/Tests/Live/Invoke-CWCLiveSmokeTest.ps1 new file mode 100644 index 0000000..fc3ed29 --- /dev/null +++ b/Tests/Live/Invoke-CWCLiveSmokeTest.ps1 @@ -0,0 +1,340 @@ +<# +.SYNOPSIS + Live smoke test against a real Control server. Answers the questions the unit tests can't. + +.DESCRIPTION + Read-only by default. -AllowWrites adds actions on ONE test session you choose (a command, a note, + a message, an optional toolbox item, a wake) and creates + deletes one throwaway Support session. + + Records results (no secrets, no headers) to a JSON file. Run once on PS 7 and once on PS 5.1. + + Questions it answers: + - Connect-CWC works with a ViewSessionGroup-only role (#14) + - Invoke-CWCCommand works over credentials, i.e. anti-forgery/cookies (#22), and queues event 44 / output 70 + - SessionEventType numbers (from the web client scripts, and from events produced by each action) + - The RESTful API Manager's GetSessionDetailsBySessionID event Time format + - PageService.CreateSession + Remove-CWCSession round trip + +.EXAMPLE + ./Tests/Live/Invoke-CWCLiveSmokeTest.ps1 -Server control.example.com -TestSessionID + +.EXAMPLE + ./Tests/Live/Invoke-CWCLiveSmokeTest.ps1 -Server control.example.com -TestSessionID -AllowWrites -ToolboxItem 'Test.ps1' +#> +[CmdletBinding()] +param( + [Parameter(Mandatory = $True)] + [string]$Server, + + # An online Access session you're happy to run 'hostname' on and send a note/message to. + [Parameter(Mandatory = $True)] + [guid]$TestSessionID, + + [string]$Group = 'All Machines', + + [switch]$AllowWrites, + + # Name of an existing toolbox item to send (skipped when empty). + [string]$ToolboxItem, + + # Probe the MFA login flow (#12) with this account: TryLogin with a one-time password, then + # call PageService with only the login cookies + anti-forgery token (no Basic auth). + [string]$MfaUserName, + + # Only delete the notes earlier runs left on the test session, then exit. + [switch]$CleanupOnly, + + [string]$OutputPath ="C:\Temp\cwc-smoke-ps$($PSVersionTable.PSVersion.Major).json" +) + +$ErrorActionPreference = 'Stop' +# Module functions report failures with non-terminating Write-Error; make them fail the step. +$PSDefaultParameterValues['*-CWC*:ErrorAction'] = 'Stop' +Import-Module (Join-Path $PSScriptRoot '..\..\ConnectWiseControlAPI\ConnectWiseControlAPI.psd1') -Force + +$Results = [ordered]@{ + PSVersion = $PSVersionTable.PSVersion.ToString() + StartedUtc = [DateTime]::UtcNow.ToString('o') + AllowWrites = [bool]$AllowWrites + Steps = [ordered]@{} +} + +function Invoke-Step { + param([string]$Name, [scriptblock]$Script) + Write-Host "== $Name" -ForegroundColor Cyan + try { + $Value = & $Script + $Results.Steps[$Name] = [ordered]@{ Ok = $True; Value = $Value } + Write-Host ' ok' -ForegroundColor Green + } + catch { + $Results.Steps[$Name] = [ordered]@{ Ok = $False; Error = "$_" } + Write-Host " FAILED: $_" -ForegroundColor Red + } +} + +function Disconnect-Test { $Module = Get-Module ConnectWiseControlAPI; & $Module { $script:CWCServerConnection = $null } } + +# Events with only the fields we need; Data/Host trimmed so output stays small. +function Select-Event { + param($Events) + $Events | ForEach-Object { + [ordered]@{ + EventType = $_.EventType + Time = $_.Time + TimeType = if ($null -ne $_.Time) { $_.Time.GetType().Name } else { $null } + Host = $_.Host + Data = if ($_.Data) { "$($_.Data)".Substring(0, [math]::Min(80, "$($_.Data)".Length)) } else { $null } + } + } +} + +# Credentials-mode events that appeared since $SinceUtc. +function Get-NewEvent { + param([datetime]$SinceUtc) + $ElapsedMs = ([DateTime]::UtcNow - $SinceUtc).TotalMilliseconds + 500 + $Detail = Get-CWCSessionDetail -Group $Group -GUID $TestSessionID + Select-Event ($Detail.Events | Where-Object { [double]$_.Time -le $ElapsedMs }) +} + +# Deletes every note this script added to the test session (any run). Needs a credentials connection. +# A note is removed by adding a DeletedEvent (SessionEventType 1) correlated to the note's EventID; +# the server checks RemoveNote permission. Returns how many notes were deleted and how many remain. +function Remove-SmokeTestNote { + $NoteType = 32 + $DeletedEventType = 1 + $Events = @((Get-CWCSessionDetail -Group $Group -GUID $TestSessionID).Events) + $AlreadyDeleted = @($Events | Where-Object { $_.EventType -eq $DeletedEventType } | ForEach-Object CorrelationEventID) + $TestNotes = @($Events | Where-Object { + $_.EventType -eq $NoteType -and "$($_.Data)" -like 'CWC smoke test note*' -and $_.EventID -notin $AlreadyDeleted + }) + if ($TestNotes.Count -gt 0) { + $DeleteEntries = @(foreach ($Note in $TestNotes) { + @{ SessionID = "$TestSessionID"; EventType = $DeletedEventType; CorrelationEventID = $Note.EventID } + }) + & (Get-Module ConnectWiseControlAPI) { + param($Group, $DeleteEntries) + $null = Invoke-CWCServiceMethod -Service PageService -Method AddSessionEvents -Arguments @(@($Group), $DeleteEntries) -ErrorAction Stop + } $Group $DeleteEntries + Start-Sleep -Seconds 2 + } + + $Events = @((Get-CWCSessionDetail -Group $Group -GUID $TestSessionID).Events) + $AlreadyDeleted = @($Events | Where-Object { $_.EventType -eq $DeletedEventType } | ForEach-Object CorrelationEventID) + $Remaining = @($Events | Where-Object { + $_.EventType -eq $NoteType -and "$($_.Data)" -like 'CWC smoke test note*' -and $_.EventID -notin $AlreadyDeleted + }).Count + if ($Remaining -gt 0) { throw "$Remaining smoke test note(s) still on session $TestSessionID" } + [ordered]@{ Deleted = $TestNotes.Count; Remaining = $Remaining } +} + +$AdminCredential = Get-Credential -Message 'Admin (non-MFA) Control account' + +if ($CleanupOnly) { + Invoke-Step 'Creds.Connect' { Connect-CWC -Server $Server -Credentials $AdminCredential -Force; 'connected' } + Invoke-Step 'Cleanup.RemoveTestNotes' { Remove-SmokeTestNote } + Disconnect-Test + $Results | ConvertTo-Json -Depth 8 | Set-Content -Path $OutputPath -Encoding UTF8 + Write-Host "`nResults: $OutputPath" -ForegroundColor Yellow + return +} +$LimitedUserName = Read-Host -Prompt 'OPTIONAL: username of an account whose role has only ViewSessionGroup (Enter to skip)' +$LimitedCredential = if ($LimitedUserName) { Get-Credential -UserName $LimitedUserName -Message 'Limited account' } else { $null } +$ApiSecret = Read-Host -AsSecureString -Prompt 'OPTIONAL: RESTful API Manager secret (Enter to skip)' + +#region Credentials, read-only +Invoke-Step 'Creds.Connect' { Connect-CWC -Server $Server -Credentials $AdminCredential -Force; 'connected' } + +Invoke-Step 'Creds.SessionEventTypeEnum' { + # The enum only exists in the web client's scripts; grab the text around each mention. + $Connection = & (Get-Module ConnectWiseControlAPI) { $script:CWCServerConnection } + $Front = Invoke-WebRequest -Uri "https://$Server" -WebSession $Connection.WebSession -UseBasicParsing + $ScriptUrls = [regex]::Matches($Front.Content, ']+src="([^"]+)"') | ForEach-Object { $_.Groups[1].Value } | + Where-Object { $_ -notmatch '^https?://' -or $_ -match [regex]::Escape($Server) } + $Found = @() + foreach ($Url in $ScriptUrls) { + $Absolute = if ($Url -match '^https?://') { $Url } else { "https://$Server/$($Url.TrimStart('/'))" } + $Content = (Invoke-WebRequest -Uri $Absolute -WebSession $Connection.WebSession -UseBasicParsing).Content + if ($Content -is [byte[]]) { $Content = [Text.Encoding]::UTF8.GetString($Content) } + foreach ($Match in [regex]::Matches($Content, 'SessionEventType')) { + $Start = [math]::Max(0, $Match.Index - 100) + $Found += [ordered]@{ Script = ($Url -replace '\?.*$', ''); Text = $Content.Substring($Start, [math]::Min(3000, $Content.Length - $Start)) } + if ($Found.Count -ge 6) { break } + } + if ($Found.Count -ge 6) { break } + } + if (-not $Found) { throw "SessionEventType not found in $(@($ScriptUrls).Count) scripts" } + $Found +} + +Invoke-Step 'Creds.GetSession' { @(Get-CWCSession -Type Access -Group $Group -Limit 5).Count } +Invoke-Step 'Creds.GetSessionDetail' { + $Detail = Get-CWCSessionDetail -Group $Group -GUID $TestSessionID + [ordered]@{ BaseTime = $Detail.BaseTime; Events = @(Select-Event ($Detail.Events | Select-Object -First 15)) } +} +Invoke-Step 'Creds.LastContact' { (Get-CWCLastContact -GUID $TestSessionID -Group $Group).ToString('o') } +#endregion + +#region Limited role (#14) +if ($LimitedCredential) { + Disconnect-Test + Invoke-Step 'Limited.Connect' { Connect-CWC -Server $Server -Credentials $LimitedCredential -Force; 'connected' } + Invoke-Step 'Limited.GetSession' { @(Get-CWCSession -Type Access -Group $Group -Limit 5).Count } +} +#endregion + +#region MFA login probe (#12): raw requests, not module code +if ($MfaUserName) { + $MfaCredential = Get-Credential -UserName $MfaUserName -Message 'MFA account' + $Mfa = @{ Session = $null; Token = $null } + + # Result object with secrets dropped and long strings cut, so it's safe to record. + function Select-LoginResult { + param($LoginResult) + # SecurityOperationResult may come back as a bare enum value (number or string) + if ($null -eq $LoginResult -or $LoginResult -is [ValueType] -or $LoginResult -is [string]) { + return [ordered]@{ Raw = $LoginResult; Type = if ($null -ne $LoginResult) { $LoginResult.GetType().Name } else { 'null' } } + } + $Safe = [ordered]@{} + foreach ($Property in @($LoginResult.PSObject.Properties)) { + if ($Property.Name -match 'nonce|token|secret|password|key') { $Safe[$Property.Name] = ''; continue } + $Value = "$($Property.Value)" + $Safe[$Property.Name] = $Value.Substring(0, [math]::Min(120, $Value.Length)) + } + $Safe + } + + function Get-AntiForgeryToken { + $Page = Invoke-WebRequest -Uri "https://$Server" -WebSession $Mfa.Session -UseBasicParsing + $Match = [regex]::Match($Page.Content, 'antiForgeryToken":"([A-Za-z0-9+/=_-]{16,512})"') + if ($Match.Success) { $Match.Groups[1].Value } else { $null } + } + + function Invoke-MfaRequest { + param([string]$Endpoint, $Arguments) + $Headers = @{ 'content-type' = 'application/json; charset=utf-8'; origin = "https://$Server" } + if ($Mfa.Token) { $Headers['x-anti-forgery-token'] = $Mfa.Token } + $Body = ConvertTo-Json -InputObject @($Arguments) -Depth 10 + (Invoke-WebRequest -Uri "https://$Server/$Endpoint" -Method Post -Headers $Headers -Body $Body -WebSession $Mfa.Session -UseBasicParsing).Content | ConvertFrom-Json + } + + Invoke-Step 'Mfa.FrontPage' { + $null = Invoke-WebRequest -Uri "https://$Server" -UseBasicParsing -SessionVariable 'MfaSession' + $Mfa.Session = $MfaSession + $Mfa.Token = Get-AntiForgeryToken + [ordered]@{ TokenFound = [bool]$Mfa.Token; Cookies = @($Mfa.Session.Cookies.GetCookies("https://$Server") | ForEach-Object Name) } + } + + $Password = $MfaCredential.GetNetworkCredential().Password + Invoke-Step 'Mfa.TryLoginWithoutOtp' { + $LoginResult = Select-LoginResult (Invoke-MfaRequest 'Services/AuthenticationService.ashx/TryLogin' @($MfaUserName, $Password, $null, $False, $null)) + [ordered]@{ Result = $LoginResult; Cookies = @($Mfa.Session.Cookies.GetCookies("https://$Server") | ForEach-Object Name) } + } + Invoke-Step 'Mfa.TryLoginWrongOtp' { + $LoginResult = Select-LoginResult (Invoke-MfaRequest 'Services/AuthenticationService.ashx/TryLogin' @($MfaUserName, $Password, '000000', $False, $null)) + [ordered]@{ Result = $LoginResult; Cookies = @($Mfa.Session.Cookies.GetCookies("https://$Server") | ForEach-Object Name) } + } + + $OneTimePassword = Read-Host -Prompt "One-time password for $MfaUserName (Enter to skip)" + if ($OneTimePassword) { + Invoke-Step 'Mfa.TryLoginWithOtp' { + $LoginResult = Select-LoginResult (Invoke-MfaRequest 'Services/AuthenticationService.ashx/TryLogin' @($MfaUserName, $Password, $OneTimePassword, $False, $null)) + [ordered]@{ Result = $LoginResult; Cookies = @($Mfa.Session.Cookies.GetCookies("https://$Server") | ForEach-Object Name) } + } + Invoke-Step 'Mfa.CookiesAfterLogin' { @($Mfa.Session.Cookies.GetCookies("https://$Server") | ForEach-Object Name) } + + # Anti-forgery tokens may be tied to the logged-in user: compare old and fresh. + Invoke-Step 'Mfa.RefreshToken' { + $OldToken = $Mfa.Token + $Mfa.Token = Get-AntiForgeryToken + [ordered]@{ TokenFound = [bool]$Mfa.Token; ChangedAfterLogin = ($OldToken -ne $Mfa.Token) } + } + Invoke-Step 'Mfa.GetEligibleHosts' { @(Invoke-MfaRequest 'Services/PageService.ashx/GetEligibleHosts' @()).Count } + Invoke-Step 'Mfa.GetSessionDetail' { + $Detail = Invoke-MfaRequest 'Services/PageService.ashx/GetSessionDetails' @($Group, "$TestSessionID") + @($Detail.Events).Count + } + if ($AllowWrites) { + Invoke-Step 'Mfa.AddNote' { + $NoteEvent = @{ SessionID = "$TestSessionID"; EventType = 32; Data = 'CWC smoke test note (MFA login)' } + $null = Invoke-MfaRequest 'Services/PageService.ashx/AddSessionEvents' @(@($Group), @($NoteEvent)) + 'sent' + } + } + } + $Password = $null +} +#endregion + +#region API secret, read-only +if ($ApiSecret.Length -gt 0) { + Disconnect-Test + Invoke-Step 'Api.Connect' { Connect-CWC -Server $Server -ApiSecret $ApiSecret -Force; 'connected' } + Invoke-Step 'Api.FindSession' { @(Find-CWCSession -GUID $TestSessionID).Count } + Invoke-Step 'Api.GetSessionDetail' { + $Detail = Get-CWCSessionDetail -GUID $TestSessionID + [ordered]@{ + TopLevelProperties = @($Detail.PSObject.Properties.Name) + BaseTime = $Detail.BaseTime + Events = @(Select-Event ($Detail.Events | Select-Object -First 15)) + } + } +} +#endregion + +#region Writes +if ($AllowWrites) { + if ($ApiSecret.Length -gt 0) { + # API-secret-only actions; read the resulting event types back over credentials. + $Since = [DateTime]::UtcNow + Invoke-Step 'Api.AddNote' { Add-CWCSessionNote -GUID $TestSessionID -Note 'CWC smoke test note'; 'sent' } + Invoke-Step 'Api.SendMessage' { Send-CWCSessionMessage -GUID $TestSessionID -Message 'CWC smoke test message'; 'sent' } + if ($ToolboxItem) { Invoke-Step 'Api.SendToolboxItem' { Send-CWCToolboxItem -GUID $TestSessionID -Name $ToolboxItem; 'sent' } } + Invoke-Step 'Api.CommandQueue' { Invoke-CWCCommand -GUID $TestSessionID -Command 'hostname' 3>$null; 'queued' } + Start-Sleep -Seconds 5 + Invoke-Step 'Api.EventsAfterActions' { + $Detail = Get-CWCSessionDetail -GUID $TestSessionID + @(Select-Event ($Detail.Events | Select-Object -First 15)) + } + } + + Disconnect-Test + Invoke-Step 'Creds.Reconnect' { Connect-CWC -Server $Server -Credentials $AdminCredential -Force; 'connected' } + if ($ApiSecret.Length -gt 0) { Invoke-Step 'Creds.EventsFromApiActions' { @(Get-NewEvent -SinceUtc $Since) } } + + $Since = [DateTime]::UtcNow + Invoke-Step 'Creds.AddNote' { $null = Add-CWCSessionNote -GUID $TestSessionID -Group $Group -Note 'CWC smoke test note (credentials)'; 'sent' } + Invoke-Step 'Creds.SendMessage' { $null = Send-CWCSessionMessage -GUID $TestSessionID -Group $Group -Message 'CWC smoke test message (credentials)'; 'sent' } + if ($ToolboxItem) { Invoke-Step 'Creds.SendToolboxItem' { $null = Send-CWCToolboxItem -GUID $TestSessionID -Group $Group -Name $ToolboxItem; 'sent' } } + Start-Sleep -Seconds 2 + Invoke-Step 'Creds.EventsFromNoteMessageTool' { @(Get-NewEvent -SinceUtc $Since) } + + $Since = [DateTime]::UtcNow + Invoke-Step 'Creds.InvokeCommand' { Invoke-CWCCommand -GUID $TestSessionID -Group $Group -Command 'hostname' -TimeOut 60000 } + Invoke-Step 'Creds.EventsFromCommand' { @(Get-NewEvent -SinceUtc $Since) } + + $Since = [DateTime]::UtcNow + Invoke-Step 'Creds.Wake' { $null = Invoke-CWCWake -GUID $TestSessionID -Type Access; 'sent' } + Start-Sleep -Seconds 2 + Invoke-Step 'Creds.EventsFromWake' { @(Get-NewEvent -SinceUtc $Since) } + + Invoke-Step 'Creds.CreateAndRemoveSession' { + $Name = "cwc-smoke-$([DateTime]::UtcNow.ToString('yyyyMMddHHmmss'))" + $Created = New-CWCSession -Type Support -Name $Name + $NewID = if ($Created.SessionID) { $Created.SessionID } else { "$Created".Trim('"') } + $FoundAfterCreate = @(Get-CWCSession -Type Support -Group 'All Sessions' -Search $Name).Count + $null = Remove-CWCSession -GUID $NewID -Group 'All Sessions' -Confirm:$False + Start-Sleep -Seconds 2 + $FoundAfterRemove = @(Get-CWCSession -Type Support -Group 'All Sessions' -Search $Name).Count + if ($FoundAfterRemove -ne 0) { throw "Session $NewID ($Name) still listed after Remove-CWCSession; delete it by hand." } + [ordered]@{ Name = $Name; Created = $Created; FoundAfterCreate = $FoundAfterCreate; FoundAfterRemove = $FoundAfterRemove } + } + + # Last: remove the notes this run (and any earlier run) added, including the API-secret and MFA ones. + Invoke-Step 'Cleanup.RemoveTestNotes' { Remove-SmokeTestNote } +} +#endregion + +Disconnect-Test +$Results | ConvertTo-Json -Depth 8 | Set-Content -Path $OutputPath -Encoding UTF8 +Write-Host "`nResults: $OutputPath" -ForegroundColor Yellow From fd0cddbd80a2f88d5022f76974c6323c22e9b1d1 Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Tue, 10 Nov 2026 09:03:23 -0700 Subject: [PATCH 06/30] Bump version to 0.5.0.0; update changelog, readme and contributor notes 0.4.0.0 is already on the PowerShell Gallery (published from 889b56b without a manifest bump), so the next release is 0.5.0.0. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 142 ++++++++++++++++++ CLAUDE.md | 107 +++++++++++++ .../ConnectWiseControlAPI.psd1 | 4 +- README.md | 42 +++++- 4 files changed, 285 insertions(+), 10 deletions(-) create mode 100644 CHANGELOG.md create mode 100644 CLAUDE.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..ca796d9 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,142 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +Planned as 0.5.0.0 (the module manifest already carries this version; 0.4.0.0 is on the PowerShell Gallery). + +### Added + +- GitHub community files: CONTRIBUTING, CODE_OF_CONDUCT, SECURITY, issue templates, PR template +- `.editorconfig` for consistent editor formatting +- `.gitattributes` for line ending normalization and diff drivers +- `.PSScriptAnalyzerSettings.psd1` with 60+ rules targeting PS 5.1+ compatibility +- `CHANGELOG.md` (this file) +- `Connect-CWC -ApiSecret`: second authentication method using the RESTful API Manager extension's + `RESTfulAuthenticationSecret` (sent as `CTRLAuthHeader`). Works with MFA-enforced servers. + `Get-CWCSessionDetail`, `Update-CWCSessionName`, `New-CWCSession`, `Add-CWCSessionNote`, + `Send-CWCSessionMessage`, `Send-CWCToolboxItem` and `Invoke-CWCCommand` work on both connection types + (`Invoke-CWCCommand` queues only on API-secret connections; output is not retrieved); other functions + return an error naming the required auth method. `-Origin` overrides the Origin header for servers + with `RESTfulAllowedOrigin` set +- `Connect-CWC` keeps the previous connection when a `-Force` reconnect fails, and warns when a cached + connection for a different server or auth method is reused +- `Find-CWCSession` (`-Filter`/`-Name`/`-GUID`; API secret only), `New-CWCSession`, + `Add-CWCSessionNote`, `Send-CWCSessionMessage`, `Send-CWCToolboxItem`. On credentials connections the + last three queue session events (AddedNote 32, QueuedMessage 45, QueuedTool 47) and take `-Group` +- Live smoke test script `Tests/Live/Invoke-CWCLiveSmokeTest.ps1` (read-only by default; `-AllowWrites` + acts on one chosen test session and cleans up its notes; `-MfaUserName` probes the MFA login flow) +- `Get-CWCRemoteWorkforceLaunchURL` (by `-GUID`, pipeline, or `-SessionName`), replacing `Get-CWCLauncURL` +- `Get-CWCRemoteWorkforceSession` lists the calling user's assigned machines (`GetRemoteWorkforceSessions`) +- `Initialize-CWCRemoteWorkforceSessionGroup` creates/repairs the extension's session group + (`EnsureCorrectSessionGroupExists`) +- `Remove-CWCSession -Uninstall` queues `QueuedUninstallAndDelete` (event 100) so the Access client is + uninstalled as well; without it the session record is only deleted (`DeletedSession`, event 21) + +### Deprecated + +- `Get-CWCLauncURL` now forwards to `Get-CWCRemoteWorkforceLaunchURL` with a warning; removal in v1.0 + +### Changed + +- Expanded `.gitignore` to cover OS files, IDEs, build artifacts, and secrets +- Updated `README.md` links to use local community files instead of external GitHub-Template references +- `Connect-CWC` validates credentials with `PageService/GetEligibleHosts` (any permission) instead of + `Get-CWCSessionGroup` (requires ManageSessionGroups), so non-admin accounts can connect +- `Get-CWCAuditLog` `-StartDate`/`-EndDate` default to the last 24 hours; `-IncludeSessionCaptures` is + deprecated (the server no longer accepts it) and now only emits a warning +- All API calls go through one internal helper that builds the endpoint and serializes arguments the same + way everywhere (single items, empty lists and nested event entries) +- HTTP 500 retries are limited to calls that are safe to repeat (reads, "set to value" updates). Before, + a 500 returned after the server had acted could queue a second command, wake, delete or user +- Session event type numbers are kept in one table, verified against a live server's web client +- `Remove-CWCSession` prompts by default (`ConfirmImpact = 'High'`), confirms each session separately and + rejects an empty GUID +- `Connect-CWC` reports a failed login with its likely causes. Wrong credentials are not rejected with a + 401: the request runs as an anonymous user and fails with "Needs permission" +- `Get-CWCLastContact` returns an error when no connection event is found, instead of the current time + +### Fixed + +Endpoint calls audited against the Control server's `Services/*.ashx` source: + +- `Invoke-CWCWake` called `PageService.AddEventToSessions`, which no longer exists; it now queues wake + events (type 43) through `AddSessionEvents` +- `Get-CWCAuditLog` sent 6 arguments to `QueryAuditLog`, which takes 5 (the capture flag landed in the + event-type slot); local times were also sent with a `Z` suffix and are now converted to UTC +- `Get-CWCSessionGroup` now calls the documented `GetSessionGroups` (POST) method instead of the + undocumented `session-groups` GET route (both return the same data on Control 26.7.6; not a bug fix) +- `Add-CWCRemoteWorkforceRequiredRole` now calls the extension's own + `EnsureRemoteWorkforceSecurityRoleExists` instead of building the role with `CreateRole`: it is + idempotent, honors the extension's `RoleName`/`SessionGroupName` settings, and sets `IsRoleCreated` +- `Update-CWCUser` erased the user's Comment field on every update +- `Invoke-CWCWebRequest -Debug` printed the Basic auth header and anti-forgery token; auth headers are now redacted +- `-Verbose`/`-Debug` output of `New-CWCUser`/`Update-CWCUser` included the password; request bodies holding + secrets are now redacted +- Cookies set by the server were sent back as a `Set-Cookie` request header, so the server never received + them; credentials connections now keep a web session (likely cause of "Invalid anti-forgery token", #22) +- The anti-forgery token regex depended on JSON key order on the server's front page +- On PS 6+, failed requests left auth headers on the request object kept in `$Error`; they are now stripped +- On PS 5.1, a non-JSON error body (IIS 401/404 page) threw while building the error and hid the real status +- `Get-CWCLastContact -Quiet -Seconds` was off by the local UTC offset (mixed UTC and local DateTimes) +- `Remove-CWCSession` packed multiple GUIDs into a single event entry; it now sends one entry per session +- `Invoke-CWCCommand` polled the rate-limited `GetSessionDetails` once a second for everything, including + the guest screenshot; it now requests events only (`Get-CWCSessionDetail -Include Events`), and + `Get-CWCLastContact` requests events and connections only +- `Get-CWCSessionDetail -Include` selects which parts of the session details to return (SessionDetailsItems + flags: SessionInfo 1, GuestScreenshotContent 4, Events 8, Connections 16, read from the web client) + +Extension calls audited against the Remote Workforce 1.3.16 `App_Extensions/2c4f522f…/Service.ashx` source: + +- `Get-CWCLauncURL` sent 6 arguments to `GetLaunchUrlForSessionId`, which takes 1 (the session ID), + including a plaintext password the server never used +- The `Launcher` extension folder was the Remote Workforce extension; functions moved under `Remote Workforce/` + +## [0.4.0.0] + +Published to the PowerShell Gallery from commit 889b56b; the repository manifest was not bumped at the time. + +### Fixed + +- `Get-CWCSession` uses the `GetLiveData` endpoint (#23) +- Error handling on PowerShell 7 no longer calls `GetResponseStream` (#15) + +## [0.3.5.0] - 2026-02-03 + +### Fixed + +- Retry logic in `Invoke-CWCWebRequest` moved into catch block (was dead code in try block) +- TLS upgraded from 1.0 to 1.2 in module loader +- Credential leak removed from verbose output in `Connect-CWC` +- Password exposure removed from `-WhatIf` output in `New-CWCUser` and `Update-CWCUser` +- SecureString BSTR memory properly zeroed in `Update-CWCUser` +- Error handling added to `Connect-CWC` initial server request +- Swallowed errors fixed in `Invoke-CWCCommand` and `Get-CWCLastContact` (changed `return $_` to `Write-Error`) +- Script-scope error variable leak fixed in `Invoke-CWCWebRequest` +- Undefined variables fixed in `Get-CWCLauncURL` (added as parameters) +- Manual JSON string replaced with `ConvertTo-Json` in `New-CWCAccessToken` +- `$Group` parameter types standardized to `[string]` across all functions +- `ShouldProcess` added to `Add-CWCRemoteWorkforceRequiredRole` +- UTC/local time mixing fixed in epoch calculations in `Get-CWCLastContact` + +## [0.3.4.0] - 2024-01-01 + +### Added + +- `Get-CWCLiveData` function for real-time session data +- Session event support via `AddSessionEvents` endpoint + +### Changed + +- Build configuration updates + +--- + +[Unreleased]: https://github.com/christaylorcodes/ConnectWiseControlAPI/compare/889b56b...HEAD +[0.4.0.0]: https://github.com/christaylorcodes/ConnectWiseControlAPI/commit/889b56b +[0.3.5.0]: https://github.com/christaylorcodes/ConnectWiseControlAPI/compare/v0.3.4.0...v0.3.5.0 +[0.3.4.0]: https://github.com/christaylorcodes/ConnectWiseControlAPI/releases/tag/v0.3.4.0 diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..0aa8f43 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,107 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +ConnectWiseControlAPI is a PowerShell module wrapping the ConnectWise Control (formerly ScreenConnect) web API. It targets PowerShell 3.0+ and is published to the PowerShell Gallery. Used in production by MSPs for remote session management automation. + +- **Repository**: https://github.com/christaylorcodes/ConnectWiseControlAPI +- **Version**: tracked in `ConnectWiseControlAPI/ConnectWiseControlAPI.psd1` (see `CHANGELOG.md`) +- **License**: MIT +- **Auth requirement**: HTTPS + either a non-MFA account with Basic auth (`Connect-CWC -Credentials`) or the RESTful API Manager extension secret (`Connect-CWC -ApiSecret`, subset of functions; `Invoke-CWCWebRequest` enforces which endpoints each mode may call) + +## Development Commands + +```powershell +# Import the module locally for development/testing +Import-Module ./ConnectWiseControlAPI/ConnectWiseControlAPI.psd1 -Force + +# Run all Pester tests +Invoke-Pester -Path ./Tests/ + +# Run tests by tag +Invoke-Pester -Path ./Tests/ -Tag 'Authentication' + +# Validate the module manifest +Test-ModuleManifest ./ConnectWiseControlAPI/ConnectWiseControlAPI.psd1 + +# Regenerate markdown docs (requires PlatyPS module) +Import-Module ./ConnectWiseControlAPI/ConnectWiseControlAPI.psd1 -Force +New-MarkdownHelp -Module ConnectWiseControlAPI -OutputFolder ./Docs -Force +``` + +CI runs on AppVeyor via `Tests/appveyor.pester.ps1`. Unit tests mock all HTTP calls; run them on PS 7 and +Windows PowerShell 5.1. `Tests/Live/Invoke-CWCLiveSmokeTest.ps1` checks behaviour against a real server. + +All API calls go through `Private/Invoke-CWCServiceMethod.ps1` (endpoint, JSON arguments, `-Idempotent` +retry opt-in, `-Sensitive` log redaction), which calls `Private/Invoke-CWCWebRequest.ps1` (transport). +Session event type numbers live in `$script:CWCSessionEventType` (`.psm1`). + +## Architecture + +### Module Loading (`ConnectWiseControlAPI.psm1`) + +The `.psm1` auto-discovers and dot-sources all `.ps1` files under `Public/` and `Private/` recursively. Only `Public/` function basenames are exported via `Export-ModuleMember`. Adding a new `.ps1` file in the right directory is enough for the module to pick it up — but you must also add the function name to `FunctionsToExport` in the `.psd1` manifest. + +The module sets `[Net.ServicePointManager]::SecurityProtocol` to enable TLS and defines `$script:InternalUserSource = 'InternalMembershipProvider'` used by SecurityService functions. + +### Authentication Flow (`Connect-CWC`) + +1. Takes `$Server` (hostname) and `$Credentials` (PSCredential) +2. Builds Basic auth header from credentials +3. Fetches the server's front page to extract an **anti-forgery token** via regex +4. Stores connection state in `$script:CWCServerConnection` (hashtable with `Server` and `Headers` including auth + anti-forgery + cookies) +5. Validates by calling `Get-CWCSessionGroup` + +All public functions check `$script:CWCServerConnection` before making API calls. + +### Centralized API Requests (`Private/Invoke-CWCWebRequest.ps1`) + +Every API call goes through `Invoke-CWCWebRequest`, which: +- Uses `Invoke-WebRequest -UseBasicParsing` for PS version compatibility +- Handles cookie tracking (`Set-Cookie` header updates) +- Implements **retry with exponential backoff** (up to 5 retries on HTTP 500) +- Has version-aware error handling (PS 5 vs PS 6+ handle `.Exception.Response` differently) +- Returns deserialized JSON or saves to file via `-OutFile` + +### Public Function Organization + +Functions are organized by Control API service endpoint: + +| Directory | Service | Key Functions | +|-----------|---------|---------------| +| `Authentication/` | Auth | `Connect-CWC` | +| `PageService/` | Sessions | `Get-CWCSession`, `Invoke-CWCCommand`, `Remove-CWCSession`, etc. | +| `SecurityService/` | Users | `New-CWCUser`, `Update-CWCUser`, `Remove-CWCUser` | +| `AuditService/` | Auditing | `Get-CWCAuditLog`, `Get-CWCAuditInfo` | +| `SessionGroupService/` | Groups | `Get-CWCSessionGroup` | +| `Extensions/` | Add-ons | Remote Workforce, Launcher URL functions | +| `Helpers/` | Utilities | `New-CWCMFA` (MFA token/QR generation) | + +### Adding a New Function + +1. Create `.ps1` in the appropriate `Public/[Service]/` directory +2. Follow the `Verb-CWCNoun` naming convention (PowerShell approved verbs, `CWC` prefix) +3. Check `$script:CWCServerConnection` at the start; use `Invoke-CWCWebRequest` for API calls +4. Add function name to `FunctionsToExport` array in the `.psd1` manifest +5. Use existing functions as templates — `Get-CWCSession.ps1` is a good reference for the pattern + +### URL Construction + +API endpoints follow the pattern: `$script:CWCServerConnection.Server/Services/{ServiceName}.ashx/{MethodName}` + +The `Private/Join-Url` helper joins URL path segments. + +## Code Conventions + +- All public functions require comment-based help (`.SYNOPSIS`, `.DESCRIPTION`, `.PARAMETER`, `.EXAMPLE`, `.NOTES` with version/author/date, `.LINK`) +- Use `[CmdletBinding()]` and parameter validation attributes (`[ValidateNotNullOrEmpty()]`, `[ValidateSet()]`, etc.) +- Return objects, not formatted output +- Use `Write-Error` for non-terminating errors, `throw` for validation failures +- Destructive operations should support `-WhatIf` and `-Confirm` via `[CmdletBinding(SupportsShouldProcess)]` +- Prefer verbose, self-documenting code over abbreviated or clever solutions + +## User Context + +Author preferences and coding standards are maintained at `C:\_Code\CHRIS\CHRIS.md` and `C:\_Code\CHRIS\config\coding_standards.md`. Reference these for style decisions. diff --git a/ConnectWiseControlAPI/ConnectWiseControlAPI.psd1 b/ConnectWiseControlAPI/ConnectWiseControlAPI.psd1 index 0d2f4e0..f550ddf 100644 --- a/ConnectWiseControlAPI/ConnectWiseControlAPI.psd1 +++ b/ConnectWiseControlAPI/ConnectWiseControlAPI.psd1 @@ -12,7 +12,7 @@ RootModule = 'ConnectWiseControlAPI.psm1' # Version number of this module. - ModuleVersion = '0.3.5.0' + ModuleVersion = '0.5.0.0' # Supported PSEditions # CompatiblePSEditions = @() @@ -69,7 +69,7 @@ # NestedModules = @() # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. - FunctionsToExport = @('Get-CWCAuditInfo','Get-CWCAuditLog','Connect-CWC','Get-CWCLauncURL','Add-CWCRemoteWorkforceRequiredRole','New-CWCRemoteWorkforceAssignment','New-CWCMFA','Get-CWCLastContact','Get-CWCSession','Get-CWCSessionDetail','Invoke-CWCCommand','Invoke-CWCWake','New-CWCAccessToken','Remove-CWCSession','Remove-CWCHostFromSession','Update-CWCCustomProperty','Update-CWCSessionName','Get-CWCSecurityConfigurationInfo','New-CWCUser','Remove-CWCUser','Update-CWCUser','Get-CWCSessionGroup') + FunctionsToExport = @('Get-CWCAuditInfo','Get-CWCAuditLog','Connect-CWC','Get-CWCLauncURL','Add-CWCRemoteWorkforceRequiredRole','New-CWCRemoteWorkforceAssignment','Get-CWCRemoteWorkforceLaunchURL','Get-CWCRemoteWorkforceSession','Initialize-CWCRemoteWorkforceSessionGroup','Find-CWCSession','New-CWCSession','Add-CWCSessionNote','Send-CWCSessionMessage','Send-CWCToolboxItem','New-CWCMFA','Get-CWCLastContact','Get-CWCSession','Get-CWCSessionDetail','Invoke-CWCCommand','Invoke-CWCWake','New-CWCAccessToken','Remove-CWCSession','Remove-CWCHostFromSession','Update-CWCCustomProperty','Update-CWCSessionName','Get-CWCSecurityConfigurationInfo','New-CWCUser','Remove-CWCUser','Update-CWCUser','Get-CWCSessionGroup') # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() diff --git a/README.md b/README.md index 2d22e49..ce71aaf 100644 --- a/README.md +++ b/README.md @@ -24,9 +24,9 @@ This is a PowerShell wrapper for ConnectWise Control List of Functions • Examples • Install • - Contribute • - Submit a Bug • - Request a Feature + Contribute • + Submit a Bug • + Request a Feature

@@ -48,17 +48,43 @@ Install-Module 'ConnectWiseControlAPI' ## Requirements -* Requires an account without MFA. Use a complex username and password. - * Requires your Control server to use https. -## [Contributing](https://github.com/christaylorcodes/GitHub-Template/blob/main/CONTRIBUTING.md) +* One of two authentication methods: + + * **Credentials** (`Connect-CWC -Credentials`): an account without MFA. Use a complex username and + password. All functions except `Find-CWCSession` are available, limited by the account's permissions. + + * **API secret** (`Connect-CWC -ApiSecret`): install the **RESTful API Manager** extension and set its + `RESTfulAuthenticationSecret` setting to a long random value. Works when every account requires MFA. + Available functions: `Find-CWCSession`, `New-CWCSession`, `Get-CWCSessionDetail`, + `Update-CWCSessionName`, `Invoke-CWCCommand` (queues the command but does not return its output), + `Add-CWCSessionNote`, `Send-CWCSessionMessage`, `Send-CWCToolboxItem`. The secret bypasses + Control's role permissions and acts on every session, so protect it like an administrator password. + If the extension's `RESTfulAllowedOrigin` setting is set, pass a matching `-Origin`. + + ```powershell + $Secret = Read-Host -AsSecureString -Prompt 'RESTful API secret' + Connect-CWC -Server 'control.example.com' -ApiSecret $Secret + Find-CWCSession -Filter "Name LIKE 'DESKTOP-*'" + ``` + +## Tutorials & Resources + +In-depth tutorials on [christaylor.codes](https://christaylor.codes): + +- [Introducing ConnectWiseControlAPI](https://christaylor.codes/powershell/msp/connectwisecontrolapi/2023/03/15/introducing-connectwisecontrolapi.html) - Module overview and key features +- [Getting Started with ConnectWiseControlAPI](https://christaylor.codes/powershell/msp/connectwisecontrolapi/2023/03/22/getting-started-connectwisecontrolapi.html) - Authentication, setup, and first commands +- [Cleaning Duplicate Control Sessions](https://christaylor.codes/powershell/msp/connectwisecontrolapi/2023/03/29/cleaning-duplicate-control-sessions.html) - Practical session management automation +- [Building PowerShell API Wrappers](https://christaylor.codes/powershell/development/connectwisecontrolapi/2023/12/05/building-powershell-api-wrappers.html) - Design patterns behind the module + +## [Contributing](.github/CONTRIBUTING.md) -If you use this project please give it a star and follow so you can get updated when new features are released. This also lets me know what projects are getting used and what ones I should dedicate more time to. If you want to get more involved please see the [contributing page](https://github.com/christaylorcodes/GitHub-Template/blob/main/CONTRIBUTING.md). Projects need all kinds of help even if you don't know how to code. +If you use this project please give it a star and follow so you can get updated when new features are released. This also lets me know what projects are getting used and what ones I should dedicate more time to. If you want to get more involved please see the [contributing page](.github/CONTRIBUTING.md). Projects need all kinds of help even if you don't know how to code. Want to share something you created using the module? Submit it to be featured as a Community Package. -## [Donating](https://github.com/christaylorcodes/GitHub-Template/blob/main/DONATE.md) +## Donating If you cant take time to contribute maybe you would like to help another way. From 6e3a438287eab498b7218efcc1db1dc4795d58c3 Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Tue, 10 Nov 2026 09:05:54 -0700 Subject: [PATCH 07/30] Clean up stale files and fix the redundant-session example - RemoveRedundantSessions example kept the OLDEST session and deleted newer ones (ascending sort, then Skip 1), and searched an undefined $GroupNameAll. - Remove the empty, never-loaded ConnectWiseControlAPI.Format.ps1xml. - Drop Invoke-CWCWebRequest's OutFile branch; its only caller was commented out. - CLAUDE.md: tighter contributor notes. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 110 ++++-------------- .../ConnectWiseControlAPI.Format.ps1xml | 0 .../Private/Invoke-CWCWebRequest.ps1 | 4 - Examples/RemoveRedundantSessions.ps1 | 5 +- Tests/ConnectWiseControlAPI.Private.Tests.ps1 | 13 --- 5 files changed, 26 insertions(+), 106 deletions(-) delete mode 100644 ConnectWiseControlAPI/ConnectWiseControlAPI.Format.ps1xml diff --git a/CLAUDE.md b/CLAUDE.md index 0aa8f43..e699267 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2,106 +2,42 @@ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. -## Project Overview +## Overview -ConnectWiseControlAPI is a PowerShell module wrapping the ConnectWise Control (formerly ScreenConnect) web API. It targets PowerShell 3.0+ and is published to the PowerShell Gallery. Used in production by MSPs for remote session management automation. +PowerShell module wrapping the ConnectWise Control (ScreenConnect) web API; published to the PowerShell Gallery and used by MSPs. Version lives in `ConnectWiseControlAPI/ConnectWiseControlAPI.psd1` (history in `CHANGELOG.md`). Two auth modes via `Connect-CWC`: -- **Repository**: https://github.com/christaylorcodes/ConnectWiseControlAPI -- **Version**: tracked in `ConnectWiseControlAPI/ConnectWiseControlAPI.psd1` (see `CHANGELOG.md`) -- **License**: MIT -- **Auth requirement**: HTTPS + either a non-MFA account with Basic auth (`Connect-CWC -Credentials`) or the RESTful API Manager extension secret (`Connect-CWC -ApiSecret`, subset of functions; `Invoke-CWCWebRequest` enforces which endpoints each mode may call) +- `-Credentials`: Basic auth, non-MFA account. Reaches the built-in `Services/*.ashx` and extensions. +- `-ApiSecret`: RESTful API Manager extension secret. Reaches only that extension's methods: `Public/RestApi/` functions plus the dual-mode ones (`Get-CWCSessionDetail`, `Update-CWCSessionName`, `Invoke-CWCCommand`), which branch on `Test-CWCApiSecretConnection`. -## Development Commands +## Commands ```powershell -# Import the module locally for development/testing Import-Module ./ConnectWiseControlAPI/ConnectWiseControlAPI.psd1 -Force - -# Run all Pester tests -Invoke-Pester -Path ./Tests/ - -# Run tests by tag -Invoke-Pester -Path ./Tests/ -Tag 'Authentication' - -# Validate the module manifest +Invoke-Pester -Path ./Tests/ # all tests (HTTP is mocked) +Invoke-Pester -Path ./Tests/ConnectWiseControlAPI.Private.Tests.ps1 # one file Test-ModuleManifest ./ConnectWiseControlAPI/ConnectWiseControlAPI.psd1 - -# Regenerate markdown docs (requires PlatyPS module) -Import-Module ./ConnectWiseControlAPI/ConnectWiseControlAPI.psd1 -Force -New-MarkdownHelp -Module ConnectWiseControlAPI -OutputFolder ./Docs -Force +New-MarkdownHelp -Module ConnectWiseControlAPI -OutputFolder ./Docs -Force # PlatyPS, after Import-Module ``` -CI runs on AppVeyor via `Tests/appveyor.pester.ps1`. Unit tests mock all HTTP calls; run them on PS 7 and -Windows PowerShell 5.1. `Tests/Live/Invoke-CWCLiveSmokeTest.ps1` checks behaviour against a real server. - -All API calls go through `Private/Invoke-CWCServiceMethod.ps1` (endpoint, JSON arguments, `-Idempotent` -retry opt-in, `-Sensitive` log redaction), which calls `Private/Invoke-CWCWebRequest.ps1` (transport). -Session event type numbers live in `$script:CWCSessionEventType` (`.psm1`). +Run unit tests on both PS 7 and Windows PowerShell 5.1. `Tests/ConnectWiseControlAPI.Live.Tests.ps1` skips unless `$env:CWC_SERVER`, `CWC_USER` and `CWC_PASSWORD` are set. `Tests/Live/Invoke-CWCLiveSmokeTest.ps1` checks behaviour against a real server (read-only unless `-AllowWrites`). CI is AppVeyor (`Tests/appveyor.pester.ps1`). ## Architecture -### Module Loading (`ConnectWiseControlAPI.psm1`) - -The `.psm1` auto-discovers and dot-sources all `.ps1` files under `Public/` and `Private/` recursively. Only `Public/` function basenames are exported via `Export-ModuleMember`. Adding a new `.ps1` file in the right directory is enough for the module to pick it up — but you must also add the function name to `FunctionsToExport` in the `.psd1` manifest. - -The module sets `[Net.ServicePointManager]::SecurityProtocol` to enable TLS and defines `$script:InternalUserSource = 'InternalMembershipProvider'` used by SecurityService functions. - -### Authentication Flow (`Connect-CWC`) - -1. Takes `$Server` (hostname) and `$Credentials` (PSCredential) -2. Builds Basic auth header from credentials -3. Fetches the server's front page to extract an **anti-forgery token** via regex -4. Stores connection state in `$script:CWCServerConnection` (hashtable with `Server` and `Headers` including auth + anti-forgery + cookies) -5. Validates by calling `Get-CWCSessionGroup` - -All public functions check `$script:CWCServerConnection` before making API calls. - -### Centralized API Requests (`Private/Invoke-CWCWebRequest.ps1`) - -Every API call goes through `Invoke-CWCWebRequest`, which: -- Uses `Invoke-WebRequest -UseBasicParsing` for PS version compatibility -- Handles cookie tracking (`Set-Cookie` header updates) -- Implements **retry with exponential backoff** (up to 5 retries on HTTP 500) -- Has version-aware error handling (PS 5 vs PS 6+ handle `.Exception.Response` differently) -- Returns deserialized JSON or saves to file via `-OutFile` - -### Public Function Organization - -Functions are organized by Control API service endpoint: - -| Directory | Service | Key Functions | -|-----------|---------|---------------| -| `Authentication/` | Auth | `Connect-CWC` | -| `PageService/` | Sessions | `Get-CWCSession`, `Invoke-CWCCommand`, `Remove-CWCSession`, etc. | -| `SecurityService/` | Users | `New-CWCUser`, `Update-CWCUser`, `Remove-CWCUser` | -| `AuditService/` | Auditing | `Get-CWCAuditLog`, `Get-CWCAuditInfo` | -| `SessionGroupService/` | Groups | `Get-CWCSessionGroup` | -| `Extensions/` | Add-ons | Remote Workforce, Launcher URL functions | -| `Helpers/` | Utilities | `New-CWCMFA` (MFA token/QR generation) | - -### Adding a New Function - -1. Create `.ps1` in the appropriate `Public/[Service]/` directory -2. Follow the `Verb-CWCNoun` naming convention (PowerShell approved verbs, `CWC` prefix) -3. Check `$script:CWCServerConnection` at the start; use `Invoke-CWCWebRequest` for API calls -4. Add function name to `FunctionsToExport` array in the `.psd1` manifest -5. Use existing functions as templates — `Get-CWCSession.ps1` is a good reference for the pattern - -### URL Construction - -API endpoints follow the pattern: `$script:CWCServerConnection.Server/Services/{ServiceName}.ashx/{MethodName}` - -The `Private/Join-Url` helper joins URL path segments. +- **Loading**: the `.psm1` dot-sources every `.ps1` under `Public/` and `Private/` and exports the `Public/` basenames, but a new function must also be added to `FunctionsToExport` in the `.psd1`. The `.psm1` also holds the shared constants: `$script:CWCSessionType`, `$script:CWCSessionEventType` (live-verified numbers) and the Remote Workforce and RESTful API Manager extension IDs. +- **Requests**: every public function calls `Private/Invoke-CWCServiceMethod.ps1`. It builds the endpoint (`-Service` → `Services/.ashx/`, `-RestApi` / `-ExtensionID` → `App_Extensions//Service.ashx/`) and sends the arguments as a **positional JSON array** matching the server method's signature. `-Idempotent` turns on retry for HTTP 500 (5 tries with backoff; otherwise none, so commands/notes/deletes never repeat). `-Sensitive` redacts the body from verbose and debug output. +- **Transport**: `Private/Invoke-CWCWebRequest.ps1` checks that a connection exists, **blocks calls that don't match the auth mode** (API-secret connections may only reach the RESTful API Manager), adds auth headers, handles PS 5 vs 6+ error shapes, and returns parsed JSON. +- **Connection state**: `$script:CWCServerConnection` holds `Server`, `AuthType`, and `Headers`. Credentials mode adds a `WebSession` (cookies) and an anti-forgery token taken from the front page. ApiSecret mode sends `CTRLAuthHeader`. Connect-CWC validates the login with a test call and restores the previous connection if that call fails. -## Code Conventions +## Adding a function -- All public functions require comment-based help (`.SYNOPSIS`, `.DESCRIPTION`, `.PARAMETER`, `.EXAMPLE`, `.NOTES` with version/author/date, `.LINK`) -- Use `[CmdletBinding()]` and parameter validation attributes (`[ValidateNotNullOrEmpty()]`, `[ValidateSet()]`, etc.) -- Return objects, not formatted output -- Use `Write-Error` for non-terminating errors, `throw` for validation failures -- Destructive operations should support `-WhatIf` and `-Confirm` via `[CmdletBinding(SupportsShouldProcess)]` -- Prefer verbose, self-documenting code over abbreviated or clever solutions +1. Add `Public//Verb-CWCNoun.ps1` (approved verb, `CWC` prefix). Use `Get-CWCSession.ps1` as the template. +2. Call `Invoke-CWCServiceMethod`. Check the method name and argument order against the server source (see memory). Pass `-Idempotent` only for reads and "set to value" updates. +3. Add the name to `FunctionsToExport` in the `.psd1`. +4. Add mocked Pester tests to `Tests/ConnectWiseControlAPI.Public.Tests.ps1`. -## User Context +## Conventions -Author preferences and coding standards are maintained at `C:\_Code\CHRIS\CHRIS.md` and `C:\_Code\CHRIS\config\coding_standards.md`. Reference these for style decisions. +- Destructive functions use `[CmdletBinding(SupportsShouldProcess)]`. Never pass the request body (it may hold a password) as the `ShouldProcess` target. +- Report errors with `Write-Error` (non-terminating) and let callers decide. Return objects, not formatted output. +- Public functions need comment-based help (`.SYNOPSIS`, `.DESCRIPTION`, `.PARAMETER`, `.EXAMPLE`). Only some functions have it so far; add it to any function you touch. +- Code must run on Windows PowerShell 5.1 (e.g. no `??`, no ternary). diff --git a/ConnectWiseControlAPI/ConnectWiseControlAPI.Format.ps1xml b/ConnectWiseControlAPI/ConnectWiseControlAPI.Format.ps1xml deleted file mode 100644 index e69de29..0000000 diff --git a/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 b/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 index 2f213a4..aacab0b 100644 --- a/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 +++ b/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 @@ -141,9 +141,5 @@ } } - # OutFile: the response body was saved to disk (used by WIP/Invoke-CWCSession) - if ($Arguments.OutFile) { - return $Result - } return $Result.content | ConvertFrom-Json } \ No newline at end of file diff --git a/Examples/RemoveRedundantSessions.ps1 b/Examples/RemoveRedundantSessions.ps1 index 440ef1d..242f807 100644 --- a/Examples/RemoveRedundantSessions.ps1 +++ b/Examples/RemoveRedundantSessions.ps1 @@ -27,11 +27,12 @@ Import-Module 'ConnectWiseControlAPI' Connect-CWC -Server $Server -Credentials $Credentials # Search for multiple sessions for the same machine, and collect all but the last connected one -$RedundantSessionColl = Get-CWCSession -Type Access -Group $GroupNameAll | +$RedundantSessionColl = Get-CWCSession -Type Access -Group $GroupName | Group-Object -Property Name | Where-Object -Property Count -gt 1 | ForEach-Object { - $_.Group | Sort-Object -Property LastConnectedEventTime | + # Newest first, so Skip 1 keeps the most recently connected session + $_.Group | Sort-Object -Property LastConnectedEventTime -Descending | Select-Object -Skip 1 } diff --git a/Tests/ConnectWiseControlAPI.Private.Tests.ps1 b/Tests/ConnectWiseControlAPI.Private.Tests.ps1 index dce04e8..b6196dc 100644 --- a/Tests/ConnectWiseControlAPI.Private.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Private.Tests.ps1 @@ -272,19 +272,6 @@ Describe 'Invoke-CWCWebRequest' { } } - It 'returns raw result when OutFile is specified' { - InModuleScope 'ConnectWiseControlAPI' { - $mockResponse = [PSCustomObject]@{ - Content = 'binary-data' - Headers = @{} - } - Mock Invoke-WebRequest { $mockResponse } - $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get'; OutFile = 'C:\temp\test.bin' } - $result = Invoke-CWCWebRequest -Arguments $arguments - $result | Should -Be $mockResponse - } - } - It 'does not store response Set-Cookie as a request header (issue #22)' { InModuleScope 'ConnectWiseControlAPI' { Mock Invoke-WebRequest { From e2063cc55e4bc094df9ae7dab15fad0d51b0d6bb Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Tue, 10 Nov 2026 09:11:17 -0700 Subject: [PATCH 08/30] Regenerate markdown and MAML help PlatyPS update of Docs/ (adds the 8 functions that had no page, refreshes parameter sets such as Connect-CWC -ApiSecret), fills the remaining placeholder descriptions, strips the PS 7.4 -ProgressAction parameter PlatyPS leaks in, removes Docs/Private (internal helpers, outdated), and rebuilds en-US/ConnectWiseControlAPI-help.xml (last built 2023). Adds comment-based help to New-CWCAccessToken. Co-Authored-By: Claude Opus 5.5 --- .../Public/PageService/New-CWCAccessToken.ps1 | 25 + .../en-US/ConnectWiseControlAPI-help.xml | 3471 ++++++++++++----- ConnectWiseControlAPI_Functions.md | 29 +- Docs/Add-CWCRemoteWorkforceRequiredRole.md | 36 +- Docs/Add-CWCSessionNote.md | 131 + Docs/Connect-CWC.md | 65 +- Docs/Find-CWCSession.md | 115 + Docs/Get-CWCAuditInfo.md | 1 + Docs/Get-CWCAuditLog.md | 13 +- Docs/Get-CWCLastContact.md | 1 + Docs/Get-CWCLauncURL.md | 132 +- Docs/Get-CWCRemoteWorkforceLaunchURL.md | 101 + Docs/Get-CWCRemoteWorkforceSession.md | 53 + Docs/Get-CWCSecurityConfigurationInfo.md | 1 + Docs/Get-CWCSession.md | 18 +- Docs/Get-CWCSessionDetail.md | 19 +- Docs/Get-CWCSessionGroup.md | 1 + ...itialize-CWCRemoteWorkforceSessionGroup.md | 87 + Docs/Invoke-CWCCommand.md | 3 +- Docs/Invoke-CWCWake.md | 1 + Docs/New-CWCAccessToken.md | 49 +- Docs/New-CWCMFA.md | 4 +- Docs/New-CWCRemoteWorkforceAssignment.md | 19 +- Docs/New-CWCSession.md | 164 + Docs/New-CWCUser.md | 4 +- Docs/Private/Invoke-CWCWebRequest.md | 75 - Docs/Private/Join-Url.md | 75 - Docs/Remove-CWCSession.md | 21 +- Docs/Remove-CWCUser.md | 1 + Docs/Send-CWCSessionMessage.md | 146 + Docs/Send-CWCToolboxItem.md | 128 + Docs/Update-CWCCustomProperty.md | 6 +- Docs/Update-CWCSessionName.md | 5 +- Docs/Update-CWCUser.md | 4 +- 34 files changed, 3723 insertions(+), 1281 deletions(-) create mode 100644 Docs/Add-CWCSessionNote.md create mode 100644 Docs/Find-CWCSession.md create mode 100644 Docs/Get-CWCRemoteWorkforceLaunchURL.md create mode 100644 Docs/Get-CWCRemoteWorkforceSession.md create mode 100644 Docs/Initialize-CWCRemoteWorkforceSessionGroup.md create mode 100644 Docs/New-CWCSession.md delete mode 100644 Docs/Private/Invoke-CWCWebRequest.md delete mode 100644 Docs/Private/Join-Url.md create mode 100644 Docs/Send-CWCSessionMessage.md create mode 100644 Docs/Send-CWCToolboxItem.md diff --git a/ConnectWiseControlAPI/Public/PageService/New-CWCAccessToken.ps1 b/ConnectWiseControlAPI/Public/PageService/New-CWCAccessToken.ps1 index 0b96ae0..00e1c07 100644 --- a/ConnectWiseControlAPI/Public/PageService/New-CWCAccessToken.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/New-CWCAccessToken.ps1 @@ -1,4 +1,29 @@ function New-CWCAccessToken { + <# + .SYNOPSIS + Gets an access token for joining a session. + + .DESCRIPTION + Calls PageService.GetAccessToken. The token lets a Host client join the session with the + connected user's permissions for that session group; the user needs the JoinSession + permission in -Group. Treat the token as a secret. + + .PARAMETER Group + Session group containing the session. Defaults to 'All Machines'. + + .PARAMETER GUID + Session ID. + + .EXAMPLE + $Token = New-CWCAccessToken -GUID $SessionID + + .NOTES + Requires Connect-CWC -Credentials. + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> [CmdletBinding()] param ( [string]$Group = 'All Machines', diff --git a/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml b/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml index 484213d..04c1a88 100644 --- a/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml +++ b/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml @@ -15,23 +15,1510 @@ Add-CWCRemoteWorkforceRequiredRole + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + SwitchParameter + + + False + + + + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + SwitchParameter + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + + + + + + -------------------------- Example 1 -------------------------- + PS C:\> Add-CWCRemoteWorkforceRequiredRole + + Adds the Remote Workforce security role + + + + + + + + Add-CWCSessionNote + Add + CWCSessionNote + + Adds a note to a session. + + + + Queues an AddedNote session event. + Credentials connections: PageService.AddSessionEvents. The note is attributed to the connected user and needs the AddNote permission in -Group. + API secret connections: the RESTful API Manager extension's AddNoteToSession. The note is attributed to the extension's RESTfulUserName setting ("RESTful API" by default); -Group is ignored. + + + + Add-CWCSessionNote + + GUID + + Session ID. + + Guid + + Guid + + + None + + + Note + + Note text. + + String + + String + + + None + + + Group + + Session group containing the session (credentials connections only). Defaults to 'All Machines'. + + String + + String + + + All Machines + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + SwitchParameter + + + False + + + + + + GUID + + Session ID. + + Guid + + Guid + + + None + + + Note + + Note text. + + String + + String + + + None + + + Group + + Session group containing the session (credentials connections only). Defaults to 'All Machines'. + + String + + String + + + All Machines + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + SwitchParameter + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + Author: Chris Taylor + + + + + -------------------------- EXAMPLE 1 -------------------------- + Add-CWCSessionNote -GUID $SessionID -Note 'Rebooted for patching' + + + + + + + + https://github.com/christaylorcodes/ConnectWiseControlAPI + https://github.com/christaylorcodes/ConnectWiseControlAPI + + + + + + Connect-CWC + Connect + CWC + + Initializes the connection parameters for the module. + + + + Initializes the connection parameters used by other commands in the module. + + + + Connect-CWC + + Server + + The URL to your control server. + + String + + String + + + None + + + Credentials + + Credentials used to authenticate with the control server. + + PSCredential + + PSCredential + + + None + + + Force + + Used to overwrite any information already loaded in the session. + + + SwitchParameter + + + False + + + + Connect-CWC + + Server + + The URL to your control server. + + String + + String + + + None + + + ApiSecret + + The RESTful API Manager extension's RESTfulAuthenticationSecret value. + + SecureString + + SecureString + + + None + + + Origin + + Origin header sent with -ApiSecret requests. Defaults to https://<Server>. Set it to match the extension's RESTfulAllowedOrigin setting if that setting is configured. + + String + + String + + + None + + + Force + + Used to overwrite any information already loaded in the session. + + + SwitchParameter + + + False + + + + + + Server + + The URL to your control server. + + String + + String + + + None + + + Credentials + + Credentials used to authenticate with the control server. + + PSCredential + + PSCredential + + + None + + + ApiSecret + + The RESTful API Manager extension's RESTfulAuthenticationSecret value. + + SecureString + + SecureString + + + None + + + Origin + + Origin header sent with -ApiSecret requests. Defaults to https://<Server>. Set it to match the extension's RESTfulAllowedOrigin setting if that setting is configured. + + String + + String + + + None + + + Force + + Used to overwrite any information already loaded in the session. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + + + + + + -------------------------- Example 1 -------------------------- + PS C:\> Connect-CWC -Server 'control.christaylor.codes' -Credentials $Credentials -Force + + Sets connection information used by the module and overwrites any previously set information. + + + + + + + + Find-CWCSession + Find + CWCSession + + Finds sessions by session filter expression, name or ID (API secret connections). + + + + Calls the RESTful API Manager extension. Searches all sessions of every type; results are not limited by role permissions or session groups. + -Filter uses Control's session filter syntax, the same syntax as session group filters, e.g. "Name LIKE 'DESKTOP-*'" or "CustomProperty1 = 'Acme'". + + + + Find-CWCSession + + Filter + + A session filter expression (GetSessionsByFilter). + + String + + String + + + None + + + + Find-CWCSession + + Name + + Exact session name (GetSessionsByName). Single quotes are not allowed because the extension inserts the name into a filter expression without escaping. + + String + + String + + + None + + + + Find-CWCSession + + GUID + + Session ID (GetSessionBySessionID). + + Guid + + Guid + + + None + + + + + + Filter + + A session filter expression (GetSessionsByFilter). + + String + + String + + + None + + + Name + + Exact session name (GetSessionsByName). Single quotes are not allowed because the extension inserts the name into a filter expression without escaping. + + String + + String + + + None + + + GUID + + Session ID (GetSessionBySessionID). + + Guid + + Guid + + + None + + + + + + + Requires Connect-CWC -ApiSecret and the RESTful API Manager extension. Author: Chris Taylor + + + + + -------------------------- EXAMPLE 1 -------------------------- + Find-CWCSession -Filter "GuestOperatingSystemName LIKE '*Server*'" + + + + + + -------------------------- EXAMPLE 2 -------------------------- + Find-CWCSession -Name 'DESKTOP-01' + + + + + + + + https://github.com/christaylorcodes/ConnectWiseControlAPI + https://github.com/christaylorcodes/ConnectWiseControlAPI + + + + + + Get-CWCAuditInfo + Get + CWCAuditInfo + + Shows current audit settings + + + + Shows current audit settings + + + + Get-CWCAuditInfo + + + + + + + None + + + + + + + + + + System.Object + + + + + + + + + + + + + + -------------------------- Example 1 -------------------------- + PS C:\> Get-CWCAuditInfo + + Displays the current audit settings + + + + + + + + Get-CWCAuditLog + Get + CWCAuditLog + + Pull audit log information + + + + Returns the same information as the audit search in web + + + + Get-CWCAuditLog + + StartDate + + Start of the time range. Defaults to 24 hours ago. Local times are converted to UTC. + + DateTime + + DateTime + + + None + + + EndDate + + End of the time range. Defaults to now. Local times are converted to UTC. + + DateTime + + DateTime + + + None + + + SessionName + + Only return entries for sessions with this name. + + String + + String + + + None + + + EventTypes + + Session event type numbers to include (for example 44 for QueuedCommand, 70 for RanCommand). + + Int32[] + + Int32[] + + + None + + + SecurityTypes + + Security event type numbers to include. + + Int32[] + + Int32[] + + + None + + + IncludeSessionCaptures + + Deprecated. The server no longer accepts this option; it is ignored with a warning. + + + SwitchParameter + + + False + + + + + + EndDate + + End of the time range. Defaults to now. Local times are converted to UTC. + + DateTime + + DateTime + + + None + + + EventTypes + + Session event type numbers to include (for example 44 for QueuedCommand, 70 for RanCommand). + + Int32[] + + Int32[] + + + None + + + IncludeSessionCaptures + + Deprecated. The server no longer accepts this option; it is ignored with a warning. + + SwitchParameter + + SwitchParameter + + + False + + + SecurityTypes + + Security event type numbers to include. + + Int32[] + + Int32[] + + + None + + + SessionName + + Only return entries for sessions with this name. + + String + + String + + + None + + + StartDate + + Start of the time range. Defaults to 24 hours ago. Local times are converted to UTC. + + DateTime + + DateTime + + + None + + + + + + None + + + + + + + + + + System.Object + + + + + + + + + + + + + + -------------------------- Example 1 -------------------------- + PS C:\> Get-CWCAuditLog -StartDate $(Get-Date).AddDays(-1) -EndDate $(Get-Date) -SessionName 'Computer1' + + Get the audit logs for Computer1 for the last day. + + + + + + + + Get-CWCLastContact + Get + CWCLastContact + + Returns the date the machine last connected to the control server. + + + + Returns the date the machine last connected to the control server. + + + + Get-CWCLastContact + + GUID + + The GUID/SessionID for the machine you wish to connect to. You can retrieve session info with the 'Get-CWCSessions' cmdlets + On Windows clients, the launch parameters are located in the registry at: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ScreenConnect Client (xxxxxxxxxxxxxxxx)\ImagePath On Linux and Mac clients, it's found in the ClientLaunchParameters.txt file in the client installation folder: /opt/screenconnect-xxxxxxxxxxxxxxxx/ClientLaunchParameters.txt + + Guid + + Guid + + + None + + + Seconds + + Used with the Quiet switch. The number of seconds a machine needs to be offline before returning $False. + + Int32 + + Int32 + + + 0 + + + Group + + Name of session group to use. + + String + + String + + + All Machines + + + Quiet + + Will output a boolean result, $True for Connected or $False for Offline. + + + SwitchParameter + + + False + + + + + + GUID + + The GUID/SessionID for the machine you wish to connect to. You can retrieve session info with the 'Get-CWCSessions' cmdlets + On Windows clients, the launch parameters are located in the registry at: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ScreenConnect Client (xxxxxxxxxxxxxxxx)\ImagePath On Linux and Mac clients, it's found in the ClientLaunchParameters.txt file in the client installation folder: /opt/screenconnect-xxxxxxxxxxxxxxxx/ClientLaunchParameters.txt + + Guid + + Guid + + + None + + + Quiet + + Will output a boolean result, $True for Connected or $False for Offline. + + SwitchParameter + + SwitchParameter + + + False + + + Seconds + + Used with the Quiet switch. The number of seconds a machine needs to be offline before returning $False. + + Int32 + + Int32 + + + 0 + + + Group + + Name of session group to use. + + String + + String + + + All Machines + + + + + + + [datetime] -or [boolean] + + + + + + + + + Version: 1.1 Author: Chris Taylor Creation Date: 1/20/2016 Purpose/Change: Initial script development + Update Date: 8/24/2018 Purpose/Change: Fix TimeSpan Seconds duration + + + + + -------------------------- EXAMPLE 1 -------------------------- + Get-CWCLastContact -GUID $GUID + + Will return the last contact of the machine with that GUID. + + + + + + + + Get-CWCLauncURL + Get + CWCLauncURL + + DEPRECATED. Use Get-CWCRemoteWorkforceLaunchURL. + + + + Retained for backwards compatibility. Forwards -GUID to Get-CWCRemoteWorkforceLaunchURL. The Remote Workforce GetLaunchUrlForSessionId endpoint takes only a session ID, so the OnSuccess, OnFailure, UserContext, UserNameOverride and PasswordOverride parameters are ignored. This function will be removed in v1.0. + + + + Get-CWCLauncURL + + GUID + + One or more session IDs. + + Guid[] + + Guid[] + + + None + + + OnSuccess + + Ignored. Not accepted by the server. + + String + + String + + + None + + + OnFailure + + Ignored. Not accepted by the server. + + String + + String + + + None + + + UserContext + + Ignored. Not accepted by the server. + + String + + String + + + None + + + UserNameOverride + + Ignored. Not accepted by the server. + + String + + String + + + None + + + PasswordOverride + + Ignored. Not accepted by the server. + + SecureString + + SecureString + + + None + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + SwitchParameter + + + False + + + + + + GUID + + One or more session IDs. + + Guid[] + + Guid[] + + + None + + + OnSuccess + + Ignored. Not accepted by the server. + + String + + String + + + None + + + OnFailure + + Ignored. Not accepted by the server. + + String + + String + + + None + + + UserContext + + Ignored. Not accepted by the server. + + String + + String + + + None + + + UserNameOverride + + Ignored. Not accepted by the server. + + String + + String + + + None + + + PasswordOverride + + Ignored. Not accepted by the server. + + SecureString + + SecureString + + + None + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + SwitchParameter + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + Deprecated in favor of Get-CWCRemoteWorkforceLaunchURL. Author: Chris Taylor + + + + + -------------------------- EXAMPLE 1 -------------------------- + Get-CWCRemoteWorkforceLaunchURL -GUID $SessionID + + + + + + + + https://github.com/christaylorcodes/ConnectWiseControlAPI + https://github.com/christaylorcodes/ConnectWiseControlAPI + + + + + + Get-CWCRemoteWorkforceLaunchURL + Get + CWCRemoteWorkforceLaunchURL + + Gets a Remote Workforce host launch URL for an assigned machine. + + + + Calls the Remote Workforce extension's GetLaunchUrlForSessionId (by session GUID) or GetLaunchUrl (by session name) endpoint and returns a ClickOnce launch URL. + The extension only returns a URL when the CALLING user is the user the machine is assigned to (the session is in their Remote Workforce session group, "My Assigned Machines" by default) and has View and Join permissions on that group. Otherwise the server returns null and this function writes a warning. An administrator cannot get launch URLs for other users' machines. + + + + Get-CWCRemoteWorkforceLaunchURL + + GUID + + One or more session IDs. Each is requested separately. + + Guid[] + + Guid[] + + + None + + + + Get-CWCRemoteWorkforceLaunchURL + + SessionName + + The session name to look up within the caller's Remote Workforce sessions. + + String + + String + + + None + + + + + + GUID + + One or more session IDs. Each is requested separately. + + Guid[] + + Guid[] + + + None + + + SessionName + + The session name to look up within the caller's Remote Workforce sessions. + + String + + String + + + None + + + + + + + Requires the Remote Workforce extension (2c4f522f-b39a-413a-8807-dc52a2fce13e), Control 23.6+. Author: Chris Taylor + + + + + -------------------------- EXAMPLE 1 -------------------------- + Get-CWCRemoteWorkforceLaunchURL -GUID 'd2b6f0a1-1111-2222-3333-444455556666' + + + + + + -------------------------- EXAMPLE 2 -------------------------- + Get-CWCRemoteWorkforceSession | Get-CWCRemoteWorkforceLaunchURL + + + + + + -------------------------- EXAMPLE 3 -------------------------- + Get-CWCRemoteWorkforceLaunchURL -SessionName 'DESKTOP-01' + + + + + + + + https://github.com/christaylorcodes/ConnectWiseControlAPI + https://github.com/christaylorcodes/ConnectWiseControlAPI + + + + + + Get-CWCRemoteWorkforceSession + Get + CWCRemoteWorkforceSession + + Lists the Remote Workforce machines assigned to the calling user. + + + + Calls the Remote Workforce extension's GetRemoteWorkforceSessions endpoint, which returns the sessions in the extension's session group for the CALLING user that they can view and join. The server's name-to-ID map is returned as objects with Name and SessionID properties. + + + + Get-CWCRemoteWorkforceSession - - + + + + + Requires the Remote Workforce extension (2c4f522f-b39a-413a-8807-dc52a2fce13e), Control 23.6+. Author: Chris Taylor + + + + + -------------------------- EXAMPLE 1 -------------------------- + Get-CWCRemoteWorkforceSession + + + + + + -------------------------- EXAMPLE 2 -------------------------- + Get-CWCRemoteWorkforceSession | Get-CWCRemoteWorkforceLaunchURL + + + + + + + + https://github.com/christaylorcodes/ConnectWiseControlAPI + https://github.com/christaylorcodes/ConnectWiseControlAPI + + + + + + Get-CWCSecurityConfigurationInfo + Get + CWCSecurityConfigurationInfo + + Will return security configuration information. + + + + Will return security configuration information. + + + + Get-CWCSecurityConfigurationInfo + + + + + + + + Version: 1.0 Author: Chris Taylor Creation Date: 1/15/2019 Purpose/Change: Initial script development + + + + + -------------------------- EXAMPLE 1 -------------------------- + Get-CWCSecurityConfigurationInfo + + Returns security configuration + + + + + + + + Get-CWCSession + Get + CWCSession + + Will return a list of sessions. + + + + Allows you to search for access, service or meeting sessions. + + + + Get-CWCSession + + Type + + The type of session Support/Access/Meeting + + Object + + Object + + + None + + + Group + + Name of session group to use. + + String + + String + + + All Machines + + + Search + + Limit results with search pattern. + + String + + String + + + None + + + Limit + + Limit the number of results returned. + + Int32 + + Int32 + + + 0 + + + FindSessionID + + Session ID to locate in the results, so the session is included even when -Limit would cut it off. + + String + + String + + + None + + + + + + Type + + The type of session Support/Access/Meeting + + Object - None + Object + + None + + + Group - + Name of session group to use. - - + String + + String + + + All Machines + + + Search + + Limit results with search pattern. + + String + + String + + + None + + + Limit + + Limit the number of results returned. + + Int32 + + Int32 + + + 0 + + + FindSessionID + + Session ID to locate in the results, so the session is included even when -Limit would cut it off. + + String + + String + + + None + + + - System.Object + ConnectWise Control session objects @@ -40,15 +1527,15 @@ - + Version: 1.0 Author: Chris Taylor Creation Date: 10/10/2018 Purpose/Change: Initial script development - -------------------------- Example 1 -------------------------- - PS C:\> Add-CWCRemoteWorkforceRequiredRole + -------------------------- EXAMPLE 1 -------------------------- + Get-CWCSessions -Type 'Access' -Search 'server1' -Limit 10 - Adds the Remote Workforce security role + Will return the first 10 access sessions that match 'server1'. @@ -56,108 +1543,100 @@ - Connect-CWC - Connect - CWC + Get-CWCSessionDetail + Get + CWCSessionDetail - Initializes the connection parameters for the module. + Will return information about a session. - Initializes the connection parameters used by other commands in the module. + Displays more information about a session. - Connect-CWC - - Server + Get-CWCSessionDetail + + Group - The URL to your control server. + Name of session group to use. String String - None + All Machines - - Credentials + + GUID - Credentials used to authenticate with the control server. + GUID of the machine to retrieve session details. - PSCredential + Guid - PSCredential + Guid None - Force + Include - Used to overwrite any information already loaded in the session. + Parts of the session details to return: SessionInfo, GuestScreenshotContent, Events, Connections. Omit to return everything, including the guest screenshot. Ignored on -ApiSecret connections. + String[] - SwitchParameter + String[] - False + None - - Credentials + + Group - Credentials used to authenticate with the control server. + Name of session group to use. - PSCredential + String - PSCredential + String - None + All Machines - - Force + + GUID - Used to overwrite any information already loaded in the session. + GUID of the machine to retrieve session details. - SwitchParameter + Guid - SwitchParameter + Guid - False + None - - Server + + Include - The URL to your control server. + Parts of the session details to return: SessionInfo, GuestScreenshotContent, Events, Connections. Omit to return everything, including the guest screenshot. Ignored on -ApiSecret connections. - String + String[] - String + String[] None - - - - None - - - - - - + - System.Object + ConnectWise Control session objects @@ -166,15 +1645,15 @@ - + Version: 1.0 Author: Chris Taylor Creation Date: 1/15/2019 Purpose/Change: Initial script development - -------------------------- Example 1 -------------------------- - PS C:\> Connect-CWC -Server 'control.christaylor.codes' -Credentials $Credentials -Force + -------------------------- EXAMPLE 1 -------------------------- + Get-CWCSessionDetail -Group 'All Sessions' -GUID $Session.SessionID - Sets connection information used by the module and overwrites any previously set information. + Will return details of the requested session. @@ -182,19 +1661,19 @@ - Get-CWCAuditInfo + Get-CWCSessionGroup Get - CWCAuditInfo + CWCSessionGroup - Shows current audit settings + Returns details of all session groups. - Shows current audit settings + Returns details of all session groups. - Get-CWCAuditInfo + Get-CWCSessionGroup @@ -226,9 +1705,9 @@ -------------------------- Example 1 -------------------------- - PS C:\> Get-CWCAuditInfo + PS C:\> Get-CWCSessionGroup - Displays the current audit settings + Returns details of all session groups. @@ -236,83 +1715,35 @@ - Get-CWCAuditLog - Get - CWCAuditLog + Initialize-CWCRemoteWorkforceSessionGroup + Initialize + CWCRemoteWorkforceSessionGroup - Pull audit log information + Creates or repairs the session group used by the Remote Workforce extension. - Returns the same information as the audit search in web + Calls the Remote Workforce extension's EnsureCorrectSessionGroupExists endpoint. The extension creates its Access session group (name from the SessionGroupName setting, "My Assigned Machines" by default) with the filter Notes LIKE ' |UserName:' + $USERLOGINNAME + ', ', or repairs an older group whose filter was missing the trailing comma. Without this group, assignments made with New-CWCRemoteWorkforceAssignment are not visible to users. + Idempotent. Requires the Administer permission. - Get-CWCAuditLog - - StartDate - - {{ Fill StartDate Description }} - - DateTime - - DateTime - - - None - - - EndDate - - {{ Fill EndDate Description }} - - DateTime - - DateTime - - - None - - - SessionName - - {{ Fill SessionName Description }} - - String - - String - - - None - - - EventTypes - - {{ Fill EventTypes Description }} - - Int32[] - - Int32[] - - - None - - - SecurityTypes + Initialize-CWCRemoteWorkforceSessionGroup + + WhatIf - {{ Fill SecurityTypes Description }} + Shows what would happen if the cmdlet runs. The cmdlet is not run. - Int32[] - Int32[] + SwitchParameter - None + False - - IncludeSessionCaptures + + Confirm - {{ Fill IncludeSessionCaptures Description }} + Prompts you for confirmation before running the cmdlet. SwitchParameter @@ -323,34 +1754,10 @@ - - EndDate - - {{ Fill EndDate Description }} - - DateTime - - DateTime - - - None - - - EventTypes - - {{ Fill EventTypes Description }} - - Int32[] - - Int32[] - - - None - - - IncludeSessionCaptures + + WhatIf - {{ Fill IncludeSessionCaptures Description }} + Shows what would happen if the cmdlet runs. The cmdlet is not run. SwitchParameter @@ -359,99 +1766,61 @@ False - - SecurityTypes - - {{ Fill SecurityTypes Description }} - - Int32[] - - Int32[] - - - None - - - SessionName - - {{ Fill SessionName Description }} - - String - - String - - - None - - - StartDate + + Confirm - {{ Fill StartDate Description }} + Prompts you for confirmation before running the cmdlet. - DateTime + SwitchParameter - DateTime + SwitchParameter - None + False - - - - None - - - - - - - - - - System.Object - - - - - - + + - + Requires the Remote Workforce extension (2c4f522f-b39a-413a-8807-dc52a2fce13e), Control 23.6+. Author: Chris Taylor - -------------------------- Example 1 -------------------------- - PS C:\> Get-CWCAuditLog -StartDate $(Get-Date).AddDays(-1) -EndDate $(Get-Date) -SessionName 'Computer1' + -------------------------- EXAMPLE 1 -------------------------- + Initialize-CWCRemoteWorkforceSessionGroup - Get the audit logs for Computer1 for the last day. + - + + + https://github.com/christaylorcodes/ConnectWiseControlAPI + https://github.com/christaylorcodes/ConnectWiseControlAPI + + - Get-CWCLastContact - Get - CWCLastContact + Invoke-CWCCommand + Invoke + CWCCommand - Returns the date the machine last connected to the control server. + Will issue a command against a given machine and return the results. - Returns the date the machine last connected to the control server. + Will issue a command against a given machine and return the results. - Get-CWCLastContact + Invoke-CWCCommand GUID - The GUID/SessionID for the machine you wish to connect to. You can retrieve session info with the 'Get-CWCSessions' cmdlets - On Windows clients, the launch parameters are located in the registry at: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ScreenConnect Client (xxxxxxxxxxxxxxxx)\ImagePath On Linux and Mac clients, it's found in the ClientLaunchParameters.txt file in the client installation folder: /opt/screenconnect-xxxxxxxxxxxxxxxx/ClientLaunchParameters.txt + The GUID identifier for the machine you wish to connect to. You can retrieve session info with the 'Get-CWCSessions' cmdlets Guid @@ -461,18 +1830,30 @@ None - Seconds + Command - Used with the Quiet switch. The number of seconds a machine needs to be offline before returning $False. + The command you wish to issue to the machine. + + String + + String + + + None + + + TimeOut + + The amount of time in milliseconds that a command can execute. The default is 10000 milliseconds. Int32 Int32 - 0 + 10000 - + Group Name of session group to use. @@ -485,9 +1866,20 @@ All Machines - Quiet + PowerShell - Will output a boolean result, $True for Connected or $False for Offline. + Issues the command in a powershell session. + + + SwitchParameter + + + False + + + NoWait + + Will not wait for the output of the command. SwitchParameter @@ -495,14 +1887,25 @@ False + + MaxLength + + Maximum number of characters of command output to return. Defaults to 10000. + + Int32 + + Int32 + + + None + GUID - The GUID/SessionID for the machine you wish to connect to. You can retrieve session info with the 'Get-CWCSessions' cmdlets - On Windows clients, the launch parameters are located in the registry at: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ScreenConnect Client (xxxxxxxxxxxxxxxx)\ImagePath On Linux and Mac clients, it's found in the ClientLaunchParameters.txt file in the client installation folder: /opt/screenconnect-xxxxxxxxxxxxxxxx/ClientLaunchParameters.txt + The GUID identifier for the machine you wish to connect to. You can retrieve session info with the 'Get-CWCSessions' cmdlets Guid @@ -511,31 +1914,43 @@ None - - Quiet + + Command - Will output a boolean result, $True for Connected or $False for Offline. + The command you wish to issue to the machine. - SwitchParameter + String - SwitchParameter + String - False + None - - Seconds + + TimeOut - Used with the Quiet switch. The number of seconds a machine needs to be offline before returning $False. + The amount of time in milliseconds that a command can execute. The default is 10000 milliseconds. Int32 Int32 - 0 + 10000 - + + PowerShell + + Issues the command in a powershell session. + + SwitchParameter + + SwitchParameter + + + False + + Group Name of session group to use. @@ -547,91 +1962,10 @@ All Machines - - - - - - [datetime] -or [boolean] - - - - - - - - - Version: 1.1 Author: Chris Taylor Creation Date: 1/20/2016 Purpose/Change: Initial script development - Update Date: 8/24/2018 Purpose/Change: Fix TimeSpan Seconds duration - - - - - -------------------------- EXAMPLE 1 -------------------------- - Get-CWCLastContact -GUID $GUID - - Will return the last contact of the machine with that GUID. - - - - - - - - Get-CWCLauncURL - Get - CWCLauncURL - - {{ Fill in the Synopsis }} - - - - {{ Fill in the Description }} - - - - Get-CWCLauncURL - - GUID - - {{ Fill GUID Description }} - - Guid[] - - Guid[] - - - None - - - Confirm - - Prompts you for confirmation before running the cmdlet. - - - SwitchParameter - - - False - - - WhatIf - - Shows what would happen if the cmdlet runs. The cmdlet is not run. - - - SwitchParameter - - - False - - - - - - Confirm + + NoWait - Prompts you for confirmation before running the cmdlet. + Will not wait for the output of the command. SwitchParameter @@ -640,45 +1974,24 @@ False - - GUID + + MaxLength - {{ Fill GUID Description }} + Maximum number of characters of command output to return. Defaults to 10000. - Guid[] + Int32 - Guid[] + Int32 None - - WhatIf - - Shows what would happen if the cmdlet runs. The cmdlet is not run. - - SwitchParameter - - SwitchParameter - - - False - - - - - None - - - - - - + - System.Object + The output of the Command provided. @@ -687,51 +2000,25 @@ - - - - - - -------------------------- Example 1 -------------------------- - PS C:\> {{ Add example code here }} - - {{ Add example description here }} - - - - - - - - Get-CWCSecurityConfigurationInfo - Get - CWCSecurityConfigurationInfo - - Will return security configuration information. - - - - Will return security configuration information. - - - - Get-CWCSecurityConfigurationInfo - - - - - - - - Version: 1.0 Author: Chris Taylor Creation Date: 1/15/2019 Purpose/Change: Initial script development + Version: 1.0 + Author: Chris Taylor + Creation Date: 1/20/2016 + Purpose/Change: Initial script development -------------------------- EXAMPLE 1 -------------------------- - Get-CWCSecurityConfigurationInfo + Invoke-CWCCommand -GUID $GUID -Command 'hostname' - Returns security configuration + Will return the hostname of the machine. + + + + -------------------------- EXAMPLE 2 -------------------------- + Invoke-CWCCommand -GUID $GUID -TimeOut 120000 -Command 'iwr -UseBasicParsing "https://bit.ly/ltposh" | iex; Restart-LTService' -PowerShell + + Will restart the Automate agent on the target machine. @@ -739,47 +2026,35 @@ - Get-CWCSession - Get - CWCSession + Invoke-CWCWake + Invoke + CWCWake - Will return a list of sessions. + Will issue a wake command to a given session. - Allows you to search for access, service or meeting sessions. + Will issue a wake command to a given access or support session. - Get-CWCSession + Invoke-CWCWake - Type + GUID - The type of session Support/Access/Meeting + The GUID identifier for the session you wish to end. Accepts an array of GUIDs - Object + Guid[] - Object + Guid[] None - - Group - - Name of session group to use. - - String - - String - - - All Machines - - - Search + + Type - Limit results with search pattern. + The type of session Support/Access String @@ -788,49 +2063,25 @@ None - - Limit - - Limit the number of results returned. - - Int32 - - Int32 - - - 0 - - Type + GUID - The type of session Support/Access/Meeting + The GUID identifier for the session you wish to end. Accepts an array of GUIDs - Object + Guid[] - Object + Guid[] None - - Group - - Name of session group to use. - - String - - String - - - All Machines - - - Search + + Type - Limit results with search pattern. + The type of session Support/Access String @@ -839,41 +2090,20 @@ None - - Limit - - Limit the number of results returned. - - Int32 - - Int32 - - - 0 - - - - - ConnectWise Control session objects - - - - - - + - Version: 1.0 Author: Chris Taylor Creation Date: 10/10/2018 Purpose/Change: Initial script development + Version: 1.0 Author: Chris Taylor Creation Date: 12/7/2018 Purpose/Change: Initial script development -------------------------- EXAMPLE 1 -------------------------- - Get-CWCSessions -Type 'Access' -Search 'server1' -Limit 10 + End-CWWake -GUID $GUID - Will return the first 10 access sessions that match 'server1'. + Will issue a wake command to a given session. @@ -881,23 +2111,23 @@ - Get-CWCSessionDetail - Get - CWCSessionDetail + New-CWCAccessToken + New + CWCAccessToken - Will return information about a session. + Gets an access token for joining a session. - Displays more information about a session. + Calls PageService.GetAccessToken. The token lets a Host client join the session with the connected user's permissions for that session group; the user needs the JoinSession permission in -Group. Treat the token as a secret. - Get-CWCSessionDetail - + New-CWCAccessToken + Group - Name of session group to use. + Session group containing the session. Defaults to 'All Machines'. String @@ -906,10 +2136,10 @@ All Machines - + GUID - GUID of the machine to retrieve session details. + Session ID. Guid @@ -921,10 +2151,10 @@ - + Group - Name of session group to use. + Session group containing the session. Defaults to 'All Machines'. String @@ -933,10 +2163,10 @@ All Machines - + GUID - GUID of the machine to retrieve session details. + Session ID. Guid @@ -947,50 +2177,141 @@ - - - - ConnectWise Control session objects - - - - - - + - Version: 1.0 Author: Chris Taylor Creation Date: 1/15/2019 Purpose/Change: Initial script development + Requires Connect-CWC -Credentials. Author: Chris Taylor -------------------------- EXAMPLE 1 -------------------------- - Get-CWCSessionDetail -Group 'All Sessions' -GUID $Session.SessionID + $Token = New-CWCAccessToken -GUID $SessionID - Will return details of the requested session. + - + + + https://github.com/christaylorcodes/ConnectWiseControlAPI + https://github.com/christaylorcodes/ConnectWiseControlAPI + + - Get-CWCSessionGroup - Get - CWCSessionGroup + New-CWCMFA + New + CWCMFA - Returns details of all session groups. + Will generate an MFA code to use with user creation. - Returns details of all session groups. + Will generate an MFA code to use with user creation. - Get-CWCSessionGroup + New-CWCMFA + + DisplayName + + Name you want to display in OTP app. + + Object + + Object + + + None + + + UserAccount + + User account to display in OTP app. + + Object + + Object + + + None + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + SwitchParameter + + + False + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + + SwitchParameter + + + False + - + + + DisplayName + + Name you want to display in OTP app. + + Object + + Object + + + None + + + UserAccount + + User account to display in OTP app. + + Object + + Object + + + None + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + SwitchParameter + + SwitchParameter + + + False + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + SwitchParameter + + SwitchParameter + + + False + + @@ -1019,9 +2340,9 @@ -------------------------- Example 1 -------------------------- - PS C:\> Get-CWCSessionGroup + PS C:\> New-CWCMFA -DisplayName 'My Control Server' -UserAccount 'CTaylor' - Returns details of all session groups. + Creates an MFA OTP code and QR URL with the provided information. @@ -1029,35 +2350,35 @@ - Invoke-CWCCommand - Invoke - CWCCommand + New-CWCRemoteWorkforceAssignment + New + CWCRemoteWorkforceAssignment - Will issue a command against a given machine and return the results. + Assign a user to machines. - Will issue a command against a given machine and return the results. + Uses the remote workforce extension to assign a user to machines - Invoke-CWCCommand - + New-CWCRemoteWorkforceAssignment + GUID - The GUID identifier for the machine you wish to connect to. You can retrieve session info with the 'Get-CWCSessions' cmdlets + GUID of the session you want to assign the user access to. - Guid + Guid[] - Guid + Guid[] None - - Command + + Username - The command you wish to issue to the machine. + Username of the account you want to assign remote workforce access to. String @@ -1066,34 +2387,22 @@ None - - TimeOut - - The amount of time in milliseconds that a command can execute. The default is 10000 milliseconds. - - Int32 - - Int32 - - - 10000 - - - Group + + DisplayName - Name of session group to use. + Name that is displayed when user is connected to a session. String String - All Machines + None - - PowerShell + + Confirm - Issues the command in a powershell session. + Prompts you for confirmation before running the cmdlet. SwitchParameter @@ -1101,10 +2410,10 @@ False - - NoWait + + WhatIf - Will not wait for the output of the command. + Shows what would happen if the cmdlet runs. The cmdlet is not run. SwitchParameter @@ -1113,13 +2422,13 @@ False - MaxLength + Group - {{ Fill MaxLength Description }} + Session group containing the session(s). Defaults to 'All Machines' where a default exists. - Int32 + String - Int32 + String None @@ -1127,22 +2436,22 @@ - + GUID - The GUID identifier for the machine you wish to connect to. You can retrieve session info with the 'Get-CWCSessions' cmdlets + GUID of the session you want to assign the user access to. - Guid + Guid[] - Guid + Guid[] None - - Command + + Username - The command you wish to issue to the machine. + Username of the account you want to assign remote workforce access to. String @@ -1151,22 +2460,22 @@ None - - TimeOut + + DisplayName - The amount of time in milliseconds that a command can execute. The default is 10000 milliseconds. + Name that is displayed when user is connected to a session. - Int32 + String - Int32 + String - 10000 + None - - PowerShell + + Confirm - Issues the command in a powershell session. + Prompts you for confirmation before running the cmdlet. SwitchParameter @@ -1175,22 +2484,10 @@ False - - Group - - Name of session group to use. - - String - - String - - - All Machines - - - NoWait + + WhatIf - Will not wait for the output of the command. + Shows what would happen if the cmdlet runs. The cmdlet is not run. SwitchParameter @@ -1200,50 +2497,34 @@ False - MaxLength + Group - {{ Fill MaxLength Description }} + Session group containing the session(s). Defaults to 'All Machines' where a default exists. - Int32 + String - Int32 + String None - - - - The output of the Command provided. - - - - - - + - Version: 1.0 + Version: 1.1 Author: Chris Taylor - Creation Date: 1/20/2016 + Creation Date: 10/25/2018 Purpose/Change: Initial script development -------------------------- EXAMPLE 1 -------------------------- - Invoke-CWCCommand -GUID $GUID -Command 'hostname' - - Will return the hostname of the machine. - - - - -------------------------- EXAMPLE 2 -------------------------- - Invoke-CWCCommand -GUID $GUID -TimeOut 120000 -Command 'iwr -UseBasicParsing "https://bit.ly/ltposh" | iex; Restart-LTService' -PowerShell + PS C:\> New-CWCRemoteWorkforceAssignment -GUID $GUID -Username 'CTaylor' -DisplayName 'Chris Taylor' - Will restart the Automate agent on the target machine. + @@ -1251,35 +2532,37 @@ - Invoke-CWCWake - Invoke - CWCWake + New-CWCSession + New + CWCSession - Will issue a wake command to a given session. + Creates a session. - Will issue a wake command to a given access or support session. + Creates a session and returns the new session ID. Works with both connection types: + -Credentials: PageService.CreateSession. Requires the create permission for the session type; the session host is the connected user. + -ApiSecret: the RESTful API Manager extension's CreateSession. The session host is the extension's RESTfulUserName setting ("RESTful API" by default). - Invoke-CWCWake - - GUID + New-CWCSession + + Type - The GUID identifier for the session you wish to end. Accepts an array of GUIDs + Support, Meeting or Access. - Guid[] + String - Guid[] + String None - - Type + + Name - The type of session Support/Access + Session name. String @@ -1288,133 +2571,156 @@ None - - - - - GUID - - The GUID identifier for the session you wish to end. Accepts an array of GUIDs - - Guid[] - - Guid[] - - - None - - - Type - - The type of session Support/Access - - String - - String - - - None - - - - - - - Version: 1.0 Author: Chris Taylor Creation Date: 12/7/2018 Purpose/Change: Initial script development - - - - - -------------------------- EXAMPLE 1 -------------------------- - End-CWWake -GUID $GUID - - Will issue a wake command to a given session. - - - - - - - - New-CWCAccessToken - New - CWCAccessToken - - {{ Fill in the Synopsis }} - - - - {{ Fill in the Description }} - - - - New-CWCAccessToken - - Group + + Code + + Session join code. + + String + + String + + + None + + + CustomPropertyValues + + Custom property values in order (CustomProperty1, CustomProperty2, ...). + + String[] + + String[] + + + @() + + + IsPublic - {{ Fill Group Description }} + Make the session publicly listed on the guest page. - String[] - String[] + SwitchParameter - None + False - - GUID + + WhatIf - {{ Fill GUID Description }} + Shows what would happen if the cmdlet runs. The cmdlet is not run. - Guid - Guid + SwitchParameter - None + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + SwitchParameter + + + False - GUID + Type - {{ Fill GUID Description }} + Support, Meeting or Access. - Guid + String - Guid + String None - - Group + + Name + + Session name. + + String + + String + + + None + + + IsPublic + + Make the session publicly listed on the guest page. + + SwitchParameter + + SwitchParameter + + + False + + + Code + + Session join code. + + String + + String + + + None + + + CustomPropertyValues - {{ Fill Group Description }} + Custom property values in order (CustomProperty1, CustomProperty2, ...). String[] String[] - None + @() - - - + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + SwitchParameter - None + SwitchParameter + + False + + + Confirm - + Prompts you for confirmation before running the cmdlet. - - + SwitchParameter + + SwitchParameter + + + False + + + - System.Object + System.Guid @@ -1423,59 +2729,100 @@ - + Not retried on HTTP 500: a retry after the server created the session would create a second one. Author: Chris Taylor - -------------------------- Example 1 -------------------------- - PS C:\> {{ Add example code here }} + -------------------------- EXAMPLE 1 -------------------------- + New-CWCSession -Type Support -Name 'Ticket 12345' -Code '12345' - {{ Add example description here }} + - + + + https://github.com/christaylorcodes/ConnectWiseControlAPI + https://github.com/christaylorcodes/ConnectWiseControlAPI + + - New-CWCMFA + New-CWCUser New - CWCMFA + CWCUser - Will generate an MFA code to use with user creation. + Creates a user. - Will generate an MFA code to use with user creation. + Creates a new local user. - New-CWCMFA + New-CWCUser + + OTP + + The OTP key used for MFA. Can be generated with `New-CWCMFA` + + String + + String + + + None + DisplayName - Name you want to display in OTP app. + The display name of the new user - Object + String - Object + String + + + None + + + Email + + Email address of the user + + String + + String None - UserAccount + SecurityGroups - User account to display in OTP app. + An array of security groups the user is a part of - Object + String[] - Object + String[] None + + ForcePassChange + + Force the user to change their password at next login + + Boolean + + Boolean + + + True + Confirm @@ -1498,33 +2845,81 @@ False + + Credentials + + PSCredential object for the new user you want to create. + + PSCredential + + PSCredential + + + None + + + OTP + + The OTP key used for MFA. Can be generated with `New-CWCMFA` + + String + + String + + + None + DisplayName - Name you want to display in OTP app. + The display name of the new user - Object + String - Object + String + + + None + + + Email + + Email address of the user + + String + + String None - UserAccount + SecurityGroups - User account to display in OTP app. + An array of security groups the user is a part of - Object + String[] - Object + String[] None + + ForcePassChange + + Force the user to change their password at next login + + Boolean + + Boolean + + + True + Confirm @@ -1549,38 +2944,40 @@ False - - - - - None - + + Credentials - + PSCredential object for the new user you want to create. - - - - + PSCredential - System.Object + PSCredential + - - - - - + None + + + + - + Version: 1.1 Author: Chris Taylor Creation Date: 4/2/2020 Purpose/Change: Initial script development - -------------------------- Example 1 -------------------------- - PS C:\> New-CWCMFA -DisplayName 'My Control Server' -UserAccount 'CTaylor' + -------------------------- EXAMPLE 1 -------------------------- + $NewUserParams = @{ + Credentials = $PSCredentials + OTP = $(New-CWCMFA).OTP + DisplayName = 'Chris Taylor' + Email = 'dont@bug.me' + SecurityGroups = 'MySecurityGroup' + ForcePassChange = $true +} +New-CWCUser @NewUserParams - Creates an MFA OTP code and QR URL with the provided information. + @@ -1588,23 +2985,23 @@ - New-CWCRemoteWorkforceAssignment - New - CWCRemoteWorkforceAssignment + Remove-CWCSession + Remove + CWCSession - Assign a user to machines. + Will end a given session. - Uses the remote workforce extension to assign a user to machines + Will end a given access or support session. - New-CWCRemoteWorkforceAssignment + Remove-CWCSession GUID - GUID of the session you want to assign the user access to. + The GUID identifier for the session you wish to end. Accepts an array of GUIDs. Guid[] @@ -1613,45 +3010,44 @@ None - - Username + + Confirm - Username of the account you want to assign remote workforce access to. + Prompts you for confirmation before running the cmdlet. - String - String + SwitchParameter - None + False - - DisplayName + + WhatIf - Name that is displayed when user is connected to a session. + Shows what would happen if the cmdlet runs. The cmdlet is not run. - String - String + SwitchParameter - None + False - - Confirm + + Group - Prompts you for confirmation before running the cmdlet. + Session group containing the session(s). Defaults to 'All Machines' where a default exists. + String - SwitchParameter + String - False + None - - WhatIf + + Uninstall - Shows what would happen if the cmdlet runs. The cmdlet is not run. + Queue an uninstall of the Access client and delete the session (QueuedUninstallAndDelete) instead of only deleting the session record. SwitchParameter @@ -1665,7 +3061,7 @@ GUID - GUID of the session you want to assign the user access to. + The GUID identifier for the session you wish to end. Accepts an array of GUIDs. Guid[] @@ -1674,46 +3070,46 @@ None - - Username + + Confirm - Username of the account you want to assign remote workforce access to. + Prompts you for confirmation before running the cmdlet. - String + SwitchParameter - String + SwitchParameter - None + False - - DisplayName + + WhatIf - Name that is displayed when user is connected to a session. + Shows what would happen if the cmdlet runs. The cmdlet is not run. - String + SwitchParameter - String + SwitchParameter - None + False - - Confirm + + Group - Prompts you for confirmation before running the cmdlet. + Session group containing the session(s). Defaults to 'All Machines' where a default exists. - SwitchParameter + String - SwitchParameter + String - False + None - - WhatIf + + Uninstall - Shows what would happen if the cmdlet runs. The cmdlet is not run. + Queue an uninstall of the Access client and delete the session (QueuedUninstallAndDelete) instead of only deleting the session record. SwitchParameter @@ -1727,18 +3123,15 @@ - Version: 1.1 - Author: Chris Taylor - Creation Date: 10/25/2018 - Purpose/Change: Initial script development + Version: 1.0 Author: Chris Taylor Creation Date: 10/10/2018 Purpose/Change: Initial script development -------------------------- EXAMPLE 1 -------------------------- - PS C:\> New-CWCRemoteWorkforceAssignment -GUID $GUID -Username 'CTaylor' -DisplayName 'Chris Taylor' + Remove-CWCAccessSession -GUID $GUID - + Will remove the given access session @@ -1746,47 +3139,23 @@ - New-CWCUser - New + Remove-CWCUser + Remove CWCUser - Creates a user. + Removes an internal user. - Creates a new local user. + Removes the provided internal user. - New-CWCUser - - OTP - - The OTP key used for MFA. Can be generated with `New-CWCMFA` - - String - - String - - - None - - - DisplayName - - The display name of the new user - - String - - String - - - None - - - Email + Remove-CWCUser + + User - Email address of the user + The user to remove. String @@ -1795,30 +3164,6 @@ None - - SecurityGroups - - An array of security groups the user is a part of - - String[] - - String[] - - - None - - - ForcePassChange - - Force the user to change their password at next login - - Boolean - - Boolean - - - True - Confirm @@ -1841,92 +3186,32 @@ False - - Credentials - - PSCredential object for the new user you want to create. - - PSCredential - - PSCredential - - - None - - - OTP - - The OTP key used for MFA. Can be generated with `New-CWCMFA` - - String - - String - - - None - - - DisplayName + + Confirm - The display name of the new user + Prompts you for confirmation before running the cmdlet. - String + SwitchParameter - String + SwitchParameter - None + False - - Email + + User - Email address of the user + The user to remove. String - String - - - None - - - SecurityGroups - - An array of security groups the user is a part of - - String[] - - String[] - - - None - - - ForcePassChange - - Force the user to change their password at next login - - Boolean - - Boolean - - - True - - - Confirm - - Prompts you for confirmation before running the cmdlet. - - SwitchParameter - - SwitchParameter + String - False + None WhatIf @@ -1940,40 +3225,38 @@ False - - Credentials + + + + + None + - PSCredential object for the new user you want to create. + - PSCredential + + + + - PSCredential - + System.Object - None - - - - + + + + + - Version: 1.1 Author: Chris Taylor Creation Date: 4/2/2020 Purpose/Change: Initial script development + - -------------------------- EXAMPLE 1 -------------------------- - $NewUserParams = @{ - Credentials = $PSCredentials - OTP = $(New-CWCMFA).OTP - DisplayName = 'Chris Taylor' - Email = 'dont@bug.me' - SecurityGroups = 'MySecurityGroup' - ForcePassChange = $true -} -New-CWCUser @NewUserParams + -------------------------- Example 1 -------------------------- + PS C:\> Remove-CWCUser -User 'ctaylor' - + Removes the 'ctaylor' user from Control. @@ -1981,41 +3264,68 @@ New-CWCUser @NewUserParams - Remove-CWCSession - Remove - CWCSession + Send-CWCSessionMessage + Send + CWCSessionMessage - Will end a given session. + Sends a chat message to a session's guest. - Will end a given access or support session. + Queues a QueuedMessage session event. + Credentials connections: PageService.AddSessionEvents. The guest sees the connected user's display name as the sender (-From is not supported) and the user needs the matching permission in -Group. + API secret connections: the RESTful API Manager extension's SendMessageToSession. The guest sees -From as the sender; -Group is ignored. - Remove-CWCSession - + Send-CWCSessionMessage + GUID - The GUID identifier for the session you wish to end. Accepts an array of GUIDs. + Session ID. - Guid[] + Guid - Guid[] + Guid None - - Confirm + + Message - Prompts you for confirmation before running the cmdlet. + Message text. + + String + + String + + + None + + + From + + Sender name shown to the guest (API secret connections only). + String - SwitchParameter + String - False + RESTful API + + + Group + + Session group containing the session (credentials connections only). Defaults to 'All Machines'. + + String + + String + + + All Machines WhatIf @@ -2028,44 +3338,67 @@ New-CWCUser @NewUserParams False - - Group + + Confirm - {{ Fill Group Description }} + Prompts you for confirmation before running the cmdlet. - String - String + SwitchParameter - None + False - + GUID - The GUID identifier for the session you wish to end. Accepts an array of GUIDs. + Session ID. - Guid[] + Guid - Guid[] + Guid None - - Confirm + + Message - Prompts you for confirmation before running the cmdlet. + Message text. - SwitchParameter + String - SwitchParameter + String - False + None + + + From + + Sender name shown to the guest (API secret connections only). + + String + + String + + + RESTful API + + + Group + + Session group containing the session (credentials connections only). Defaults to 'All Machines'. + + String + + String + + + All Machines WhatIf @@ -2079,56 +3412,75 @@ New-CWCUser @NewUserParams False - - Group + + Confirm - {{ Fill Group Description }} + Prompts you for confirmation before running the cmdlet. - String + SwitchParameter - String + SwitchParameter - None + False - Version: 1.0 Author: Chris Taylor Creation Date: 10/10/2018 Purpose/Change: Initial script development + Author: Chris Taylor -------------------------- EXAMPLE 1 -------------------------- - Remove-CWCAccessSession -GUID $GUID + Send-CWCSessionMessage -GUID $SessionID -Message 'Your computer will restart in 5 minutes.' - Will remove the given access session + - + + + https://github.com/christaylorcodes/ConnectWiseControlAPI + https://github.com/christaylorcodes/ConnectWiseControlAPI + + - Remove-CWCUser - Remove - CWCUser + Send-CWCToolboxItem + Send + CWCToolboxItem - Removes an internal user. + Queues a Toolbox item to run on a session. - Removes the provided internal user. + Queues a QueuedTool session event naming the Toolbox item. + Credentials connections: PageService.AddSessionEvents; the user needs the RunSharedTool permission in -Group. + API secret connections: the RESTful API Manager extension's SendToolboxItemToSession; -Group is ignored. - Remove-CWCUser - - User + Send-CWCToolboxItem + + GUID - The user to remove. + Session ID. + + Guid + + Guid + + + None + + + Name + + Toolbox item name as shown in the Control Toolbox. String @@ -2137,16 +3489,17 @@ New-CWCUser @NewUserParams None - - Confirm + + Group - Prompts you for confirmation before running the cmdlet. + Session group containing the session (credentials connections only). Defaults to 'All Machines'. + String - SwitchParameter + String - False + All Machines WhatIf @@ -2159,25 +3512,36 @@ New-CWCUser @NewUserParams False + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + SwitchParameter + + + False + - - Confirm + + GUID - Prompts you for confirmation before running the cmdlet. + Session ID. - SwitchParameter + Guid - SwitchParameter + Guid - False + None - - User + + Name - The user to remove. + Toolbox item name as shown in the Control Toolbox. String @@ -2186,6 +3550,18 @@ New-CWCUser @NewUserParams None + + Group + + Session group containing the session (credentials connections only). Defaults to 'All Machines'. + + String + + String + + + All Machines + WhatIf @@ -2198,42 +3574,41 @@ New-CWCUser @NewUserParams False - - - - - None - + + Confirm - + Prompts you for confirmation before running the cmdlet. - - - - + SwitchParameter - System.Object + SwitchParameter + - - - - - + False + + + + - + Author: Chris Taylor - -------------------------- Example 1 -------------------------- - PS C:\> Remove-CWCUser -User 'ctaylor' + -------------------------- EXAMPLE 1 -------------------------- + Send-CWCToolboxItem -GUID $SessionID -Name 'Cleanup.ps1' - Removes the 'ctaylor' user from Control. + - + + + https://github.com/christaylorcodes/ConnectWiseControlAPI + https://github.com/christaylorcodes/ConnectWiseControlAPI + + @@ -2268,9 +3643,9 @@ New-CWCUser @NewUserParams Look for the session in these groups. - String[] + String - String[] + String All Machines @@ -2342,9 +3717,9 @@ New-CWCUser @NewUserParams Look for the session in these groups. - String[] + String - String[] + String All Machines diff --git a/ConnectWiseControlAPI_Functions.md b/ConnectWiseControlAPI_Functions.md index 5609a15..e657225 100644 --- a/ConnectWiseControlAPI_Functions.md +++ b/ConnectWiseControlAPI_Functions.md @@ -14,9 +14,15 @@ This module wraps the web API into PowerShell functions. ### [Add-CWCRemoteWorkforceRequiredRole](Docs/Add-CWCRemoteWorkforceRequiredRole.md) Create a new Remote Workforce security role +### [Add-CWCSessionNote](Docs/Add-CWCSessionNote.md) +Adds a note to a session. + ### [Connect-CWC](Docs/Connect-CWC.md) Initializes the connection parameters for the module. +### [Find-CWCSession](Docs/Find-CWCSession.md) +Finds sessions by session filter expression, name or ID (API secret connections). + ### [Get-CWCAuditInfo](Docs/Get-CWCAuditInfo.md) Shows current audit settings @@ -27,7 +33,14 @@ Pull audit log information Returns the date the machine last connected to the control server. ### [Get-CWCLauncURL](Docs/Get-CWCLauncURL.md) -{{ Fill in the Synopsis }} +DEPRECATED. +Use Get-CWCRemoteWorkforceLaunchURL. + +### [Get-CWCRemoteWorkforceLaunchURL](Docs/Get-CWCRemoteWorkforceLaunchURL.md) +Gets a Remote Workforce host launch URL for an assigned machine. + +### [Get-CWCRemoteWorkforceSession](Docs/Get-CWCRemoteWorkforceSession.md) +Lists the Remote Workforce machines assigned to the calling user. ### [Get-CWCSecurityConfigurationInfo](Docs/Get-CWCSecurityConfigurationInfo.md) Will return security configuration information. @@ -41,6 +54,9 @@ Will return information about a session. ### [Get-CWCSessionGroup](Docs/Get-CWCSessionGroup.md) Returns details of all session groups. +### [Initialize-CWCRemoteWorkforceSessionGroup](Docs/Initialize-CWCRemoteWorkforceSessionGroup.md) +Creates or repairs the session group used by the Remote Workforce extension. + ### [Invoke-CWCCommand](Docs/Invoke-CWCCommand.md) Will issue a command against a given machine and return the results. @@ -48,7 +64,7 @@ Will issue a command against a given machine and return the results. Will issue a wake command to a given session. ### [New-CWCAccessToken](Docs/New-CWCAccessToken.md) -{{ Fill in the Synopsis }} +Gets an access token for joining a session. ### [New-CWCMFA](Docs/New-CWCMFA.md) Will generate an MFA code to use with user creation. @@ -56,6 +72,9 @@ Will generate an MFA code to use with user creation. ### [New-CWCRemoteWorkforceAssignment](Docs/New-CWCRemoteWorkforceAssignment.md) Assign a user to machines. +### [New-CWCSession](Docs/New-CWCSession.md) +Creates a session. + ### [New-CWCUser](Docs/New-CWCUser.md) Creates a user. @@ -65,6 +84,12 @@ Will end a given session. ### [Remove-CWCUser](Docs/Remove-CWCUser.md) Removes an internal user. +### [Send-CWCSessionMessage](Docs/Send-CWCSessionMessage.md) +Sends a chat message to a session's guest. + +### [Send-CWCToolboxItem](Docs/Send-CWCToolboxItem.md) +Queues a Toolbox item to run on a session. + ### [Update-CWCCustomProperty](Docs/Update-CWCCustomProperty.md) Will update a custom property for a session. diff --git a/Docs/Add-CWCRemoteWorkforceRequiredRole.md b/Docs/Add-CWCRemoteWorkforceRequiredRole.md index 096bb91..b498cdc 100644 --- a/Docs/Add-CWCRemoteWorkforceRequiredRole.md +++ b/Docs/Add-CWCRemoteWorkforceRequiredRole.md @@ -13,7 +13,8 @@ Create a new Remote Workforce security role ## SYNTAX ``` -Add-CWCRemoteWorkforceRequiredRole [] +Add-CWCRemoteWorkforceRequiredRole [-WhatIf] [-Confirm] + [] ``` ## DESCRIPTION @@ -30,15 +31,44 @@ Adds the Remote Workforce security role ## PARAMETERS +### -WhatIf +Shows what would happen if the cmdlet runs. The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS -### None ## OUTPUTS -### System.Object ## NOTES ## RELATED LINKS diff --git a/Docs/Add-CWCSessionNote.md b/Docs/Add-CWCSessionNote.md new file mode 100644 index 0000000..b333ae1 --- /dev/null +++ b/Docs/Add-CWCSessionNote.md @@ -0,0 +1,131 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# Add-CWCSessionNote + +## SYNOPSIS +Adds a note to a session. + +## SYNTAX + +``` +Add-CWCSessionNote [-GUID] [-Note] [[-Group] ] + [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +Queues an AddedNote session event. + +Credentials connections: PageService.AddSessionEvents. +The note is attributed to the connected +user and needs the AddNote permission in -Group. + +API secret connections: the RESTful API Manager extension's AddNoteToSession. +The note is +attributed to the extension's RESTfulUserName setting ("RESTful API" by default); -Group is ignored. + +## EXAMPLES + +### EXAMPLE 1 +``` +Add-CWCSessionNote -GUID $SessionID -Note 'Rebooted for patching' +``` + +## PARAMETERS + +### -GUID +Session ID. + +```yaml +Type: Guid +Parameter Sets: (All) +Aliases: SessionID + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Note +Note text. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Group +Session group containing the session (credentials connections only). +Defaults to 'All Machines'. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: All Machines +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/Connect-CWC.md b/Docs/Connect-CWC.md index 0a195b5..64d1fb4 100644 --- a/Docs/Connect-CWC.md +++ b/Docs/Connect-CWC.md @@ -12,8 +12,15 @@ Initializes the connection parameters for the module. ## SYNTAX +### Credentials (Default) ``` -Connect-CWC [-Server] [-Credentials] [-Force] [] +Connect-CWC -Server -Credentials [-Force] + [] +``` + +### ApiSecret +``` +Connect-CWC -Server -ApiSecret [-Origin ] [-Force] [] ``` ## DESCRIPTION @@ -30,60 +37,90 @@ Sets connection information used by the module and overwrites any previously set ## PARAMETERS +### -Server +The URL to your control server. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -Credentials Credentials used to authenticate with the control server. ```yaml Type: PSCredential -Parameter Sets: (All) +Parameter Sets: Credentials Aliases: Required: True -Position: 1 +Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -Force -Used to overwrite any information already loaded in the session. +### -ApiSecret +The RESTful API Manager extension's RESTfulAuthenticationSecret value. ```yaml -Type: SwitchParameter -Parameter Sets: (All) +Type: SecureString +Parameter Sets: ApiSecret Aliases: -Required: False +Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -Server -The URL to your control server. +### -Origin +Origin header sent with -ApiSecret requests. Defaults to https://. Set it to match the +extension's RESTfulAllowedOrigin setting if that setting is configured. ```yaml Type: String +Parameter Sets: ApiSecret +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Force +Used to overwrite any information already loaded in the session. + +```yaml +Type: SwitchParameter Parameter Sets: (All) Aliases: -Required: True -Position: 0 +Required: False +Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS -### None ## OUTPUTS -### System.Object ## NOTES ## RELATED LINKS diff --git a/Docs/Find-CWCSession.md b/Docs/Find-CWCSession.md new file mode 100644 index 0000000..d9ff939 --- /dev/null +++ b/Docs/Find-CWCSession.md @@ -0,0 +1,115 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# Find-CWCSession + +## SYNOPSIS +Finds sessions by session filter expression, name or ID (API secret connections). + +## SYNTAX + +### Filter (Default) +``` +Find-CWCSession -Filter [] +``` + +### Name +``` +Find-CWCSession -Name [] +``` + +### GUID +``` +Find-CWCSession -GUID [] +``` + +## DESCRIPTION +Calls the RESTful API Manager extension. +Searches all sessions of every type; results are not +limited by role permissions or session groups. + +-Filter uses Control's session filter syntax, the same syntax as session group filters, +e.g. +"Name LIKE 'DESKTOP-*'" or "CustomProperty1 = 'Acme'". + +## EXAMPLES + +### EXAMPLE 1 +``` +Find-CWCSession -Filter "GuestOperatingSystemName LIKE '*Server*'" +``` + +### EXAMPLE 2 +``` +Find-CWCSession -Name 'DESKTOP-01' +``` + +## PARAMETERS + +### -Filter +A session filter expression (GetSessionsByFilter). + +```yaml +Type: String +Parameter Sets: Filter +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Name +Exact session name (GetSessionsByName). +Single quotes are not allowed because the extension +inserts the name into a filter expression without escaping. + +```yaml +Type: String +Parameter Sets: Name +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -GUID +Session ID (GetSessionBySessionID). + +```yaml +Type: Guid +Parameter Sets: GUID +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +Requires Connect-CWC -ApiSecret and the RESTful API Manager extension. +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/Get-CWCAuditInfo.md b/Docs/Get-CWCAuditInfo.md index 59f7cd5..d7dcbbc 100644 --- a/Docs/Get-CWCAuditInfo.md +++ b/Docs/Get-CWCAuditInfo.md @@ -30,6 +30,7 @@ Displays the current audit settings ## PARAMETERS + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). diff --git a/Docs/Get-CWCAuditLog.md b/Docs/Get-CWCAuditLog.md index 1a02226..d8ae9f5 100644 --- a/Docs/Get-CWCAuditLog.md +++ b/Docs/Get-CWCAuditLog.md @@ -32,7 +32,7 @@ Get the audit logs for Computer1 for the last day. ## PARAMETERS ### -EndDate -{{ Fill EndDate Description }} +End of the time range. Defaults to now. Local times are converted to UTC. ```yaml Type: DateTime @@ -47,7 +47,7 @@ Accept wildcard characters: False ``` ### -EventTypes -{{ Fill EventTypes Description }} +Session event type numbers to include (for example 44 for QueuedCommand, 70 for RanCommand). ```yaml Type: Int32[] @@ -62,7 +62,7 @@ Accept wildcard characters: False ``` ### -IncludeSessionCaptures -{{ Fill IncludeSessionCaptures Description }} +Deprecated. The server no longer accepts this option; it is ignored with a warning. ```yaml Type: SwitchParameter @@ -77,7 +77,7 @@ Accept wildcard characters: False ``` ### -SecurityTypes -{{ Fill SecurityTypes Description }} +Security event type numbers to include. ```yaml Type: Int32[] @@ -92,7 +92,7 @@ Accept wildcard characters: False ``` ### -SessionName -{{ Fill SessionName Description }} +Only return entries for sessions with this name. ```yaml Type: String @@ -107,7 +107,7 @@ Accept wildcard characters: False ``` ### -StartDate -{{ Fill StartDate Description }} +Start of the time range. Defaults to 24 hours ago. Local times are converted to UTC. ```yaml Type: DateTime @@ -121,6 +121,7 @@ Accept pipeline input: False Accept wildcard characters: False ``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). diff --git a/Docs/Get-CWCLastContact.md b/Docs/Get-CWCLastContact.md index c4c080e..421ca68 100644 --- a/Docs/Get-CWCLastContact.md +++ b/Docs/Get-CWCLastContact.md @@ -97,6 +97,7 @@ Accept pipeline input: False Accept wildcard characters: False ``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). diff --git a/Docs/Get-CWCLauncURL.md b/Docs/Get-CWCLauncURL.md index 2a146eb..aedfa1c 100644 --- a/Docs/Get-CWCLauncURL.md +++ b/Docs/Get-CWCLauncURL.md @@ -1,60 +1,131 @@ --- external help file: ConnectWiseControlAPI-help.xml Module Name: ConnectWiseControlAPI -online version: +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI schema: 2.0.0 --- # Get-CWCLauncURL ## SYNOPSIS -{{ Fill in the Synopsis }} +DEPRECATED. +Use Get-CWCRemoteWorkforceLaunchURL. ## SYNTAX ``` -Get-CWCLauncURL [-GUID] [-WhatIf] [-Confirm] [] +Get-CWCLauncURL [-GUID] [[-OnSuccess] ] [[-OnFailure] ] [[-UserContext] ] + [[-UserNameOverride] ] [[-PasswordOverride] ] + [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION -{{ Fill in the Description }} +Retained for backwards compatibility. +Forwards -GUID to Get-CWCRemoteWorkforceLaunchURL. +The Remote Workforce GetLaunchUrlForSessionId endpoint takes only a session ID, so the +OnSuccess, OnFailure, UserContext, UserNameOverride and PasswordOverride parameters are +ignored. +This function will be removed in v1.0. ## EXAMPLES -### Example 1 -```powershell -PS C:\> {{ Add example code here }} +### EXAMPLE 1 +``` +Get-CWCRemoteWorkforceLaunchURL -GUID $SessionID ``` - -{{ Add example description here }} ## PARAMETERS -### -Confirm -Prompts you for confirmation before running the cmdlet. +### -GUID +One or more session IDs. ```yaml -Type: SwitchParameter +Type: Guid[] Parameter Sets: (All) -Aliases: cf +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -OnSuccess +Ignored. +Not accepted by the server. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: Required: False -Position: Named +Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -GUID -{{ Fill GUID Description }} +### -OnFailure +Ignored. +Not accepted by the server. ```yaml -Type: Guid[] +Type: String Parameter Sets: (All) Aliases: -Required: True -Position: 0 +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UserContext +Ignored. +Not accepted by the server. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UserNameOverride +Ignored. +Not accepted by the server. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PasswordOverride +Ignored. +Not accepted by the server. + +```yaml +Type: SecureString +Parameter Sets: (All) +Aliases: + +Required: False +Position: 6 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -76,15 +147,34 @@ Accept pipeline input: False Accept wildcard characters: False ``` +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS -### None ## OUTPUTS -### System.Object ## NOTES +Deprecated in favor of Get-CWCRemoteWorkforceLaunchURL. +Author: Chris Taylor ## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/Get-CWCRemoteWorkforceLaunchURL.md b/Docs/Get-CWCRemoteWorkforceLaunchURL.md new file mode 100644 index 0000000..1d3a6d1 --- /dev/null +++ b/Docs/Get-CWCRemoteWorkforceLaunchURL.md @@ -0,0 +1,101 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# Get-CWCRemoteWorkforceLaunchURL + +## SYNOPSIS +Gets a Remote Workforce host launch URL for an assigned machine. + +## SYNTAX + +### GUID (Default) +``` +Get-CWCRemoteWorkforceLaunchURL -GUID [] +``` + +### SessionName +``` +Get-CWCRemoteWorkforceLaunchURL -SessionName [] +``` + +## DESCRIPTION +Calls the Remote Workforce extension's GetLaunchUrlForSessionId (by session GUID) or +GetLaunchUrl (by session name) endpoint and returns a ClickOnce launch URL. + +The extension only returns a URL when the CALLING user is the user the machine is assigned to +(the session is in their Remote Workforce session group, "My Assigned Machines" by default) +and has View and Join permissions on that group. +Otherwise the server returns null and this +function writes a warning. +An administrator cannot get launch URLs for other users' machines. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-CWCRemoteWorkforceLaunchURL -GUID 'd2b6f0a1-1111-2222-3333-444455556666' +``` + +### EXAMPLE 2 +``` +Get-CWCRemoteWorkforceSession | Get-CWCRemoteWorkforceLaunchURL +``` + +### EXAMPLE 3 +``` +Get-CWCRemoteWorkforceLaunchURL -SessionName 'DESKTOP-01' +``` + +## PARAMETERS + +### -GUID +One or more session IDs. +Each is requested separately. + +```yaml +Type: Guid[] +Parameter Sets: GUID +Aliases: SessionID + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -SessionName +The session name to look up within the caller's Remote Workforce sessions. + +```yaml +Type: String +Parameter Sets: SessionName +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +Requires the Remote Workforce extension (2c4f522f-b39a-413a-8807-dc52a2fce13e), Control 23.6+. +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/Get-CWCRemoteWorkforceSession.md b/Docs/Get-CWCRemoteWorkforceSession.md new file mode 100644 index 0000000..9668e19 --- /dev/null +++ b/Docs/Get-CWCRemoteWorkforceSession.md @@ -0,0 +1,53 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# Get-CWCRemoteWorkforceSession + +## SYNOPSIS +Lists the Remote Workforce machines assigned to the calling user. + +## SYNTAX + +``` +Get-CWCRemoteWorkforceSession [] +``` + +## DESCRIPTION +Calls the Remote Workforce extension's GetRemoteWorkforceSessions endpoint, which returns the +sessions in the extension's session group for the CALLING user that they can view and join. +The server's name-to-ID map is returned as objects with Name and SessionID properties. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-CWCRemoteWorkforceSession +``` + +### EXAMPLE 2 +``` +Get-CWCRemoteWorkforceSession | Get-CWCRemoteWorkforceLaunchURL +``` + +## PARAMETERS + + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +Requires the Remote Workforce extension (2c4f522f-b39a-413a-8807-dc52a2fce13e), Control 23.6+. +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/Get-CWCSecurityConfigurationInfo.md b/Docs/Get-CWCSecurityConfigurationInfo.md index 48967f9..461f553 100644 --- a/Docs/Get-CWCSecurityConfigurationInfo.md +++ b/Docs/Get-CWCSecurityConfigurationInfo.md @@ -30,6 +30,7 @@ Returns security configuration ## PARAMETERS + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). diff --git a/Docs/Get-CWCSession.md b/Docs/Get-CWCSession.md index c614118..498acb9 100644 --- a/Docs/Get-CWCSession.md +++ b/Docs/Get-CWCSession.md @@ -13,7 +13,7 @@ Will return a list of sessions. ## SYNTAX ``` -Get-CWCSession -Type [-Group ] [-Search ] [-Limit ] [] +Get-CWCSession -Type [-Group ] [-Search ] [-FindSessionID ] [-Limit ] [] ``` ## DESCRIPTION @@ -90,6 +90,22 @@ Accept pipeline input: False Accept wildcard characters: False ``` +### -FindSessionID +Session ID to locate in the results, so the session is included even when -Limit would cut it off. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). diff --git a/Docs/Get-CWCSessionDetail.md b/Docs/Get-CWCSessionDetail.md index 6dcb0c1..13fec66 100644 --- a/Docs/Get-CWCSessionDetail.md +++ b/Docs/Get-CWCSessionDetail.md @@ -13,7 +13,8 @@ Will return information about a session. ## SYNTAX ``` -Get-CWCSessionDetail [-Group ] -GUID [] +Get-CWCSessionDetail [-Group ] -GUID [-Include ] + [] ``` ## DESCRIPTION @@ -60,6 +61,22 @@ Accept pipeline input: False Accept wildcard characters: False ``` +### -Include +Parts of the session details to return: SessionInfo, GuestScreenshotContent, Events, Connections. Omit to return everything, including the guest screenshot. Ignored on -ApiSecret connections. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). diff --git a/Docs/Get-CWCSessionGroup.md b/Docs/Get-CWCSessionGroup.md index 8d116e1..a33e74f 100644 --- a/Docs/Get-CWCSessionGroup.md +++ b/Docs/Get-CWCSessionGroup.md @@ -30,6 +30,7 @@ Returns details of all session groups. ## PARAMETERS + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). diff --git a/Docs/Initialize-CWCRemoteWorkforceSessionGroup.md b/Docs/Initialize-CWCRemoteWorkforceSessionGroup.md new file mode 100644 index 0000000..0b10106 --- /dev/null +++ b/Docs/Initialize-CWCRemoteWorkforceSessionGroup.md @@ -0,0 +1,87 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# Initialize-CWCRemoteWorkforceSessionGroup + +## SYNOPSIS +Creates or repairs the session group used by the Remote Workforce extension. + +## SYNTAX + +``` +Initialize-CWCRemoteWorkforceSessionGroup [-WhatIf] [-Confirm] + [] +``` + +## DESCRIPTION +Calls the Remote Workforce extension's EnsureCorrectSessionGroupExists endpoint. +The extension +creates its Access session group (name from the SessionGroupName setting, "My Assigned Machines" +by default) with the filter Notes LIKE '*|UserName:' + $USERLOGINNAME + ',*', or repairs an +older group whose filter was missing the trailing comma. +Without this group, assignments made +with New-CWCRemoteWorkforceAssignment are not visible to users. + +Idempotent. +Requires the Administer permission. + +## EXAMPLES + +### EXAMPLE 1 +``` +Initialize-CWCRemoteWorkforceSessionGroup +``` + +## PARAMETERS + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +Requires the Remote Workforce extension (2c4f522f-b39a-413a-8807-dc52a2fce13e), Control 23.6+. +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/Invoke-CWCCommand.md b/Docs/Invoke-CWCCommand.md index 3bd1e50..6c78f3a 100644 --- a/Docs/Invoke-CWCCommand.md +++ b/Docs/Invoke-CWCCommand.md @@ -131,7 +131,7 @@ Accept wildcard characters: False ``` ### -MaxLength -{{ Fill MaxLength Description }} +Maximum number of characters of command output to return. Defaults to 10000. ```yaml Type: Int32 @@ -145,6 +145,7 @@ Accept pipeline input: False Accept wildcard characters: False ``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). diff --git a/Docs/Invoke-CWCWake.md b/Docs/Invoke-CWCWake.md index a6a8b91..f916cdc 100644 --- a/Docs/Invoke-CWCWake.md +++ b/Docs/Invoke-CWCWake.md @@ -61,6 +61,7 @@ Accept pipeline input: False Accept wildcard characters: False ``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). diff --git a/Docs/New-CWCAccessToken.md b/Docs/New-CWCAccessToken.md index d3a7e79..a650853 100644 --- a/Docs/New-CWCAccessToken.md +++ b/Docs/New-CWCAccessToken.md @@ -1,74 +1,81 @@ --- external help file: ConnectWiseControlAPI-help.xml Module Name: ConnectWiseControlAPI -online version: +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI schema: 2.0.0 --- # New-CWCAccessToken ## SYNOPSIS -{{ Fill in the Synopsis }} +Gets an access token for joining a session. ## SYNTAX ``` -New-CWCAccessToken [[-Group] ] [-GUID] [] +New-CWCAccessToken [[-Group] ] [-GUID] [] ``` ## DESCRIPTION -{{ Fill in the Description }} +Calls PageService.GetAccessToken. +The token lets a Host client join the session with the +connected user's permissions for that session group; the user needs the JoinSession +permission in -Group. +Treat the token as a secret. ## EXAMPLES -### Example 1 -```powershell -PS C:\> {{ Add example code here }} +### EXAMPLE 1 +``` +$Token = New-CWCAccessToken -GUID $SessionID ``` - -{{ Add example description here }} ## PARAMETERS -### -GUID -{{ Fill GUID Description }} +### -Group +Session group containing the session. +Defaults to 'All Machines'. ```yaml -Type: Guid +Type: String Parameter Sets: (All) Aliases: -Required: True +Required: False Position: 1 -Default value: None +Default value: All Machines Accept pipeline input: False Accept wildcard characters: False ``` -### -Group -{{ Fill Group Description }} +### -GUID +Session ID. ```yaml -Type: String[] +Type: Guid Parameter Sets: (All) Aliases: -Required: False -Position: 0 +Required: True +Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS -### None ## OUTPUTS -### System.Object ## NOTES +Requires Connect-CWC -Credentials. +Author: Chris Taylor ## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/New-CWCMFA.md b/Docs/New-CWCMFA.md index d327518..95ea1ce 100644 --- a/Docs/New-CWCMFA.md +++ b/Docs/New-CWCMFA.md @@ -13,7 +13,8 @@ Will generate an MFA code to use with user creation. ## SYNTAX ``` -New-CWCMFA [-DisplayName ] [-UserAccount ] [-WhatIf] [-Confirm] [] +New-CWCMFA [-DisplayName ] [-UserAccount ] [-WhatIf] + [-Confirm] [] ``` ## DESCRIPTION @@ -90,6 +91,7 @@ Accept pipeline input: False Accept wildcard characters: False ``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). diff --git a/Docs/New-CWCRemoteWorkforceAssignment.md b/Docs/New-CWCRemoteWorkforceAssignment.md index af5fdd1..8cdc971 100644 --- a/Docs/New-CWCRemoteWorkforceAssignment.md +++ b/Docs/New-CWCRemoteWorkforceAssignment.md @@ -13,8 +13,7 @@ Assign a user to machines. ## SYNTAX ``` -New-CWCRemoteWorkforceAssignment -GUID -Username [-DisplayName ] [-WhatIf] [-Confirm] - [] +New-CWCRemoteWorkforceAssignment -GUID -Username [-DisplayName ] [-Group ] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION @@ -104,6 +103,22 @@ Accept pipeline input: False Accept wildcard characters: False ``` +### -Group +Session group containing the session(s). Defaults to 'All Machines' where a default exists. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). diff --git a/Docs/New-CWCSession.md b/Docs/New-CWCSession.md new file mode 100644 index 0000000..b220a36 --- /dev/null +++ b/Docs/New-CWCSession.md @@ -0,0 +1,164 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# New-CWCSession + +## SYNOPSIS +Creates a session. + +## SYNTAX + +``` +New-CWCSession [-Type] [-Name] [-IsPublic] [[-Code] ] + [[-CustomPropertyValues] ] [-WhatIf] [-Confirm] + [] +``` + +## DESCRIPTION +Creates a session and returns the new session ID. +Works with both connection types: + +-Credentials: PageService.CreateSession. +Requires the create permission for the session type; +the session host is the connected user. + +-ApiSecret: the RESTful API Manager extension's CreateSession. +The session host is the +extension's RESTfulUserName setting ("RESTful API" by default). + +## EXAMPLES + +### EXAMPLE 1 +``` +New-CWCSession -Type Support -Name 'Ticket 12345' -Code '12345' +``` + +## PARAMETERS + +### -Type +Support, Meeting or Access. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Name +Session name. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -IsPublic +Make the session publicly listed on the guest page. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Code +Session join code. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CustomPropertyValues +Custom property values in order (CustomProperty1, CustomProperty2, ...). + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: @() +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### System.Guid +## NOTES +Not retried on HTTP 500: a retry after the server created the session would create a second one. +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/New-CWCUser.md b/Docs/New-CWCUser.md index 80e1478..198a5f3 100644 --- a/Docs/New-CWCUser.md +++ b/Docs/New-CWCUser.md @@ -14,7 +14,8 @@ Creates a user. ``` New-CWCUser -Credentials [-OTP ] [-DisplayName ] -Email - [-SecurityGroups ] [-ForcePassChange ] [-WhatIf] [-Confirm] [] + [-SecurityGroups ] [-ForcePassChange ] [-WhatIf] + [-Confirm] [] ``` ## DESCRIPTION @@ -157,6 +158,7 @@ Accept pipeline input: False Accept wildcard characters: False ``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). diff --git a/Docs/Private/Invoke-CWCWebRequest.md b/Docs/Private/Invoke-CWCWebRequest.md deleted file mode 100644 index ca26865..0000000 --- a/Docs/Private/Invoke-CWCWebRequest.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -external help file: -Module Name: -online version: -schema: 2.0.0 ---- - -# Invoke-CWCWebRequest - -## SYNOPSIS -Used to make the web requests for the module - -## SYNTAX - -``` -Invoke-CWCWebRequest [[-Arguments] ] [[-MaxRetry] ] [] -``` - -## DESCRIPTION -Used by the module to invoke requests and handle errors - -## EXAMPLES - -### Example 1 -```powershell -PS C:\> Invoke-CWCWebRequest -Arguments $Args -``` - -Passes a set of arguments to the web request handler. - -## PARAMETERS - -### -Arguments -An object containing parameters for the web request - -```yaml -Type: Object -Parameter Sets: (All) -Aliases: - -Required: False -Position: 0 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -MaxRetry -amount of times a request will be attempted before failing - -```yaml -Type: Int32 -Parameter Sets: (All) -Aliases: - -Required: False -Position: 1 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### None - -## OUTPUTS - -### System.Object -## NOTES - -## RELATED LINKS diff --git a/Docs/Private/Join-Url.md b/Docs/Private/Join-Url.md deleted file mode 100644 index 3f30b94..0000000 --- a/Docs/Private/Join-Url.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -external help file: -Module Name: -online version: -schema: 2.0.0 ---- - -# Join-Url - -## SYNOPSIS -{{ Fill in the Synopsis }} - -## SYNTAX - -``` -Join-Url [-Path] [-ChildPath] [] -``` - -## DESCRIPTION -{{ Fill in the Description }} - -## EXAMPLES - -### Example 1 -```powershell -PS C:\> {{ Add example code here }} -``` - -{{ Add example description here }} - -## PARAMETERS - -### -ChildPath -{{ Fill ChildPath Description }} - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: True -Position: 1 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Path -{{ Fill Path Description }} - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: True -Position: 0 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### None - -## OUTPUTS - -### System.Object -## NOTES - -## RELATED LINKS diff --git a/Docs/Remove-CWCSession.md b/Docs/Remove-CWCSession.md index c3f7ce8..9cf19f9 100644 --- a/Docs/Remove-CWCSession.md +++ b/Docs/Remove-CWCSession.md @@ -13,7 +13,8 @@ Will end a given session. ## SYNTAX ``` -Remove-CWCSession -GUID -Group [-WhatIf] [-Confirm] [] +Remove-CWCSession -GUID -Group [-Uninstall] [-WhatIf] + [-Confirm] [] ``` ## DESCRIPTION @@ -77,7 +78,7 @@ Accept wildcard characters: False ``` ### -Group -{{ Fill Group Description }} +Session group containing the session(s). Defaults to 'All Machines' where a default exists. ```yaml Type: String @@ -91,6 +92,22 @@ Accept pipeline input: False Accept wildcard characters: False ``` + +### -Uninstall +Queue an uninstall of the Access client and delete the session (QueuedUninstallAndDelete) instead of only deleting the session record. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). diff --git a/Docs/Remove-CWCUser.md b/Docs/Remove-CWCUser.md index 90dc062..ab05e48 100644 --- a/Docs/Remove-CWCUser.md +++ b/Docs/Remove-CWCUser.md @@ -76,6 +76,7 @@ Accept pipeline input: False Accept wildcard characters: False ``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). diff --git a/Docs/Send-CWCSessionMessage.md b/Docs/Send-CWCSessionMessage.md new file mode 100644 index 0000000..3b1a7ab --- /dev/null +++ b/Docs/Send-CWCSessionMessage.md @@ -0,0 +1,146 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# Send-CWCSessionMessage + +## SYNOPSIS +Sends a chat message to a session's guest. + +## SYNTAX + +``` +Send-CWCSessionMessage [-GUID] [-Message] [[-From] ] [[-Group] ] [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +Queues a QueuedMessage session event. + +Credentials connections: PageService.AddSessionEvents. +The guest sees the connected user's +display name as the sender (-From is not supported) and the user needs the matching permission +in -Group. + +API secret connections: the RESTful API Manager extension's SendMessageToSession. +The guest sees +-From as the sender; -Group is ignored. + +## EXAMPLES + +### EXAMPLE 1 +``` +Send-CWCSessionMessage -GUID $SessionID -Message 'Your computer will restart in 5 minutes.' +``` + +## PARAMETERS + +### -GUID +Session ID. + +```yaml +Type: Guid +Parameter Sets: (All) +Aliases: SessionID + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Message +Message text. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -From +Sender name shown to the guest (API secret connections only). + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: RESTful API +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Group +Session group containing the session (credentials connections only). +Defaults to 'All Machines'. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: All Machines +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/Send-CWCToolboxItem.md b/Docs/Send-CWCToolboxItem.md new file mode 100644 index 0000000..90f568b --- /dev/null +++ b/Docs/Send-CWCToolboxItem.md @@ -0,0 +1,128 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# Send-CWCToolboxItem + +## SYNOPSIS +Queues a Toolbox item to run on a session. + +## SYNTAX + +``` +Send-CWCToolboxItem [-GUID] [-Name] [[-Group] ] + [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +Queues a QueuedTool session event naming the Toolbox item. + +Credentials connections: PageService.AddSessionEvents; the user needs the RunSharedTool +permission in -Group. + +API secret connections: the RESTful API Manager extension's SendToolboxItemToSession; -Group is ignored. + +## EXAMPLES + +### EXAMPLE 1 +``` +Send-CWCToolboxItem -GUID $SessionID -Name 'Cleanup.ps1' +``` + +## PARAMETERS + +### -GUID +Session ID. + +```yaml +Type: Guid +Parameter Sets: (All) +Aliases: SessionID + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Name +Toolbox item name as shown in the Control Toolbox. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Group +Session group containing the session (credentials connections only). +Defaults to 'All Machines'. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: All Machines +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/Update-CWCCustomProperty.md b/Docs/Update-CWCCustomProperty.md index 0f65d2e..a62c4ee 100644 --- a/Docs/Update-CWCCustomProperty.md +++ b/Docs/Update-CWCCustomProperty.md @@ -13,8 +13,7 @@ Will update a custom property for a session. ## SYNTAX ``` -Update-CWCCustomProperty -GUID -Property [-Value ] [-Group ] [-WhatIf] - [-Confirm] [] +Update-CWCCustomProperty -GUID -Property [-Value ] [-Group ] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION @@ -56,7 +55,7 @@ Accept wildcard characters: False Look for the session in these groups. ```yaml -Type: String[] +Type: String Parameter Sets: (All) Aliases: @@ -127,6 +126,7 @@ Accept pipeline input: False Accept wildcard characters: False ``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). diff --git a/Docs/Update-CWCSessionName.md b/Docs/Update-CWCSessionName.md index 9b8bcbb..10a4a0a 100644 --- a/Docs/Update-CWCSessionName.md +++ b/Docs/Update-CWCSessionName.md @@ -13,8 +13,8 @@ Updates the name of a session. ## SYNTAX ``` -Update-CWCSessionName -GUID -NewName [-Group ] [-WhatIf] [-Confirm] - [] +Update-CWCSessionName -GUID -NewName [-Group ] + [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION @@ -112,6 +112,7 @@ Accept pipeline input: False Accept wildcard characters: False ``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). diff --git a/Docs/Update-CWCUser.md b/Docs/Update-CWCUser.md index d7156af..9aefbb8 100644 --- a/Docs/Update-CWCUser.md +++ b/Docs/Update-CWCUser.md @@ -14,8 +14,7 @@ Update properties of an internal user. ``` Update-CWCUser [-UserToUpdate] [-NewUserName ] [-Password ] [[-OTP] ] - [[-DisplayName] ] [[-Email] ] [[-SecurityGroups] ] [[-ForcePassChange] ] - [-WhatIf] [-Confirm] [] + [[-DisplayName] ] [[-Email] ] [[-SecurityGroups] ] [[-ForcePassChange] ] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION @@ -183,6 +182,7 @@ Accept pipeline input: False Accept wildcard characters: False ``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). From beae4c3b797121f475fe77943eb1dddd7877749e Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Tue, 10 Nov 2026 09:19:43 -0700 Subject: [PATCH 09/30] Fix review findings: ignored source file, retry/error handling, example sort - .gitignore's *secret* pattern hid Private/Test-CWCApiSecretConnection.ps1, so a clean clone could not connect at all. Whitelist module source, tests and docs, commit the file, and add a test that fails if any module file is git-ignored. - RemoveRedundantSessions example: LastConnectedEventTime is seconds since the last connection, so the original ascending sort was right; restore it. - HTTP 500: a final failure keeps the server's error body instead of only "Max retries hit"; retries wait 2/4/8 seconds (were 2-32 ms), 3 retries. - Strip auth headers from the failed request on PS 5.1 too (HttpWebRequest). - Invoke-CWCCommand compares event times on the server clock (BaseTime). - Restore [string[]] -Group (nested group path parts) on Update-CWCCustomProperty and New-CWCAccessToken. - CHANGELOG: mark the Remove-CWCSession prompt as breaking. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 5 +++ CHANGELOG.md | 12 +++-- .../Private/Invoke-CWCServiceMethod.ps1 | 3 +- .../Private/Invoke-CWCWebRequest.ps1 | 44 ++++++++++--------- .../Private/Test-CWCApiSecretConnection.ps1 | 8 ++++ .../Public/PageService/Invoke-CWCCommand.ps1 | 18 +++++--- .../Public/PageService/New-CWCAccessToken.ps1 | 5 ++- .../PageService/Update-CWCCustomProperty.ps1 | 5 ++- Examples/RemoveRedundantSessions.ps1 | 5 ++- Tests/ConnectWiseControlAPI.Module.Tests.ps1 | 17 +++++++ 10 files changed, 83 insertions(+), 39 deletions(-) create mode 100644 ConnectWiseControlAPI/Private/Test-CWCApiSecretConnection.ps1 diff --git a/.gitignore b/.gitignore index 2392713..3ff188f 100644 --- a/.gitignore +++ b/.gitignore @@ -83,6 +83,11 @@ publish/ *credentials* *secret* !.github/SECURITY.md +# Source, tests and docs are never secrets, even when a name matches (e.g. Test-CWCApiSecretConnection.ps1) +!ConnectWiseControlAPI/**/*.ps1 +!ConnectWiseControlAPI/en-US/*-help.xml +!Tests/**/*.ps1 +!Docs/**/*.md # ---- Claude Code ---- .claude/settings.local.json diff --git a/CHANGELOG.md b/CHANGELOG.md index ca796d9..95fe41f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,10 +52,12 @@ Planned as 0.5.0.0 (the module manifest already carries this version; 0.4.0.0 is - All API calls go through one internal helper that builds the endpoint and serializes arguments the same way everywhere (single items, empty lists and nested event entries) - HTTP 500 retries are limited to calls that are safe to repeat (reads, "set to value" updates). Before, - a 500 returned after the server had acted could queue a second command, wake, delete or user + a 500 returned after the server had acted could queue a second command, wake, delete or user. Retries + now wait 2, 4 and 8 seconds (3 retries); the old 2-32 ms waits gave a struggling server no time to + recover. A final 500 error now includes the server's error message - Session event type numbers are kept in one table, verified against a live server's web client -- `Remove-CWCSession` prompts by default (`ConfirmImpact = 'High'`), confirms each session separately and - rejects an empty GUID +- **Breaking:** `Remove-CWCSession` prompts by default (`ConfirmImpact = 'High'`), confirms each session + separately and rejects an empty GUID. Unattended scripts must add `-Confirm:$false` - `Connect-CWC` reports a failed login with its likely causes. Wrong credentials are not rejected with a 401: the request runs as an anonymous user and fails with "Needs permission" - `Get-CWCLastContact` returns an error when no connection event is found, instead of the current time @@ -80,7 +82,9 @@ Endpoint calls audited against the Control server's `Services/*.ashx` source: - Cookies set by the server were sent back as a `Set-Cookie` request header, so the server never received them; credentials connections now keep a web session (likely cause of "Invalid anti-forgery token", #22) - The anti-forgery token regex depended on JSON key order on the server's front page -- On PS 6+, failed requests left auth headers on the request object kept in `$Error`; they are now stripped +- Failed requests left auth headers on the request object kept in `$Error` (PS 5.1 and PS 6+); they are now stripped +- `Invoke-CWCCommand` compares event times on the server's clock, so poll latency can no longer make it + skip a fast command's output or return a previous command's output - On PS 5.1, a non-JSON error body (IIS 401/404 page) threw while building the error and hid the real status - `Get-CWCLastContact -Quiet -Seconds` was off by the local UTC offset (mixed UTC and local DateTimes) - `Remove-CWCSession` packed multiple GUIDs into a single event entry; it now sends one entry per session diff --git a/ConnectWiseControlAPI/Private/Invoke-CWCServiceMethod.ps1 b/ConnectWiseControlAPI/Private/Invoke-CWCServiceMethod.ps1 index af7c1ea..9e2e336 100644 --- a/ConnectWiseControlAPI/Private/Invoke-CWCServiceMethod.ps1 +++ b/ConnectWiseControlAPI/Private/Invoke-CWCServiceMethod.ps1 @@ -66,8 +66,9 @@ function Invoke-CWCServiceMethod { if ($Sensitive) { Write-Verbose "POST $Endpoint (arguments redacted)" } else { Write-Verbose "POST $Endpoint $($WebRequestArguments.Body)" } + # 3 retries with 2, 4, 8 second waits $MaxRetry = 0 - if ($Idempotent) { $MaxRetry = 5 } + if ($Idempotent) { $MaxRetry = 3 } Invoke-CWCWebRequest -Arguments $WebRequestArguments -MaxRetry $MaxRetry -SensitiveBody:$Sensitive } diff --git a/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 b/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 index aacab0b..cbebbdc 100644 --- a/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 +++ b/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 @@ -73,39 +73,40 @@ break } catch { - # PS 6+ puts the HttpRequestMessage (with auth headers) on the error record, which stays in - # $Error. Strip the secrets from it. + # The failed request object (with auth headers) stays on the error record in $Error: + # HttpRequestMessage on PS 6+, HttpWebRequest on PS 5.1. Strip the secrets from it. # Type-name check: a [System.Net.Http.HttpRequestMessage] literal fails on PS 5.1 when the assembly isn't loaded. - if ($_.TargetObject -and $_.TargetObject.GetType().FullName -eq 'System.Net.Http.HttpRequestMessage') { + $FailedRequest = $_.TargetObject + if ($FailedRequest -and $FailedRequest.GetType().FullName -in 'System.Net.Http.HttpRequestMessage', 'System.Net.HttpWebRequest') { foreach ($SecretHeader in 'Authorization', 'CTRLAuthHeader', 'x-anti-forgery-token') { - $null = $_.TargetObject.Headers.Remove($SecretHeader) + try { $null = $FailedRequest.Headers.Remove($SecretHeader) } catch { Write-Verbose "Could not strip $SecretHeader from the failed request." } } } - # Retry on HTTP 500 (no response yields 0) + # Retry on HTTP 500 when the caller allows it (no response yields 0) $StatusCode = [int]$_.Exception.Response.StatusCode - if ($StatusCode -eq 500) { - if ($Retry -ge $MaxRetry) { - return Write-Error "Max retries hit. Status: 500" - } + if ($StatusCode -eq 500 -and $Retry -lt $MaxRetry) { $Retry++ - # ConnectWise Manage recommended wait time - $Wait = [math]::pow(2, $Retry) - Write-Warning "Issue with request, status: 500" - Write-Warning "$($Retry)/$($MaxRetry) retries, waiting $($Wait)ms." - Start-Sleep -Milliseconds $Wait + # Exponential backoff: 2, 4, 8 ... seconds + $Wait = [math]::Pow(2, $Retry) + Write-Warning "HTTP 500 from the server; retry $Retry/$MaxRetry in $Wait seconds." + Start-Sleep -Seconds $Wait continue } - # Build error message for non-retryable errors + # Build the error message, keeping the server's error body $ErrorMessage = @() + if ($StatusCode -eq 500 -and $MaxRetry -gt 0) { $ErrorMessage += "Max retries hit ($MaxRetry). Status: 500" } if ($_.Exception.Response -and $PSVersionTable.PSVersion.Major -lt 6) { - $ErrorStream = $_.Exception.Response.GetResponseStream() - $Reader = New-Object System.IO.StreamReader($ErrorStream) - # Error bodies are not always JSON (IIS 401/404 pages); don't let the parse mask the status. + # Error bodies are not always JSON (IIS 401/404 pages) and the stream may be unreadable; + # don't let reading or parsing it mask the status. $ErrBody = $null - try { $ErrBody = $Reader.ReadToEnd() | ConvertFrom-Json } catch { $ErrBody = $null } + try { + $Reader = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream()) + $ErrBody = $Reader.ReadToEnd() | ConvertFrom-Json + } + catch { $ErrBody = $null } if ($ErrBody.code) { $ErrorMessage += 'An exception has been thrown.' @@ -134,8 +135,9 @@ } } - if ($ErrorMessage.Length -lt 1) { $ErrorMessage = $_ } - else { $ErrorMessage += $_.ScriptStackTrace } + # Nothing beyond the retry line: fall back to the exception itself + if ($ErrorMessage.Count -le 1) { $ErrorMessage += "$_" } + $ErrorMessage += $_.ScriptStackTrace return Write-Error ($ErrorMessage | Out-String) } diff --git a/ConnectWiseControlAPI/Private/Test-CWCApiSecretConnection.ps1 b/ConnectWiseControlAPI/Private/Test-CWCApiSecretConnection.ps1 new file mode 100644 index 0000000..e9a3472 --- /dev/null +++ b/ConnectWiseControlAPI/Private/Test-CWCApiSecretConnection.ps1 @@ -0,0 +1,8 @@ +function Test-CWCApiSecretConnection { + [CmdletBinding()] + [OutputType([bool])] + param() + + # True when Connect-CWC was called with -ApiSecret (RESTful API Manager extension auth) + [bool]($script:CWCServerConnection -and $script:CWCServerConnection.AuthType -eq 'ApiSecret') +} diff --git a/ConnectWiseControlAPI/Public/PageService/Invoke-CWCCommand.ps1 b/ConnectWiseControlAPI/Public/PageService/Invoke-CWCCommand.ps1 index c560732..c14e28b 100644 --- a/ConnectWiseControlAPI/Public/PageService/Invoke-CWCCommand.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Invoke-CWCCommand.ps1 @@ -46,8 +46,10 @@ } # Poll for the command's output: the first RanCommand event newer than the queued command. + # Event times are compared on the server's clock (response BaseTime minus elapsed ms), so the + # round-trip time of each poll doesn't shift them. $TimeOutDateTime = (Get-Date).AddMilliseconds($TimeOut).AddSeconds(1) - $QueuedAtUtc = $null + $QueuedAtServerMs = $null do { # Events only: this polls every second against a rate-limited endpoint. try { $SessionDetails = Get-CWCSessionDetail -Group $Group -GUID $GUID -Include 'Events' -ErrorAction Stop } @@ -56,18 +58,20 @@ return } - if (-not $QueuedAtUtc) { + $BaseTime = [double]$SessionDetails.BaseTime + + if ($null -eq $QueuedAtServerMs) { # The most recent queued command (smallest elapsed time) is the one just sent $QueuedEvent = $SessionDetails.Events | Where-Object { $_.EventType -eq $QueuedCommandEventType } | Sort-Object { [double]$_.Time } | Select-Object -First 1 - if ($QueuedEvent) { $QueuedAtUtc = ConvertFrom-CWCEventTime -SessionEvent $QueuedEvent } + if ($QueuedEvent) { $QueuedAtServerMs = $BaseTime - [double]$QueuedEvent.Time } } - if ($QueuedAtUtc) { + if ($null -ne $QueuedAtServerMs) { $OutputEvent = $SessionDetails.Events | Where-Object { - $_.EventType -eq $RanCommandEventType -and $_.Time -and - (ConvertFrom-CWCEventTime -SessionEvent $_) -gt $QueuedAtUtc - } | Select-Object -First 1 + $_.EventType -eq $RanCommandEventType -and $null -ne $_.Time -and + ($BaseTime - [double]$_.Time) -gt $QueuedAtServerMs + } | Sort-Object { [double]$_.Time } -Descending | Select-Object -First 1 if ($OutputEvent) { Write-Verbose $OutputEvent.Data return $OutputEvent.Data -split '[\r\n]' | Where-Object { $_ -and $_ -ne "C:\WINDOWS\system32>$Command" } diff --git a/ConnectWiseControlAPI/Public/PageService/New-CWCAccessToken.ps1 b/ConnectWiseControlAPI/Public/PageService/New-CWCAccessToken.ps1 index 00e1c07..30f34d1 100644 --- a/ConnectWiseControlAPI/Public/PageService/New-CWCAccessToken.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/New-CWCAccessToken.ps1 @@ -9,7 +9,8 @@ permission in -Group. Treat the token as a secret. .PARAMETER Group - Session group containing the session. Defaults to 'All Machines'. + Session group containing the session: a name, or the path parts of a nested group + (e.g. 'Clients','Acme'). Defaults to 'All Machines'. .PARAMETER GUID Session ID. @@ -26,7 +27,7 @@ #> [CmdletBinding()] param ( - [string]$Group = 'All Machines', + [string[]]$Group = 'All Machines', [Parameter(Mandatory = $True)] [guid]$GUID ) diff --git a/ConnectWiseControlAPI/Public/PageService/Update-CWCCustomProperty.ps1 b/ConnectWiseControlAPI/Public/PageService/Update-CWCCustomProperty.ps1 index a4d765e..0491950 100644 --- a/ConnectWiseControlAPI/Public/PageService/Update-CWCCustomProperty.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Update-CWCCustomProperty.ps1 @@ -6,11 +6,12 @@ function Update-CWCCustomProperty { [Parameter(Mandatory=$True)] [int]$Property, [string]$Value, - [string]$Group = 'All Machines' + # Session group name, or the path parts of a nested group (e.g. 'Clients','Acme') + [string[]]$Group = 'All Machines' ) if ($PSCmdlet.ShouldProcess("$GUID", "Set custom property $Property to '$Value'")) { # Sets a value, so it is safe to retry - Invoke-CWCServiceMethod -Service PageService -Method UpdateSessionCustomPropertyValue -Arguments @($Group, $GUID, $Property, $Value) -Idempotent + Invoke-CWCServiceMethod -Service PageService -Method UpdateSessionCustomPropertyValue -Arguments @(@($Group), $GUID, $Property, $Value) -Idempotent } } diff --git a/Examples/RemoveRedundantSessions.ps1 b/Examples/RemoveRedundantSessions.ps1 index 242f807..784018e 100644 --- a/Examples/RemoveRedundantSessions.ps1 +++ b/Examples/RemoveRedundantSessions.ps1 @@ -31,8 +31,9 @@ $RedundantSessionColl = Get-CWCSession -Type Access -Group $GroupName | Group-Object -Property Name | Where-Object -Property Count -gt 1 | ForEach-Object { - # Newest first, so Skip 1 keeps the most recently connected session - $_.Group | Sort-Object -Property LastConnectedEventTime -Descending | + # LastConnectedEventTime is seconds since the last connection: smallest first, so Skip 1 keeps + # the most recently connected session + $_.Group | Sort-Object -Property { [double]$_.LastConnectedEventTime } | Select-Object -Skip 1 } diff --git a/Tests/ConnectWiseControlAPI.Module.Tests.ps1 b/Tests/ConnectWiseControlAPI.Module.Tests.ps1 index d0fcaa3..bea6b9d 100644 --- a/Tests/ConnectWiseControlAPI.Module.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Module.Tests.ps1 @@ -359,3 +359,20 @@ Describe 'Parameter Validation' { } } } + +Describe 'Repository' { + # A .gitignore pattern once hid Private/Test-CWCApiSecretConnection.ps1 (matched *secret*), so the + # module only worked on machines that already had the file. + It 'does not git-ignore any module source file' { + $RepoRoot = Split-Path $PSScriptRoot -Parent + if (-not (Get-Command git -ErrorAction SilentlyContinue) -or -not (Test-Path (Join-Path $RepoRoot '.git'))) { + Set-ItResult -Skipped -Because 'git or the repository is not available' + return + } + $SourceFiles = Get-ChildItem (Join-Path $RepoRoot 'ConnectWiseControlAPI') -Recurse -File | + ForEach-Object { $_.FullName.Substring($RepoRoot.Length + 1).Replace('\', '/') } + # Paths as arguments, not --stdin: piped lines carry a trailing CR on Windows, which defeats the patterns + $Ignored = @(git -C $RepoRoot check-ignore --no-index -- $SourceFiles | Where-Object { $_ }) + $Ignored | Should -BeNullOrEmpty + } +} From b29acdfc784ebf816fd42dbec85dfe337e6ee680 Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Tue, 10 Nov 2026 09:27:51 -0700 Subject: [PATCH 10/30] Bring Remove-CWCHostFromSession (#28) to module conventions - Single -SessionID/-ConnectionID values: with [guid[]], several IDs were serialized into one event entry. - ConfirmImpact High with a readable ShouldProcess target (was the raw body), empty-GUID validation, [string[]] -Group for nested group paths. - Uses Invoke-CWCServiceMethod and the shared event table (48 = QueuedForceDisconnect, verified live); never retried. - Comment-based help crediting the contributor, tests, docs, changelog. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 + .../PageService/Remove-CWCHostFromSession.ps1 | 94 +++++---- .../en-US/ConnectWiseControlAPI-help.xml | 178 +++++++++++++++++- ConnectWiseControlAPI_Functions.md | 3 + Docs/New-CWCAccessToken.md | 5 +- Docs/Remove-CWCHostFromSession.md | 129 +++++++++++++ Docs/Remove-CWCSession.md | 2 +- Docs/Update-CWCCustomProperty.md | 4 +- Tests/ConnectWiseControlAPI.Module.Tests.ps1 | 2 + Tests/ConnectWiseControlAPI.Public.Tests.ps1 | 39 ++++ 10 files changed, 408 insertions(+), 50 deletions(-) create mode 100644 Docs/Remove-CWCHostFromSession.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 95fe41f..3352ed8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,8 @@ Planned as 0.5.0.0 (the module manifest already carries this version; 0.4.0.0 is - `Get-CWCRemoteWorkforceSession` lists the calling user's assigned machines (`GetRemoteWorkforceSessions`) - `Initialize-CWCRemoteWorkforceSessionGroup` creates/repairs the extension's session group (`EnsureCorrectSessionGroupExists`) +- `Remove-CWCHostFromSession` disconnects one connection from a session (QueuedForceDisconnect, event 48); + contributed by turbo-donkey (#28). Takes single `-SessionID`/`-ConnectionID` values and prompts by default - `Remove-CWCSession -Uninstall` queues `QueuedUninstallAndDelete` (event 100) so the Access client is uninstalled as well; without it the session record is only deleted (`DeletedSession`, event 21) diff --git a/ConnectWiseControlAPI/Public/PageService/Remove-CWCHostFromSession.ps1 b/ConnectWiseControlAPI/Public/PageService/Remove-CWCHostFromSession.ps1 index d50da55..3d2256b 100644 --- a/ConnectWiseControlAPI/Public/PageService/Remove-CWCHostFromSession.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Remove-CWCHostFromSession.ps1 @@ -1,38 +1,58 @@ -function Remove-CWCHostFromSession -{ - [CmdletBinding(SupportsShouldProcess)] - param ( - [Parameter(Mandatory = $True)] - [guid[]]$SessionID, - [Parameter(Mandatory = $True)] - [guid[]]$ConnectionID, - [Parameter(Mandatory = $True)] - [string]$Group - ) - - $Endpoint = 'Services/PageService.ashx/AddSessionEvents' - - $SessionEventType = 48 - $Body = ConvertTo-Json @( - @( - $Group - ), - @( - @{ - SessionID = $SessionID - EventType = $SessionEventType - ConnectionID = $ConnectionID - } +function Remove-CWCHostFromSession { + <# + .SYNOPSIS + Disconnects one connection (for example a host) from a session. + + .DESCRIPTION + Queues a QueuedForceDisconnect session event (type 48) for the given connection, the same + action as disconnecting a participant in the Control web UI. Connection IDs are listed in + (Get-CWCSessionDetail -GUID -Include Connections).Connections. + + .PARAMETER SessionID + Session ID. + + .PARAMETER ConnectionID + ID of the connection to disconnect. + + .PARAMETER Group + Session group containing the session: a name, or the path parts of a nested group. + + .EXAMPLE + $Connections = (Get-CWCSessionDetail -GUID $SessionID -Include Connections).Connections + $HostConnection = $Connections | Where-Object { $_.ProcessType -eq 1 } | Select-Object -First 1 + Remove-CWCHostFromSession -SessionID $SessionID -ConnectionID $HostConnection.ConnectionID -Group 'All Machines' + + Disconnects the first host connected to the session (ProcessType 1 = Host). + + .NOTES + Contributed by turbo-donkey (#28). + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] + param ( + [Parameter(Mandatory = $True)] + [ValidateScript({ $_ -ne [guid]::Empty })] + [guid]$SessionID, + + [Parameter(Mandatory = $True)] + [ValidateScript({ $_ -ne [guid]::Empty })] + [guid]$ConnectionID, + + [Parameter(Mandatory = $True)] + [string[]]$Group ) - ) - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - if ($PSCmdlet.ShouldProcess($WebRequestArguments.Body, 'Remove-CWCHostFromSession')) - { - Invoke-CWCWebRequest -Arguments $WebRequestArguments - } -} \ No newline at end of file + + if (-not $PSCmdlet.ShouldProcess("Connection $ConnectionID in session $SessionID", 'Force disconnect')) { return } + + $DisconnectEvent = @{ + SessionID = $SessionID + EventType = $script:CWCSessionEventType.QueuedForceDisconnect + ConnectionID = $ConnectionID + } + + # Not idempotent: never retried + Invoke-CWCServiceMethod -Service PageService -Method AddSessionEvents -Arguments @(@($Group), @($DisconnectEvent)) +} diff --git a/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml b/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml index 04c1a88..90dc973 100644 --- a/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml +++ b/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml @@ -2129,9 +2129,9 @@ Session group containing the session. Defaults to 'All Machines'. - String + String[] - String + String[] All Machines @@ -2156,9 +2156,9 @@ Session group containing the session. Defaults to 'All Machines'. - String + String[] - String + String[] All Machines @@ -2983,6 +2983,168 @@ New-CWCUser @NewUserParams + + + Remove-CWCHostFromSession + Remove + CWCHostFromSession + + Disconnects one connection (for example a host) from a session. + + + + Queues a QueuedForceDisconnect session event (type 48) for the given connection, the same action as disconnecting a participant in the Control web UI. Connection IDs are listed in (Get-CWCSessionDetail -GUID <session> -Include Connections).Connections. + + + + Remove-CWCHostFromSession + + SessionID + + Session ID. + + Guid + + Guid + + + None + + + ConnectionID + + ID of the connection to disconnect. + + Guid + + Guid + + + None + + + Group + + Session group containing the session: a name, or the path parts of a nested group. + + String[] + + String[] + + + None + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + SwitchParameter + + + False + + + + + + SessionID + + Session ID. + + Guid + + Guid + + + None + + + ConnectionID + + ID of the connection to disconnect. + + Guid + + Guid + + + None + + + Group + + Session group containing the session: a name, or the path parts of a nested group. + + String[] + + String[] + + + None + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + SwitchParameter + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + Contributed by turbo-donkey (#28). Author: Chris Taylor + + + + + -------------------------- EXAMPLE 1 -------------------------- + $Connections = (Get-CWCSessionDetail -GUID $SessionID -Include Connections).Connections +$HostConnection = $Connections | Where-Object { $_.ProcessType -eq 1 } | Select-Object -First 1 +Remove-CWCHostFromSession -SessionID $SessionID -ConnectionID $HostConnection.ConnectionID -Group 'All Machines' + + Disconnects the first host connected to the session (ProcessType 1 = Host). + + + + + + https://github.com/christaylorcodes/ConnectWiseControlAPI + https://github.com/christaylorcodes/ConnectWiseControlAPI + + + Remove-CWCSession @@ -3643,9 +3805,9 @@ New-CWCUser @NewUserParams Look for the session in these groups. - String + String[] - String + String[] All Machines @@ -3717,9 +3879,9 @@ New-CWCUser @NewUserParams Look for the session in these groups. - String + String[] - String + String[] All Machines diff --git a/ConnectWiseControlAPI_Functions.md b/ConnectWiseControlAPI_Functions.md index e657225..9d72a8b 100644 --- a/ConnectWiseControlAPI_Functions.md +++ b/ConnectWiseControlAPI_Functions.md @@ -78,6 +78,9 @@ Creates a session. ### [New-CWCUser](Docs/New-CWCUser.md) Creates a user. +### [Remove-CWCHostFromSession](Docs/Remove-CWCHostFromSession.md) +Disconnects one connection (for example a host) from a session. + ### [Remove-CWCSession](Docs/Remove-CWCSession.md) Will end a given session. diff --git a/Docs/New-CWCAccessToken.md b/Docs/New-CWCAccessToken.md index a650853..542d860 100644 --- a/Docs/New-CWCAccessToken.md +++ b/Docs/New-CWCAccessToken.md @@ -13,7 +13,8 @@ Gets an access token for joining a session. ## SYNTAX ``` -New-CWCAccessToken [[-Group] ] [-GUID] [] +New-CWCAccessToken [[-Group] ] [-GUID] + [] ``` ## DESCRIPTION @@ -37,7 +38,7 @@ Session group containing the session. Defaults to 'All Machines'. ```yaml -Type: String +Type: String[] Parameter Sets: (All) Aliases: diff --git a/Docs/Remove-CWCHostFromSession.md b/Docs/Remove-CWCHostFromSession.md new file mode 100644 index 0000000..bd6f2c7 --- /dev/null +++ b/Docs/Remove-CWCHostFromSession.md @@ -0,0 +1,129 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# Remove-CWCHostFromSession + +## SYNOPSIS +Disconnects one connection (for example a host) from a session. + +## SYNTAX + +``` +Remove-CWCHostFromSession [-SessionID] [-ConnectionID] [-Group] [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +Queues a QueuedForceDisconnect session event (type 48) for the given connection, the same +action as disconnecting a participant in the Control web UI. +Connection IDs are listed in +(Get-CWCSessionDetail -GUID \ -Include Connections).Connections. + +## EXAMPLES + +### EXAMPLE 1 +``` +$Connections = (Get-CWCSessionDetail -GUID $SessionID -Include Connections).Connections +$HostConnection = $Connections | Where-Object { $_.ProcessType -eq 1 } | Select-Object -First 1 +Remove-CWCHostFromSession -SessionID $SessionID -ConnectionID $HostConnection.ConnectionID -Group 'All Machines' +``` + +Disconnects the first host connected to the session (ProcessType 1 = Host). + +## PARAMETERS + +### -SessionID +Session ID. + +```yaml +Type: Guid +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ConnectionID +ID of the connection to disconnect. + +```yaml +Type: Guid +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Group +Session group containing the session: a name, or the path parts of a nested group. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: True +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +Contributed by turbo-donkey (#28). +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/Remove-CWCSession.md b/Docs/Remove-CWCSession.md index 9cf19f9..8d7b951 100644 --- a/Docs/Remove-CWCSession.md +++ b/Docs/Remove-CWCSession.md @@ -92,7 +92,6 @@ Accept pipeline input: False Accept wildcard characters: False ``` - ### -Uninstall Queue an uninstall of the Access client and delete the session (QueuedUninstallAndDelete) instead of only deleting the session record. @@ -108,6 +107,7 @@ Accept pipeline input: False Accept wildcard characters: False ``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). diff --git a/Docs/Update-CWCCustomProperty.md b/Docs/Update-CWCCustomProperty.md index a62c4ee..848cf89 100644 --- a/Docs/Update-CWCCustomProperty.md +++ b/Docs/Update-CWCCustomProperty.md @@ -13,7 +13,7 @@ Will update a custom property for a session. ## SYNTAX ``` -Update-CWCCustomProperty -GUID -Property [-Value ] [-Group ] [-WhatIf] [-Confirm] [] +Update-CWCCustomProperty -GUID -Property [-Value ] [-Group ] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION @@ -55,7 +55,7 @@ Accept wildcard characters: False Look for the session in these groups. ```yaml -Type: String +Type: String[] Parameter Sets: (All) Aliases: diff --git a/Tests/ConnectWiseControlAPI.Module.Tests.ps1 b/Tests/ConnectWiseControlAPI.Module.Tests.ps1 index bea6b9d..59692c7 100644 --- a/Tests/ConnectWiseControlAPI.Module.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Module.Tests.ps1 @@ -25,6 +25,7 @@ BeforeDiscovery { 'Invoke-CWCWake' 'New-CWCAccessToken' 'Remove-CWCSession' + 'Remove-CWCHostFromSession' 'Update-CWCCustomProperty' 'Update-CWCSessionName' 'Get-CWCSecurityConfigurationInfo' @@ -166,6 +167,7 @@ Describe 'Function Structure' { Context 'ShouldProcess on destructive functions' { It '<_> supports ShouldProcess' -ForEach @( 'Remove-CWCSession' + 'Remove-CWCHostFromSession' 'Update-CWCCustomProperty' 'Update-CWCSessionName' 'New-CWCUser' diff --git a/Tests/ConnectWiseControlAPI.Public.Tests.ps1 b/Tests/ConnectWiseControlAPI.Public.Tests.ps1 index 3cb22ee..9b5d17a 100644 --- a/Tests/ConnectWiseControlAPI.Public.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Public.Tests.ps1 @@ -1715,3 +1715,42 @@ Describe 'New-CWCMFA' { $result | Should -Not -BeNullOrEmpty } } + +Describe 'Remove-CWCHostFromSession' { + + BeforeEach { Set-CWCTestConnection } + + It 'queues one QueuedForceDisconnect (48) event for the connection, without retry' { + InModuleScope 'ConnectWiseControlAPI' { + $session = [guid]::NewGuid(); $connection = [guid]::NewGuid() + Mock Invoke-CWCWebRequest { + param($Arguments, $MaxRetry) + $Arguments.Endpoint | Should -Be 'Services/PageService.ashx/AddSessionEvents' + $MaxRetry | Should -Be 0 + $body = $Arguments.Body | ConvertFrom-Json + @($body[0]) | Should -Be @('All Machines') + @($body[1]).Count | Should -Be 1 + $body[1][0].SessionID | Should -Be $session.ToString() + $body[1][0].ConnectionID | Should -Be $connection.ToString() + $body[1][0].EventType | Should -Be 48 + } + Remove-CWCHostFromSession -SessionID $session -ConnectionID $connection -Group 'All Machines' -Confirm:$false + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'prompts by default (ConfirmImpact High) and sends nothing with -WhatIf' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest {} + (Get-Command Remove-CWCHostFromSession).ScriptBlock.Attributes.Where({ $_ -is [System.Management.Automation.CmdletBindingAttribute] }).ConfirmImpact | + Should -Be 'High' + Remove-CWCHostFromSession -SessionID ([guid]::NewGuid()) -ConnectionID ([guid]::NewGuid()) -Group 'All Machines' -WhatIf + Should -Invoke Invoke-CWCWebRequest -Times 0 + } + } + + It 'rejects an empty session ID' { + { Remove-CWCHostFromSession -SessionID ([guid]::Empty) -ConnectionID ([guid]::NewGuid()) -Group 'x' -Confirm:$false } | + Should -Throw + } +} From 2b9b388c52f5c5086108ca1e55de653783e6dd73 Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Tue, 10 Nov 2026 09:35:35 -0700 Subject: [PATCH 11/30] Add Remove-CWCSessionNote, based on #27 Removes notes by event ID (-NoteEventID) or every note on a session (-All) by adding a DeletedEvent (1) correlated to each note, as the web UI does; notes already deleted are skipped. Credentials connections only. Design and event mechanics from PR #27 by CitybookServicesLTD. Get-CWCSessionDetail -Group now takes nested group path parts ([string[]]), like the other session functions. The live smoke test's note cleanup uses the new function. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 + .../ConnectWiseControlAPI.psd1 | 2 +- .../ConnectWiseControlAPI.psm1 | 1 + .../PageService/Get-CWCSessionDetail.ps1 | 5 +- .../PageService/Remove-CWCSessionNote.ps1 | 101 +++++++ .../en-US/ConnectWiseControlAPI-help.xml | 251 +++++++++++++++++- ConnectWiseControlAPI_Functions.md | 3 + Docs/Get-CWCSessionDetail.md | 5 +- Docs/Remove-CWCSessionNote.md | 162 +++++++++++ Tests/ConnectWiseControlAPI.Module.Tests.ps1 | 2 + Tests/ConnectWiseControlAPI.Public.Tests.ps1 | 71 +++++ Tests/Live/Invoke-CWCLiveSmokeTest.ps1 | 9 +- 12 files changed, 597 insertions(+), 17 deletions(-) create mode 100644 ConnectWiseControlAPI/Public/PageService/Remove-CWCSessionNote.ps1 create mode 100644 Docs/Remove-CWCSessionNote.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 3352ed8..80ca523 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,8 @@ Planned as 0.5.0.0 (the module manifest already carries this version; 0.4.0.0 is - `Get-CWCRemoteWorkforceSession` lists the calling user's assigned machines (`GetRemoteWorkforceSessions`) - `Initialize-CWCRemoteWorkforceSessionGroup` creates/repairs the extension's session group (`EnsureCorrectSessionGroupExists`) +- `Remove-CWCSessionNote` removes notes by event ID (`-NoteEventID`) or all notes on a session (`-All`), + skipping notes already deleted; based on the design in #27 by CitybookServicesLTD - `Remove-CWCHostFromSession` disconnects one connection from a session (QueuedForceDisconnect, event 48); contributed by turbo-donkey (#28). Takes single `-SessionID`/`-ConnectionID` values and prompts by default - `Remove-CWCSession -Uninstall` queues `QueuedUninstallAndDelete` (event 100) so the Access client is diff --git a/ConnectWiseControlAPI/ConnectWiseControlAPI.psd1 b/ConnectWiseControlAPI/ConnectWiseControlAPI.psd1 index f550ddf..3809081 100644 --- a/ConnectWiseControlAPI/ConnectWiseControlAPI.psd1 +++ b/ConnectWiseControlAPI/ConnectWiseControlAPI.psd1 @@ -69,7 +69,7 @@ # NestedModules = @() # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. - FunctionsToExport = @('Get-CWCAuditInfo','Get-CWCAuditLog','Connect-CWC','Get-CWCLauncURL','Add-CWCRemoteWorkforceRequiredRole','New-CWCRemoteWorkforceAssignment','Get-CWCRemoteWorkforceLaunchURL','Get-CWCRemoteWorkforceSession','Initialize-CWCRemoteWorkforceSessionGroup','Find-CWCSession','New-CWCSession','Add-CWCSessionNote','Send-CWCSessionMessage','Send-CWCToolboxItem','New-CWCMFA','Get-CWCLastContact','Get-CWCSession','Get-CWCSessionDetail','Invoke-CWCCommand','Invoke-CWCWake','New-CWCAccessToken','Remove-CWCSession','Remove-CWCHostFromSession','Update-CWCCustomProperty','Update-CWCSessionName','Get-CWCSecurityConfigurationInfo','New-CWCUser','Remove-CWCUser','Update-CWCUser','Get-CWCSessionGroup') + FunctionsToExport = @('Get-CWCAuditInfo','Get-CWCAuditLog','Connect-CWC','Get-CWCLauncURL','Add-CWCRemoteWorkforceRequiredRole','New-CWCRemoteWorkforceAssignment','Get-CWCRemoteWorkforceLaunchURL','Get-CWCRemoteWorkforceSession','Initialize-CWCRemoteWorkforceSessionGroup','Find-CWCSession','New-CWCSession','Add-CWCSessionNote','Remove-CWCSessionNote','Send-CWCSessionMessage','Send-CWCToolboxItem','New-CWCMFA','Get-CWCLastContact','Get-CWCSession','Get-CWCSessionDetail','Invoke-CWCCommand','Invoke-CWCWake','New-CWCAccessToken','Remove-CWCSession','Remove-CWCHostFromSession','Update-CWCCustomProperty','Update-CWCSessionName','Get-CWCSecurityConfigurationInfo','New-CWCUser','Remove-CWCUser','Update-CWCUser','Get-CWCSessionGroup') # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() diff --git a/ConnectWiseControlAPI/ConnectWiseControlAPI.psm1 b/ConnectWiseControlAPI/ConnectWiseControlAPI.psm1 index 8c6b63e..cd1e30d 100644 --- a/ConnectWiseControlAPI/ConnectWiseControlAPI.psm1 +++ b/ConnectWiseControlAPI/ConnectWiseControlAPI.psm1 @@ -24,6 +24,7 @@ $script:CWCSessionType = @{ Support = 0; Meeting = 1; Access = 2 } # ScreenConnect.SessionEventType values used by this module (verified live from the web client's # SC.types.SessionEventType, 2026-11-10) $script:CWCSessionEventType = @{ + DeletedEvent = 1 Connected = 10 Disconnected = 11 DeletedSession = 21 diff --git a/ConnectWiseControlAPI/Public/PageService/Get-CWCSessionDetail.ps1 b/ConnectWiseControlAPI/Public/PageService/Get-CWCSessionDetail.ps1 index a7d389b..a87eab2 100644 --- a/ConnectWiseControlAPI/Public/PageService/Get-CWCSessionDetail.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Get-CWCSessionDetail.ps1 @@ -1,7 +1,8 @@ function Get-CWCSessionDetail { [CmdletBinding()] param ( - [string]$Group = 'All Machines', + # Session group name, or the path parts of a nested group (e.g. 'Clients','Acme') + [string[]]$Group = 'All Machines', [Parameter(Mandatory=$True)] [guid]$GUID, # Parts of the session details to return (server SessionDetailsItems flags). Omit for everything. @@ -26,7 +27,7 @@ function Get-CWCSessionDetail { } # GetSessionDetails(group, sessionID[, items]). Without items the server returns All. - $DetailArguments = @($Group, $GUID) + $DetailArguments = @(@($Group), $GUID) if ($Include) { $Items = 0 foreach ($Item in ($Include | Select-Object -Unique)) { $Items = $Items -bor $SessionDetailsItemFlags[$Item] } diff --git a/ConnectWiseControlAPI/Public/PageService/Remove-CWCSessionNote.ps1 b/ConnectWiseControlAPI/Public/PageService/Remove-CWCSessionNote.ps1 new file mode 100644 index 0000000..eab9ded --- /dev/null +++ b/ConnectWiseControlAPI/Public/PageService/Remove-CWCSessionNote.ps1 @@ -0,0 +1,101 @@ +function Remove-CWCSessionNote { + <# + .SYNOPSIS + Removes notes from a session. + + .DESCRIPTION + Deletes notes (AddedNote events) by adding a DeletedEvent correlated to each note, the same way + the Control web UI removes a note. The user needs the RemoveNote permission in -Group. + + -NoteEventID removes specific notes; -All removes every note still on the session. Notes that + are already deleted are skipped. + + .PARAMETER GUID + Session ID. + + .PARAMETER NoteEventID + Event ID of each note to remove (the EventID of an AddedNote event in Get-CWCSessionDetail). + + .PARAMETER All + Remove every note on the session. + + .PARAMETER Group + Session group containing the session: a name, or the path parts of a nested group. + Defaults to 'All Machines'. + + .EXAMPLE + Remove-CWCSessionNote -GUID $SessionID -All + + Removes every note on the session, prompting for each one. + + .EXAMPLE + $Notes = (Get-CWCSessionDetail -GUID $SessionID -Include Events).Events | Where-Object EventType -eq 32 + $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { + Remove-CWCSessionNote -GUID $SessionID -NoteEventID $_.EventID -Confirm:$false + } + + .NOTES + Requires Connect-CWC -Credentials (the RESTful API Manager extension cannot delete notes). + Based on the design in #27 by CitybookServicesLTD. + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> + [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'ById')] + param( + [Parameter(Mandatory = $True)] + [Alias('SessionID')] + [guid]$GUID, + + [Parameter(Mandatory = $True, ParameterSetName = 'ById')] + [Alias('EventID')] + [ValidateScript({ $_ -ne [guid]::Empty })] + [guid[]]$NoteEventID, + + [Parameter(Mandatory = $True, ParameterSetName = 'All')] + [switch]$All, + + [string[]]$Group = 'All Machines' + ) + + if (Test-CWCApiSecretConnection) { + return Write-Error "Remove-CWCSessionNote is not available when connected with -ApiSecret (RESTful API Manager). Connect with 'Connect-CWC -Credentials' to use it." + } + + $NoteType = $script:CWCSessionEventType.AddedNote + $DeletedType = $script:CWCSessionEventType.DeletedEvent + + $NotesToRemove = @($NoteEventID) + if ($All) { + try { $Events = @((Get-CWCSessionDetail -Group $Group -GUID $GUID -Include 'Events' -ErrorAction Stop).Events) } + catch { + Write-Error $_ + return + } + # A deleted note stays in the event list; its DeletedEvent points back at it + $AlreadyDeleted = @($Events | Where-Object { $_.EventType -eq $DeletedType } | ForEach-Object { "$($_.CorrelationEventID)" }) + $NotesToRemove = @($Events | Where-Object { $_.EventType -eq $NoteType -and "$($_.EventID)" -notin $AlreadyDeleted } | + ForEach-Object { [guid]$_.EventID }) + if ($NotesToRemove.Count -eq 0) { + Write-Verbose "No notes on session $GUID." + return + } + } + + $EventEntries = @( + foreach ($NoteID in $NotesToRemove) { + if ($PSCmdlet.ShouldProcess("Note $NoteID on session $GUID", 'Remove note')) { + @{ + SessionID = $GUID + EventType = $DeletedType + CorrelationEventID = $NoteID + } + } + } + ) + if ($EventEntries.Count -eq 0) { return } + + # Not idempotent: never retried + $null = Invoke-CWCServiceMethod -Service PageService -Method AddSessionEvents -Arguments @(@($Group), $EventEntries) +} diff --git a/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml b/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml index 90dc973..ade80d8 100644 --- a/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml +++ b/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml @@ -1561,9 +1561,9 @@ Name of session group to use. - String + String[] - String + String[] All Machines @@ -1600,9 +1600,9 @@ Name of session group to use. - String + String[] - String + String[] All Machines @@ -3299,6 +3299,249 @@ Remove-CWCHostFromSession -SessionID $SessionID -ConnectionID $HostConnection.Co + + + Remove-CWCSessionNote + Remove + CWCSessionNote + + Removes notes from a session. + + + + Deletes notes (AddedNote events) by adding a DeletedEvent correlated to each note, the same way the Control web UI removes a note. The user needs the RemoveNote permission in -Group. + -NoteEventID removes specific notes; -All removes every note still on the session. Notes that are already deleted are skipped. + + + + Remove-CWCSessionNote + + GUID + + Session ID. + + Guid + + Guid + + + None + + + NoteEventID + + Event ID of each note to remove (the EventID of an AddedNote event in Get-CWCSessionDetail). + + Guid[] + + Guid[] + + + None + + + Group + + Session group containing the session: a name, or the path parts of a nested group. Defaults to 'All Machines'. + + String[] + + String[] + + + All Machines + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + SwitchParameter + + + False + + + + Remove-CWCSessionNote + + GUID + + Session ID. + + Guid + + Guid + + + None + + + All + + Remove every note on the session. + + + SwitchParameter + + + False + + + Group + + Session group containing the session: a name, or the path parts of a nested group. Defaults to 'All Machines'. + + String[] + + String[] + + + All Machines + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + SwitchParameter + + + False + + + + + + GUID + + Session ID. + + Guid + + Guid + + + None + + + NoteEventID + + Event ID of each note to remove (the EventID of an AddedNote event in Get-CWCSessionDetail). + + Guid[] + + Guid[] + + + None + + + All + + Remove every note on the session. + + SwitchParameter + + SwitchParameter + + + False + + + Group + + Session group containing the session: a name, or the path parts of a nested group. Defaults to 'All Machines'. + + String[] + + String[] + + + All Machines + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + SwitchParameter + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + Requires Connect-CWC -Credentials (the RESTful API Manager extension cannot delete notes). Based on the design in #27 by CitybookServicesLTD. Author: Chris Taylor + + + + + -------------------------- EXAMPLE 1 -------------------------- + Remove-CWCSessionNote -GUID $SessionID -All + + Removes every note on the session, prompting for each one. + + + + -------------------------- EXAMPLE 2 -------------------------- + $Notes = (Get-CWCSessionDetail -GUID $SessionID -Include Events).Events | Where-Object EventType -eq 32 +$Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { + Remove-CWCSessionNote -GUID $SessionID -NoteEventID $_.EventID -Confirm:$false +} + + + + + + + + https://github.com/christaylorcodes/ConnectWiseControlAPI + https://github.com/christaylorcodes/ConnectWiseControlAPI + + + Remove-CWCUser diff --git a/ConnectWiseControlAPI_Functions.md b/ConnectWiseControlAPI_Functions.md index 9d72a8b..5c469b4 100644 --- a/ConnectWiseControlAPI_Functions.md +++ b/ConnectWiseControlAPI_Functions.md @@ -84,6 +84,9 @@ Disconnects one connection (for example a host) from a session. ### [Remove-CWCSession](Docs/Remove-CWCSession.md) Will end a given session. +### [Remove-CWCSessionNote](Docs/Remove-CWCSessionNote.md) +Removes notes from a session. + ### [Remove-CWCUser](Docs/Remove-CWCUser.md) Removes an internal user. diff --git a/Docs/Get-CWCSessionDetail.md b/Docs/Get-CWCSessionDetail.md index 13fec66..bc79de4 100644 --- a/Docs/Get-CWCSessionDetail.md +++ b/Docs/Get-CWCSessionDetail.md @@ -13,8 +13,7 @@ Will return information about a session. ## SYNTAX ``` -Get-CWCSessionDetail [-Group ] -GUID [-Include ] - [] +Get-CWCSessionDetail [-Group ] -GUID [-Include ] [] ``` ## DESCRIPTION @@ -35,7 +34,7 @@ Will return details of the requested session. Name of session group to use. ```yaml -Type: String +Type: String[] Parameter Sets: (All) Aliases: diff --git a/Docs/Remove-CWCSessionNote.md b/Docs/Remove-CWCSessionNote.md new file mode 100644 index 0000000..b3a5cbc --- /dev/null +++ b/Docs/Remove-CWCSessionNote.md @@ -0,0 +1,162 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# Remove-CWCSessionNote + +## SYNOPSIS +Removes notes from a session. + +## SYNTAX + +### ById (Default) +``` +Remove-CWCSessionNote -GUID -NoteEventID [-Group ] [-WhatIf] [-Confirm] [] +``` + +### All +``` +Remove-CWCSessionNote -GUID [-All] [-Group ] [-WhatIf] + [-Confirm] [] +``` + +## DESCRIPTION +Deletes notes (AddedNote events) by adding a DeletedEvent correlated to each note, the same way +the Control web UI removes a note. +The user needs the RemoveNote permission in -Group. + +-NoteEventID removes specific notes; -All removes every note still on the session. +Notes that +are already deleted are skipped. + +## EXAMPLES + +### EXAMPLE 1 +``` +Remove-CWCSessionNote -GUID $SessionID -All +``` + +Removes every note on the session, prompting for each one. + +### EXAMPLE 2 +``` +$Notes = (Get-CWCSessionDetail -GUID $SessionID -Include Events).Events | Where-Object EventType -eq 32 +$Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { + Remove-CWCSessionNote -GUID $SessionID -NoteEventID $_.EventID -Confirm:$false +} +``` + +## PARAMETERS + +### -GUID +Session ID. + +```yaml +Type: Guid +Parameter Sets: (All) +Aliases: SessionID + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoteEventID +Event ID of each note to remove (the EventID of an AddedNote event in Get-CWCSessionDetail). + +```yaml +Type: Guid[] +Parameter Sets: ById +Aliases: EventID + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -All +Remove every note on the session. + +```yaml +Type: SwitchParameter +Parameter Sets: All +Aliases: + +Required: True +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Group +Session group containing the session: a name, or the path parts of a nested group. +Defaults to 'All Machines'. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: All Machines +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +Requires Connect-CWC -Credentials (the RESTful API Manager extension cannot delete notes). +Based on the design in #27 by CitybookServicesLTD. +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Tests/ConnectWiseControlAPI.Module.Tests.ps1 b/Tests/ConnectWiseControlAPI.Module.Tests.ps1 index 59692c7..822feaf 100644 --- a/Tests/ConnectWiseControlAPI.Module.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Module.Tests.ps1 @@ -26,6 +26,7 @@ BeforeDiscovery { 'New-CWCAccessToken' 'Remove-CWCSession' 'Remove-CWCHostFromSession' + 'Remove-CWCSessionNote' 'Update-CWCCustomProperty' 'Update-CWCSessionName' 'Get-CWCSecurityConfigurationInfo' @@ -168,6 +169,7 @@ Describe 'Function Structure' { It '<_> supports ShouldProcess' -ForEach @( 'Remove-CWCSession' 'Remove-CWCHostFromSession' + 'Remove-CWCSessionNote' 'Update-CWCCustomProperty' 'Update-CWCSessionName' 'New-CWCUser' diff --git a/Tests/ConnectWiseControlAPI.Public.Tests.ps1 b/Tests/ConnectWiseControlAPI.Public.Tests.ps1 index 9b5d17a..4006d17 100644 --- a/Tests/ConnectWiseControlAPI.Public.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Public.Tests.ps1 @@ -1754,3 +1754,74 @@ Describe 'Remove-CWCHostFromSession' { Should -Throw } } + +Describe 'Remove-CWCSessionNote' { + + BeforeEach { Set-CWCTestConnection } + + It 'sends one DeletedEvent (1) per note, correlated to the note, without retry' { + InModuleScope 'ConnectWiseControlAPI' { + $session = [guid]::NewGuid(); $note1 = [guid]::NewGuid(); $note2 = [guid]::NewGuid() + Mock Invoke-CWCWebRequest { + param($Arguments, $MaxRetry) + $Arguments.Endpoint | Should -Be 'Services/PageService.ashx/AddSessionEvents' + $MaxRetry | Should -Be 0 + $body = $Arguments.Body | ConvertFrom-Json + @($body[1]).Count | Should -Be 2 + $body[1][0].EventType | Should -Be 1 + $body[1][0].SessionID | Should -Be $session.ToString() + @($body[1].CorrelationEventID) | Should -Be @($note1.ToString(), $note2.ToString()) + } + Remove-CWCSessionNote -GUID $session -NoteEventID $note1, $note2 -Confirm:$false + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It '-All removes only notes that are not already deleted' { + InModuleScope 'ConnectWiseControlAPI' { + $session = [guid]::NewGuid(); $script:live = [guid]::NewGuid(); $script:gone = [guid]::NewGuid() + Mock Get-CWCSessionDetail { + [PSCustomObject]@{ Events = @( + [PSCustomObject]@{ EventID = "$script:live"; EventType = 32; Data = 'keep?' } + [PSCustomObject]@{ EventID = "$script:gone"; EventType = 32; Data = 'old' } + [PSCustomObject]@{ EventID = "$([guid]::NewGuid())"; EventType = 1; CorrelationEventID = "$script:gone" } + [PSCustomObject]@{ EventID = "$([guid]::NewGuid())"; EventType = 44; Data = 'hostname' } + ) } + } + Mock Invoke-CWCWebRequest { + param($Arguments) + $body = $Arguments.Body | ConvertFrom-Json + @($body[1]).Count | Should -Be 1 + $body[1][0].CorrelationEventID | Should -Be "$script:live" + } + Remove-CWCSessionNote -GUID $session -All -Confirm:$false + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It '-All sends nothing when the session has no notes' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Get-CWCSessionDetail { [PSCustomObject]@{ Events = @() } } + Mock Invoke-CWCWebRequest {} + Remove-CWCSessionNote -GUID ([guid]::NewGuid()) -All -Confirm:$false + Should -Invoke Invoke-CWCWebRequest -Times 0 + } + } + + It 'sends nothing with -WhatIf' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest {} + Remove-CWCSessionNote -GUID ([guid]::NewGuid()) -NoteEventID ([guid]::NewGuid()) -WhatIf + Should -Invoke Invoke-CWCWebRequest -Times 0 + } + } + + It 'fails clearly on an API-secret connection' { + Set-CWCTestApiSecretConnection + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest {} + { Remove-CWCSessionNote -GUID ([guid]::NewGuid()) -All -Confirm:$false -ErrorAction Stop } | Should -Throw '*Connect-CWC -Credentials*' + Should -Invoke Invoke-WebRequest -Times 0 + } + } +} diff --git a/Tests/Live/Invoke-CWCLiveSmokeTest.ps1 b/Tests/Live/Invoke-CWCLiveSmokeTest.ps1 index fc3ed29..0dfa0c3 100644 --- a/Tests/Live/Invoke-CWCLiveSmokeTest.ps1 +++ b/Tests/Live/Invoke-CWCLiveSmokeTest.ps1 @@ -109,13 +109,8 @@ function Remove-SmokeTestNote { $_.EventType -eq $NoteType -and "$($_.Data)" -like 'CWC smoke test note*' -and $_.EventID -notin $AlreadyDeleted }) if ($TestNotes.Count -gt 0) { - $DeleteEntries = @(foreach ($Note in $TestNotes) { - @{ SessionID = "$TestSessionID"; EventType = $DeletedEventType; CorrelationEventID = $Note.EventID } - }) - & (Get-Module ConnectWiseControlAPI) { - param($Group, $DeleteEntries) - $null = Invoke-CWCServiceMethod -Service PageService -Method AddSessionEvents -Arguments @(@($Group), $DeleteEntries) -ErrorAction Stop - } $Group $DeleteEntries + # Also exercises Remove-CWCSessionNote live + Remove-CWCSessionNote -GUID $TestSessionID -Group $Group -NoteEventID ($TestNotes | ForEach-Object { [guid]$_.EventID }) -Confirm:$false Start-Sleep -Seconds 2 } From 13fffe363608ece1aeec44f42b31141a5042c084 Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Tue, 10 Nov 2026 09:43:14 -0700 Subject: [PATCH 12/30] Add Enter-CWCSession to open the Host client for a session (#13) Builds the web client's sc-:// launch URL (format and encoding taken from SC.main.ts getSchemeUrlFunc) from the launch settings in Script.ashx and a Host access token, checks the client's protocol handler, opens it without exposing the URL, and logs the join (LogInitiatedJoin) as the web UI does. -UrlOnly returns the URL with a 5-minute delegated token when the role allows it. Credentials connections only. Also: Connect-CWC no longer blames the credentials for local failures; the module test's expected list gains Remove-CWCHostFromSession; live discovery script Tests/Live/Invoke-CWCHostLaunchDiscovery.ps1; WIP/ prototype removed. Verified live on PS 7 and 5.1 against a real server. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 +- .../ConnectWiseControlAPI.psd1 | 2 +- .../Private/Get-CWCHostLaunchContext.ps1 | 53 ++++ .../Private/New-CWCHostLaunchUrl.ps1 | 44 +++ .../Private/Start-CWCHostClient.ps1 | 31 ++ .../Public/Authentication/Connect-CWC.ps1 | 14 +- .../Public/PageService/Enter-CWCSession.ps1 | 163 ++++++++++ .../en-US/ConnectWiseControlAPI-help.xml | 188 ++++++++++++ Docs/Enter-CWCSession.md | 158 ++++++++++ Tests/ConnectWiseControlAPI.Module.Tests.ps1 | 2 + Tests/ConnectWiseControlAPI.Private.Tests.ps1 | 88 ++++++ Tests/ConnectWiseControlAPI.Public.Tests.ps1 | 160 ++++++++++ Tests/Live/Invoke-CWCHostLaunchDiscovery.ps1 | 283 ++++++++++++++++++ WIP/Invoke-CWCSession.ps1 | 50 ---- 14 files changed, 1192 insertions(+), 56 deletions(-) create mode 100644 ConnectWiseControlAPI/Private/Get-CWCHostLaunchContext.ps1 create mode 100644 ConnectWiseControlAPI/Private/New-CWCHostLaunchUrl.ps1 create mode 100644 ConnectWiseControlAPI/Private/Start-CWCHostClient.ps1 create mode 100644 ConnectWiseControlAPI/Public/PageService/Enter-CWCSession.ps1 create mode 100644 Docs/Enter-CWCSession.md create mode 100644 Tests/Live/Invoke-CWCHostLaunchDiscovery.ps1 delete mode 100644 WIP/Invoke-CWCSession.ps1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 80ca523..cca10a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,14 @@ Planned as 0.5.0.0 (the module manifest already carries this version; 0.4.0.0 is contributed by turbo-donkey (#28). Takes single `-SessionID`/`-ConnectionID` values and prompts by default - `Remove-CWCSession -Uninstall` queues `QueuedUninstallAndDelete` (event 100) so the Access client is uninstalled as well; without it the session record is only deleted (`DeletedSession`, event 21) +- `Enter-CWCSession` opens the Host client joined to a session, like Join in the web UI (#13). It builds + the web client's `sc-://` launch URL from the server's published launch settings and a Host + access token, checks that the client is installed for the current user, and logs the join + (`InitiatedJoin`). `-UrlOnly` returns the URL instead (for macOS/Linux or custom launchers), using a + 5-minute delegated token when the role allows it. The token is never written to any output stream. + Credentials connections only; launching is Windows only +- Live discovery script `Tests/Live/Invoke-CWCHostLaunchDiscovery.ps1` (read-only; redacts secrets; + `-Launch` opens the client for one test session) ### Deprecated @@ -63,7 +71,9 @@ Planned as 0.5.0.0 (the module manifest already carries this version; 0.4.0.0 is - **Breaking:** `Remove-CWCSession` prompts by default (`ConfirmImpact = 'High'`), confirms each session separately and rejects an empty GUID. Unattended scripts must add `-Confirm:$false` - `Connect-CWC` reports a failed login with its likely causes. Wrong credentials are not rejected with a - 401: the request runs as an anonymous user and fails with "Needs permission" + 401: the request runs as an anonymous user and fails with "Needs permission". A local failure (e.g. a + PowerShell error) is reported as such instead of being blamed on the credentials +- Removed the unloaded `WIP/Invoke-CWCSession.ps1` prototype, superseded by `Enter-CWCSession` - `Get-CWCLastContact` returns an error when no connection event is found, instead of the current time ### Fixed diff --git a/ConnectWiseControlAPI/ConnectWiseControlAPI.psd1 b/ConnectWiseControlAPI/ConnectWiseControlAPI.psd1 index 3809081..9f98381 100644 --- a/ConnectWiseControlAPI/ConnectWiseControlAPI.psd1 +++ b/ConnectWiseControlAPI/ConnectWiseControlAPI.psd1 @@ -69,7 +69,7 @@ # NestedModules = @() # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. - FunctionsToExport = @('Get-CWCAuditInfo','Get-CWCAuditLog','Connect-CWC','Get-CWCLauncURL','Add-CWCRemoteWorkforceRequiredRole','New-CWCRemoteWorkforceAssignment','Get-CWCRemoteWorkforceLaunchURL','Get-CWCRemoteWorkforceSession','Initialize-CWCRemoteWorkforceSessionGroup','Find-CWCSession','New-CWCSession','Add-CWCSessionNote','Remove-CWCSessionNote','Send-CWCSessionMessage','Send-CWCToolboxItem','New-CWCMFA','Get-CWCLastContact','Get-CWCSession','Get-CWCSessionDetail','Invoke-CWCCommand','Invoke-CWCWake','New-CWCAccessToken','Remove-CWCSession','Remove-CWCHostFromSession','Update-CWCCustomProperty','Update-CWCSessionName','Get-CWCSecurityConfigurationInfo','New-CWCUser','Remove-CWCUser','Update-CWCUser','Get-CWCSessionGroup') + FunctionsToExport = @('Get-CWCAuditInfo','Get-CWCAuditLog','Connect-CWC','Get-CWCLauncURL','Add-CWCRemoteWorkforceRequiredRole','New-CWCRemoteWorkforceAssignment','Get-CWCRemoteWorkforceLaunchURL','Get-CWCRemoteWorkforceSession','Initialize-CWCRemoteWorkforceSessionGroup','Find-CWCSession','New-CWCSession','Add-CWCSessionNote','Remove-CWCSessionNote','Send-CWCSessionMessage','Send-CWCToolboxItem','New-CWCMFA','Get-CWCLastContact','Get-CWCSession','Get-CWCSessionDetail','Invoke-CWCCommand','Invoke-CWCWake','New-CWCAccessToken','Enter-CWCSession','Remove-CWCSession','Remove-CWCHostFromSession','Update-CWCCustomProperty','Update-CWCSessionName','Get-CWCSecurityConfigurationInfo','New-CWCUser','Remove-CWCUser','Update-CWCUser','Get-CWCSessionGroup') # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() diff --git a/ConnectWiseControlAPI/Private/Get-CWCHostLaunchContext.ps1 b/ConnectWiseControlAPI/Private/Get-CWCHostLaunchContext.ps1 new file mode 100644 index 0000000..a86a5ef --- /dev/null +++ b/ConnectWiseControlAPI/Private/Get-CWCHostLaunchContext.ps1 @@ -0,0 +1,53 @@ +function Get-CWCHostLaunchContext { + <# + .SYNOPSIS + Returns the server's client launch settings: URL scheme, relay host and port, public key. + + .DESCRIPTION + The web client reads these from SC.context in Script.ashx (instanceUrlScheme and clp = h, p, k). + Script.ashx is public, so no authentication is sent. The result is cached on the connection; + Connect-CWC -Force starts a new connection and so a fresh read. + #> + [CmdletBinding()] + param() + + $Connection = $script:CWCServerConnection + if ($Connection.HostLaunch) { return $Connection.HostLaunch } + + $Uri = "https://$($Connection.Server)/Script.ashx" + try { + $Response = Invoke-WebRequest -Uri $Uri -UseBasicParsing -ErrorAction Stop + } + catch { + return Write-Error "Could not read the client launch settings from $Uri : $($_.Exception.Message)" + } + + $Content = $Response.Content + if ($Content -is [byte[]]) { $Content = [Text.Encoding]::UTF8.GetString($Content) } + + # The scheme is used as a shell-executed URL, so accept only the sc- form the web client uses. + $SchemeMatch = [regex]::Match("$Content", '"instanceUrlScheme"\s*:\s*"(sc-[A-Za-z0-9]+)"') + $ClpMatch = [regex]::Match("$Content", '"clp"\s*:\s*(\{[^{}]*\})') + if (-not $SchemeMatch.Success -or -not $ClpMatch.Success) { + return Write-Error "The server at $($Connection.Server) did not publish client launch settings (instanceUrlScheme, clp) in Script.ashx. This server version may not be supported." + } + + try { $Clp = $ClpMatch.Groups[1].Value | ConvertFrom-Json -ErrorAction Stop } + catch { return Write-Error "Could not parse the client launch settings from $Uri." } + + $Port = 0 + if (-not ("$($Clp.h)" -match '^[A-Za-z0-9.:\[\]-]+$') -or + -not [int]::TryParse("$($Clp.p)", [ref]$Port) -or $Port -lt 1 -or $Port -gt 65535 -or + -not $Clp.k) { + return Write-Error "The client launch settings from $Uri are incomplete or invalid (relay host, port or key)." + } + + $Context = @{ + Scheme = $SchemeMatch.Groups[1].Value + RelayHost = "$($Clp.h)" + RelayPort = $Port + PublicKey = "$($Clp.k)" + } + $Connection.HostLaunch = $Context + $Context +} diff --git a/ConnectWiseControlAPI/Private/New-CWCHostLaunchUrl.ps1 b/ConnectWiseControlAPI/Private/New-CWCHostLaunchUrl.ps1 new file mode 100644 index 0000000..808f349 --- /dev/null +++ b/ConnectWiseControlAPI/Private/New-CWCHostLaunchUrl.ps1 @@ -0,0 +1,44 @@ +function New-CWCHostLaunchUrl { + <# + .SYNOPSIS + Builds the sc-:// URL that opens the Control client, in the web client's format. + + .DESCRIPTION + Mirrors getSchemeUrlFunc in the web client (SC.main.ts): + {scheme}://{h}:{p}/{s}/{k}/{n}/{r}/{e}/{i}/{a}/{l} + k, n, r, i, a and l are escaped like JavaScript's encodeURIComponent ([uri]::EscapeDataString); + h, p, s and e are not. The result contains the access token: never log it. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Builds a string; changes nothing.')] + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory = $True)][string]$Scheme, + [Parameter(Mandatory = $True)][string]$RelayHost, + [Parameter(Mandatory = $True)][int]$RelayPort, + [Parameter(Mandatory = $True)][guid]$SessionID, + [Parameter(Mandatory = $True)][string]$PublicKey, + [Parameter(Mandatory = $True)][string]$AccessToken, + [Parameter(Mandatory = $True)][ValidateSet('Support', 'Meeting', 'Access')][string]$SessionType, + [string]$Title = '', + [string]$ParticipantName = '', + [string]$Attributes = 'None', + [string]$LogonSessionID = '' + ) + + $Encode = { param([string]$Value) if ($Value) { [uri]::EscapeDataString($Value) } else { '' } } + + '{0}://{1}:{2}/{3}/{4}/{5}/{6}/{7}/{8}/{9}/{10}' -f @( + $Scheme + $RelayHost + $RelayPort + $SessionID.ToString() + (& $Encode $PublicKey) + (& $Encode $AccessToken) + (& $Encode $ParticipantName) + $SessionType + (& $Encode $Title) + (& $Encode $Attributes) + (& $Encode $LogonSessionID) + ) +} diff --git a/ConnectWiseControlAPI/Private/Start-CWCHostClient.ps1 b/ConnectWiseControlAPI/Private/Start-CWCHostClient.ps1 new file mode 100644 index 0000000..0171a86 --- /dev/null +++ b/ConnectWiseControlAPI/Private/Start-CWCHostClient.ps1 @@ -0,0 +1,31 @@ +function Start-CWCHostClient { + <# + .SYNOPSIS + Opens a client launch URL with its registered protocol handler, without exposing the URL. + + .DESCRIPTION + Uses Process.Start instead of Start-Process: module logging (event 4103) records cmdlet + parameter bindings, which would put the URL and its access token in the event log, and a + Start-Process error repeats the URL. On failure the error record is removed from $Error and a + fixed message is thrown. Windows usually shows an app picker rather than failing when no + handler is registered, so callers must check for the handler first. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Opens a viewer; Enter-CWCSession owns the user-facing decision.')] + [CmdletBinding()] + param( + [Parameter(Mandatory = $True)] + [string]$Url + ) + + $StartInfo = New-Object System.Diagnostics.ProcessStartInfo + $StartInfo.FileName = $Url + $StartInfo.UseShellExecute = $true + try { + $null = [System.Diagnostics.Process]::Start($StartInfo) + } + catch { + $ExceptionType = $_.Exception.GetType().Name + if ($Error.Count -gt 0) { $Error.RemoveAt(0) } + throw "Could not start the Control client ($ExceptionType)." + } +} diff --git a/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 b/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 index 5b14853..fbaf9a1 100644 --- a/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 +++ b/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 @@ -171,9 +171,15 @@ function Connect-CWC { catch{ $script:CWCServerConnection = $PreviousConnection Write-Verbose 'Authentication failed.' - # Bad credentials are not rejected with a 401: the request runs as an anonymous user and fails - # with "Needs permission", so name the likely causes. - Write-Error ("Authentication to 'https://$Server' failed. Check the username and password, that the " + - "account does not require MFA, and that its role grants at least one permission. $_") + if ($_.FullyQualifiedErrorId -like '*WriteErrorException*') { + # The server rejected the call. Bad credentials are not rejected with a 401: the request runs + # as an anonymous user and fails with "Needs permission", so name the likely causes. + Write-Error ("Authentication to 'https://$Server' failed. Check the username and password, that the " + + "account does not require MFA, and that its role grants at least one permission. $_") + } + else { + # A local failure (e.g. a PowerShell error) says nothing about the credentials. + Write-Error "Connecting to 'https://$Server' failed before authentication could be checked: $_" + } } } diff --git a/ConnectWiseControlAPI/Public/PageService/Enter-CWCSession.ps1 b/ConnectWiseControlAPI/Public/PageService/Enter-CWCSession.ps1 new file mode 100644 index 0000000..a98d493 --- /dev/null +++ b/ConnectWiseControlAPI/Public/PageService/Enter-CWCSession.ps1 @@ -0,0 +1,163 @@ +function Enter-CWCSession { + <# + .SYNOPSIS + Opens the ConnectWise Control Host client joined to a session, like Join in the web UI. + + .DESCRIPTION + Gets a Host access token for the session (PageService.GetAccessToken), builds the client launch + URL the web client uses (sc-://...) and opens it with the installed Control client. + The join is recorded in the session's audit trail (InitiatedJoin), as a web UI join is. + + The client must already be installed for the current Windows user: join any session once from + the web UI. Launching works on Windows only; on other systems use -UrlOnly and open the URL + yourself. + + Requires Connect-CWC -Credentials and the JoinSession permission in -Group. + + .PARAMETER GUID + Session ID. Accepts SessionID from the pipeline (e.g. from Get-CWCSession). + + .PARAMETER Type + Session type. Defaults to Access. + + .PARAMETER Group + Session group containing the session. Defaults to 'All Machines' for Access, 'All Sessions' for + Support and 'All Meetings' for Meeting. + + .PARAMETER UrlOnly + Return the launch URL instead of opening the client. The URL holds an access token: treat it + like a password. It uses a delegated token that expires in 5 minutes when your role has the + CreateDelegatedAccessToken permission; otherwise a regular Host token (with a warning), which + is valid for the server's access token lifetime (7 days by default). + + .EXAMPLE + Enter-CWCSession -GUID 'a1b2c3d4-0000-0000-0000-000000000000' + + .EXAMPLE + Get-CWCSession -Type Access -Search 'DESKTOP-01' -Limit 1 | Enter-CWCSession + + .EXAMPLE + $Url = Enter-CWCSession -GUID $SessionID -UrlOnly + open $Url # macOS + + .NOTES + The access token is not written to verbose, debug, warning or error output. It does appear in + the launched client's command line (as with a web UI join), and PowerShell module or + script-block logging, when enabled, can record the API response that carries it. + The token is tied to the public IP address this call comes from, so the URL may not work from + another network (a different proxy or VPN exit). + + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> + [CmdletBinding()] + [OutputType([string])] + param ( + [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] + [Alias('SessionID')] + [guid]$GUID, + + [ValidateSet('Support', 'Meeting', 'Access')] + [string]$Type = 'Access', + + [string]$Group, + + [switch]$UrlOnly + ) + + begin { + # SessionPermissions.All; the server grants only what the user may delegate for the session. + $AllSessionPermissions = 268435455 + $DelegatedTokenSeconds = 300 + $ModuleVersion = $MyInvocation.MyCommand.Module.Version + } + + process { + if (-not $script:CWCServerConnection) { + return Write-Error "Not connected to a Control server. Run 'Connect-CWC' first." + } + if (Test-CWCApiSecretConnection) { + return Write-Error "Enter-CWCSession is not available when connected with -ApiSecret (RESTful API Manager). Connect with 'Connect-CWC -Credentials' to use it." + } + + # Local copy: a default chosen for one pipeline item must not stick to the next. + $SessionGroup = $Group + if (-not $SessionGroup) { + $SessionGroup = switch ($Type) { + 'Support' { 'All Sessions' } + 'Meeting' { 'All Meetings' } + default { 'All Machines' } + } + } + + $LaunchContext = Get-CWCHostLaunchContext + if (-not $LaunchContext) { return } + + # Title shown by the client, and a check that the session exists as this type in this group. + $Session = Get-CWCSession -Type $Type -Group $SessionGroup -FindSessionID $GUID | + Where-Object { "$($_.SessionID)" -eq "$GUID" } | Select-Object -First 1 + if (-not $Session) { + return Write-Error "Session $GUID was not found among $Type sessions in group '$SessionGroup'. Check -Type and -Group." + } + + if (-not $UrlOnly) { + if ([Environment]::OSVersion.Platform -ne 'Win32NT') { + return Write-Error 'Launching the Control client is supported on Windows only. Use -UrlOnly to get the launch URL and open it yourself.' + } + if (-not (Test-Path -LiteralPath "Registry::HKEY_CLASSES_ROOT\$($LaunchContext.Scheme)")) { + return Write-Error ("The Control client for $($script:CWCServerConnection.Server) is not installed for this Windows user " + + "(no handler for $($LaunchContext.Scheme)://). Join any session once from the web UI to install it, or use -UrlOnly.") + } + } + + $Token = $null + if ($UrlOnly) { + try { + $Token = Invoke-CWCServiceMethod -Service PageService -Method GetDelegatedAccessToken -Arguments @( + @($SessionGroup), "$GUID", $AllSessionPermissions, $DelegatedTokenSeconds, 'ConnectWiseControlAPI Enter-CWCSession -UrlOnly' + ) -ErrorAction Stop + } + catch { + Write-Verbose "Delegated access token not available: $($_.Exception.Message)" + Write-Warning ("Could not get a short-lived delegated token (needs CreateDelegatedAccessToken); the URL uses a regular " + + "Host token valid for the server's access token lifetime. Treat it like a password.") + } + } + if (-not $Token) { + try { $Token = New-CWCAccessToken -Group $SessionGroup -GUID $GUID -ErrorAction Stop } + catch { return Write-Error "Could not get an access token for session $GUID (JoinSession permission in '$SessionGroup' is required): $($_.Exception.Message)" } + } + if (-not $Token) { return Write-Error "The server returned no access token for session $GUID." } + + $UrlParameters = @{ + Scheme = $LaunchContext.Scheme + RelayHost = $LaunchContext.RelayHost + RelayPort = $LaunchContext.RelayPort + SessionID = $GUID + PublicKey = $LaunchContext.PublicKey + AccessToken = "$Token" + SessionType = $Type + Title = "$($Session.Name)" + } + $Url = New-CWCHostLaunchUrl @UrlParameters + $Token = $null + + if ($UrlOnly) { return $Url } + + Write-Verbose "Opening the Control client for session $GUID." + try { Start-CWCHostClient -Url $Url } + catch { return Write-Error "$($_.Exception.Message)" } + finally { $Url = $null } + + # Same audit entry as a web UI join: LogInitiatedJoin(sessionID, ProcessType.Host = 1, data). + try { + $JoinData = "(UrlLaunch) ConnectWiseControlAPI/$ModuleVersion PowerShell/$($PSVersionTable.PSVersion)" + $null = Invoke-CWCServiceMethod -Service PageService -Method LogInitiatedJoin -Arguments @("$GUID", 1, $JoinData) -ErrorAction Stop + } + catch { + Write-Warning "The client was opened, but the join could not be logged on the server: $($_.Exception.Message)" + } + } +} diff --git a/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml b/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml index ade80d8..63233a8 100644 --- a/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml +++ b/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml @@ -427,6 +427,194 @@ + + + Enter-CWCSession + Enter + CWCSession + + Opens the ConnectWise Control Host client joined to a session, like Join in the web UI. + + + + Gets a Host access token for the session (PageService.GetAccessToken), builds the client launch URL the web client uses (sc-<instance>://...) and opens it with the installed Control client. The join is recorded in the session's audit trail (InitiatedJoin), as a web UI join is. + The client must already be installed for the current Windows user: join any session once from the web UI. Launching works on Windows only; on other systems use -UrlOnly and open the URL yourself. + Requires Connect-CWC -Credentials and the JoinSession permission in -Group. + + + + Enter-CWCSession + + GUID + + Session ID. Accepts SessionID from the pipeline (e.g. from Get-CWCSession). + + Guid + + Guid + + + None + + + Type + + Session type. Defaults to Access. + + String + + String + + + Access + + + Group + + Session group containing the session. Defaults to 'All Machines' for Access, 'All Sessions' for Support and 'All Meetings' for Meeting. + + String + + String + + + None + + + UrlOnly + + Return the launch URL instead of opening the client. The URL holds an access token: treat it like a password. It uses a delegated token that expires in 5 minutes when your role has the CreateDelegatedAccessToken permission; otherwise a regular Host token (with a warning), which is valid for the server's access token lifetime (7 days by default). + + + SwitchParameter + + + False + + + ProgressAction + + {{ Fill ProgressAction Description }} + + ActionPreference + + ActionPreference + + + None + + + + + + GUID + + Session ID. Accepts SessionID from the pipeline (e.g. from Get-CWCSession). + + Guid + + Guid + + + None + + + Type + + Session type. Defaults to Access. + + String + + String + + + Access + + + Group + + Session group containing the session. Defaults to 'All Machines' for Access, 'All Sessions' for Support and 'All Meetings' for Meeting. + + String + + String + + + None + + + UrlOnly + + Return the launch URL instead of opening the client. The URL holds an access token: treat it like a password. It uses a delegated token that expires in 5 minutes when your role has the CreateDelegatedAccessToken permission; otherwise a regular Host token (with a warning), which is valid for the server's access token lifetime (7 days by default). + + SwitchParameter + + SwitchParameter + + + False + + + ProgressAction + + {{ Fill ProgressAction Description }} + + ActionPreference + + ActionPreference + + + None + + + + + + + System.String + + + + + + + + + The access token is not written to verbose, debug, warning or error output. It does appear in the launched client's command line (as with a web UI join), and PowerShell module or script-block logging, when enabled, can record the API response that carries it. The token is tied to the public IP address this call comes from, so the URL may not work from another network (a different proxy or VPN exit). + Author: Chris Taylor + + + + + -------------------------- EXAMPLE 1 -------------------------- + Enter-CWCSession -GUID 'a1b2c3d4-0000-0000-0000-000000000000' + + + + + + -------------------------- EXAMPLE 2 -------------------------- + Get-CWCSession -Type Access -Search 'DESKTOP-01' -Limit 1 | Enter-CWCSession + + + + + + -------------------------- EXAMPLE 3 -------------------------- + $Url = Enter-CWCSession -GUID $SessionID -UrlOnly +open $Url # macOS + + + + + + + + https://github.com/christaylorcodes/ConnectWiseControlAPI + https://github.com/christaylorcodes/ConnectWiseControlAPI + + + Find-CWCSession diff --git a/Docs/Enter-CWCSession.md b/Docs/Enter-CWCSession.md new file mode 100644 index 0000000..82e30fb --- /dev/null +++ b/Docs/Enter-CWCSession.md @@ -0,0 +1,158 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# Enter-CWCSession + +## SYNOPSIS +Opens the ConnectWise Control Host client joined to a session, like Join in the web UI. + +## SYNTAX + +``` +Enter-CWCSession [-GUID] [[-Type] ] [[-Group] ] [-UrlOnly] + [-ProgressAction ] [] +``` + +## DESCRIPTION +Gets a Host access token for the session (PageService.GetAccessToken), builds the client launch +URL the web client uses (sc-\://...) and opens it with the installed Control client. +The join is recorded in the session's audit trail (InitiatedJoin), as a web UI join is. + +The client must already be installed for the current Windows user: join any session once from +the web UI. +Launching works on Windows only; on other systems use -UrlOnly and open the URL +yourself. + +Requires Connect-CWC -Credentials and the JoinSession permission in -Group. + +## EXAMPLES + +### EXAMPLE 1 +``` +Enter-CWCSession -GUID 'a1b2c3d4-0000-0000-0000-000000000000' +``` + +### EXAMPLE 2 +``` +Get-CWCSession -Type Access -Search 'DESKTOP-01' -Limit 1 | Enter-CWCSession +``` + +### EXAMPLE 3 +``` +$Url = Enter-CWCSession -GUID $SessionID -UrlOnly +open $Url # macOS +``` + +## PARAMETERS + +### -GUID +Session ID. +Accepts SessionID from the pipeline (e.g. +from Get-CWCSession). + +```yaml +Type: Guid +Parameter Sets: (All) +Aliases: SessionID + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Type +Session type. +Defaults to Access. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: Access +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Group +Session group containing the session. +Defaults to 'All Machines' for Access, 'All Sessions' for +Support and 'All Meetings' for Meeting. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UrlOnly +Return the launch URL instead of opening the client. +The URL holds an access token: treat it +like a password. +It uses a delegated token that expires in 5 minutes when your role has the +CreateDelegatedAccessToken permission; otherwise a regular Host token (with a warning), which +is valid for the server's access token lifetime (7 days by default). + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ProgressAction +{{ Fill ProgressAction Description }} + +```yaml +Type: ActionPreference +Parameter Sets: (All) +Aliases: proga + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### System.String +## NOTES +The access token is not written to verbose, debug, warning or error output. +It does appear in +the launched client's command line (as with a web UI join), and PowerShell module or +script-block logging, when enabled, can record the API response that carries it. +The token is tied to the public IP address this call comes from, so the URL may not work from +another network (a different proxy or VPN exit). + +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Tests/ConnectWiseControlAPI.Module.Tests.ps1 b/Tests/ConnectWiseControlAPI.Module.Tests.ps1 index 822feaf..f2add3b 100644 --- a/Tests/ConnectWiseControlAPI.Module.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Module.Tests.ps1 @@ -46,6 +46,8 @@ BeforeDiscovery { 'Send-CWCSessionMessage' 'Send-CWCToolboxItem' 'New-CWCMFA' + 'Remove-CWCHostFromSession' + 'Enter-CWCSession' ) } diff --git a/Tests/ConnectWiseControlAPI.Private.Tests.ps1 b/Tests/ConnectWiseControlAPI.Private.Tests.ps1 index b6196dc..dee38ef 100644 --- a/Tests/ConnectWiseControlAPI.Private.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Private.Tests.ps1 @@ -463,3 +463,91 @@ Describe 'Connection-type mismatch through Invoke-CWCServiceMethod' { } } } + + +# ============================================================================= +# Host client launch (Enter-CWCSession helpers) +# ============================================================================= +Describe 'New-CWCHostLaunchUrl' { + + It 'builds the web client format and escapes key, token and title like encodeURIComponent' { + InModuleScope 'ConnectWiseControlAPI' { + $Url = New-CWCHostLaunchUrl -Scheme 'sc-0123456789abcdef' -RelayHost 'relay.example.com' -RelayPort 443 ` + -SessionID '11111111-2222-3333-4444-555555555555' -PublicKey 'Bg+A/b==' -AccessToken 'T+o/k=' ` + -SessionType 'Support' -Title "B$([char]0x00FC)ro PC #1" + $Url | Should -BeExactly 'sc-0123456789abcdef://relay.example.com:443/11111111-2222-3333-4444-555555555555/Bg%2BA%2Fb%3D%3D/T%2Bo%2Fk%3D//Support/B%C3%BCro%20PC%20%231/None/' + } + } + + It 'fills participant name, attributes and logon session when given' { + InModuleScope 'ConnectWiseControlAPI' { + $Url = New-CWCHostLaunchUrl -Scheme 'sc-1' -RelayHost 'h' -RelayPort 80 -SessionID ([guid]::Empty) -PublicKey 'k' ` + -AccessToken 't' -SessionType 'Access' -ParticipantName 'A B' -Attributes 'SuspendedInput' -LogonSessionID '0' + $Url | Should -BeExactly 'sc-1://h:80/00000000-0000-0000-0000-000000000000/k/t/A%20B/Access//SuspendedInput/0' + } + } +} + +Describe 'Get-CWCHostLaunchContext' { + + BeforeEach { + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection = @{ Server = 'test.example.com'; Headers = @{} } + } + } + + It 'reads scheme, relay and key from Script.ashx and caches them on the connection' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest { + [PSCustomObject]@{ Content = 'SC={"res":{},"context":{"clp":{"h":"relay.example.com","p":8041,"k":"Bg+A\/b=="},"x":1,"instanceUrlScheme":"sc-0123456789abcdef"}};' } + } + $Context = Get-CWCHostLaunchContext + $Context.Scheme | Should -Be 'sc-0123456789abcdef' + $Context.RelayHost | Should -Be 'relay.example.com' + $Context.RelayPort | Should -Be 8041 + $Context.PublicKey | Should -BeExactly 'Bg+A/b==' + $null = Get-CWCHostLaunchContext + Should -Invoke Invoke-WebRequest -Times 1 -Exactly -ParameterFilter { $Uri -eq 'https://test.example.com/Script.ashx' -and -not $Headers } + $script:CWCServerConnection.HostLaunch.Scheme | Should -Be 'sc-0123456789abcdef' + } + } + + It 'rejects a scheme that is not sc-' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest { [PSCustomObject]@{ Content = '{"clp":{"h":"h","p":80,"k":"k"},"instanceUrlScheme":"javascript"}' } } + { Get-CWCHostLaunchContext -ErrorAction Stop } | Should -Throw '*did not publish client launch settings*' + $script:CWCServerConnection.HostLaunch | Should -BeNullOrEmpty + } + } + + It 'rejects an invalid ' -ForEach @( + @{ Case = 'port'; Clp = '{"h":"h","p":70000,"k":"k"}' } + @{ Case = 'host'; Clp = '{"h":"h/../x","p":80,"k":"k"}' } + @{ Case = 'key'; Clp = '{"h":"h","p":80,"k":""}' } + ) { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ Clp = $Clp } { + param($Clp) + $script:TestClpJson = $Clp + Mock Invoke-WebRequest { [PSCustomObject]@{ Content = "{`"clp`":$($script:TestClpJson),`"instanceUrlScheme`":`"sc-1`"}" } } + { Get-CWCHostLaunchContext -ErrorAction Stop } | Should -Throw '*incomplete or invalid*' + } + } + + It 'reports a failed request' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest { throw 'Connection refused' } + { Get-CWCHostLaunchContext -ErrorAction Stop } | Should -Throw '*Could not read the client launch settings*Connection refused*' + } + } +} + +Describe 'Start-CWCHostClient' { + + It 'throws a fixed message and leaves no trace of the URL in $Error' -Skip:([Environment]::OSVersion.Platform -ne 'Win32NT') { + InModuleScope 'ConnectWiseControlAPI' { + $Missing = Join-Path ([IO.Path]::GetTempPath()) 'cwc-missing-SECRETTOKEN\client.exe' + { Start-CWCHostClient -Url $Missing } | Should -Throw 'Could not start the Control client (*).' + ($Error | Out-String) | Should -Not -Match 'SECRETTOKEN' + } + } +} \ No newline at end of file diff --git a/Tests/ConnectWiseControlAPI.Public.Tests.ps1 b/Tests/ConnectWiseControlAPI.Public.Tests.ps1 index 4006d17..ec70205 100644 --- a/Tests/ConnectWiseControlAPI.Public.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Public.Tests.ps1 @@ -214,6 +214,22 @@ Describe 'Connect-CWC' { $script:CWCServerConnection | Should -BeNullOrEmpty } } + + It 'blames the credentials when the server rejects the validation call' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { + param($cred) + Mock Invoke-CWCWebRequest { Write-Error 'Needs permission' } + { Connect-CWC -Server 'server.example.com' -Credentials $cred -ErrorAction Stop } | Should -Throw "Authentication to*Check the username and password*" + } + } + + It 'does not blame the credentials for a local failure' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { + param($cred) + Mock Invoke-CWCWebRequest { Test-CWCMissingHelper } + { Connect-CWC -Server 'server.example.com' -Credentials $cred -ErrorAction Stop } | Should -Throw "*failed before authentication could be checked*Test-CWCMissingHelper*" + } + } } Context 'Connection failure' { @@ -685,6 +701,150 @@ Describe 'Invoke-CWCWake' { } } +Describe 'Enter-CWCSession' { + + BeforeEach { + Set-CWCTestConnection + $Id = '11111111-2222-3333-4444-555555555555' + Mock -ModuleName 'ConnectWiseControlAPI' Get-CWCHostLaunchContext { + @{ Scheme = 'sc-0123456789abcdef'; RelayHost = 'relay.example.com'; RelayPort = 8041; PublicKey = 'KEY+pub/lic==' } + } + Mock -ModuleName 'ConnectWiseControlAPI' Invoke-CWCWebRequest { + param($Arguments) + switch -Wildcard ($Arguments.Endpoint) { + '*/GetLiveData' { + @{ ResponseInfoMap = @{ HostSessionInfo = @{ Sessions = @( + @{ SessionID = '11111111-2222-3333-4444-555555555555'; Name = 'PC 01'; SessionType = 2 } + ) } } } + } + '*/GetAccessToken' { 'TOKEN+primary/abc==' } + '*/GetDelegatedAccessToken' { 'TOKEN+delegated/xyz==' } + default { $null } + } + } + Mock -ModuleName 'ConnectWiseControlAPI' Test-Path { $true } -ParameterFilter { $LiteralPath -like 'Registry::*' } + Mock -ModuleName 'ConnectWiseControlAPI' Start-CWCHostClient {} + } + + It 'opens the client with the web client URL format and a primary token' -Skip:([Environment]::OSVersion.Platform -ne 'Win32NT') { + $Result = Enter-CWCSession -GUID $Id + $Result | Should -BeNullOrEmpty + $Expected = 'sc-0123456789abcdef://relay.example.com:8041/11111111-2222-3333-4444-555555555555/' + + 'KEY%2Bpub%2Flic%3D%3D/TOKEN%2Bprimary%2Fabc%3D%3D//Access/PC%2001/None/' + Should -Invoke Start-CWCHostClient -ModuleName 'ConnectWiseControlAPI' -Times 1 -Exactly -ParameterFilter { $Url -eq $Expected } + Should -Invoke Invoke-CWCWebRequest -ModuleName 'ConnectWiseControlAPI' -Times 0 -ParameterFilter { $Arguments.Endpoint -like '*/GetDelegatedAccessToken' } + } + + It 'checks for the protocol handler of the server scheme' -Skip:([Environment]::OSVersion.Platform -ne 'Win32NT') { + Enter-CWCSession -GUID $Id + Should -Invoke Test-Path -ModuleName 'ConnectWiseControlAPI' -Times 1 -ParameterFilter { $LiteralPath -eq 'Registry::HKEY_CLASSES_ROOT\sc-0123456789abcdef' } + } + + It 'logs the join like the web UI (LogInitiatedJoin, ProcessType Host = 1)' -Skip:([Environment]::OSVersion.Platform -ne 'Win32NT') { + Enter-CWCSession -GUID $Id + Should -Invoke Invoke-CWCWebRequest -ModuleName 'ConnectWiseControlAPI' -Times 1 -Exactly -ParameterFilter { + $Body = $Arguments.Body | ConvertFrom-Json + $Arguments.Endpoint -eq 'Services/PageService.ashx/LogInitiatedJoin' -and + $Body[0] -eq '11111111-2222-3333-4444-555555555555' -and $Body[1] -eq 1 -and $Body[2] -like '(UrlLaunch) ConnectWiseControlAPI/*' + } + } + + It 'warns but still opens the client when the join cannot be logged' -Skip:([Environment]::OSVersion.Platform -ne 'Win32NT') { + Mock -ModuleName 'ConnectWiseControlAPI' Invoke-CWCWebRequest { + param($Arguments) + switch -Wildcard ($Arguments.Endpoint) { + '*/GetLiveData' { @{ ResponseInfoMap = @{ HostSessionInfo = @{ Sessions = @(@{ SessionID = '11111111-2222-3333-4444-555555555555'; Name = 'PC 01' }) } } } } + '*/GetAccessToken' { 'TOKEN+primary/abc==' } + '*/LogInitiatedJoin' { throw 'Rate limited' } + } + } + Enter-CWCSession -GUID $Id -WarningVariable Warnings -WarningAction SilentlyContinue -ErrorAction Stop + Should -Invoke Start-CWCHostClient -ModuleName 'ConnectWiseControlAPI' -Times 1 -Exactly + $Warnings | Should -Match 'could not be logged' + } + + It 'never writes the token to verbose, debug or warning output' -Skip:([Environment]::OSVersion.Platform -ne 'Win32NT') { + $Output = & { + $VerbosePreference = 'Continue' + $DebugPreference = 'Continue' + Enter-CWCSession -GUID $Id + } *>&1 | Out-String + $Output | Should -Not -Match 'TOKEN\+|TOKEN%2B' + } + + It 'reports a launch failure without the URL' -Skip:([Environment]::OSVersion.Platform -ne 'Win32NT') { + Mock -ModuleName 'ConnectWiseControlAPI' Start-CWCHostClient { throw 'Could not start the Control client (Win32Exception).' } + { Enter-CWCSession -GUID $Id -ErrorAction Stop } | Should -Throw 'Could not start the Control client*' + Should -Invoke Invoke-CWCWebRequest -ModuleName 'ConnectWiseControlAPI' -Times 0 -ParameterFilter { $Arguments.Endpoint -like '*/LogInitiatedJoin' } + } + + It 'errors without requesting a token when the client is not installed' -Skip:([Environment]::OSVersion.Platform -ne 'Win32NT') { + Mock -ModuleName 'ConnectWiseControlAPI' Test-Path { $false } -ParameterFilter { $LiteralPath -like 'Registry::*' } + { Enter-CWCSession -GUID $Id -ErrorAction Stop } | Should -Throw '*not installed*-UrlOnly*' + Should -Invoke Start-CWCHostClient -ModuleName 'ConnectWiseControlAPI' -Times 0 + Should -Invoke Invoke-CWCWebRequest -ModuleName 'ConnectWiseControlAPI' -Times 0 -ParameterFilter { $Arguments.Endpoint -like '*AccessToken' } + } + + It '-UrlOnly returns the URL with a short-lived delegated token and does not launch or log' { + $Url = Enter-CWCSession -GUID $Id -UrlOnly + $Url | Should -BeLike 'sc-0123456789abcdef://relay.example.com:8041/11111111-*/TOKEN%2Bdelegated%2Fxyz%3D%3D//Access/*' + Should -Invoke Invoke-CWCWebRequest -ModuleName 'ConnectWiseControlAPI' -Times 1 -Exactly -ParameterFilter { + $Body = $Arguments.Body | ConvertFrom-Json + $Arguments.Endpoint -like '*/GetDelegatedAccessToken' -and $Body[2] -eq 268435455 -and $Body[3] -eq 300 + } + Should -Invoke Start-CWCHostClient -ModuleName 'ConnectWiseControlAPI' -Times 0 + Should -Invoke Invoke-CWCWebRequest -ModuleName 'ConnectWiseControlAPI' -Times 0 -ParameterFilter { $Arguments.Endpoint -like '*/LogInitiatedJoin' } + } + + It '-UrlOnly falls back to a primary token with a warning' { + Mock -ModuleName 'ConnectWiseControlAPI' Invoke-CWCWebRequest { + param($Arguments) + switch -Wildcard ($Arguments.Endpoint) { + '*/GetLiveData' { @{ ResponseInfoMap = @{ HostSessionInfo = @{ Sessions = @(@{ SessionID = '11111111-2222-3333-4444-555555555555'; Name = 'PC 01' }) } } } } + '*/GetDelegatedAccessToken' { throw 'Needs permission' } + '*/GetAccessToken' { 'TOKEN+primary/abc==' } + } + } + $Url = Enter-CWCSession -GUID $Id -UrlOnly -WarningVariable Warnings -WarningAction SilentlyContinue + $Url | Should -BeLike '*/TOKEN%2Bprimary%2Fabc%3D%3D/*' + $Warnings | Should -Match 'Treat it like a password' + $Warnings | Should -Not -Match 'TOKEN\+|TOKEN%2B' + } + + It 'is blocked on an API-secret connection without any request' { + Set-CWCTestApiSecretConnection + { Enter-CWCSession -GUID $Id -ErrorAction Stop } | Should -Throw '*-ApiSecret*Connect-CWC -Credentials*' + Should -Invoke Invoke-CWCWebRequest -ModuleName 'ConnectWiseControlAPI' -Times 0 + Should -Invoke Get-CWCHostLaunchContext -ModuleName 'ConnectWiseControlAPI' -Times 0 + } + + It 'errors when not connected' { + InModuleScope 'ConnectWiseControlAPI' { $script:CWCServerConnection = $null } + { Enter-CWCSession -GUID $Id -ErrorAction Stop } | Should -Throw '*Connect-CWC*' + } + + It 'errors without requesting a token when the session is not in the group' { + { Enter-CWCSession -GUID ([guid]::NewGuid()) -ErrorAction Stop } | Should -Throw '*was not found among Access sessions*' + Should -Invoke Invoke-CWCWebRequest -ModuleName 'ConnectWiseControlAPI' -Times 0 -ParameterFilter { $Arguments.Endpoint -like '*AccessToken' } + } + + It 'uses as the default group for sessions' -ForEach @( + @{ Type = 'Access'; Group = 'All Machines' } + @{ Type = 'Support'; Group = 'All Sessions' } + @{ Type = 'Meeting'; Group = 'All Meetings' } + ) { + $null = Enter-CWCSession -GUID $Id -Type $Type -UrlOnly + Should -Invoke Invoke-CWCWebRequest -ModuleName 'ConnectWiseControlAPI' -Times 1 -ParameterFilter { + $Arguments.Endpoint -like '*/GetLiveData' -and ($Arguments.Body | ConvertFrom-Json)[0].HostSessionInfo.sessionGroupPathParts[0] -eq $Group + } + } + + It 'accepts SessionID from the pipeline' { + $Url = [pscustomobject]@{ SessionID = $Id } | Enter-CWCSession -UrlOnly + $Url | Should -BeLike '*/11111111-2222-3333-4444-555555555555/*' + } +} + Describe 'New-CWCAccessToken' { BeforeEach { Set-CWCTestConnection } diff --git a/Tests/Live/Invoke-CWCHostLaunchDiscovery.ps1 b/Tests/Live/Invoke-CWCHostLaunchDiscovery.ps1 new file mode 100644 index 0000000..d60e368 --- /dev/null +++ b/Tests/Live/Invoke-CWCHostLaunchDiscovery.ps1 @@ -0,0 +1,283 @@ +<# +.SYNOPSIS + Live discovery for Enter-CWCSession (issue #13): how the web client launches the Host client. + +.DESCRIPTION + Read-only. Connects with a non-MFA account and records, without secrets: + - whether SC.context (instanceUrlScheme, clp = relay host/port/public key) is on '/' and '/Host' + - web client code around the launch URL builder, ProcessType/SessionType enums, LogInitiatedJoin + and the join-reason prompt, so the URL format and encoding can be copied exactly + - whether this Windows user has the protocol handler for the instance's sc- scheme + + Every captured text is scrubbed (anti-forgery token, the server public key, cookie values, + token-shaped strings, user names) and the output is checked for the known secrets before it is + written. Run once on PS 7 and once on Windows PowerShell 5.1. + +.EXAMPLE + ./Tests/Live/Invoke-CWCHostLaunchDiscovery.ps1 -Server control.example.com + +.EXAMPLE + ./Tests/Live/Invoke-CWCHostLaunchDiscovery.ps1 -Server control.example.com -Launch -TestSessionID +#> +[CmdletBinding()] +param( + [Parameter(Mandatory = $True)] + [string]$Server, + + [string]$OutputPath = "C:\Temp\cwc-hostlaunch-discovery-ps$($PSVersionTable.PSVersion.Major).json", + + # Also test Enter-CWCSession on this session: -UrlOnly (URL shape only, no secrets recorded), then a + # real launch you confirm, then a check that the join was logged. + [switch]$Launch, + [guid]$TestSessionID, + [ValidateSet('Support', 'Meeting', 'Access')] + [string]$Type = 'Access', + [string]$Group, + + # Module manifest to load. Defaults to this checkout's copy. + [string]$ModulePath +) + +$ErrorActionPreference = 'Stop' +$PSDefaultParameterValues['*-CWC*:ErrorAction'] = 'Stop' +# $PSScriptRoot is empty in parameter defaults on Windows PowerShell 5.1, so resolve the default here. +if (-not $ModulePath) { $ModulePath = Join-Path $PSScriptRoot '..\..\ConnectWiseControlAPI\ConnectWiseControlAPI.psd1' } +Import-Module $ModulePath -Force + +$Server = $Server -replace '^https?://', '' -replace '/+$', '' + +$Results = [ordered]@{ + PSVersion = $PSVersionTable.PSVersion.ToString() + StartedUtc = [DateTime]::UtcNow.ToString('o') + Steps = [ordered]@{} +} + +# Values that must never reach the output file. Filled in as they are discovered. +$Secrets = New-Object System.Collections.Generic.List[string] + +function Invoke-Step { + param([string]$Name, [scriptblock]$Script) + Write-Host "== $Name" -ForegroundColor Cyan + try { + $Value = & $Script + $Results.Steps[$Name] = [ordered]@{ Ok = $True; Value = $Value } + Write-Host ' ok' -ForegroundColor Green + } + catch { + $Results.Steps[$Name] = [ordered]@{ Ok = $False; Error = (Protect-Text "$_") } + Write-Host " FAILED: $(Protect-Text "$_")" -ForegroundColor Red + } +} + +# Removes secrets from captured text. Code stays readable: only token-shaped runs are replaced. +function Protect-Text { + param([string]$Text) + if (-not $Text) { return $Text } + foreach ($Secret in $Secrets) { + if (-not $Secret) { continue } + $Text = $Text.Replace($Secret, '') + $Text = $Text.Replace($Secret.Replace('/', '\/'), '') # JSON-escaped form + $Text = $Text.Replace([uri]::EscapeDataString($Secret), '') # URL-encoded form + } + $Text = $Text -replace 'antiForgeryToken"\s*:\s*"[^"]*"', 'antiForgeryToken":""' + $Text = $Text -replace '(?i)(\.ASPXAUTH|ASP\.NET_SessionId|__RequestVerificationToken)=[^;"\s&]+', '$1=' + $Text = $Text -replace '(?i)"(userName|userDisplayName|userEmail|loginUserName)"\s*:\s*"[^"]*"', '"$1":""' + # Base64-looking runs (keys, tokens): 40+ chars with a digit and both letter cases. + $Text = [regex]::Replace($Text, '[A-Za-z0-9+/_%-]{40,}={0,2}', { + param($M) + $V = $M.Value + if ($V -cmatch '[0-9]' -and $V -cmatch '[A-Z]' -and $V -cmatch '[a-z]') { '' } else { $V } + }) + $Text +} + +function Get-Page { + param([string]$Path) + $Connection = & (Get-Module ConnectWiseControlAPI) { $script:CWCServerConnection } + $Headers = @{} + foreach ($Key in $Connection.Headers.Keys) { if ($Key -ne 'content-type') { $Headers[$Key] = $Connection.Headers[$Key] } } + $Response = Invoke-WebRequest -Uri "https://$Server/$($Path.TrimStart('/'))" -Headers $Headers -WebSession $Connection.WebSession -UseBasicParsing + $Content = $Response.Content + if ($Content -is [byte[]]) { $Content = [Text.Encoding]::UTF8.GetString($Content) } + $Content +} + +function Get-CharacterClass { + param([string]$Value) + [ordered]@{ + Length = $Value.Length + HasPlus = $Value.Contains('+') + HasSlash = $Value.Contains('/') + HasEquals = $Value.Contains('=') + HasPercent = $Value.Contains('%') + HasDashOrUnderscore = ($Value -match '[-_]') + } +} + +$Credential = Get-Credential -Message 'Non-MFA Control account (needs JoinSession)' + +Invoke-Step 'Connect' { + Connect-CWC -Server $Server -Credentials $Credential -Force + $Connection = & (Get-Module ConnectWiseControlAPI) { $script:CWCServerConnection } + if ($Connection.Headers.'x-anti-forgery-token') { $Secrets.Add($Connection.Headers.'x-anti-forgery-token') } + $Secrets.Add($Credential.GetNetworkCredential().Password) + $Secrets.Add(($Connection.Headers.authorization -replace '^Basic ', '')) + 'connected' +} + +if (-not $Results.Steps['Connect'].Ok) { + $Results | ConvertTo-Json -Depth 10 | Set-Content -Path $OutputPath -Encoding UTF8 + throw "Connect failed; see $OutputPath. Nothing else was run." +} + +$Pages = [ordered]@{} +$ScriptUrls = New-Object System.Collections.Generic.List[string] +$State = @{ Scheme = $null } + +foreach ($Path in @('/', '/Host')) { + Invoke-Step "Page $Path" { + $Html = Get-Page $Path + $Pages[$Path] = $Html + + foreach ($M in [regex]::Matches($Html, ']*\ssrc="([^"]+)"')) { + $Url = [System.Net.WebUtility]::HtmlDecode($M.Groups[1].Value) + if (($Url -notmatch '^https?://' -or $Url -match [regex]::Escape($Server)) -and -not $ScriptUrls.Contains($Url)) { $ScriptUrls.Add($Url) } + } + + $SchemeMatch = [regex]::Match($Html, '"instanceUrlScheme"\s*:\s*"([^"]*)"') + $ClpMatch = [regex]::Match($Html, '"clp"\s*:\s*\{([^}]*)\}') + $Clp = $null + if ($ClpMatch.Success) { + $Body = $ClpMatch.Groups[1].Value + $K = [regex]::Match($Body, '"k"\s*:\s*"([^"]*)"').Groups[1].Value + $KDecoded = $K.Replace('\/', '/') + if ($K) { $Secrets.Add($K); $Secrets.Add($KDecoded) } + $Clp = [ordered]@{ + Keys = @([regex]::Matches($Body, '"(\w+)"\s*:') | ForEach-Object { $_.Groups[1].Value }) + h = [regex]::Match($Body, '"h"\s*:\s*"([^"]*)"').Groups[1].Value + p = [regex]::Match($Body, '"p"\s*:\s*("?)([^,"}]*)\1').Groups[2].Value + k = if ($K) { Get-CharacterClass $KDecoded } else { $null } + kJsonEscapesSlash = $K.Contains('\/') + Context = Protect-Text $Html.Substring([math]::Max(0, $ClpMatch.Index - 300), [math]::Min(600, $Html.Length - [math]::Max(0, $ClpMatch.Index - 300))) + } + } + if ($SchemeMatch.Success -and -not $State.Scheme) { $State.Scheme = $SchemeMatch.Groups[1].Value } + + [ordered]@{ + Length = $Html.Length + InstanceUrlScheme = if ($SchemeMatch.Success) { $SchemeMatch.Groups[1].Value } else { $null } + Clp = $Clp + HasProcessType = [regex]::Match($Html, '"processType"\s*:\s*[^,}]+').Value + ContextAssignment = @([regex]::Matches($Html, 'SC\.(context\s*=|util\.mergeIntoContext\()') | ForEach-Object { $_.Value }) + } + } +} + +# Web client code around the launch logic. Patterns are case-sensitive JS identifiers. +$Patterns = [ordered]@{ + InstanceUrlScheme = 'instanceUrlScheme' + Clp = 'context\.clp' + StartJoinSession = 'startJoinSession' + LaunchUrl = '(?i)launchUrl|getClientLaunchUrl|buildLaunchUrl|ClientLaunchParameters' + LogInitiatedJoin = 'LogInitiatedJoin' + ProcessTypeEnum = 'ProcessType\s*[=:]\s*\{|ProcessType\b[^;]{0,40}Host' + SessionTypeEnum = 'SessionType\s*[=:]\s*\{' + JoinPrompt = 'PromptVisible' + ReasonCode = 'AddReasonCodeToSession|ReasonCode' + AccessToken = 'GetAccessToken' + HostLaunchParams = 'getClientLaunchParameters\(' + AccessTokenExpiry = 'accessTokenExpireSeconds' +} +$MaxHitsPerPattern = 4 + +Invoke-Step 'WebClientScripts' { + $Found = [ordered]@{} + foreach ($Name in $Patterns.Keys) { $Found[$Name] = New-Object System.Collections.ArrayList } + $Scanned = @() + foreach ($Url in $ScriptUrls) { + $Path = if ($Url -match '^https?://') { $Url -replace '^https?://[^/]+', '' } else { $Url } + try { $Content = Get-Page $Path } + catch { $Scanned += [ordered]@{ Script = ($Url -replace '\?.*$', ''); Error = (Protect-Text "$_") }; continue } + $Scanned += [ordered]@{ Script = ($Url -replace '\?.*$', ''); Length = $Content.Length } + foreach ($Name in $Patterns.Keys) { + foreach ($M in [regex]::Matches($Content, $Patterns[$Name])) { + if ($Found[$Name].Count -ge $MaxHitsPerPattern) { break } + $Start = [math]::Max(0, $M.Index - 400) + $null = $Found[$Name].Add([ordered]@{ + Script = ($Url -replace '\?.*$', '') + Text = Protect-Text $Content.Substring($Start, [math]::Min(3000, $Content.Length - $Start)) + }) + } + } + } + [ordered]@{ Scanned = $Scanned; Found = $Found } +} + +Invoke-Step 'ProtocolHandler' { + $Scheme = $State.Scheme + # The scheme is published in Script.ashx, not the HTML pages. + if (-not $Scheme) { $Scheme = & (Get-Module ConnectWiseControlAPI) { (Get-CWCHostLaunchContext -ErrorAction Stop).Scheme } } + if (-not $Scheme) { throw 'instanceUrlScheme not found on any page' } + $OnWindows = [Environment]::OSVersion.Platform -eq 'Win32NT' + if (-not $OnWindows) { return 'not Windows' } + $Key = "Registry::HKEY_CLASSES_ROOT\$Scheme" + $Command = $null + if (Test-Path "$Key\shell\open\command") { $Command = (Get-ItemProperty "$Key\shell\open\command").'(default)' } + [ordered]@{ + Scheme = $Scheme + Registered = Test-Path $Key + PerUser = Test-Path "Registry::HKEY_CURRENT_USER\Software\Classes\$Scheme" + PerMachine = Test-Path "Registry::HKEY_LOCAL_MACHINE\Software\Classes\$Scheme" + OpenCommand = Protect-Text $Command + } +} + +if ($Launch) { + if (-not $TestSessionID) { throw '-Launch needs -TestSessionID.' } + $EnterParameters = @{ GUID = $TestSessionID; Type = $Type } + if ($Group) { $EnterParameters.Group = $Group } + + Invoke-Step 'Launch.UrlOnly' { + $Url = Enter-CWCSession @EnterParameters -UrlOnly -WarningVariable UrlWarnings -WarningAction SilentlyContinue + $Segments = "$Url" -split '/' + $Token = [uri]::UnescapeDataString($Segments[5]) + $Secrets.Add($Token); $Secrets.Add($Segments[5]); $Secrets.Add($Segments[4]) + $Shape = [ordered]@{ + Scheme = $Segments[0] + RelayHostPort = $Segments[2] + SessionID = $Segments[3] + Key = Get-CharacterClass ([uri]::UnescapeDataString($Segments[4])) + Token = Get-CharacterClass $Token + ParticipantName = $Segments[6] + SessionType = $Segments[7] + Title = [uri]::UnescapeDataString($Segments[8]) + Attributes = $Segments[9] + LogonSessionID = $Segments[10] + SegmentCount = $Segments.Count + } + $Url = $null + [ordered]@{ UsedDelegatedToken = (@($UrlWarnings).Count -eq 0); Warnings = @($UrlWarnings | ForEach-Object { Protect-Text "$_" }); Shape = $Shape } + } + + Invoke-Step 'Launch.Open' { + $Before = [DateTime]::UtcNow + $Output = & { Enter-CWCSession @EnterParameters -Verbose } 4>&1 3>&1 | ForEach-Object { Protect-Text "$_" } + $Answer = Read-Host 'Did the Control client open and join the test session? (y/n)' + Start-Sleep -Seconds 2 + $ElapsedMs = ([DateTime]::UtcNow - $Before).TotalMilliseconds + 1000 + $DetailParameters = @{ GUID = $TestSessionID; Include = 'Events' } + if ($Group) { $DetailParameters.Group = $Group } + $Detail = Get-CWCSessionDetail @DetailParameters + $Joins = @($Detail.Events | Where-Object { $_.EventType -eq 30 -and [double]$_.Time -le $ElapsedMs } | + ForEach-Object { [ordered]@{ Host = Protect-Text "$($_.Host)"; Data = Protect-Text "$($_.Data)" } }) + [ordered]@{ ClientJoined = ($Answer -match '^y'); Output = @($Output); InitiatedJoinEvents = $Joins } + } +} + +$Json = $Results | ConvertTo-Json -Depth 10 +$Leaks = @($Secrets | Where-Object { $_ -and $_.Length -ge 8 -and $Json.Contains($_) }) +if ($Leaks.Count -gt 0) { + throw "Refusing to write $OutputPath : $($Leaks.Count) known secret value(s) survived redaction. Nothing was written." +} +$Json | Set-Content -Path $OutputPath -Encoding UTF8 +Write-Host "`nResults: $OutputPath (scrubbed; review before sharing)" -ForegroundColor Yellow diff --git a/WIP/Invoke-CWCSession.ps1 b/WIP/Invoke-CWCSession.ps1 deleted file mode 100644 index 6b1c45b..0000000 --- a/WIP/Invoke-CWCSession.ps1 +++ /dev/null @@ -1,50 +0,0 @@ -function Invoke-CWCSession { - [CmdletBinding()] - param ( - $Group, - $GUID, - $Type - ) - - try { - $Token = New-CWCAccessToken -GUID $GUID -Group $Group -ErrorAction Stop - $Details = Get-CWCSessionDetail -GUID $GUID -Group $Group - } - catch { return $_ } - - $Endpoint = 'Bin/i.t.Connect.ClientSetup.exe' - - $Splat = @{ - h = $script:CWCServerConnection.Server - p = 80 - k = [System.Web.HTTPUtility]::UrlEncode($(($script:CWCServerConnection['Headers']['Set-Cookie'] -split '; ')[0] -replace '.ASPXAUTH=', '')) - s = $GUID - i = $Details.Session.GuestMachineName - e = $Type - y = 'Host' - n = [System.Web.HTTPUtility]::UrlEncode($Token) - a = 'None' - } - $AppId = 'sc-2fed754e7d45a198' - $CLI = "$($AppId)://$($Splat.h):$($Splat.p)/$($Splat.s)/$($Splat.k)/$($Splat.n)//$($Splat.e)/$($Splat.i)/$($Splat.a)/" - Write-Verbose $CLI - - #$Cache = Invoke-RestMethod "https://$($script:CWCServerConnection.Server)/Script.ashx?__Cache=1b1722c7-9687-46e3-8b05-7e6ea2c7d5c2" - #$Cache | Select-String 'context' - try { - Start-Process $CLI - } - catch { - # if launch error download installer - $nvCollection = [System.Web.HttpUtility]::ParseQueryString([String]::Empty) - $Splat | ForEach-Object { $nvCollection.Add($_.Name, $_.Value) } - - $WebRequestArguments = @{ - Endpoint = '{0}?{1}' -f $Endpoint, $nvCollection.ToString() - Method = 'Get' - OutFile = 'C:\temp\test.exe' - } - - #Invoke-CWCWebRequest -Arguments $WebRequestArguments - } -} \ No newline at end of file From 1e8a0642bb020d3da899f5a0705151faa65f8f43 Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Tue, 10 Nov 2026 09:50:33 -0700 Subject: [PATCH 13/30] Refresh help after folding in Enter-CWCSession Regenerated docs and MAML help with the full function list; dropped a duplicate entry in the module test's expected-function list left by the rebase. Co-Authored-By: Claude Opus 5.5 --- .../en-US/ConnectWiseControlAPI-help.xml | 24 ------------------- ConnectWiseControlAPI_Functions.md | 3 +++ Docs/Enter-CWCSession.md | 17 +------------ Tests/ConnectWiseControlAPI.Module.Tests.ps1 | 1 - 4 files changed, 4 insertions(+), 41 deletions(-) diff --git a/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml b/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml index 63233a8..589b74b 100644 --- a/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml +++ b/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml @@ -491,18 +491,6 @@ False - - ProgressAction - - {{ Fill ProgressAction Description }} - - ActionPreference - - ActionPreference - - - None - @@ -554,18 +542,6 @@ False - - ProgressAction - - {{ Fill ProgressAction Description }} - - ActionPreference - - ActionPreference - - - None - diff --git a/ConnectWiseControlAPI_Functions.md b/ConnectWiseControlAPI_Functions.md index 5c469b4..49b1a4b 100644 --- a/ConnectWiseControlAPI_Functions.md +++ b/ConnectWiseControlAPI_Functions.md @@ -20,6 +20,9 @@ Adds a note to a session. ### [Connect-CWC](Docs/Connect-CWC.md) Initializes the connection parameters for the module. +### [Enter-CWCSession](Docs/Enter-CWCSession.md) +Opens the ConnectWise Control Host client joined to a session, like Join in the web UI. + ### [Find-CWCSession](Docs/Find-CWCSession.md) Finds sessions by session filter expression, name or ID (API secret connections). diff --git a/Docs/Enter-CWCSession.md b/Docs/Enter-CWCSession.md index 82e30fb..8fb13ab 100644 --- a/Docs/Enter-CWCSession.md +++ b/Docs/Enter-CWCSession.md @@ -13,8 +13,7 @@ Opens the ConnectWise Control Host client joined to a session, like Join in the ## SYNTAX ``` -Enter-CWCSession [-GUID] [[-Type] ] [[-Group] ] [-UrlOnly] - [-ProgressAction ] [] +Enter-CWCSession [-GUID] [[-Type] ] [[-Group] ] [-UrlOnly] [] ``` ## DESCRIPTION @@ -119,20 +118,6 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -ProgressAction -{{ Fill ProgressAction Description }} - -```yaml -Type: ActionPreference -Parameter Sets: (All) -Aliases: proga - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). diff --git a/Tests/ConnectWiseControlAPI.Module.Tests.ps1 b/Tests/ConnectWiseControlAPI.Module.Tests.ps1 index f2add3b..0586622 100644 --- a/Tests/ConnectWiseControlAPI.Module.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Module.Tests.ps1 @@ -46,7 +46,6 @@ BeforeDiscovery { 'Send-CWCSessionMessage' 'Send-CWCToolboxItem' 'New-CWCMFA' - 'Remove-CWCHostFromSession' 'Enter-CWCSession' ) } From 43882a1b38bdc209fc75c9b659d6caa7abfc7be6 Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Tue, 10 Nov 2026 09:58:12 -0700 Subject: [PATCH 14/30] Simplify: shared session-event helper, typed errors, lookup tables From the /simplify review of the release branch: - Private Add-CWCSessionEvent owns the AddSessionEvents envelope, skips empty batches and is never retried; the 8 event-queuing functions use it. Request bodies are unchanged. - -Group accepts nested group path parts ([string[]]) on every PageService function that takes it (the server's sessionGroupPathPartsOrName); a single name still binds. - Invoke-CWCWebRequest errors carry ErrorIds (CWC.NotConnected, CWC.AuthModeMismatch, CWC.Http, CWC.NoResponse). Connect-CWC blames the credentials only when the server answered, instead of inferring it from Write-Error. The error text keeps the server's message and drops the ConnectWise Manage-shaped parsing (and its Disconnect-CWC hint). - One auth-mode message (Get-CWCAuthModeMessage) for the transport and the three functions that must check up front. - .psm1 tables for default session groups, ProcessType and SessionPermissions.All. - Enter-CWCSession: platform check before any request, -Name from the pipeline skips the session lookup, a failed delegated-token request isn't retried per pipeline item. - Invoke-CWCCommand polls with a growing delay (1-5 s) on the rate-limited GetSessionDetails. - Get-CWCLastContact reads elapsed time directly; ConvertFrom-CWCEventTime removed. Co-Authored-By: Claude Opus 5.5 --- .../ConnectWiseControlAPI.psm1 | 11 ++- .../Private/Add-CWCSessionEvent.ps1 | 31 ++++++++ .../Private/ConvertFrom-CWCEventTime.ps1 | 19 ----- .../Private/Get-CWCAuthModeMessage.ps1 | 27 +++++++ .../Private/Invoke-CWCWebRequest.ps1 | 70 +++++------------- .../Public/Authentication/Connect-CWC.ps1 | 9 +-- .../Public/PageService/Enter-CWCSession.ps1 | 71 ++++++++++--------- .../Public/PageService/Get-CWCLastContact.ps1 | 47 ++++++------ .../Public/PageService/Get-CWCSession.ps1 | 3 +- .../Public/PageService/Invoke-CWCCommand.ps1 | 17 +++-- .../Public/PageService/Invoke-CWCWake.ps1 | 13 +--- .../PageService/Remove-CWCHostFromSession.ps1 | 5 +- .../Public/PageService/Remove-CWCSession.ps1 | 16 ++--- .../PageService/Remove-CWCSessionNote.ps1 | 14 ++-- .../PageService/Update-CWCSessionName.ps1 | 5 +- .../Public/RestApi/Add-CWCSessionNote.ps1 | 9 +-- .../Public/RestApi/Send-CWCSessionMessage.ps1 | 9 +-- .../Public/RestApi/Send-CWCToolboxItem.ps1 | 9 +-- Tests/ConnectWiseControlAPI.Public.Tests.ps1 | 10 ++- 19 files changed, 190 insertions(+), 205 deletions(-) create mode 100644 ConnectWiseControlAPI/Private/Add-CWCSessionEvent.ps1 delete mode 100644 ConnectWiseControlAPI/Private/ConvertFrom-CWCEventTime.ps1 create mode 100644 ConnectWiseControlAPI/Private/Get-CWCAuthModeMessage.ps1 diff --git a/ConnectWiseControlAPI/ConnectWiseControlAPI.psm1 b/ConnectWiseControlAPI/ConnectWiseControlAPI.psm1 index cd1e30d..1bca1da 100644 --- a/ConnectWiseControlAPI/ConnectWiseControlAPI.psm1 +++ b/ConnectWiseControlAPI/ConnectWiseControlAPI.psm1 @@ -21,6 +21,15 @@ $script:InternalUserSource = 'InternalMembershipProvider' # ScreenConnect.SessionType values (verified against ScreenConnect.Core.dll) $script:CWCSessionType = @{ Support = 0; Meeting = 1; Access = 2 } +# Built-in session group that lists every session of each type +$script:CWCDefaultSessionGroup = @{ Support = 'All Sessions'; Meeting = 'All Meetings'; Access = 'All Machines' } + +# ScreenConnect.ProcessType values (SC.types.ProcessType in the web client) +$script:CWCProcessType = @{ Host = 1; Guest = 2 } + +# SessionPermissions.All (SC.types.SessionPermissions); the server grants only what the user may delegate +$script:CWCAllSessionPermissions = 268435455 + # ScreenConnect.SessionEventType values used by this module (verified live from the web client's # SC.types.SessionEventType, 2026-11-10) $script:CWCSessionEventType = @{ @@ -44,5 +53,5 @@ $script:CWCRemoteWorkforceExtensionID = '2c4f522f-b39a-413a-8807-dc52a2fce13e' # RESTful API Manager extension ID, used by Connect-CWC -ApiSecret $script:CWCRestApiExtensionID = '2d558935-686a-4bd0-9991-07539f5fe749' -# Export Public functions ($Public.BaseName) for WIP modules +# Export only the Public/ functions Export-ModuleMember -Function $Public.Basename \ No newline at end of file diff --git a/ConnectWiseControlAPI/Private/Add-CWCSessionEvent.ps1 b/ConnectWiseControlAPI/Private/Add-CWCSessionEvent.ps1 new file mode 100644 index 0000000..bf335cc --- /dev/null +++ b/ConnectWiseControlAPI/Private/Add-CWCSessionEvent.ps1 @@ -0,0 +1,31 @@ +function Add-CWCSessionEvent { + <# + .SYNOPSIS + Adds session events through PageService.AddSessionEvents. Every event-queuing function uses this. + + .DESCRIPTION + Server signature: AddSessionEvents(object sessionGroupPathPartsOrName, SessionEventEntry[] eventEntries), + SessionEventEntry = SessionID, EventType, Data, CorrelationEventID, ConnectionID. Each entry is + sent as given (only the keys it has). Nothing is sent when no entries are passed (e.g. every + ShouldProcess prompt was declined). Adding an event is not idempotent (a second command, note, + wake or delete), so the call is never retried. + + .PARAMETER Group + Session group name, or the path parts of a nested group. + + .PARAMETER Entry + One hashtable per event. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Callers confirm each event with ShouldProcess.')] + [CmdletBinding()] + param( + [Parameter(Mandatory = $True)] + [string[]]$Group, + + [AllowEmptyCollection()] + [hashtable[]]$Entry + ) + + if (@($Entry).Count -eq 0) { return } + $null = Invoke-CWCServiceMethod -Service PageService -Method AddSessionEvents -Arguments @(@($Group), @($Entry)) +} diff --git a/ConnectWiseControlAPI/Private/ConvertFrom-CWCEventTime.ps1 b/ConnectWiseControlAPI/Private/ConvertFrom-CWCEventTime.ps1 deleted file mode 100644 index cd357ac..0000000 --- a/ConnectWiseControlAPI/Private/ConvertFrom-CWCEventTime.ps1 +++ /dev/null @@ -1,19 +0,0 @@ -function ConvertFrom-CWCEventTime { - <# - .SYNOPSIS - Converts a PageService session event's Time to an absolute UTC DateTime. - - .DESCRIPTION - PageService.GetSessionDetails reports each event's Time as the milliseconds elapsed before the - response (not an epoch). Converting to an absolute time lets callers compare events across - separate polls. - #> - [CmdletBinding()] - [OutputType([datetime])] - param( - [Parameter(Mandatory = $True)] - $SessionEvent - ) - - [DateTime]::UtcNow.AddMilliseconds(-[double]$SessionEvent.Time) -} diff --git a/ConnectWiseControlAPI/Private/Get-CWCAuthModeMessage.ps1 b/ConnectWiseControlAPI/Private/Get-CWCAuthModeMessage.ps1 new file mode 100644 index 0000000..b63aa1c --- /dev/null +++ b/ConnectWiseControlAPI/Private/Get-CWCAuthModeMessage.ps1 @@ -0,0 +1,27 @@ +function Get-CWCAuthModeMessage { + <# + .SYNOPSIS + The error text for a command used with the wrong Connect-CWC authentication method. + + .PARAMETER Command + Name of the public command the user ran. + + .PARAMETER Required + The authentication method the command needs. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory = $True)] + [string]$Command, + + [Parameter(Mandatory = $True)] + [ValidateSet('Credentials', 'ApiSecret')] + [string]$Required + ) + + if ($Required -eq 'Credentials') { + return "$Command is not available when connected with -ApiSecret (RESTful API Manager). Connect with 'Connect-CWC -Credentials' to use it." + } + "$Command requires the RESTful API Manager extension. Connect with 'Connect-CWC -ApiSecret' to use it." +} diff --git a/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 b/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 index cbebbdc..7323e23 100644 --- a/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 +++ b/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 @@ -9,13 +9,10 @@ [switch]$SensitiveBody ) - # Check that we have cached connection info + # Errors carry an ErrorId so callers can tell them apart without parsing text: + # CWC.NotConnected, CWC.AuthModeMismatch, CWC.Http (the server answered), CWC.NoResponse. if (!$script:CWCServerConnection) { - $ErrorMessage = @() - $ErrorMessage += 'Not connected to a Control server.' - $ErrorMessage += '--> $CWCServerConnection variable not found.' - $ErrorMessage += "----> Run 'Connect-CWC' to initialize the connection before issuing other CWC cmdlets." - return Write-Error ($ErrorMessage | Out-String) + return Write-Error "Not connected to a Control server. Run 'Connect-CWC' first." -ErrorId 'CWC.NotConnected' -Category ConnectionError } # The two auth methods reach different endpoints: an API secret is only accepted by the @@ -25,12 +22,10 @@ if ($IsApiSecretConnection -ne $IsRestApiEndpoint) { # Name the public function the user called, not the private request helpers. $Caller = Get-PSCallStack | Select-Object -Skip 1 -ExpandProperty Command | - Where-Object { $_ -notin 'Invoke-CWCServiceMethod', 'Invoke-CWCWebRequest' } | Select-Object -First 1 + Where-Object { $_ -notin 'Invoke-CWCServiceMethod', 'Invoke-CWCWebRequest', 'Add-CWCSessionEvent' } | Select-Object -First 1 if (-not $Caller -or $Caller -eq '') { $Caller = 'This command' } - if ($IsApiSecretConnection) { - return Write-Error "$Caller is not available when connected with -ApiSecret (RESTful API Manager). Connect with 'Connect-CWC -Credentials' to use it." - } - return Write-Error "$Caller requires the RESTful API Manager extension. Connect with 'Connect-CWC -ApiSecret' to use it." + $Required = if ($IsApiSecretConnection) { 'Credentials' } else { 'ApiSecret' } + return Write-Error (Get-CWCAuthModeMessage -Command $Caller -Required $Required) -ErrorId 'CWC.AuthModeMismatch' -Category InvalidOperation } $BaseURI = "https://$($script:CWCServerConnection.Server)" @@ -94,52 +89,23 @@ continue } - # Build the error message, keeping the server's error body + # Build the error message, keeping the server's error body (e.g. {"errorType":"SecurityException","message":"Needs permission"}) $ErrorMessage = @() if ($StatusCode -eq 500 -and $MaxRetry -gt 0) { $ErrorMessage += "Max retries hit ($MaxRetry). Status: 500" } + elseif ($StatusCode -gt 0) { $ErrorMessage += "HTTP $StatusCode" } - if ($_.Exception.Response -and $PSVersionTable.PSVersion.Major -lt 6) { - # Error bodies are not always JSON (IIS 401/404 pages) and the stream may be unreadable; - # don't let reading or parsing it mask the status. - $ErrBody = $null - try { - $Reader = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream()) - $ErrBody = $Reader.ReadToEnd() | ConvertFrom-Json - } - catch { $ErrBody = $null } - - if ($ErrBody.code) { - $ErrorMessage += 'An exception has been thrown.' - $ErrorMessage += "--> $($ErrBody.code)" - if ($ErrBody.code -eq 'Unauthorized') { - $ErrorMessage += "-----> $($ErrBody.message)" - $ErrorMessage += "-----> Use 'Disconnect-CWC' or 'Connect-CWC -Force' to set new authentication." - } - else { - $ErrorMessage += "-----> $($ErrBody.code): $($ErrBody.message)" - $ErrorMessage += '-----> ^ Error has not been documented please report. ^' - } - } - elseif ($_.Exception.message) { - $ErrorMessage += 'An exception has been thrown.' - $ErrorMessage += "--> $($_.Exception.message)" - } + $ServerMessage = $_.ErrorDetails.Message + if (-not $ServerMessage -and $_.Exception.Response -and $PSVersionTable.PSVersion.Major -lt 6) { + # Fallback for Windows PowerShell when ErrorDetails is empty; the stream may be unreadable. + try { $ServerMessage = (New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream())).ReadToEnd() } + catch { $ServerMessage = $null } } + if ($ServerMessage) { $ErrorMessage += $ServerMessage } + else { $ErrorMessage += "$_" } - if ($_.ErrorDetails) { - $ErrorMessage += 'An error has been thrown.' - $ErrorMessage += "--> $($_.ErrorDetails.code)" - $ErrorMessage += "--> $($_.ErrorDetails.message)" - if ($_.ErrorDetails.errors.message) { - $ErrorMessage += "-----> $($_.ErrorDetails.errors.message)" - } - } - - # Nothing beyond the retry line: fall back to the exception itself - if ($ErrorMessage.Count -le 1) { $ErrorMessage += "$_" } - $ErrorMessage += $_.ScriptStackTrace - - return Write-Error ($ErrorMessage | Out-String) + if ($StatusCode -gt 0) { $ErrorId = "CWC.Http$StatusCode"; $Category = 'InvalidResult' } + else { $ErrorId = 'CWC.NoResponse'; $Category = 'ConnectionError' } + return Write-Error ($ErrorMessage -join ' ') -ErrorId $ErrorId -Category $Category } } diff --git a/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 b/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 index fbaf9a1..3e04cef 100644 --- a/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 +++ b/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 @@ -171,14 +171,15 @@ function Connect-CWC { catch{ $script:CWCServerConnection = $PreviousConnection Write-Verbose 'Authentication failed.' - if ($_.FullyQualifiedErrorId -like '*WriteErrorException*') { - # The server rejected the call. Bad credentials are not rejected with a 401: the request runs - # as an anonymous user and fails with "Needs permission", so name the likely causes. + if ($_.FullyQualifiedErrorId -like 'CWC.Http*') { + # The server answered and rejected the call. Bad credentials are not rejected with a 401: the + # request runs as an anonymous user and fails with "Needs permission", so name the likely causes. Write-Error ("Authentication to 'https://$Server' failed. Check the username and password, that the " + "account does not require MFA, and that its role grants at least one permission. $_") } else { - # A local failure (e.g. a PowerShell error) says nothing about the credentials. + # No answer from the server (DNS, TLS, network) or a local PowerShell error: says nothing + # about the credentials. Write-Error "Connecting to 'https://$Server' failed before authentication could be checked: $_" } } diff --git a/ConnectWiseControlAPI/Public/PageService/Enter-CWCSession.ps1 b/ConnectWiseControlAPI/Public/PageService/Enter-CWCSession.ps1 index a98d493..614f7dc 100644 --- a/ConnectWiseControlAPI/Public/PageService/Enter-CWCSession.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Enter-CWCSession.ps1 @@ -21,8 +21,12 @@ function Enter-CWCSession { Session type. Defaults to Access. .PARAMETER Group - Session group containing the session. Defaults to 'All Machines' for Access, 'All Sessions' for - Support and 'All Meetings' for Meeting. + Session group containing the session: a name, or the path parts of a nested group. Defaults to + 'All Machines' for Access, 'All Sessions' for Support and 'All Meetings' for Meeting. + + .PARAMETER Name + Session name shown as the client's title. Taken from the pipeline (e.g. from Get-CWCSession); + when given, the session lookup is skipped. .PARAMETER UrlOnly Return the launch URL instead of opening the client. The URL holds an access token: treat it @@ -62,64 +66,67 @@ function Enter-CWCSession { [ValidateSet('Support', 'Meeting', 'Access')] [string]$Type = 'Access', - [string]$Group, + [string[]]$Group, + + [Parameter(ValueFromPipelineByPropertyName = $True)] + [string]$Name, [switch]$UrlOnly ) begin { - # SessionPermissions.All; the server grants only what the user may delegate for the session. - $AllSessionPermissions = 268435455 $DelegatedTokenSeconds = 300 $ModuleVersion = $MyInvocation.MyCommand.Module.Version + # Set after the first failed delegated-token request, so a pipeline doesn't retry and warn per item + $DelegatedTokenUnavailable = $False } process { if (-not $script:CWCServerConnection) { - return Write-Error "Not connected to a Control server. Run 'Connect-CWC' first." + return Write-Error "Not connected to a Control server. Run 'Connect-CWC' first." -ErrorId 'CWC.NotConnected' -Category ConnectionError } + # Checked up front: the launch settings below are read without going through the request helper. if (Test-CWCApiSecretConnection) { - return Write-Error "Enter-CWCSession is not available when connected with -ApiSecret (RESTful API Manager). Connect with 'Connect-CWC -Credentials' to use it." + return Write-Error (Get-CWCAuthModeMessage -Command $MyInvocation.MyCommand.Name -Required Credentials) -ErrorId 'CWC.AuthModeMismatch' -Category InvalidOperation + } + if (-not $UrlOnly -and [Environment]::OSVersion.Platform -ne 'Win32NT') { + return Write-Error 'Launching the Control client is supported on Windows only. Use -UrlOnly to get the launch URL and open it yourself.' } # Local copy: a default chosen for one pipeline item must not stick to the next. $SessionGroup = $Group - if (-not $SessionGroup) { - $SessionGroup = switch ($Type) { - 'Support' { 'All Sessions' } - 'Meeting' { 'All Meetings' } - default { 'All Machines' } - } - } + if (-not $SessionGroup) { $SessionGroup = $script:CWCDefaultSessionGroup[$Type] } + $GroupText = $SessionGroup -join '/' $LaunchContext = Get-CWCHostLaunchContext if (-not $LaunchContext) { return } - # Title shown by the client, and a check that the session exists as this type in this group. - $Session = Get-CWCSession -Type $Type -Group $SessionGroup -FindSessionID $GUID | - Where-Object { "$($_.SessionID)" -eq "$GUID" } | Select-Object -First 1 - if (-not $Session) { - return Write-Error "Session $GUID was not found among $Type sessions in group '$SessionGroup'. Check -Type and -Group." + if (-not $UrlOnly -and -not (Test-Path -LiteralPath "Registry::HKEY_CLASSES_ROOT\$($LaunchContext.Scheme)")) { + return Write-Error ("The Control client for $($script:CWCServerConnection.Server) is not installed for this Windows user " + + "(no handler for $($LaunchContext.Scheme)://). Join any session once from the web UI to install it, or use -UrlOnly.") } - if (-not $UrlOnly) { - if ([Environment]::OSVersion.Platform -ne 'Win32NT') { - return Write-Error 'Launching the Control client is supported on Windows only. Use -UrlOnly to get the launch URL and open it yourself.' - } - if (-not (Test-Path -LiteralPath "Registry::HKEY_CLASSES_ROOT\$($LaunchContext.Scheme)")) { - return Write-Error ("The Control client for $($script:CWCServerConnection.Server) is not installed for this Windows user " + - "(no handler for $($LaunchContext.Scheme)://). Join any session once from the web UI to install it, or use -UrlOnly.") + # Title shown by the client. Without -Name, look the session up, which also checks that it exists + # as this type in this group. + $Title = $Name + if (-not $PSBoundParameters.ContainsKey('Name')) { + $Session = Get-CWCSession -Type $Type -Group $SessionGroup -FindSessionID $GUID | + Where-Object { "$($_.SessionID)" -eq "$GUID" } | Select-Object -First 1 + if (-not $Session) { + return Write-Error "Session $GUID was not found among $Type sessions in group '$GroupText'. Check -Type and -Group." } + $Title = "$($Session.Name)" } $Token = $null - if ($UrlOnly) { + if ($UrlOnly -and -not $DelegatedTokenUnavailable) { try { $Token = Invoke-CWCServiceMethod -Service PageService -Method GetDelegatedAccessToken -Arguments @( - @($SessionGroup), "$GUID", $AllSessionPermissions, $DelegatedTokenSeconds, 'ConnectWiseControlAPI Enter-CWCSession -UrlOnly' + @($SessionGroup), "$GUID", $script:CWCAllSessionPermissions, $DelegatedTokenSeconds, 'ConnectWiseControlAPI Enter-CWCSession -UrlOnly' ) -ErrorAction Stop } catch { + $DelegatedTokenUnavailable = $True Write-Verbose "Delegated access token not available: $($_.Exception.Message)" Write-Warning ("Could not get a short-lived delegated token (needs CreateDelegatedAccessToken); the URL uses a regular " + "Host token valid for the server's access token lifetime. Treat it like a password.") @@ -127,7 +134,7 @@ function Enter-CWCSession { } if (-not $Token) { try { $Token = New-CWCAccessToken -Group $SessionGroup -GUID $GUID -ErrorAction Stop } - catch { return Write-Error "Could not get an access token for session $GUID (JoinSession permission in '$SessionGroup' is required): $($_.Exception.Message)" } + catch { return Write-Error "Could not get an access token for session $GUID (JoinSession permission in '$GroupText' is required): $($_.Exception.Message)" } } if (-not $Token) { return Write-Error "The server returned no access token for session $GUID." } @@ -139,7 +146,7 @@ function Enter-CWCSession { PublicKey = $LaunchContext.PublicKey AccessToken = "$Token" SessionType = $Type - Title = "$($Session.Name)" + Title = $Title } $Url = New-CWCHostLaunchUrl @UrlParameters $Token = $null @@ -151,10 +158,10 @@ function Enter-CWCSession { catch { return Write-Error "$($_.Exception.Message)" } finally { $Url = $null } - # Same audit entry as a web UI join: LogInitiatedJoin(sessionID, ProcessType.Host = 1, data). + # Same audit entry as a web UI join: LogInitiatedJoin(sessionID, processType, data). try { $JoinData = "(UrlLaunch) ConnectWiseControlAPI/$ModuleVersion PowerShell/$($PSVersionTable.PSVersion)" - $null = Invoke-CWCServiceMethod -Service PageService -Method LogInitiatedJoin -Arguments @("$GUID", 1, $JoinData) -ErrorAction Stop + $null = Invoke-CWCServiceMethod -Service PageService -Method LogInitiatedJoin -Arguments @("$GUID", $script:CWCProcessType.Host, $JoinData) -ErrorAction Stop } catch { Write-Warning "The client was opened, but the join could not be logged on the server: $($_.Exception.Message)" diff --git a/ConnectWiseControlAPI/Public/PageService/Get-CWCLastContact.ps1 b/ConnectWiseControlAPI/Public/PageService/Get-CWCLastContact.ps1 index 4b1ec7f..1220164 100644 --- a/ConnectWiseControlAPI/Public/PageService/Get-CWCLastContact.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Get-CWCLastContact.ps1 @@ -8,12 +8,13 @@ [parameter(ParameterSetName = 'Quiet')] [switch]$Quiet, [int]$Seconds, - [string]$Group = 'All Machines' + # Session group name, or the path parts of a nested group + [string[]]$Group = 'All Machines' ) # Relies on PageService's elapsed-milliseconds event times; the RESTful API Manager returns raw DateTimes. if (Test-CWCApiSecretConnection) { - return Write-Error "Get-CWCLastContact is not available when connected with -ApiSecret (RESTful API Manager). Connect with 'Connect-CWC -Credentials' to use it." + return Write-Error (Get-CWCAuthModeMessage -Command $MyInvocation.MyCommand.Name -Required Credentials) -ErrorId 'CWC.AuthModeMismatch' -Category InvalidOperation } try { $SessionDetails = Get-CWCSessionDetail -Group $Group -GUID $GUID -Include 'Events', 'Connections' -ErrorAction Stop } @@ -22,35 +23,27 @@ return } - if ($SessionDetails -eq 'null' -or !$SessionDetails) { + if (-not $SessionDetails) { Write-Warning 'Machine not found.' return $null } - $GuestSessionEvents = $SessionDetails.Events + # The latest connect/disconnect event of a guest connection that is no longer open $GuestSessionConnections = $SessionDetails.Connections | Where-Object { $_.ParticipantName } + $LatestEvent = $SessionDetails.Events | Where-Object { + $_.EventType -in ($script:CWCSessionEventType.Connected, $script:CWCSessionEventType.Disconnected) -and + $_.ConnectionID -NotIn $GuestSessionConnections.ConnectionID + } | Sort-Object { [double]$_.Time } | Select-Object -First 1 + if (-not $LatestEvent) { return Write-Error 'Unable to determine last contact.' } - if ($GuestSessionEvents) { - - # Get connection events - $LatestEvent = $GuestSessionEvents | Where-Object { - $_.EventType -in ($script:CWCSessionEventType.Connected, $script:CWCSessionEventType.Disconnected) -and - $_.ConnectionID -NotIn $GuestSessionConnections.ConnectionID - } | Sort-Object { [double]$_.Time } | Select-Object -First 1 - if (-not $LatestEvent) { return Write-Error 'Unable to determine last contact.' } - if ($LatestEvent.EventType -eq $script:CWCSessionEventType.Connected) { - # Currently connected - if ($Quiet) { return $True } - else { return Get-Date } - } - else { - $LastContactUtc = ConvertFrom-CWCEventTime -SessionEvent $LatestEvent - $SecondsSinceContact = ([DateTime]::UtcNow - $LastContactUtc).TotalSeconds - $OfflineTime = $LastContactUtc.ToLocalTime() - if ($Quiet -and $SecondsSinceContact -lt $Seconds) { return $True } - elseif ($Quiet) { return $False } - else { return $OfflineTime } - } + if ($LatestEvent.EventType -eq $script:CWCSessionEventType.Connected) { + # Currently connected + if ($Quiet) { return $True } + return Get-Date } - else { return Write-Error 'Unable to determine last contact.' } -} \ No newline at end of file + + # Event Time is milliseconds elapsed since the event + $ElapsedMs = [double]$LatestEvent.Time + if ($Quiet) { return ($ElapsedMs / 1000) -lt $Seconds } + (Get-Date).AddMilliseconds(-$ElapsedMs) +} diff --git a/ConnectWiseControlAPI/Public/PageService/Get-CWCSession.ps1 b/ConnectWiseControlAPI/Public/PageService/Get-CWCSession.ps1 index c121693..2707fd1 100644 --- a/ConnectWiseControlAPI/Public/PageService/Get-CWCSession.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Get-CWCSession.ps1 @@ -4,7 +4,8 @@ function Get-CWCSession { [Parameter(Mandatory = $True)] [ValidateSet('Support', 'Access', 'Meeting')] $Type, - [string]$Group = 'All Machines', + # Session group name, or the path parts of a nested group + [string[]]$Group = 'All Machines', [string]$Search, [string]$FindSessionID, [int]$Limit diff --git a/ConnectWiseControlAPI/Public/PageService/Invoke-CWCCommand.ps1 b/ConnectWiseControlAPI/Public/PageService/Invoke-CWCCommand.ps1 index c14e28b..bf032b0 100644 --- a/ConnectWiseControlAPI/Public/PageService/Invoke-CWCCommand.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Invoke-CWCCommand.ps1 @@ -7,7 +7,8 @@ [int]$TimeOut = 10000, [int]$MaxLength = 10000, [switch]$PowerShell, - [string]$Group = 'All Machines', + # Session group name, or the path parts of a nested group + [string[]]$Group = 'All Machines', [switch]$NoWait ) @@ -29,12 +30,7 @@ $null = Invoke-CWCServiceMethod -RestApi -Method SendCommandToSession -Arguments @($GUID.ToString(), $FormattedCommand) } else { - $CommandEvent = @{ - SessionID = $GUID - EventType = $QueuedCommandEventType - Data = $FormattedCommand - } - $null = Invoke-CWCServiceMethod -Service PageService -Method AddSessionEvents -Arguments @(@($Group), @($CommandEvent)) + Add-CWCSessionEvent -Group $Group -Entry @{ SessionID = $GUID; EventType = $QueuedCommandEventType; Data = $FormattedCommand } } if ($NoWait) { return } @@ -50,8 +46,9 @@ # round-trip time of each poll doesn't shift them. $TimeOutDateTime = (Get-Date).AddMilliseconds($TimeOut).AddSeconds(1) $QueuedAtServerMs = $null + $PollDelaySeconds = 1 do { - # Events only: this polls every second against a rate-limited endpoint. + # Events only, with a growing delay (1, 2, 3 ... 5 s): GetSessionDetails is rate limited. try { $SessionDetails = Get-CWCSessionDetail -Group $Group -GUID $GUID -Include 'Events' -ErrorAction Stop } catch { Write-Error $_ @@ -78,7 +75,9 @@ } } - Start-Sleep -Seconds 1 + $SecondsLeft = [math]::Ceiling(($TimeOutDateTime - (Get-Date)).TotalSeconds) + Start-Sleep -Seconds ([math]::Max(0, [math]::Min($PollDelaySeconds, $SecondsLeft))) + $PollDelaySeconds = [math]::Min($PollDelaySeconds + 1, 5) } while ((Get-Date) -le $TimeOutDateTime) Write-Warning 'Command timed out.' diff --git a/ConnectWiseControlAPI/Public/PageService/Invoke-CWCWake.ps1 b/ConnectWiseControlAPI/Public/PageService/Invoke-CWCWake.ps1 index 5235a28..0894b95 100644 --- a/ConnectWiseControlAPI/Public/PageService/Invoke-CWCWake.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Invoke-CWCWake.ps1 @@ -9,19 +9,10 @@ function Invoke-CWCWake { ) # PageService.AddEventToSessions no longer exists on the server; wake is queued as a session event. - $SessionEventType = $script:CWCSessionEventType.QueuedWake - - if ($Type -eq 'Support') { $Group = 'All Sessions' } - else { $Group = 'All Machines' } - $EventEntries = @( foreach ($SessionID in $GUID) { - @{ - SessionID = $SessionID - EventType = $SessionEventType - } + @{ SessionID = $SessionID; EventType = $script:CWCSessionEventType.QueuedWake } } ) - - Invoke-CWCServiceMethod -Service PageService -Method AddSessionEvents -Arguments @(@($Group), $EventEntries) + Add-CWCSessionEvent -Group $script:CWCDefaultSessionGroup[$Type] -Entry $EventEntries } diff --git a/ConnectWiseControlAPI/Public/PageService/Remove-CWCHostFromSession.ps1 b/ConnectWiseControlAPI/Public/PageService/Remove-CWCHostFromSession.ps1 index 3d2256b..946644a 100644 --- a/ConnectWiseControlAPI/Public/PageService/Remove-CWCHostFromSession.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Remove-CWCHostFromSession.ps1 @@ -47,12 +47,9 @@ function Remove-CWCHostFromSession { if (-not $PSCmdlet.ShouldProcess("Connection $ConnectionID in session $SessionID", 'Force disconnect')) { return } - $DisconnectEvent = @{ + Add-CWCSessionEvent -Group $Group -Entry @{ SessionID = $SessionID EventType = $script:CWCSessionEventType.QueuedForceDisconnect ConnectionID = $ConnectionID } - - # Not idempotent: never retried - Invoke-CWCServiceMethod -Service PageService -Method AddSessionEvents -Arguments @(@($Group), @($DisconnectEvent)) } diff --git a/ConnectWiseControlAPI/Public/PageService/Remove-CWCSession.ps1 b/ConnectWiseControlAPI/Public/PageService/Remove-CWCSession.ps1 index d87f0f8..d94db2a 100644 --- a/ConnectWiseControlAPI/Public/PageService/Remove-CWCSession.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Remove-CWCSession.ps1 @@ -7,8 +7,9 @@ function Remove-CWCSession [Parameter(Mandatory = $True)] [ValidateScript({ $_ -ne [guid]::Empty })] [guid[]]$GUID, + # Session group name, or the path parts of a nested group [Parameter(Mandatory = $True)] - [string]$Group, + [string[]]$Group, # Queue an uninstall of the Access client and delete the session (QueuedUninstallAndDelete), # instead of only deleting the session record (DeletedSession). [switch]$Uninstall @@ -27,17 +28,10 @@ function Remove-CWCSession # SessionEventEntry per approved session in a single request. $EventEntries = @( foreach ($SessionID in $GUID) { - if ($PSCmdlet.ShouldProcess("Session $SessionID (group '$Group')", $Action)) { - @{ - SessionID = $SessionID - EventType = $SessionEventType - } + if ($PSCmdlet.ShouldProcess("Session $SessionID (group '$($Group -join '/')')", $Action)) { + @{ SessionID = $SessionID; EventType = $SessionEventType } } } ) - - if ($EventEntries.Count -eq 0) { return } - - # Not idempotent: never retried - Invoke-CWCServiceMethod -Service PageService -Method AddSessionEvents -Arguments @(@($Group), $EventEntries) + Add-CWCSessionEvent -Group $Group -Entry $EventEntries } diff --git a/ConnectWiseControlAPI/Public/PageService/Remove-CWCSessionNote.ps1 b/ConnectWiseControlAPI/Public/PageService/Remove-CWCSessionNote.ps1 index eab9ded..88e4fda 100644 --- a/ConnectWiseControlAPI/Public/PageService/Remove-CWCSessionNote.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Remove-CWCSessionNote.ps1 @@ -59,8 +59,9 @@ function Remove-CWCSessionNote { [string[]]$Group = 'All Machines' ) + # Checked up front: with -All, the read below would otherwise succeed through the extension first. if (Test-CWCApiSecretConnection) { - return Write-Error "Remove-CWCSessionNote is not available when connected with -ApiSecret (RESTful API Manager). Connect with 'Connect-CWC -Credentials' to use it." + return Write-Error (Get-CWCAuthModeMessage -Command $MyInvocation.MyCommand.Name -Required Credentials) -ErrorId 'CWC.AuthModeMismatch' -Category InvalidOperation } $NoteType = $script:CWCSessionEventType.AddedNote @@ -86,16 +87,9 @@ function Remove-CWCSessionNote { $EventEntries = @( foreach ($NoteID in $NotesToRemove) { if ($PSCmdlet.ShouldProcess("Note $NoteID on session $GUID", 'Remove note')) { - @{ - SessionID = $GUID - EventType = $DeletedType - CorrelationEventID = $NoteID - } + @{ SessionID = $GUID; EventType = $DeletedType; CorrelationEventID = $NoteID } } } ) - if ($EventEntries.Count -eq 0) { return } - - # Not idempotent: never retried - $null = Invoke-CWCServiceMethod -Service PageService -Method AddSessionEvents -Arguments @(@($Group), $EventEntries) + Add-CWCSessionEvent -Group $Group -Entry $EventEntries } diff --git a/ConnectWiseControlAPI/Public/PageService/Update-CWCSessionName.ps1 b/ConnectWiseControlAPI/Public/PageService/Update-CWCSessionName.ps1 index 4f6ae12..5f72e74 100644 --- a/ConnectWiseControlAPI/Public/PageService/Update-CWCSessionName.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Update-CWCSessionName.ps1 @@ -5,7 +5,8 @@ function Update-CWCSessionName { [guid]$GUID, [Parameter(Mandatory=$True)] [string]$NewName, - [string]$Group = 'All Machines' + # Session group name, or the path parts of a nested group + [string[]]$Group = 'All Machines' ) if ($PSCmdlet.ShouldProcess("$GUID", "Rename to '$NewName'")) { @@ -15,7 +16,7 @@ function Update-CWCSessionName { Invoke-CWCServiceMethod -RestApi -Method UpdateSessionName -Arguments @($GUID.ToString(), $NewName) -Idempotent } else { - Invoke-CWCServiceMethod -Service PageService -Method UpdateSessionName -Arguments @($Group, $GUID, $NewName) -Idempotent + Invoke-CWCServiceMethod -Service PageService -Method UpdateSessionName -Arguments @(@($Group), $GUID, $NewName) -Idempotent } } } \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/RestApi/Add-CWCSessionNote.ps1 b/ConnectWiseControlAPI/Public/RestApi/Add-CWCSessionNote.ps1 index 1e8c143..36e1aa1 100644 --- a/ConnectWiseControlAPI/Public/RestApi/Add-CWCSessionNote.ps1 +++ b/ConnectWiseControlAPI/Public/RestApi/Add-CWCSessionNote.ps1 @@ -41,7 +41,7 @@ function Add-CWCSessionNote { [string]$Note, [ValidateNotNullOrEmpty()] - [string]$Group = 'All Machines' + [string[]]$Group = 'All Machines' ) process { @@ -53,12 +53,7 @@ function Add-CWCSessionNote { Invoke-CWCServiceMethod -RestApi -Method AddNoteToSession -Arguments @($GUID.ToString(), $Note) } else { - $NoteEvent = @{ - SessionID = $GUID - EventType = $script:CWCSessionEventType.AddedNote - Data = $Note - } - Invoke-CWCServiceMethod -Service PageService -Method AddSessionEvents -Arguments @(@($Group), @($NoteEvent)) + Add-CWCSessionEvent -Group $Group -Entry @{ SessionID = $GUID; EventType = $script:CWCSessionEventType.AddedNote; Data = $Note } } } } diff --git a/ConnectWiseControlAPI/Public/RestApi/Send-CWCSessionMessage.ps1 b/ConnectWiseControlAPI/Public/RestApi/Send-CWCSessionMessage.ps1 index d34ffd8..2f9027f 100644 --- a/ConnectWiseControlAPI/Public/RestApi/Send-CWCSessionMessage.ps1 +++ b/ConnectWiseControlAPI/Public/RestApi/Send-CWCSessionMessage.ps1 @@ -48,7 +48,7 @@ function Send-CWCSessionMessage { [string]$From = 'RESTful API', [ValidateNotNullOrEmpty()] - [string]$Group = 'All Machines' + [string[]]$Group = 'All Machines' ) process { @@ -64,12 +64,7 @@ function Send-CWCSessionMessage { if ($PSBoundParameters.ContainsKey('From')) { Write-Warning '-From is only used with -ApiSecret connections; the guest sees the connected user as the sender.' } - $MessageEvent = @{ - SessionID = $GUID - EventType = $script:CWCSessionEventType.QueuedMessage - Data = $Message - } - Invoke-CWCServiceMethod -Service PageService -Method AddSessionEvents -Arguments @(@($Group), @($MessageEvent)) + Add-CWCSessionEvent -Group $Group -Entry @{ SessionID = $GUID; EventType = $script:CWCSessionEventType.QueuedMessage; Data = $Message } } } } diff --git a/ConnectWiseControlAPI/Public/RestApi/Send-CWCToolboxItem.ps1 b/ConnectWiseControlAPI/Public/RestApi/Send-CWCToolboxItem.ps1 index 5e56249..26754d7 100644 --- a/ConnectWiseControlAPI/Public/RestApi/Send-CWCToolboxItem.ps1 +++ b/ConnectWiseControlAPI/Public/RestApi/Send-CWCToolboxItem.ps1 @@ -40,7 +40,7 @@ function Send-CWCToolboxItem { [string]$Name, [ValidateNotNullOrEmpty()] - [string]$Group = 'All Machines' + [string[]]$Group = 'All Machines' ) process { @@ -52,12 +52,7 @@ function Send-CWCToolboxItem { Invoke-CWCServiceMethod -RestApi -Method SendToolboxItemToSession -Arguments @($GUID.ToString(), $Name) } else { - $ToolEvent = @{ - SessionID = $GUID - EventType = $script:CWCSessionEventType.QueuedTool - Data = $Name - } - Invoke-CWCServiceMethod -Service PageService -Method AddSessionEvents -Arguments @(@($Group), @($ToolEvent)) + Add-CWCSessionEvent -Group $Group -Entry @{ SessionID = $GUID; EventType = $script:CWCSessionEventType.QueuedTool; Data = $Name } } } } diff --git a/Tests/ConnectWiseControlAPI.Public.Tests.ps1 b/Tests/ConnectWiseControlAPI.Public.Tests.ps1 index ec70205..2c4f653 100644 --- a/Tests/ConnectWiseControlAPI.Public.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Public.Tests.ps1 @@ -218,11 +218,19 @@ Describe 'Connect-CWC' { It 'blames the credentials when the server rejects the validation call' { InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { param($cred) - Mock Invoke-CWCWebRequest { Write-Error 'Needs permission' } + Mock Invoke-CWCWebRequest { Write-Error 'Needs permission' -ErrorId 'CWC.Http500' } { Connect-CWC -Server 'server.example.com' -Credentials $cred -ErrorAction Stop } | Should -Throw "Authentication to*Check the username and password*" } } + It 'does not blame the credentials when the server does not answer' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { + param($cred) + Mock Invoke-CWCWebRequest { Write-Error 'No such host is known.' -ErrorId 'CWC.NoResponse' } + { Connect-CWC -Server 'server.example.com' -Credentials $cred -ErrorAction Stop } | Should -Throw "*failed before authentication could be checked*No such host*" + } + } + It 'does not blame the credentials for a local failure' { InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { param($cred) From 0e9bc4201f8b43bf8ae6fe17abe74fe336beeff9 Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Tue, 10 Nov 2026 10:01:30 -0700 Subject: [PATCH 15/30] Simplify: help build script, derived test lists, narrower .gitignore From the /simplify review: - Build/Update-Help.ps1 regenerates Docs/ and the MAML help, strips platyPS's -ProgressAction leak and fixes module-page links (was done by hand). Module tests fail if a function has no Docs page or -ProgressAction reappears. - The module test derives the expected functions from Public/*.ps1 and checks FunctionsToExport lists each exactly once (no hand-kept copy to drift). - .gitignore: secret patterns now match secret data files only, so the negation lines for source/tests/docs and the *-help.xml rule are gone; the guard test covers ConnectWiseControlAPI/, Tests/, Docs/, Build/, Examples/. - Live smoke test: requests events only from the rate-limited session details, one note filter instead of two copies, one TryLogin step helper. The live Pester suite limits its session query. - CHANGELOG entries for the user-visible changes. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 18 ++-- Build/Update-Help.ps1 | 44 ++++++++++ CHANGELOG.md | 9 ++ .../en-US/ConnectWiseControlAPI-help.xml | 88 ++++++++++++------- Docs/Add-CWCSessionNote.md | 4 +- Docs/Enter-CWCSession.md | 20 ++++- Docs/Get-CWCLastContact.md | 4 +- Docs/Get-CWCSession.md | 4 +- Docs/Invoke-CWCCommand.md | 4 +- Docs/Remove-CWCSession.md | 4 +- Docs/Send-CWCSessionMessage.md | 4 +- Docs/Send-CWCToolboxItem.md | 4 +- Docs/Update-CWCSessionName.md | 4 +- Tests/ConnectWiseControlAPI.Live.Tests.ps1 | 2 +- Tests/ConnectWiseControlAPI.Module.Tests.ps1 | 69 +++++++-------- Tests/Live/Invoke-CWCLiveSmokeTest.ps1 | 62 ++++++------- 16 files changed, 217 insertions(+), 127 deletions(-) create mode 100644 Build/Update-Help.ps1 diff --git a/.gitignore b/.gitignore index 3ff188f..69da4e3 100644 --- a/.gitignore +++ b/.gitignore @@ -8,7 +8,6 @@ output/ coverage.xml testResults.xml nul -*-help.xml # ---- Operating Systems ---- @@ -80,14 +79,15 @@ publish/ *.key *.pem *.p12 -*credentials* -*secret* -!.github/SECURITY.md -# Source, tests and docs are never secrets, even when a name matches (e.g. Test-CWCApiSecretConnection.ps1) -!ConnectWiseControlAPI/**/*.ps1 -!ConnectWiseControlAPI/en-US/*-help.xml -!Tests/**/*.ps1 -!Docs/**/*.md +# Secret *data* files only (Export-Clixml credentials, secret JSON/text). Not name-only patterns like +# *secret*: those matched module source such as Test-CWCApiSecretConnection.ps1. +secrets/ +*.secret +*credential*.xml +*credential*.json +*secret*.xml +*secret*.json +*secret*.txt # ---- Claude Code ---- .claude/settings.local.json diff --git a/Build/Update-Help.ps1 b/Build/Update-Help.ps1 new file mode 100644 index 0000000..6b7386c --- /dev/null +++ b/Build/Update-Help.ps1 @@ -0,0 +1,44 @@ +<# +.SYNOPSIS + Regenerates Docs/*.md, the module page and the MAML help from the functions' comment-based help. + +.DESCRIPTION + Run after adding or changing a public function. Requires platyPS (Install-Module platyPS). + Creates pages for new functions, updates existing ones (keeping hand-written text), then fixes what + platyPS gets wrong for this repo: + - PowerShell 7.4+ adds the -ProgressAction common parameter to every page; it is removed. + - The module page lives at the repo root, so its links need the Docs/ prefix. + Finally rebuilds ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml. + +.EXAMPLE + ./Build/Update-Help.ps1 +#> +[CmdletBinding()] +param() + +$ErrorActionPreference = 'Stop' +$RepoRoot = Split-Path -Parent $PSScriptRoot +$DocsPath = Join-Path $RepoRoot 'Docs' +$ModulePagePath = Join-Path $RepoRoot 'ConnectWiseControlAPI_Functions.md' + +Import-Module platyPS +$Module = Import-Module (Join-Path $RepoRoot 'ConnectWiseControlAPI\ConnectWiseControlAPI.psd1') -Force -PassThru + +$Missing = @($Module.ExportedFunctions.Keys | Where-Object { -not (Test-Path (Join-Path $DocsPath "$_.md")) }) +if ($Missing) { $null = New-MarkdownHelp -Command $Missing -OutputFolder $DocsPath } +$null = Update-MarkdownHelpModule -Path $DocsPath -ModulePagePath $ModulePagePath -RefreshModulePage -Force + +foreach ($Page in Get-ChildItem $DocsPath -Filter '*.md') { + $Text = [IO.File]::ReadAllText($Page.FullName) + $Fixed = [regex]::Replace($Text, '(?s)### -ProgressAction\r?\n.*?(?=\r?\n### |\r?\n## )', '') + $Fixed = [regex]::Replace($Fixed, '\s*\[-ProgressAction \]', '') + if ($Fixed -ne $Text) { [IO.File]::WriteAllText($Page.FullName, $Fixed) } +} + +$Text = [IO.File]::ReadAllText($ModulePagePath) +[IO.File]::WriteAllText($ModulePagePath, [regex]::Replace($Text, '\]\((?!Docs/)([A-Za-z-]+\.md)\)', '](Docs/$1)')) + +$null = New-ExternalHelp -Path $DocsPath -OutputPath (Join-Path $RepoRoot 'ConnectWiseControlAPI\en-US') -Force + +$Placeholders = Select-String -Path (Join-Path $DocsPath '*.md'), $ModulePagePath -Pattern '\{\{' +foreach ($Hit in $Placeholders) { Write-Warning "Placeholder left to fill: $($Hit.Filename):$($Hit.LineNumber)" } diff --git a/CHANGELOG.md b/CHANGELOG.md index cca10a3..7d50539 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -75,6 +75,15 @@ Planned as 0.5.0.0 (the module manifest already carries this version; 0.4.0.0 is PowerShell error) is reported as such instead of being blamed on the credentials - Removed the unloaded `WIP/Invoke-CWCSession.ps1` prototype, superseded by `Enter-CWCSession` - `Get-CWCLastContact` returns an error when no connection event is found, instead of the current time +- `-Group` accepts the path parts of a nested session group (e.g. `'Clients','Acme'`) on every session + function that takes it; a single group name works as before +- Errors from API calls carry an ErrorId: `CWC.NotConnected`, `CWC.AuthModeMismatch`, `CWC.Http` + (the server answered) or `CWC.NoResponse`, so scripts can branch on `$_.FullyQualifiedErrorId`. The + message now shows the HTTP status and the server's own error text +- `Invoke-CWCCommand` waits 1, 2, 3 … up to 5 seconds between polls of the rate-limited session details +- `Enter-CWCSession` takes `-Name` from the pipeline (e.g. from `Get-CWCSession`) and then skips its + session lookup +- `Build/Update-Help.ps1` regenerates `Docs/` and the MAML help in one step ### Fixed diff --git a/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml b/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml index 589b74b..5bee06e 100644 --- a/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml +++ b/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml @@ -129,9 +129,9 @@ Session group containing the session (credentials connections only). Defaults to 'All Machines'. - String + String[] - String + String[] All Machines @@ -190,9 +190,9 @@ Session group containing the session (credentials connections only). Defaults to 'All Machines'. - String + String[] - String + String[] All Machines @@ -473,6 +473,18 @@ Session group containing the session. Defaults to 'All Machines' for Access, 'All Sessions' for Support and 'All Meetings' for Meeting. + String[] + + String[] + + + None + + + Name + + Session name shown as the client's title. Taken from the pipeline (e.g. from Get-CWCSession); when given, the session lookup is skipped. + String String @@ -523,6 +535,18 @@ Session group containing the session. Defaults to 'All Machines' for Access, 'All Sessions' for Support and 'All Meetings' for Meeting. + String[] + + String[] + + + None + + + Name + + Session name shown as the client's title. Taken from the pipeline (e.g. from Get-CWCSession); when given, the session lookup is skipped. + String String @@ -1016,9 +1040,9 @@ open $Url # macOS Name of session group to use. - String + String[] - String + String[] All Machines @@ -1079,9 +1103,9 @@ open $Url # macOS Name of session group to use. - String + String[] - String + String[] All Machines @@ -1571,9 +1595,9 @@ open $Url # macOS Name of session group to use. - String + String[] - String + String[] All Machines @@ -1634,9 +1658,9 @@ open $Url # macOS Name of session group to use. - String + String[] - String + String[] All Machines @@ -2022,9 +2046,9 @@ open $Url # macOS Name of session group to use. - String + String[] - String + String[] All Machines @@ -2119,9 +2143,9 @@ open $Url # macOS Name of session group to use. - String + String[] - String + String[] All Machines @@ -3363,9 +3387,9 @@ Remove-CWCHostFromSession -SessionID $SessionID -ConnectionID $HostConnection.Co Session group containing the session(s). Defaults to 'All Machines' where a default exists. - String + String[] - String + String[] None @@ -3425,9 +3449,9 @@ Remove-CWCHostFromSession -SessionID $SessionID -ConnectionID $HostConnection.Co Session group containing the session(s). Defaults to 'All Machines' where a default exists. - String + String[] - String + String[] None @@ -3889,9 +3913,9 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { Session group containing the session (credentials connections only). Defaults to 'All Machines'. - String + String[] - String + String[] All Machines @@ -3962,9 +3986,9 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { Session group containing the session (credentials connections only). Defaults to 'All Machines'. - String + String[] - String + String[] All Machines @@ -4063,9 +4087,9 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { Session group containing the session (credentials connections only). Defaults to 'All Machines'. - String + String[] - String + String[] All Machines @@ -4124,9 +4148,9 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { Session group containing the session (credentials connections only). Defaults to 'All Machines'. - String + String[] - String + String[] All Machines @@ -4408,9 +4432,9 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { Group to look for the session in. - String + String[] - String + String[] All Machines @@ -4470,9 +4494,9 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { Group to look for the session in. - String + String[] - String + String[] All Machines diff --git a/Docs/Add-CWCSessionNote.md b/Docs/Add-CWCSessionNote.md index b333ae1..245767c 100644 --- a/Docs/Add-CWCSessionNote.md +++ b/Docs/Add-CWCSessionNote.md @@ -13,7 +13,7 @@ Adds a note to a session. ## SYNTAX ``` -Add-CWCSessionNote [-GUID] [-Note] [[-Group] ] +Add-CWCSessionNote [-GUID] [-Note] [[-Group] ] [-WhatIf] [-Confirm] [] ``` @@ -72,7 +72,7 @@ Session group containing the session (credentials connections only). Defaults to 'All Machines'. ```yaml -Type: String +Type: String[] Parameter Sets: (All) Aliases: diff --git a/Docs/Enter-CWCSession.md b/Docs/Enter-CWCSession.md index 8fb13ab..2fa391a 100644 --- a/Docs/Enter-CWCSession.md +++ b/Docs/Enter-CWCSession.md @@ -13,7 +13,7 @@ Opens the ConnectWise Control Host client joined to a session, like Join in the ## SYNTAX ``` -Enter-CWCSession [-GUID] [[-Type] ] [[-Group] ] [-UrlOnly] [] +Enter-CWCSession [-GUID] [[-Type] ] [[-Group] ] [[-Name] ] [-UrlOnly] [] ``` ## DESCRIPTION @@ -87,7 +87,7 @@ Defaults to 'All Machines' for Access, 'All Sessions' for Support and 'All Meetings' for Meeting. ```yaml -Type: String +Type: String[] Parameter Sets: (All) Aliases: @@ -98,6 +98,22 @@ Accept pipeline input: False Accept wildcard characters: False ``` +### -Name +Session name shown as the client's title. Taken from the pipeline (e.g. from Get-CWCSession); +when given, the session lookup is skipped. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + ### -UrlOnly Return the launch URL instead of opening the client. The URL holds an access token: treat it diff --git a/Docs/Get-CWCLastContact.md b/Docs/Get-CWCLastContact.md index 421ca68..23519da 100644 --- a/Docs/Get-CWCLastContact.md +++ b/Docs/Get-CWCLastContact.md @@ -13,7 +13,7 @@ Returns the date the machine last connected to the control server. ## SYNTAX ``` -Get-CWCLastContact [-GUID] [-Quiet] [[-Seconds] ] [[-Group] ] [] +Get-CWCLastContact [-GUID] [-Quiet] [[-Seconds] ] [[-Group] ] [] ``` ## DESCRIPTION @@ -86,7 +86,7 @@ Accept wildcard characters: False Name of session group to use. ```yaml -Type: String +Type: String[] Parameter Sets: (All) Aliases: diff --git a/Docs/Get-CWCSession.md b/Docs/Get-CWCSession.md index 498acb9..d190b27 100644 --- a/Docs/Get-CWCSession.md +++ b/Docs/Get-CWCSession.md @@ -13,7 +13,7 @@ Will return a list of sessions. ## SYNTAX ``` -Get-CWCSession -Type [-Group ] [-Search ] [-FindSessionID ] [-Limit ] [] +Get-CWCSession -Type [-Group ] [-Search ] [-FindSessionID ] [-Limit ] [] ``` ## DESCRIPTION @@ -49,7 +49,7 @@ Accept wildcard characters: False Name of session group to use. ```yaml -Type: String +Type: String[] Parameter Sets: (All) Aliases: diff --git a/Docs/Invoke-CWCCommand.md b/Docs/Invoke-CWCCommand.md index 6c78f3a..e553b3a 100644 --- a/Docs/Invoke-CWCCommand.md +++ b/Docs/Invoke-CWCCommand.md @@ -14,7 +14,7 @@ Will issue a command against a given machine and return the results. ``` Invoke-CWCCommand [-GUID] [[-Command] ] [[-TimeOut] ] [-MaxLength ] [-PowerShell] - [[-Group] ] [-NoWait] [] + [[-Group] ] [-NoWait] [] ``` ## DESCRIPTION @@ -104,7 +104,7 @@ Accept wildcard characters: False Name of session group to use. ```yaml -Type: String +Type: String[] Parameter Sets: (All) Aliases: diff --git a/Docs/Remove-CWCSession.md b/Docs/Remove-CWCSession.md index 8d7b951..1c579b2 100644 --- a/Docs/Remove-CWCSession.md +++ b/Docs/Remove-CWCSession.md @@ -13,7 +13,7 @@ Will end a given session. ## SYNTAX ``` -Remove-CWCSession -GUID -Group [-Uninstall] [-WhatIf] +Remove-CWCSession -GUID -Group [-Uninstall] [-WhatIf] [-Confirm] [] ``` @@ -81,7 +81,7 @@ Accept wildcard characters: False Session group containing the session(s). Defaults to 'All Machines' where a default exists. ```yaml -Type: String +Type: String[] Parameter Sets: (All) Aliases: diff --git a/Docs/Send-CWCSessionMessage.md b/Docs/Send-CWCSessionMessage.md index 3b1a7ab..43a4080 100644 --- a/Docs/Send-CWCSessionMessage.md +++ b/Docs/Send-CWCSessionMessage.md @@ -13,7 +13,7 @@ Sends a chat message to a session's guest. ## SYNTAX ``` -Send-CWCSessionMessage [-GUID] [-Message] [[-From] ] [[-Group] ] [-WhatIf] [-Confirm] [] +Send-CWCSessionMessage [-GUID] [-Message] [[-From] ] [[-Group] ] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION @@ -87,7 +87,7 @@ Session group containing the session (credentials connections only). Defaults to 'All Machines'. ```yaml -Type: String +Type: String[] Parameter Sets: (All) Aliases: diff --git a/Docs/Send-CWCToolboxItem.md b/Docs/Send-CWCToolboxItem.md index 90f568b..84307b3 100644 --- a/Docs/Send-CWCToolboxItem.md +++ b/Docs/Send-CWCToolboxItem.md @@ -13,7 +13,7 @@ Queues a Toolbox item to run on a session. ## SYNTAX ``` -Send-CWCToolboxItem [-GUID] [-Name] [[-Group] ] +Send-CWCToolboxItem [-GUID] [-Name] [[-Group] ] [-WhatIf] [-Confirm] [] ``` @@ -69,7 +69,7 @@ Session group containing the session (credentials connections only). Defaults to 'All Machines'. ```yaml -Type: String +Type: String[] Parameter Sets: (All) Aliases: diff --git a/Docs/Update-CWCSessionName.md b/Docs/Update-CWCSessionName.md index 10a4a0a..43e630d 100644 --- a/Docs/Update-CWCSessionName.md +++ b/Docs/Update-CWCSessionName.md @@ -13,7 +13,7 @@ Updates the name of a session. ## SYNTAX ``` -Update-CWCSessionName -GUID -NewName [-Group ] +Update-CWCSessionName -GUID -NewName [-Group ] [-WhatIf] [-Confirm] [] ``` @@ -71,7 +71,7 @@ Accept wildcard characters: False Group to look for the session in. ```yaml -Type: String +Type: String[] Parameter Sets: (All) Aliases: diff --git a/Tests/ConnectWiseControlAPI.Live.Tests.ps1 b/Tests/ConnectWiseControlAPI.Live.Tests.ps1 index 39fd5d3..a05d80e 100644 --- a/Tests/ConnectWiseControlAPI.Live.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Live.Tests.ps1 @@ -54,7 +54,7 @@ BeforeAll { # Access sessions are used by the Session, Session Detail and Last Contact tests $script:AccessSessionsError = $null try { - $script:AccessSessions = Get-CWCSession -Type 'Access' + $script:AccessSessions = Get-CWCSession -Type 'Access' -Limit 5 } catch { $script:AccessSessionsError = $_ diff --git a/Tests/ConnectWiseControlAPI.Module.Tests.ps1 b/Tests/ConnectWiseControlAPI.Module.Tests.ps1 index 0586622..028e9bb 100644 --- a/Tests/ConnectWiseControlAPI.Module.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Module.Tests.ps1 @@ -14,40 +14,10 @@ #> BeforeDiscovery { - $ExpectedFunctions = @( - 'Connect-CWC' - 'Get-CWCAuditInfo' - 'Get-CWCAuditLog' - 'Get-CWCSession' - 'Get-CWCSessionDetail' - 'Get-CWCLastContact' - 'Invoke-CWCCommand' - 'Invoke-CWCWake' - 'New-CWCAccessToken' - 'Remove-CWCSession' - 'Remove-CWCHostFromSession' - 'Remove-CWCSessionNote' - 'Update-CWCCustomProperty' - 'Update-CWCSessionName' - 'Get-CWCSecurityConfigurationInfo' - 'New-CWCUser' - 'Remove-CWCUser' - 'Update-CWCUser' - 'Get-CWCSessionGroup' - 'Get-CWCLauncURL' - 'Add-CWCRemoteWorkforceRequiredRole' - 'New-CWCRemoteWorkforceAssignment' - 'Get-CWCRemoteWorkforceLaunchURL' - 'Get-CWCRemoteWorkforceSession' - 'Initialize-CWCRemoteWorkforceSessionGroup' - 'Find-CWCSession' - 'New-CWCSession' - 'Add-CWCSessionNote' - 'Send-CWCSessionMessage' - 'Send-CWCToolboxItem' - 'New-CWCMFA' - 'Enter-CWCSession' - ) + # One public function per Public/**/*.ps1 file; the tests below check the manifest and the loaded + # module against this list, so a new function needs no test edit. + $ExpectedFunctions = @(Get-ChildItem -Path (Join-Path (Split-Path -Parent $PSScriptRoot) 'ConnectWiseControlAPI\Public') -Filter '*.ps1' -Recurse | + ForEach-Object BaseName | Sort-Object) } BeforeAll { @@ -93,6 +63,12 @@ Describe 'Module: ConnectWiseControlAPI' { It 'exports no cmdlets' { $Manifest.ExportedCmdlets.Keys | Should -HaveCount 0 } + + It 'lists every public function in FunctionsToExport exactly once' -ForEach @(@{ Expected = $ExpectedFunctions }) { + $Listed = @((Import-PowerShellDataFile -Path $ManifestPath).FunctionsToExport) + @($Listed | Group-Object | Where-Object Count -gt 1 | ForEach-Object Name) | Should -BeNullOrEmpty + @($Listed | Sort-Object) | Should -Be $Expected + } } Context 'Module Import' { @@ -368,16 +344,37 @@ Describe 'Parameter Validation' { Describe 'Repository' { # A .gitignore pattern once hid Private/Test-CWCApiSecretConnection.ps1 (matched *secret*), so the # module only worked on machines that already had the file. - It 'does not git-ignore any module source file' { + It 'does not git-ignore any source, test, docs, build or example file' { $RepoRoot = Split-Path $PSScriptRoot -Parent if (-not (Get-Command git -ErrorAction SilentlyContinue) -or -not (Test-Path (Join-Path $RepoRoot '.git'))) { Set-ItResult -Skipped -Because 'git or the repository is not available' return } - $SourceFiles = Get-ChildItem (Join-Path $RepoRoot 'ConnectWiseControlAPI') -Recurse -File | + $SourceFolders = 'ConnectWiseControlAPI', 'Tests', 'Docs', 'Build', 'Examples' | + ForEach-Object { Join-Path $RepoRoot $_ } | Where-Object { Test-Path $_ } + $SourceFiles = Get-ChildItem $SourceFolders -Recurse -File | ForEach-Object { $_.FullName.Substring($RepoRoot.Length + 1).Replace('\', '/') } # Paths as arguments, not --stdin: piped lines carry a trailing CR on Windows, which defeats the patterns $Ignored = @(git -C $RepoRoot check-ignore --no-index -- $SourceFiles | Where-Object { $_ }) $Ignored | Should -BeNullOrEmpty } } + +Describe 'Generated help' { + BeforeAll { + $RepoRoot = Split-Path $PSScriptRoot -Parent + $DocsPath = Join-Path $RepoRoot 'Docs' + } + + It 'has a Docs page for <_>' -ForEach $ExpectedFunctions { + Join-Path $DocsPath "$_.md" | Should -Exist -Because 'run ./Build/Update-Help.ps1 after adding a function' + } + + # platyPS on PowerShell 7.4+ adds -ProgressAction to every page; Build/Update-Help.ps1 strips it. + It 'does not document the -ProgressAction common parameter' { + $Files = @(Get-ChildItem $DocsPath -Filter '*.md' | ForEach-Object FullName) + + (Join-Path $RepoRoot 'ConnectWiseControlAPI\en-US\ConnectWiseControlAPI-help.xml') + @(Select-String -Path $Files -Pattern 'ProgressAction' | ForEach-Object { "$($_.Filename):$($_.LineNumber)" }) | + Should -BeNullOrEmpty -Because 'run ./Build/Update-Help.ps1 to regenerate the help' + } +} diff --git a/Tests/Live/Invoke-CWCLiveSmokeTest.ps1 b/Tests/Live/Invoke-CWCLiveSmokeTest.ps1 index 0dfa0c3..5b98195 100644 --- a/Tests/Live/Invoke-CWCLiveSmokeTest.ps1 +++ b/Tests/Live/Invoke-CWCLiveSmokeTest.ps1 @@ -93,32 +93,29 @@ function Select-Event { function Get-NewEvent { param([datetime]$SinceUtc) $ElapsedMs = ([DateTime]::UtcNow - $SinceUtc).TotalMilliseconds + 500 - $Detail = Get-CWCSessionDetail -Group $Group -GUID $TestSessionID + $Detail = Get-CWCSessionDetail -Group $Group -GUID $TestSessionID -Include Events Select-Event ($Detail.Events | Where-Object { [double]$_.Time -le $ElapsedMs }) } -# Deletes every note this script added to the test session (any run). Needs a credentials connection. -# A note is removed by adding a DeletedEvent (SessionEventType 1) correlated to the note's EventID; -# the server checks RemoveNote permission. Returns how many notes were deleted and how many remain. -function Remove-SmokeTestNote { - $NoteType = 32 - $DeletedEventType = 1 - $Events = @((Get-CWCSessionDetail -Group $Group -GUID $TestSessionID).Events) - $AlreadyDeleted = @($Events | Where-Object { $_.EventType -eq $DeletedEventType } | ForEach-Object CorrelationEventID) - $TestNotes = @($Events | Where-Object { - $_.EventType -eq $NoteType -and "$($_.Data)" -like 'CWC smoke test note*' -and $_.EventID -notin $AlreadyDeleted +# Notes this script added to the test session (any run) that are not deleted yet. The event numbers are +# written out (AddedNote 32, DeletedEvent 1) so this checks the server independently of the module. +function Get-OpenSmokeTestNote { + $Events = @((Get-CWCSessionDetail -Group $Group -GUID $TestSessionID -Include Events).Events) + $AlreadyDeleted = @($Events | Where-Object { $_.EventType -eq 1 } | ForEach-Object CorrelationEventID) + @($Events | Where-Object { + $_.EventType -eq 32 -and "$($_.Data)" -like 'CWC smoke test note*' -and $_.EventID -notin $AlreadyDeleted }) +} + +# Deletes every note this script added, with Remove-CWCSessionNote (so it is exercised live), and +# checks none remain. Needs a credentials connection and the RemoveNote permission. +function Remove-SmokeTestNote { + $TestNotes = @(Get-OpenSmokeTestNote) if ($TestNotes.Count -gt 0) { - # Also exercises Remove-CWCSessionNote live Remove-CWCSessionNote -GUID $TestSessionID -Group $Group -NoteEventID ($TestNotes | ForEach-Object { [guid]$_.EventID }) -Confirm:$false Start-Sleep -Seconds 2 } - - $Events = @((Get-CWCSessionDetail -Group $Group -GUID $TestSessionID).Events) - $AlreadyDeleted = @($Events | Where-Object { $_.EventType -eq $DeletedEventType } | ForEach-Object CorrelationEventID) - $Remaining = @($Events | Where-Object { - $_.EventType -eq $NoteType -and "$($_.Data)" -like 'CWC smoke test note*' -and $_.EventID -notin $AlreadyDeleted - }).Count + $Remaining = @(Get-OpenSmokeTestNote).Count if ($Remaining -gt 0) { throw "$Remaining smoke test note(s) still on session $TestSessionID" } [ordered]@{ Deleted = $TestNotes.Count; Remaining = $Remaining } } @@ -164,7 +161,7 @@ Invoke-Step 'Creds.SessionEventTypeEnum' { Invoke-Step 'Creds.GetSession' { @(Get-CWCSession -Type Access -Group $Group -Limit 5).Count } Invoke-Step 'Creds.GetSessionDetail' { - $Detail = Get-CWCSessionDetail -Group $Group -GUID $TestSessionID + $Detail = Get-CWCSessionDetail -Group $Group -GUID $TestSessionID -Include Events [ordered]@{ BaseTime = $Detail.BaseTime; Events = @(Select-Event ($Detail.Events | Select-Object -First 15)) } } Invoke-Step 'Creds.LastContact' { (Get-CWCLastContact -GUID $TestSessionID -Group $Group).ToString('o') } @@ -221,22 +218,25 @@ if ($MfaUserName) { } $Password = $MfaCredential.GetNetworkCredential().Password - Invoke-Step 'Mfa.TryLoginWithoutOtp' { - $LoginResult = Select-LoginResult (Invoke-MfaRequest 'Services/AuthenticationService.ashx/TryLogin' @($MfaUserName, $Password, $null, $False, $null)) - [ordered]@{ Result = $LoginResult; Cookies = @($Mfa.Session.Cookies.GetCookies("https://$Server") | ForEach-Object Name) } - } - Invoke-Step 'Mfa.TryLoginWrongOtp' { - $LoginResult = Select-LoginResult (Invoke-MfaRequest 'Services/AuthenticationService.ashx/TryLogin' @($MfaUserName, $Password, '000000', $False, $null)) - [ordered]@{ Result = $LoginResult; Cookies = @($Mfa.Session.Cookies.GetCookies("https://$Server") | ForEach-Object Name) } + function Get-MfaCookieName { @($Mfa.Session.Cookies.GetCookies("https://$Server") | ForEach-Object Name) } + # One TryLogin attempt: the login result code and which cookies the session holds afterwards + function Invoke-TryLoginStep { + param([string]$Name, $OneTimeCode) + Invoke-Step $Name { + [ordered]@{ + Result = Select-LoginResult (Invoke-MfaRequest 'Services/AuthenticationService.ashx/TryLogin' @($MfaUserName, $Password, $OneTimeCode, $False, $null)) + Cookies = Get-MfaCookieName + } + } } + Invoke-TryLoginStep 'Mfa.TryLoginWithoutOtp' $null + Invoke-TryLoginStep 'Mfa.TryLoginWrongOtp' '000000' + $OneTimePassword = Read-Host -Prompt "One-time password for $MfaUserName (Enter to skip)" if ($OneTimePassword) { - Invoke-Step 'Mfa.TryLoginWithOtp' { - $LoginResult = Select-LoginResult (Invoke-MfaRequest 'Services/AuthenticationService.ashx/TryLogin' @($MfaUserName, $Password, $OneTimePassword, $False, $null)) - [ordered]@{ Result = $LoginResult; Cookies = @($Mfa.Session.Cookies.GetCookies("https://$Server") | ForEach-Object Name) } - } - Invoke-Step 'Mfa.CookiesAfterLogin' { @($Mfa.Session.Cookies.GetCookies("https://$Server") | ForEach-Object Name) } + Invoke-TryLoginStep 'Mfa.TryLoginWithOtp' $OneTimePassword + Invoke-Step 'Mfa.CookiesAfterLogin' { Get-MfaCookieName } # Anti-forgery tokens may be tied to the logged-in user: compare old and fresh. Invoke-Step 'Mfa.RefreshToken' { From 9493e78762176ad4062adf6ec506626dd78a0d16 Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Tue, 10 Nov 2026 10:09:17 -0700 Subject: [PATCH 16/30] Fix review round 1 findings; add help to touched functions - HTTP 500 with a SecurityException body (permission failure, including a wrong password at Connect-CWC) is no longer retried; it only delayed the error by 14 s. - Invoke-CWCCommand identifies its own QueuedCommand by its exact text and prefers the RanCommand whose CorrelationEventID points at it, so a command queued by someone else at the same time can't be returned as ours. - Enter-CWCSession stops trying delegated tokens only after a permission failure, not after any error. - Get-CWCSession defaults -Group to the built-in group for -Type (Support and Meeting queries used 'All Machines'). - Remove-CWCSessionNote help: only -All skips already-deleted notes. - Comment-based help for the 14 public functions this release touched that had none; docs regenerated. CLAUDE.md retry count corrected (3, not 5). Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- .../Private/Invoke-CWCWebRequest.ps1 | 26 +- .../Public/AuditService/Get-CWCAuditInfo.ps1 | 16 + .../Public/AuditService/Get-CWCAuditLog.ps1 | 34 + .../Public/PageService/Enter-CWCSession.ps1 | 3 +- .../Public/PageService/Get-CWCLastContact.ps1 | 33 +- .../Public/PageService/Get-CWCSession.ps1 | 39 +- .../PageService/Get-CWCSessionDetail.ps1 | 33 +- .../Public/PageService/Invoke-CWCCommand.ps1 | 72 +- .../Public/PageService/Invoke-CWCWake.ps1 | 22 + .../Public/PageService/Remove-CWCSession.ps1 | 27 + .../PageService/Remove-CWCSessionNote.ps1 | 4 +- .../PageService/Update-CWCCustomProperty.ps1 | 29 + .../PageService/Update-CWCSessionName.ps1 | 29 +- .../Get-CWCSecurityConfigurationInfo.ps1 | 16 + .../Public/SecurityService/New-CWCUser.ps1 | 38 +- .../Public/SecurityService/Remove-CWCUser.ps1 | 21 +- .../Public/SecurityService/Update-CWCUser.ps1 | 45 +- .../Get-CWCSessionGroup.ps1 | 16 + .../en-US/ConnectWiseControlAPI-help.xml | 748 +++++++++--------- Docs/Get-CWCAuditLog.md | 44 +- Docs/Get-CWCLastContact.md | 8 +- Docs/Get-CWCSession.md | 29 +- Docs/Get-CWCSessionDetail.md | 8 +- Docs/Invoke-CWCCommand.md | 42 +- Docs/Invoke-CWCWake.md | 6 +- Docs/New-CWCUser.md | 54 +- Docs/Remove-CWCSession.md | 40 +- Docs/Remove-CWCUser.md | 32 +- Docs/Update-CWCCustomProperty.md | 56 +- Docs/Update-CWCSessionName.md | 21 +- Docs/Update-CWCUser.md | 89 +-- 32 files changed, 1059 insertions(+), 623 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index e699267..89931cc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -24,7 +24,7 @@ Run unit tests on both PS 7 and Windows PowerShell 5.1. `Tests/ConnectWiseContro ## Architecture - **Loading**: the `.psm1` dot-sources every `.ps1` under `Public/` and `Private/` and exports the `Public/` basenames, but a new function must also be added to `FunctionsToExport` in the `.psd1`. The `.psm1` also holds the shared constants: `$script:CWCSessionType`, `$script:CWCSessionEventType` (live-verified numbers) and the Remote Workforce and RESTful API Manager extension IDs. -- **Requests**: every public function calls `Private/Invoke-CWCServiceMethod.ps1`. It builds the endpoint (`-Service` → `Services/.ashx/`, `-RestApi` / `-ExtensionID` → `App_Extensions//Service.ashx/`) and sends the arguments as a **positional JSON array** matching the server method's signature. `-Idempotent` turns on retry for HTTP 500 (5 tries with backoff; otherwise none, so commands/notes/deletes never repeat). `-Sensitive` redacts the body from verbose and debug output. +- **Requests**: every public function calls `Private/Invoke-CWCServiceMethod.ps1`. It builds the endpoint (`-Service` → `Services/.ashx/`, `-RestApi` / `-ExtensionID` → `App_Extensions//Service.ashx/`) and sends the arguments as a **positional JSON array** matching the server method's signature. `-Idempotent` turns on retry for HTTP 500 (3 retries, waiting 2/4/8 s; never for permission errors; otherwise none, so commands/notes/deletes never repeat). Session events go through `Private/Add-CWCSessionEvent.ps1`. Transport errors carry an ErrorId (`CWC.NotConnected`, `CWC.AuthModeMismatch`, `CWC.Http`, `CWC.NoResponse`). `-Sensitive` redacts the body from verbose and debug output. - **Transport**: `Private/Invoke-CWCWebRequest.ps1` checks that a connection exists, **blocks calls that don't match the auth mode** (API-secret connections may only reach the RESTful API Manager), adds auth headers, handles PS 5 vs 6+ error shapes, and returns parsed JSON. - **Connection state**: `$script:CWCServerConnection` holds `Server`, `AuthType`, and `Headers`. Credentials mode adds a `WebSession` (cookies) and an anti-forgery token taken from the front page. ApiSecret mode sends `CTRLAuthHeader`. Connect-CWC validates the login with a test call and restores the previous connection if that call fails. diff --git a/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 b/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 index 7323e23..62e5c98 100644 --- a/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 +++ b/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 @@ -78,9 +78,20 @@ } } - # Retry on HTTP 500 when the caller allows it (no response yields 0) + # The server's error body, e.g. {"errorType":"SecurityException","message":"Needs permission"} $StatusCode = [int]$_.Exception.Response.StatusCode - if ($StatusCode -eq 500 -and $Retry -lt $MaxRetry) { + $ServerMessage = $_.ErrorDetails.Message + if (-not $ServerMessage -and $_.Exception.Response -and $PSVersionTable.PSVersion.Major -lt 6) { + # Fallback for Windows PowerShell when ErrorDetails is empty; the stream may be unreadable. + try { $ServerMessage = (New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream())).ReadToEnd() } + catch { $ServerMessage = $null } + } + + # Retry on HTTP 500 when the caller allows it (no response yields 0). Control also answers + # permission failures (including a wrong password) with 500 + SecurityException: retrying + # those only delays the error. + $IsPermissionFailure = "$ServerMessage" -match 'SecurityException' + if ($StatusCode -eq 500 -and -not $IsPermissionFailure -and $Retry -lt $MaxRetry) { $Retry++ # Exponential backoff: 2, 4, 8 ... seconds $Wait = [math]::Pow(2, $Retry) @@ -89,17 +100,10 @@ continue } - # Build the error message, keeping the server's error body (e.g. {"errorType":"SecurityException","message":"Needs permission"}) + # Build the error message, keeping the server's error body $ErrorMessage = @() - if ($StatusCode -eq 500 -and $MaxRetry -gt 0) { $ErrorMessage += "Max retries hit ($MaxRetry). Status: 500" } + if ($StatusCode -eq 500 -and $Retry -gt 0) { $ErrorMessage += "Max retries hit ($MaxRetry). Status: 500" } elseif ($StatusCode -gt 0) { $ErrorMessage += "HTTP $StatusCode" } - - $ServerMessage = $_.ErrorDetails.Message - if (-not $ServerMessage -and $_.Exception.Response -and $PSVersionTable.PSVersion.Major -lt 6) { - # Fallback for Windows PowerShell when ErrorDetails is empty; the stream may be unreadable. - try { $ServerMessage = (New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream())).ReadToEnd() } - catch { $ServerMessage = $null } - } if ($ServerMessage) { $ErrorMessage += $ServerMessage } else { $ErrorMessage += "$_" } diff --git a/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditInfo.ps1 b/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditInfo.ps1 index 1fd4a2d..8b11ea1 100644 --- a/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditInfo.ps1 +++ b/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditInfo.ps1 @@ -1,4 +1,20 @@ function Get-CWCAuditInfo { + <# + .SYNOPSIS + Shows the current audit settings. + + .DESCRIPTION + Calls AuditService.GetAuditInfo. + + .EXAMPLE + Get-CWCAuditInfo + + .NOTES + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> [CmdletBinding()] param () diff --git a/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditLog.ps1 b/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditLog.ps1 index cfc8028..13fe9af 100644 --- a/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditLog.ps1 +++ b/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditLog.ps1 @@ -1,4 +1,38 @@ function Get-CWCAuditLog { + <# + .SYNOPSIS + Returns audit log entries for a time range. + + .DESCRIPTION + Calls AuditService.QueryAuditLog. Times are converted to UTC. + + .PARAMETER StartDate + Start of the time range. Defaults to 24 hours ago. + + .PARAMETER EndDate + End of the time range. Defaults to now. + + .PARAMETER SessionName + Only return entries for sessions with this name. + + .PARAMETER IncludeSessionCaptures + Deprecated. The server no longer accepts this option; it is ignored with a warning. + + .PARAMETER EventTypes + Session event type numbers to include. + + .PARAMETER SecurityTypes + Security event type numbers to include. + + .EXAMPLE + Get-CWCAuditLog -StartDate (Get-Date).AddDays(-7) -SessionName 'DESKTOP-01' + + .NOTES + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> [CmdletBinding()] param ( [datetime]$StartDate = (Get-Date).AddDays(-1), diff --git a/ConnectWiseControlAPI/Public/PageService/Enter-CWCSession.ps1 b/ConnectWiseControlAPI/Public/PageService/Enter-CWCSession.ps1 index 614f7dc..dbfff79 100644 --- a/ConnectWiseControlAPI/Public/PageService/Enter-CWCSession.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Enter-CWCSession.ps1 @@ -126,7 +126,8 @@ function Enter-CWCSession { ) -ErrorAction Stop } catch { - $DelegatedTokenUnavailable = $True + # Only a permission failure holds for the rest of the pipeline; anything else is retried per item. + if ("$($_.Exception.Message)" -match 'SecurityException|permission') { $DelegatedTokenUnavailable = $True } Write-Verbose "Delegated access token not available: $($_.Exception.Message)" Write-Warning ("Could not get a short-lived delegated token (needs CreateDelegatedAccessToken); the URL uses a regular " + "Host token valid for the server's access token lifetime. Treat it like a password.") diff --git a/ConnectWiseControlAPI/Public/PageService/Get-CWCLastContact.ps1 b/ConnectWiseControlAPI/Public/PageService/Get-CWCLastContact.ps1 index 1220164..82901ce 100644 --- a/ConnectWiseControlAPI/Public/PageService/Get-CWCLastContact.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Get-CWCLastContact.ps1 @@ -1,4 +1,35 @@ -function Get-CWCLastContact { +function Get-CWCLastContact { + <# + .SYNOPSIS + Returns when a machine was last connected, or whether it connected recently. + + .DESCRIPTION + Reads the session's connect/disconnect events. Returns the current time if the guest is connected + now, otherwise the time of its last disconnect. With -Quiet, returns $True when the guest is + connected or was connected within -Seconds, else $False. + + .PARAMETER GUID + Session ID. + + .PARAMETER Quiet + Return $True or $False instead of a date. + + .PARAMETER Seconds + Used with -Quiet: how recent the last contact must be to count. + + .PARAMETER Group + Session group containing the session: a name, or the path parts of a nested group. Defaults to + 'All Machines'. + + .EXAMPLE + Get-CWCLastContact -GUID $SessionID -Quiet -Seconds 300 + + .NOTES + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> [CmdletBinding()] [OutputType([boolean], ParameterSetName = ('Quiet'))] [OutputType([datetime])] diff --git a/ConnectWiseControlAPI/Public/PageService/Get-CWCSession.ps1 b/ConnectWiseControlAPI/Public/PageService/Get-CWCSession.ps1 index 2707fd1..face76f 100644 --- a/ConnectWiseControlAPI/Public/PageService/Get-CWCSession.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Get-CWCSession.ps1 @@ -1,16 +1,51 @@ function Get-CWCSession { + <# + .SYNOPSIS + Lists sessions of one type in a session group. + + .DESCRIPTION + Calls PageService.GetLiveData, the same query the web UI's session list uses. + + .PARAMETER Type + Session type: Support, Access or Meeting. + + .PARAMETER Group + Session group: a name, or the path parts of a nested group (e.g. 'Clients','Acme'). Defaults to + the built-in group for -Type: 'All Machines' (Access), 'All Sessions' (Support) or + 'All Meetings' (Meeting). + + .PARAMETER Search + Filter text, as typed in the web UI's search box. + + .PARAMETER FindSessionID + Session ID to locate, so it is included even when -Limit would cut it off. + + .PARAMETER Limit + Maximum number of sessions to return. + + .EXAMPLE + Get-CWCSession -Type Access -Search 'DESKTOP-01' -Limit 1 + + .NOTES + Requires Connect-CWC -Credentials. + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> [CmdletBinding()] param ( [Parameter(Mandatory = $True)] [ValidateSet('Support', 'Access', 'Meeting')] $Type, - # Session group name, or the path parts of a nested group - [string[]]$Group = 'All Machines', + [string[]]$Group, [string]$Search, [string]$FindSessionID, [int]$Limit ) + if (-not $Group) { $Group = $script:CWCDefaultSessionGroup[$Type] } + # GetLiveData(requestInfoMap, version) $RequestInfoMap = @{ HostSessionInfo = @{ diff --git a/ConnectWiseControlAPI/Public/PageService/Get-CWCSessionDetail.ps1 b/ConnectWiseControlAPI/Public/PageService/Get-CWCSessionDetail.ps1 index a87eab2..3ab62c5 100644 --- a/ConnectWiseControlAPI/Public/PageService/Get-CWCSessionDetail.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Get-CWCSessionDetail.ps1 @@ -1,4 +1,35 @@ function Get-CWCSessionDetail { + <# + .SYNOPSIS + Returns the details of a session: session info, events, connections and guest screenshot. + + .DESCRIPTION + Credentials connections: PageService.GetSessionDetails. Event Time values are milliseconds elapsed + since the event, relative to the response's BaseTime. The call is rate limited by the server. + + API secret connections: the RESTful API Manager extension's GetSessionDetailsBySessionID, which + returns the server's raw session details; -Group and -Include are ignored. + + .PARAMETER Group + Session group containing the session: a name, or the path parts of a nested group. Defaults to + 'All Machines'. + + .PARAMETER GUID + Session ID. + + .PARAMETER Include + Parts to return: SessionInfo, GuestScreenshotContent, Events, Connections. Omit for everything, + including the guest screenshot. Request only what you need when polling. + + .EXAMPLE + (Get-CWCSessionDetail -GUID $SessionID -Include Events).Events | Where-Object EventType -eq 32 + + .NOTES + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> [CmdletBinding()] param ( # Session group name, or the path parts of a nested group (e.g. 'Clients','Acme') @@ -35,4 +66,4 @@ function Get-CWCSessionDetail { } Invoke-CWCServiceMethod -Service PageService -Method GetSessionDetails -Arguments $DetailArguments -Idempotent -} \ No newline at end of file +} diff --git a/ConnectWiseControlAPI/Public/PageService/Invoke-CWCCommand.ps1 b/ConnectWiseControlAPI/Public/PageService/Invoke-CWCCommand.ps1 index bf032b0..abf47d0 100644 --- a/ConnectWiseControlAPI/Public/PageService/Invoke-CWCCommand.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Invoke-CWCCommand.ps1 @@ -1,4 +1,46 @@ -function Invoke-CWCCommand { +function Invoke-CWCCommand { + <# + .SYNOPSIS + Runs a command on a session's machine and returns its output. + + .DESCRIPTION + Queues a QueuedCommand event (44) and polls the session's events until the matching RanCommand + output (70) arrives or -TimeOut passes. + + API secret connections queue the command through the RESTful API Manager extension; the output is + not retrieved (a warning says so unless -NoWait is used). + + .PARAMETER GUID + Session ID. + + .PARAMETER Command + Command line to run (cmd.exe unless -PowerShell is used). + + .PARAMETER TimeOut + Milliseconds the command may run, and how long to wait for its output. Defaults to 10000. + + .PARAMETER MaxLength + Maximum number of characters of output to return. Defaults to 10000. + + .PARAMETER PowerShell + Run the command in PowerShell. + + .PARAMETER Group + Session group containing the session: a name, or the path parts of a nested group. Defaults to + 'All Machines'. + + .PARAMETER NoWait + Queue the command and return without waiting for output. + + .EXAMPLE + Invoke-CWCCommand -GUID $SessionID -Command 'Get-Service Spooler' -PowerShell -TimeOut 30000 + + .NOTES + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> [CmdletBinding()] param ( [Parameter(Mandatory = $True)] @@ -46,6 +88,7 @@ # round-trip time of each poll doesn't shift them. $TimeOutDateTime = (Get-Date).AddMilliseconds($TimeOut).AddSeconds(1) $QueuedAtServerMs = $null + $QueuedEventID = $null $PollDelaySeconds = 1 do { # Events only, with a growing delay (1, 2, 3 ... 5 s): GetSessionDetails is rate limited. @@ -58,17 +101,26 @@ $BaseTime = [double]$SessionDetails.BaseTime if ($null -eq $QueuedAtServerMs) { - # The most recent queued command (smallest elapsed time) is the one just sent - $QueuedEvent = $SessionDetails.Events | Where-Object { $_.EventType -eq $QueuedCommandEventType } | - Sort-Object { [double]$_.Time } | Select-Object -First 1 - if ($QueuedEvent) { $QueuedAtServerMs = $BaseTime - [double]$QueuedEvent.Time } + # Our queued command: the most recent (smallest elapsed time) whose text is exactly what we + # sent, so a command queued by someone else at the same time isn't taken for ours. + $QueuedEvent = $SessionDetails.Events | Where-Object { + $_.EventType -eq $QueuedCommandEventType -and "$($_.Data)" -eq $FormattedCommand + } | Sort-Object { [double]$_.Time } | Select-Object -First 1 + if ($QueuedEvent) { + $QueuedAtServerMs = $BaseTime - [double]$QueuedEvent.Time + $QueuedEventID = "$($QueuedEvent.EventID)" + } } if ($null -ne $QueuedAtServerMs) { - $OutputEvent = $SessionDetails.Events | Where-Object { - $_.EventType -eq $RanCommandEventType -and $null -ne $_.Time -and - ($BaseTime - [double]$_.Time) -gt $QueuedAtServerMs - } | Sort-Object { [double]$_.Time } -Descending | Select-Object -First 1 + $RanEvents = @($SessionDetails.Events | Where-Object { $_.EventType -eq $RanCommandEventType -and $null -ne $_.Time }) + # Output that names our command (CorrelationEventID) wins; otherwise the first output after it. + $OutputEvent = $RanEvents | Where-Object { $QueuedEventID -and "$($_.CorrelationEventID)" -eq $QueuedEventID } | + Select-Object -First 1 + if (-not $OutputEvent) { + $OutputEvent = $RanEvents | Where-Object { ($BaseTime - [double]$_.Time) -gt $QueuedAtServerMs } | + Sort-Object { [double]$_.Time } -Descending | Select-Object -First 1 + } if ($OutputEvent) { Write-Verbose $OutputEvent.Data return $OutputEvent.Data -split '[\r\n]' | Where-Object { $_ -and $_ -ne "C:\WINDOWS\system32>$Command" } @@ -81,4 +133,4 @@ } while ((Get-Date) -le $TimeOutDateTime) Write-Warning 'Command timed out.' -} \ No newline at end of file +} diff --git a/ConnectWiseControlAPI/Public/PageService/Invoke-CWCWake.ps1 b/ConnectWiseControlAPI/Public/PageService/Invoke-CWCWake.ps1 index 0894b95..9d0cd52 100644 --- a/ConnectWiseControlAPI/Public/PageService/Invoke-CWCWake.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Invoke-CWCWake.ps1 @@ -1,4 +1,26 @@ function Invoke-CWCWake { + <# + .SYNOPSIS + Sends a wake (Wake-on-LAN) request to sessions. + + .DESCRIPTION + Queues a QueuedWake event (43) for each session, in the built-in group for -Type. + + .PARAMETER GUID + One or more session IDs. + + .PARAMETER Type + Session type: Support or Access. + + .EXAMPLE + Invoke-CWCWake -GUID $SessionID -Type Access + + .NOTES + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> [CmdletBinding()] param ( [Parameter(Mandatory=$True)] diff --git a/ConnectWiseControlAPI/Public/PageService/Remove-CWCSession.ps1 b/ConnectWiseControlAPI/Public/PageService/Remove-CWCSession.ps1 index d94db2a..4ac9f3a 100644 --- a/ConnectWiseControlAPI/Public/PageService/Remove-CWCSession.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Remove-CWCSession.ps1 @@ -1,5 +1,32 @@ function Remove-CWCSession { + <# + .SYNOPSIS + Deletes sessions, optionally uninstalling the Access client first. + + .DESCRIPTION + Queues a DeletedSession event (21) per session, or QueuedUninstallAndDelete (100) with -Uninstall. + Prompts for each session by default (ConfirmImpact High); use -Confirm:$false in unattended scripts. + + .PARAMETER GUID + One or more session IDs. + + .PARAMETER Group + Session group containing the sessions: a name, or the path parts of a nested group. + + .PARAMETER Uninstall + Uninstall the Access client from the machine and delete the session, instead of only deleting the + session record. + + .EXAMPLE + Remove-CWCSession -GUID $SessionID -Group 'All Machines' -Uninstall -Confirm:$false + + .NOTES + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> # ConfirmImpact High: deleting (or uninstalling) sessions is irreversible, and -GUID accepts # many IDs at once, so prompt by default. [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] diff --git a/ConnectWiseControlAPI/Public/PageService/Remove-CWCSessionNote.ps1 b/ConnectWiseControlAPI/Public/PageService/Remove-CWCSessionNote.ps1 index 88e4fda..c2a191d 100644 --- a/ConnectWiseControlAPI/Public/PageService/Remove-CWCSessionNote.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Remove-CWCSessionNote.ps1 @@ -7,8 +7,8 @@ function Remove-CWCSessionNote { Deletes notes (AddedNote events) by adding a DeletedEvent correlated to each note, the same way the Control web UI removes a note. The user needs the RemoveNote permission in -Group. - -NoteEventID removes specific notes; -All removes every note still on the session. Notes that - are already deleted are skipped. + -NoteEventID removes the given notes (without checking them first). -All reads the session and + removes every note still on it, skipping notes that are already deleted. .PARAMETER GUID Session ID. diff --git a/ConnectWiseControlAPI/Public/PageService/Update-CWCCustomProperty.ps1 b/ConnectWiseControlAPI/Public/PageService/Update-CWCCustomProperty.ps1 index 0491950..c05db5c 100644 --- a/ConnectWiseControlAPI/Public/PageService/Update-CWCCustomProperty.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Update-CWCCustomProperty.ps1 @@ -1,4 +1,33 @@ function Update-CWCCustomProperty { + <# + .SYNOPSIS + Sets one custom property of a session. + + .DESCRIPTION + Calls PageService.UpdateSessionCustomPropertyValue. + + .PARAMETER GUID + Session ID. + + .PARAMETER Property + The property number of the property to change. + + .PARAMETER Value + New value. + + .PARAMETER Group + Session group containing the session: a name, or the path parts of a nested group. Defaults to + 'All Machines'. + + .EXAMPLE + Update-CWCCustomProperty -GUID $SessionID -Property 1 -Value 'Acme' + + .NOTES + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> [CmdletBinding(SupportsShouldProcess)] param( [Parameter(Mandatory=$True)] diff --git a/ConnectWiseControlAPI/Public/PageService/Update-CWCSessionName.ps1 b/ConnectWiseControlAPI/Public/PageService/Update-CWCSessionName.ps1 index 5f72e74..e6f34ca 100644 --- a/ConnectWiseControlAPI/Public/PageService/Update-CWCSessionName.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Update-CWCSessionName.ps1 @@ -1,4 +1,31 @@ function Update-CWCSessionName { + <# + .SYNOPSIS + Renames a session. + + .DESCRIPTION + Credentials connections: PageService.UpdateSessionName. API secret connections: the RESTful API + Manager extension's UpdateSessionName (-Group is ignored). + + .PARAMETER GUID + Session ID. + + .PARAMETER NewName + New session name. + + .PARAMETER Group + Session group containing the session: a name, or the path parts of a nested group. Defaults to + 'All Machines'. + + .EXAMPLE + Update-CWCSessionName -GUID $SessionID -NewName 'ACME-FrontDesk' + + .NOTES + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> [CmdletBinding(SupportsShouldProcess)] param( [Parameter(Mandatory=$True)] @@ -19,4 +46,4 @@ function Update-CWCSessionName { Invoke-CWCServiceMethod -Service PageService -Method UpdateSessionName -Arguments @(@($Group), $GUID, $NewName) -Idempotent } } -} \ No newline at end of file +} diff --git a/ConnectWiseControlAPI/Public/SecurityService/Get-CWCSecurityConfigurationInfo.ps1 b/ConnectWiseControlAPI/Public/SecurityService/Get-CWCSecurityConfigurationInfo.ps1 index 1280de5..1cff009 100644 --- a/ConnectWiseControlAPI/Public/SecurityService/Get-CWCSecurityConfigurationInfo.ps1 +++ b/ConnectWiseControlAPI/Public/SecurityService/Get-CWCSecurityConfigurationInfo.ps1 @@ -1,4 +1,20 @@ function Get-CWCSecurityConfigurationInfo { + <# + .SYNOPSIS + Returns the server's security configuration (user sources, roles, users). + + .DESCRIPTION + Calls SecurityService.GetSecurityConfigurationInfo. + + .EXAMPLE + (Get-CWCSecurityConfigurationInfo).UserSources + + .NOTES + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> [CmdletBinding()] param () diff --git a/ConnectWiseControlAPI/Public/SecurityService/New-CWCUser.ps1 b/ConnectWiseControlAPI/Public/SecurityService/New-CWCUser.ps1 index f0de653..3b81a91 100644 --- a/ConnectWiseControlAPI/Public/SecurityService/New-CWCUser.ps1 +++ b/ConnectWiseControlAPI/Public/SecurityService/New-CWCUser.ps1 @@ -1,4 +1,38 @@ -function New-CWCUser { +function New-CWCUser { + <# + .SYNOPSIS + Creates an internal user. + + .DESCRIPTION + Calls SecurityService.SaveUser. The password is never written to verbose or debug output. + + .PARAMETER Credentials + User name and password of the new user. + + .PARAMETER OTP + The OTP key used for MFA. Can be generated with New-CWCMFA. + + .PARAMETER DisplayName + Display name. + + .PARAMETER Email + Email address. + + .PARAMETER SecurityGroups + Roles the user is a member of. + + .PARAMETER ForcePassChange + Force the user to change their password at next login. Defaults to $true. + + .EXAMPLE + New-CWCUser -Credentials (Get-Credential -UserName 'jdoe') -Email 'jdoe@example.com' -SecurityGroups 'Technicians' + + .NOTES + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> [CmdletBinding(SupportsShouldProcess)] param( [Parameter(Mandatory=$True)] @@ -28,4 +62,4 @@ if ($PSCmdlet.ShouldProcess($Credentials.UserName, "New-CWCUser")) { Invoke-CWCServiceMethod -Service SecurityService -Method SaveUser -Arguments $SaveUserArguments -Sensitive } -} \ No newline at end of file +} diff --git a/ConnectWiseControlAPI/Public/SecurityService/Remove-CWCUser.ps1 b/ConnectWiseControlAPI/Public/SecurityService/Remove-CWCUser.ps1 index 886faa0..e296aea 100644 --- a/ConnectWiseControlAPI/Public/SecurityService/Remove-CWCUser.ps1 +++ b/ConnectWiseControlAPI/Public/SecurityService/Remove-CWCUser.ps1 @@ -1,4 +1,23 @@ -function Remove-CWCUser { +function Remove-CWCUser { + <# + .SYNOPSIS + Deletes an internal user. + + .DESCRIPTION + Calls SecurityService.DeleteUser. + + .PARAMETER User + User name of the account to delete. + + .EXAMPLE + Remove-CWCUser -User 'jdoe' + + .NOTES + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> [CmdletBinding(SupportsShouldProcess)] param( [Parameter(Mandatory=$True)] diff --git a/ConnectWiseControlAPI/Public/SecurityService/Update-CWCUser.ps1 b/ConnectWiseControlAPI/Public/SecurityService/Update-CWCUser.ps1 index 9079848..973efaa 100644 --- a/ConnectWiseControlAPI/Public/SecurityService/Update-CWCUser.ps1 +++ b/ConnectWiseControlAPI/Public/SecurityService/Update-CWCUser.ps1 @@ -1,4 +1,45 @@ -function Update-CWCUser { +function Update-CWCUser { + <# + .SYNOPSIS + Updates an internal user. + + .DESCRIPTION + Reads the user, applies the given changes and saves it (SecurityService.SaveUser). Parameters not + given keep their current values. The password is never written to verbose or debug output. + + .PARAMETER UserToUpdate + User name of the account to update. + + .PARAMETER NewUserName + New user name. + + .PARAMETER Password + New password. + + .PARAMETER OTP + The OTP key used for MFA. Can be generated with New-CWCMFA. + + .PARAMETER DisplayName + New display name. + + .PARAMETER Email + New email address. + + .PARAMETER SecurityGroups + Roles the user should be a member of. + + .PARAMETER ForcePassChange + Force the user to change their password at next login. + + .EXAMPLE + Update-CWCUser -UserToUpdate 'jdoe' -Password (Read-Host -AsSecureString) + + .NOTES + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> [CmdletBinding(SupportsShouldProcess)] param( [Parameter(Mandatory=$True)] @@ -46,4 +87,4 @@ if ($PSCmdlet.ShouldProcess($UserToUpdate, "Update-CWCUser")) { Invoke-CWCServiceMethod -Service SecurityService -Method SaveUser -Arguments $Update -Sensitive } -} \ No newline at end of file +} diff --git a/ConnectWiseControlAPI/Public/SessionGroupService/Get-CWCSessionGroup.ps1 b/ConnectWiseControlAPI/Public/SessionGroupService/Get-CWCSessionGroup.ps1 index ae77b26..cf36c59 100644 --- a/ConnectWiseControlAPI/Public/SessionGroupService/Get-CWCSessionGroup.ps1 +++ b/ConnectWiseControlAPI/Public/SessionGroupService/Get-CWCSessionGroup.ps1 @@ -1,4 +1,20 @@ function Get-CWCSessionGroup { + <# + .SYNOPSIS + Returns all session groups. + + .DESCRIPTION + Calls SessionGroupService.GetSessionGroups. Requires the ManageSessionGroups permission. + + .EXAMPLE + Get-CWCSessionGroup | Select-Object Name, SessionType + + .NOTES + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> [CmdletBinding()] param () diff --git a/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml b/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml index 5bee06e..372a571 100644 --- a/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml +++ b/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml @@ -812,7 +812,7 @@ open $Url # macOS Get-CWCAuditLog - + StartDate Start of the time range. Defaults to 24 hours ago. Local times are converted to UTC. @@ -824,7 +824,7 @@ open $Url # macOS None - + EndDate End of the time range. Defaults to now. Local times are converted to UTC. @@ -836,7 +836,7 @@ open $Url # macOS None - + SessionName Only return entries for sessions with this name. @@ -848,7 +848,7 @@ open $Url # macOS None - + EventTypes Session event type numbers to include (for example 44 for QueuedCommand, 70 for RanCommand). @@ -860,7 +860,7 @@ open $Url # macOS None - + SecurityTypes Security event type numbers to include. @@ -887,6 +887,18 @@ open $Url # macOS + StartDate + + Start of the time range. Defaults to 24 hours ago. Local times are converted to UTC. + + DateTime + + DateTime + + + None + + EndDate End of the time range. Defaults to now. Local times are converted to UTC. @@ -899,13 +911,13 @@ open $Url # macOS None - EventTypes + SessionName - Session event type numbers to include (for example 44 for QueuedCommand, 70 for RanCommand). + Only return entries for sessions with this name. - Int32[] + String - Int32[] + String None @@ -923,9 +935,9 @@ open $Url # macOS False - SecurityTypes + EventTypes - Security event type numbers to include. + Session event type numbers to include (for example 44 for QueuedCommand, 70 for RanCommand). Int32[] @@ -934,26 +946,14 @@ open $Url # macOS None - - SessionName - - Only return entries for sessions with this name. - - String - - String - - - None - - - StartDate + + SecurityTypes - Start of the time range. Defaults to 24 hours ago. Local times are converted to UTC. + Security event type numbers to include. - DateTime + Int32[] - DateTime + Int32[] None @@ -1010,7 +1010,7 @@ open $Url # macOS Get-CWCLastContact - + GUID The GUID/SessionID for the machine you wish to connect to. You can retrieve session info with the 'Get-CWCSessions' cmdlets @@ -1023,7 +1023,18 @@ open $Url # macOS None - + + Quiet + + Will output a boolean result, $True for Connected or $False for Offline. + + + SwitchParameter + + + False + + Seconds Used with the Quiet switch. The number of seconds a machine needs to be offline before returning $False. @@ -1035,7 +1046,7 @@ open $Url # macOS 0 - + Group Name of session group to use. @@ -1047,21 +1058,10 @@ open $Url # macOS All Machines - - Quiet - - Will output a boolean result, $True for Connected or $False for Offline. - - - SwitchParameter - - - False - - + GUID The GUID/SessionID for the machine you wish to connect to. You can retrieve session info with the 'Get-CWCSessions' cmdlets @@ -1086,7 +1086,7 @@ open $Url # macOS False - + Seconds Used with the Quiet switch. The number of seconds a machine needs to be offline before returning $False. @@ -1098,7 +1098,7 @@ open $Url # macOS 0 - + Group Name of session group to use. @@ -1578,7 +1578,7 @@ open $Url # macOS Get-CWCSession - + Type The type of session Support/Access/Meeting @@ -1590,7 +1590,7 @@ open $Url # macOS None - + Group Name of session group to use. @@ -1602,7 +1602,7 @@ open $Url # macOS All Machines - + Search Limit results with search pattern. @@ -1614,34 +1614,34 @@ open $Url # macOS None - - Limit + + FindSessionID - Limit the number of results returned. + Session ID to locate in the results, so the session is included even when -Limit would cut it off. - Int32 + String - Int32 + String - 0 + None - - FindSessionID + + Limit - Session ID to locate in the results, so the session is included even when -Limit would cut it off. + Limit the number of results returned. - String + Int32 - String + Int32 - None + 0 - + Type The type of session Support/Access/Meeting @@ -1653,7 +1653,7 @@ open $Url # macOS None - + Group Name of session group to use. @@ -1665,7 +1665,7 @@ open $Url # macOS All Machines - + Search Limit results with search pattern. @@ -1677,29 +1677,29 @@ open $Url # macOS None - - Limit + + FindSessionID - Limit the number of results returned. + Session ID to locate in the results, so the session is included even when -Limit would cut it off. - Int32 + String - Int32 + String - 0 + None - - FindSessionID + + Limit - Session ID to locate in the results, so the session is included even when -Limit would cut it off. + Limit the number of results returned. - String + Int32 - String + Int32 - None + 0 @@ -1744,7 +1744,7 @@ open $Url # macOS Get-CWCSessionDetail - + Group Name of session group to use. @@ -1756,7 +1756,7 @@ open $Url # macOS All Machines - + GUID GUID of the machine to retrieve session details. @@ -1768,7 +1768,7 @@ open $Url # macOS None - + Include Parts of the session details to return: SessionInfo, GuestScreenshotContent, Events, Connections. Omit to return everything, including the guest screenshot. Ignored on -ApiSecret connections. @@ -1783,7 +1783,7 @@ open $Url # macOS - + Group Name of session group to use. @@ -1795,7 +1795,7 @@ open $Url # macOS All Machines - + GUID GUID of the machine to retrieve session details. @@ -1807,7 +1807,7 @@ open $Url # macOS None - + Include Parts of the session details to return: SessionInfo, GuestScreenshotContent, Events, Connections. Omit to return everything, including the guest screenshot. Ignored on -ApiSecret connections. @@ -2005,7 +2005,7 @@ open $Url # macOS Invoke-CWCCommand - + GUID The GUID identifier for the machine you wish to connect to. You can retrieve session info with the 'Get-CWCSessions' cmdlets @@ -2017,7 +2017,7 @@ open $Url # macOS None - + Command The command you wish to issue to the machine. @@ -2029,7 +2029,7 @@ open $Url # macOS None - + TimeOut The amount of time in milliseconds that a command can execute. The default is 10000 milliseconds. @@ -2041,7 +2041,19 @@ open $Url # macOS 10000 - + + MaxLength + + Maximum number of characters of command output to return. Defaults to 10000. + + Int32 + + Int32 + + + None + + Group Name of session group to use. @@ -2075,22 +2087,10 @@ open $Url # macOS False - - MaxLength - - Maximum number of characters of command output to return. Defaults to 10000. - - Int32 - - Int32 - - - None - - + GUID The GUID identifier for the machine you wish to connect to. You can retrieve session info with the 'Get-CWCSessions' cmdlets @@ -2102,7 +2102,7 @@ open $Url # macOS None - + Command The command you wish to issue to the machine. @@ -2114,7 +2114,7 @@ open $Url # macOS None - + TimeOut The amount of time in milliseconds that a command can execute. The default is 10000 milliseconds. @@ -2126,6 +2126,18 @@ open $Url # macOS 10000 + + MaxLength + + Maximum number of characters of command output to return. Defaults to 10000. + + Int32 + + Int32 + + + None + PowerShell @@ -2138,7 +2150,7 @@ open $Url # macOS False - + Group Name of session group to use. @@ -2162,18 +2174,6 @@ open $Url # macOS False - - MaxLength - - Maximum number of characters of command output to return. Defaults to 10000. - - Int32 - - Int32 - - - None - @@ -2227,7 +2227,7 @@ open $Url # macOS Invoke-CWCWake - + GUID The GUID identifier for the session you wish to end. Accepts an array of GUIDs @@ -2239,7 +2239,7 @@ open $Url # macOS None - + Type The type of session Support/Access @@ -2254,7 +2254,7 @@ open $Url # macOS - + GUID The GUID identifier for the session you wish to end. Accepts an array of GUIDs @@ -2266,7 +2266,7 @@ open $Url # macOS None - + Type The type of session Support/Access @@ -2951,7 +2951,19 @@ open $Url # macOS New-CWCUser - + + Credentials + + PSCredential object for the new user you want to create. + + PSCredential + + PSCredential + + + None + + OTP The OTP key used for MFA. Can be generated with `New-CWCMFA` @@ -2963,7 +2975,7 @@ open $Url # macOS None - + DisplayName The display name of the new user @@ -2975,7 +2987,7 @@ open $Url # macOS None - + Email Email address of the user @@ -2987,7 +2999,7 @@ open $Url # macOS None - + SecurityGroups An array of security groups the user is a part of @@ -2999,7 +3011,7 @@ open $Url # macOS None - + ForcePassChange Force the user to change their password at next login @@ -3011,17 +3023,6 @@ open $Url # macOS True - - Confirm - - Prompts you for confirmation before running the cmdlet. - - - SwitchParameter - - - False - WhatIf @@ -3033,22 +3034,33 @@ open $Url # macOS False - - Credentials + + Confirm - PSCredential object for the new user you want to create. + Prompts you for confirmation before running the cmdlet. - PSCredential - PSCredential + SwitchParameter - None + False - + + Credentials + + PSCredential object for the new user you want to create. + + PSCredential + + PSCredential + + + None + + OTP The OTP key used for MFA. Can be generated with `New-CWCMFA` @@ -3060,7 +3072,7 @@ open $Url # macOS None - + DisplayName The display name of the new user @@ -3072,7 +3084,7 @@ open $Url # macOS None - + Email Email address of the user @@ -3084,7 +3096,7 @@ open $Url # macOS None - + SecurityGroups An array of security groups the user is a part of @@ -3096,7 +3108,7 @@ open $Url # macOS None - + ForcePassChange Force the user to change their password at next login @@ -3108,18 +3120,6 @@ open $Url # macOS True - - Confirm - - Prompts you for confirmation before running the cmdlet. - - SwitchParameter - - SwitchParameter - - - False - WhatIf @@ -3132,17 +3132,17 @@ open $Url # macOS False - - Credentials + + Confirm - PSCredential object for the new user you want to create. + Prompts you for confirmation before running the cmdlet. - PSCredential + SwitchParameter - PSCredential + SwitchParameter - None + False @@ -3348,7 +3348,7 @@ Remove-CWCHostFromSession -SessionID $SessionID -ConnectionID $HostConnection.Co Remove-CWCSession - + GUID The GUID identifier for the session you wish to end. Accepts an array of GUIDs. @@ -3360,21 +3360,22 @@ Remove-CWCHostFromSession -SessionID $SessionID -ConnectionID $HostConnection.Co None - - Confirm + + Group - Prompts you for confirmation before running the cmdlet. + Session group containing the session(s). Defaults to 'All Machines' where a default exists. + String[] - SwitchParameter + String[] - False + None - - WhatIf + + Uninstall - Shows what would happen if the cmdlet runs. The cmdlet is not run. + Queue an uninstall of the Access client and delete the session (QueuedUninstallAndDelete) instead of only deleting the session record. SwitchParameter @@ -3382,22 +3383,21 @@ Remove-CWCHostFromSession -SessionID $SessionID -ConnectionID $HostConnection.Co False - - Group + + WhatIf - Session group containing the session(s). Defaults to 'All Machines' where a default exists. + Shows what would happen if the cmdlet runs. The cmdlet is not run. - String[] - String[] + SwitchParameter - None + False - - Uninstall + + Confirm - Queue an uninstall of the Access client and delete the session (QueuedUninstallAndDelete) instead of only deleting the session record. + Prompts you for confirmation before running the cmdlet. SwitchParameter @@ -3408,7 +3408,7 @@ Remove-CWCHostFromSession -SessionID $SessionID -ConnectionID $HostConnection.Co - + GUID The GUID identifier for the session you wish to end. Accepts an array of GUIDs. @@ -3420,22 +3420,22 @@ Remove-CWCHostFromSession -SessionID $SessionID -ConnectionID $HostConnection.Co None - - Confirm + + Group - Prompts you for confirmation before running the cmdlet. + Session group containing the session(s). Defaults to 'All Machines' where a default exists. - SwitchParameter + String[] - SwitchParameter + String[] - False + None - - WhatIf + + Uninstall - Shows what would happen if the cmdlet runs. The cmdlet is not run. + Queue an uninstall of the Access client and delete the session (QueuedUninstallAndDelete) instead of only deleting the session record. SwitchParameter @@ -3444,22 +3444,22 @@ Remove-CWCHostFromSession -SessionID $SessionID -ConnectionID $HostConnection.Co False - - Group + + WhatIf - Session group containing the session(s). Defaults to 'All Machines' where a default exists. + Shows what would happen if the cmdlet runs. The cmdlet is not run. - String[] + SwitchParameter - String[] + SwitchParameter - None + False - - Uninstall + + Confirm - Queue an uninstall of the Access client and delete the session (QueuedUninstallAndDelete) instead of only deleting the session record. + Prompts you for confirmation before running the cmdlet. SwitchParameter @@ -3745,7 +3745,7 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { Remove-CWCUser - + User The user to remove. @@ -3757,10 +3757,10 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { None - - Confirm + + WhatIf - Prompts you for confirmation before running the cmdlet. + Shows what would happen if the cmdlet runs. The cmdlet is not run. SwitchParameter @@ -3768,10 +3768,10 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { False - - WhatIf + + Confirm - Shows what would happen if the cmdlet runs. The cmdlet is not run. + Prompts you for confirmation before running the cmdlet. SwitchParameter @@ -3782,19 +3782,7 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { - - Confirm - - Prompts you for confirmation before running the cmdlet. - - SwitchParameter - - SwitchParameter - - - False - - + User The user to remove. @@ -3818,6 +3806,18 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { False + + Confirm + + Prompts you for confirmation before running the cmdlet. + + SwitchParameter + + SwitchParameter + + + False + @@ -4218,7 +4218,7 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { Update-CWCCustomProperty - + GUID The GUID/SessionID for the machine you wish to connect to. You can retrieve session info with the 'Get-CWCSessions' cmdlets @@ -4231,68 +4231,68 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { None - - Group + + Property - Look for the session in these groups. + The property number of the property you want to change. - String[] + Int32 - String[] + Int32 - All Machines + None - - Confirm + + Value - Prompts you for confirmation before running the cmdlet. + The value you want to set the property to. + String - SwitchParameter + String - False + None - - WhatIf + + Group - Shows what would happen if the cmdlet runs. The cmdlet is not run. + Look for the session in these groups. + String[] - SwitchParameter + String[] - False + All Machines - - Property + + WhatIf - The property number of the property you want to change. + Shows what would happen if the cmdlet runs. The cmdlet is not run. - Int32 - Int32 + SwitchParameter - None + False - - Value + + Confirm - The value you want to set the property to. + Prompts you for confirmation before running the cmdlet. - String - String + SwitchParameter - None + False - + GUID The GUID/SessionID for the machine you wish to connect to. You can retrieve session info with the 'Get-CWCSessions' cmdlets @@ -4305,65 +4305,65 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { None - - Group + + Property - Look for the session in these groups. + The property number of the property you want to change. - String[] + Int32 - String[] + Int32 - All Machines + None - - Confirm + + Value - Prompts you for confirmation before running the cmdlet. + The value you want to set the property to. - SwitchParameter + String - SwitchParameter + String - False + None - - WhatIf + + Group - Shows what would happen if the cmdlet runs. The cmdlet is not run. + Look for the session in these groups. - SwitchParameter + String[] - SwitchParameter + String[] - False + All Machines - - Property + + WhatIf - The property number of the property you want to change. + Shows what would happen if the cmdlet runs. The cmdlet is not run. - Int32 + SwitchParameter - Int32 + SwitchParameter - None + False - - Value + + Confirm - The value you want to set the property to. + Prompts you for confirmation before running the cmdlet. - String + SwitchParameter - String + SwitchParameter - None + False @@ -4402,7 +4402,7 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { Update-CWCSessionName - + GUID The GUID/SessionID for the machine you wish to connect to. You can retrieve session info with the 'Get-CWCSessions' cmdlets @@ -4415,7 +4415,7 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { None - + NewName The new name for the session. @@ -4427,7 +4427,7 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { None - + Group Group to look for the session in. @@ -4439,10 +4439,10 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { All Machines - - Confirm + + WhatIf - Prompts you for confirmation before running the cmdlet. + Shows what would happen if the cmdlet runs. The cmdlet is not run. SwitchParameter @@ -4450,10 +4450,10 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { False - - WhatIf + + Confirm - Shows what would happen if the cmdlet runs. The cmdlet is not run. + Prompts you for confirmation before running the cmdlet. SwitchParameter @@ -4464,7 +4464,7 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { - + GUID The GUID/SessionID for the machine you wish to connect to. You can retrieve session info with the 'Get-CWCSessions' cmdlets @@ -4477,7 +4477,7 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { None - + NewName The new name for the session. @@ -4489,7 +4489,7 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { None - + Group Group to look for the session in. @@ -4501,10 +4501,10 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { All Machines - - Confirm + + WhatIf - Prompts you for confirmation before running the cmdlet. + Shows what would happen if the cmdlet runs. The cmdlet is not run. SwitchParameter @@ -4513,10 +4513,10 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { False - - WhatIf + + Confirm - Shows what would happen if the cmdlet runs. The cmdlet is not run. + Prompts you for confirmation before running the cmdlet. SwitchParameter @@ -4559,7 +4559,7 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { Update-CWCUser - + UserToUpdate The user account you want to update. @@ -4572,6 +4572,30 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { None + NewUserName + + The new username of the user you are updating. + + String + + String + + + None + + + Password + + The wanted password of the user. + + SecureString + + SecureString + + + None + + OTP The wanted MFA option for the user. @@ -4583,7 +4607,7 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { None - + DisplayName The wanted display name for the user. @@ -4595,7 +4619,7 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { None - + Email The wanted email address for the user. @@ -4607,7 +4631,7 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { None - + SecurityGroups The wanted security groups the user should be a member of. @@ -4619,7 +4643,7 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { None - + ForcePassChange Force the user to change their password at next logon. @@ -4631,17 +4655,6 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { None - - Confirm - - Prompts you for confirmation before running the cmdlet. - - - SwitchParameter - - - False - WhatIf @@ -4653,49 +4666,36 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { False - - NewUserName - - The new username of the user you are updating. - - String - - String - - - None - - - Password + + Confirm - The wanted password of the user. + Prompts you for confirmation before running the cmdlet. - SecureString - SecureString + SwitchParameter - None + False - - Confirm + + UserToUpdate - Prompts you for confirmation before running the cmdlet. + The user account you want to update. - SwitchParameter + String - SwitchParameter + String - False + None - - DisplayName + + NewUserName - The wanted display name for the user. + The new username of the user you are updating. String @@ -4704,10 +4704,22 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { None + + Password + + The wanted password of the user. + + SecureString + + SecureString + + + None + - Email + OTP - The wanted email address for the user. + The wanted MFA option for the user. String @@ -4716,22 +4728,22 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { None - - ForcePassChange + + DisplayName - Force the user to change their password at next logon. + The wanted display name for the user. - Boolean + String - Boolean + String None - - OTP + + Email - The wanted MFA option for the user. + The wanted email address for the user. String @@ -4740,7 +4752,7 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { None - + SecurityGroups The wanted security groups the user should be a member of. @@ -4752,14 +4764,14 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { None - - UserToUpdate + + ForcePassChange - The user account you want to update. + Force the user to change their password at next logon. - String + Boolean - String + Boolean None @@ -4776,29 +4788,17 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { False - - NewUserName - - The new username of the user you are updating. - - String - - String - - - None - - - Password + + Confirm - The wanted password of the user. + Prompts you for confirmation before running the cmdlet. - SecureString + SwitchParameter - SecureString + SwitchParameter - None + False diff --git a/Docs/Get-CWCAuditLog.md b/Docs/Get-CWCAuditLog.md index d8ae9f5..399356a 100644 --- a/Docs/Get-CWCAuditLog.md +++ b/Docs/Get-CWCAuditLog.md @@ -31,8 +31,8 @@ Get the audit logs for Computer1 for the last day. ## PARAMETERS -### -EndDate -End of the time range. Defaults to now. Local times are converted to UTC. +### -StartDate +Start of the time range. Defaults to 24 hours ago. Local times are converted to UTC. ```yaml Type: DateTime @@ -46,76 +46,76 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -EventTypes -Session event type numbers to include (for example 44 for QueuedCommand, 70 for RanCommand). +### -EndDate +End of the time range. Defaults to now. Local times are converted to UTC. ```yaml -Type: Int32[] +Type: DateTime Parameter Sets: (All) Aliases: Required: False -Position: 3 +Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -IncludeSessionCaptures -Deprecated. The server no longer accepts this option; it is ignored with a warning. +### -SessionName +Only return entries for sessions with this name. ```yaml -Type: SwitchParameter +Type: String Parameter Sets: (All) Aliases: Required: False -Position: Named +Position: 3 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -SecurityTypes -Security event type numbers to include. +### -IncludeSessionCaptures +Deprecated. The server no longer accepts this option; it is ignored with a warning. ```yaml -Type: Int32[] +Type: SwitchParameter Parameter Sets: (All) Aliases: Required: False -Position: 4 +Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -SessionName -Only return entries for sessions with this name. +### -EventTypes +Session event type numbers to include (for example 44 for QueuedCommand, 70 for RanCommand). ```yaml -Type: String +Type: Int32[] Parameter Sets: (All) Aliases: Required: False -Position: 2 +Position: 4 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -StartDate -Start of the time range. Defaults to 24 hours ago. Local times are converted to UTC. +### -SecurityTypes +Security event type numbers to include. ```yaml -Type: DateTime +Type: Int32[] Parameter Sets: (All) Aliases: Required: False -Position: 0 +Position: 5 Default value: None Accept pipeline input: False Accept wildcard characters: False diff --git a/Docs/Get-CWCLastContact.md b/Docs/Get-CWCLastContact.md index 23519da..741c1e3 100644 --- a/Docs/Get-CWCLastContact.md +++ b/Docs/Get-CWCLastContact.md @@ -13,7 +13,7 @@ Returns the date the machine last connected to the control server. ## SYNTAX ``` -Get-CWCLastContact [-GUID] [-Quiet] [[-Seconds] ] [[-Group] ] [] +Get-CWCLastContact -GUID [-Quiet] [-Seconds ] [-Group ] [] ``` ## DESCRIPTION @@ -45,7 +45,7 @@ Parameter Sets: (All) Aliases: Required: True -Position: 3 +Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -76,7 +76,7 @@ Parameter Sets: (All) Aliases: Required: False -Position: 4 +Position: Named Default value: 0 Accept pipeline input: False Accept wildcard characters: False @@ -91,7 +91,7 @@ Parameter Sets: (All) Aliases: Required: False -Position: 5 +Position: Named Default value: All Machines Accept pipeline input: False Accept wildcard characters: False diff --git a/Docs/Get-CWCSession.md b/Docs/Get-CWCSession.md index d190b27..0c1aeab 100644 --- a/Docs/Get-CWCSession.md +++ b/Docs/Get-CWCSession.md @@ -13,7 +13,8 @@ Will return a list of sessions. ## SYNTAX ``` -Get-CWCSession -Type [-Group ] [-Search ] [-FindSessionID ] [-Limit ] [] +Get-CWCSession [-Type] [[-Group] ] [[-Search] ] [[-FindSessionID] ] + [[-Limit] ] [] ``` ## DESCRIPTION @@ -39,7 +40,7 @@ Parameter Sets: (All) Aliases: Required: True -Position: Named +Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -54,7 +55,7 @@ Parameter Sets: (All) Aliases: Required: False -Position: Named +Position: 2 Default value: All Machines Accept pipeline input: False Accept wildcard characters: False @@ -69,38 +70,38 @@ Parameter Sets: (All) Aliases: Required: False -Position: Named +Position: 3 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -Limit -Limit the number of results returned. +### -FindSessionID +Session ID to locate in the results, so the session is included even when -Limit would cut it off. ```yaml -Type: Int32 +Type: String Parameter Sets: (All) Aliases: Required: False -Position: Named -Default value: 0 +Position: 4 +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -FindSessionID -Session ID to locate in the results, so the session is included even when -Limit would cut it off. +### -Limit +Limit the number of results returned. ```yaml -Type: String +Type: Int32 Parameter Sets: (All) Aliases: Required: False -Position: Named -Default value: None +Position: 5 +Default value: 0 Accept pipeline input: False Accept wildcard characters: False ``` diff --git a/Docs/Get-CWCSessionDetail.md b/Docs/Get-CWCSessionDetail.md index bc79de4..05f319e 100644 --- a/Docs/Get-CWCSessionDetail.md +++ b/Docs/Get-CWCSessionDetail.md @@ -13,7 +13,7 @@ Will return information about a session. ## SYNTAX ``` -Get-CWCSessionDetail [-Group ] -GUID [-Include ] [] +Get-CWCSessionDetail [[-Group] ] [-GUID] [[-Include] ] [] ``` ## DESCRIPTION @@ -39,7 +39,7 @@ Parameter Sets: (All) Aliases: Required: False -Position: Named +Position: 1 Default value: All Machines Accept pipeline input: False Accept wildcard characters: False @@ -54,7 +54,7 @@ Parameter Sets: (All) Aliases: Required: True -Position: Named +Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -69,7 +69,7 @@ Parameter Sets: (All) Aliases: Required: False -Position: Named +Position: 3 Default value: None Accept pipeline input: False Accept wildcard characters: False diff --git a/Docs/Invoke-CWCCommand.md b/Docs/Invoke-CWCCommand.md index e553b3a..bdce59f 100644 --- a/Docs/Invoke-CWCCommand.md +++ b/Docs/Invoke-CWCCommand.md @@ -13,8 +13,8 @@ Will issue a command against a given machine and return the results. ## SYNTAX ``` -Invoke-CWCCommand [-GUID] [[-Command] ] [[-TimeOut] ] [-MaxLength ] [-PowerShell] - [[-Group] ] [-NoWait] [] +Invoke-CWCCommand [-GUID] [[-Command] ] [[-TimeOut] ] [[-MaxLength] ] + [-PowerShell] [[-Group] ] [-NoWait] [] ``` ## DESCRIPTION @@ -48,7 +48,7 @@ Parameter Sets: (All) Aliases: Required: True -Position: 3 +Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -63,7 +63,7 @@ Parameter Sets: (All) Aliases: Required: False -Position: 4 +Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -79,12 +79,27 @@ Parameter Sets: (All) Aliases: Required: False -Position: 5 +Position: 3 Default value: 10000 Accept pipeline input: False Accept wildcard characters: False ``` +### -MaxLength +Maximum number of characters of command output to return. Defaults to 10000. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -PowerShell Issues the command in a powershell session. @@ -109,7 +124,7 @@ Parameter Sets: (All) Aliases: Required: False -Position: 6 +Position: 5 Default value: All Machines Accept pipeline input: False Accept wildcard characters: False @@ -130,21 +145,6 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -MaxLength -Maximum number of characters of command output to return. Defaults to 10000. - -```yaml -Type: Int32 -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). diff --git a/Docs/Invoke-CWCWake.md b/Docs/Invoke-CWCWake.md index f916cdc..0da2e14 100644 --- a/Docs/Invoke-CWCWake.md +++ b/Docs/Invoke-CWCWake.md @@ -13,7 +13,7 @@ Will issue a wake command to a given session. ## SYNTAX ``` -Invoke-CWCWake -GUID -Type [] +Invoke-CWCWake [-GUID] [-Type] [] ``` ## DESCRIPTION @@ -40,7 +40,7 @@ Parameter Sets: (All) Aliases: Required: True -Position: Named +Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -55,7 +55,7 @@ Parameter Sets: (All) Aliases: Required: True -Position: Named +Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False diff --git a/Docs/New-CWCUser.md b/Docs/New-CWCUser.md index 198a5f3..998785e 100644 --- a/Docs/New-CWCUser.md +++ b/Docs/New-CWCUser.md @@ -13,8 +13,8 @@ Creates a user. ## SYNTAX ``` -New-CWCUser -Credentials [-OTP ] [-DisplayName ] -Email - [-SecurityGroups ] [-ForcePassChange ] [-WhatIf] +New-CWCUser [-Credentials] [[-OTP] ] [[-DisplayName] ] [-Email] + [[-SecurityGroups] ] [[-ForcePassChange] ] [-WhatIf] [-Confirm] [] ``` @@ -38,6 +38,21 @@ New-CWCUser @NewUserParams ## PARAMETERS +### -Credentials +PSCredential object for the new user you want to create. + +```yaml +Type: PSCredential +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -OTP The OTP key used for MFA. Can be generated with `New-CWCMFA` @@ -47,7 +62,7 @@ Parameter Sets: (All) Aliases: Required: False -Position: Named +Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -62,7 +77,7 @@ Parameter Sets: (All) Aliases: Required: False -Position: Named +Position: 3 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -77,7 +92,7 @@ Parameter Sets: (All) Aliases: Required: True -Position: Named +Position: 4 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -92,7 +107,7 @@ Parameter Sets: (All) Aliases: Required: False -Position: Named +Position: 5 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -107,27 +122,12 @@ Parameter Sets: (All) Aliases: Required: False -Position: Named +Position: 6 Default value: True Accept pipeline input: False Accept wildcard characters: False ``` -### -Confirm -Prompts you for confirmation before running the cmdlet. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: cf - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. @@ -143,15 +143,15 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -Credentials -PSCredential object for the new user you want to create. +### -Confirm +Prompts you for confirmation before running the cmdlet. ```yaml -Type: PSCredential +Type: SwitchParameter Parameter Sets: (All) -Aliases: +Aliases: cf -Required: True +Required: False Position: Named Default value: None Accept pipeline input: False diff --git a/Docs/Remove-CWCSession.md b/Docs/Remove-CWCSession.md index 1c579b2..41a3897 100644 --- a/Docs/Remove-CWCSession.md +++ b/Docs/Remove-CWCSession.md @@ -13,8 +13,8 @@ Will end a given session. ## SYNTAX ``` -Remove-CWCSession -GUID -Group [-Uninstall] [-WhatIf] - [-Confirm] [] +Remove-CWCSession [-GUID] [-Group] [-Uninstall] + [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION @@ -41,34 +41,34 @@ Parameter Sets: (All) Aliases: Required: True -Position: Named +Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -Confirm -Prompts you for confirmation before running the cmdlet. +### -Group +Session group containing the session(s). Defaults to 'All Machines' where a default exists. ```yaml -Type: SwitchParameter +Type: String[] Parameter Sets: (All) -Aliases: cf +Aliases: -Required: False -Position: Named +Required: True +Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -WhatIf -Shows what would happen if the cmdlet runs. The cmdlet is not run. +### -Uninstall +Queue an uninstall of the Access client and delete the session (QueuedUninstallAndDelete) instead of only deleting the session record. ```yaml Type: SwitchParameter Parameter Sets: (All) -Aliases: wi +Aliases: Required: False Position: Named @@ -77,28 +77,28 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -Group -Session group containing the session(s). Defaults to 'All Machines' where a default exists. +### -WhatIf +Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml -Type: String[] +Type: SwitchParameter Parameter Sets: (All) -Aliases: +Aliases: wi -Required: True +Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -Uninstall -Queue an uninstall of the Access client and delete the session (QueuedUninstallAndDelete) instead of only deleting the session record. +### -Confirm +Prompts you for confirmation before running the cmdlet. ```yaml Type: SwitchParameter Parameter Sets: (All) -Aliases: +Aliases: cf Required: False Position: Named diff --git a/Docs/Remove-CWCUser.md b/Docs/Remove-CWCUser.md index ab05e48..5e184fc 100644 --- a/Docs/Remove-CWCUser.md +++ b/Docs/Remove-CWCUser.md @@ -30,21 +30,6 @@ Removes the 'ctaylor' user from Control. ## PARAMETERS -### -Confirm -Prompts you for confirmation before running the cmdlet. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: cf - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - ### -User The user to remove. @@ -54,7 +39,7 @@ Parameter Sets: (All) Aliases: Required: True -Position: 0 +Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -76,6 +61,21 @@ Accept pipeline input: False Accept wildcard characters: False ``` +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). diff --git a/Docs/Update-CWCCustomProperty.md b/Docs/Update-CWCCustomProperty.md index 848cf89..2788bb2 100644 --- a/Docs/Update-CWCCustomProperty.md +++ b/Docs/Update-CWCCustomProperty.md @@ -13,7 +13,7 @@ Will update a custom property for a session. ## SYNTAX ``` -Update-CWCCustomProperty -GUID -Property [-Value ] [-Group ] [-WhatIf] [-Confirm] [] +Update-CWCCustomProperty [-GUID] [-Property] [[-Value] ] [[-Group] ] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION @@ -45,79 +45,79 @@ Parameter Sets: (All) Aliases: Required: True -Position: Named +Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -Group -Look for the session in these groups. +### -Property +The property number of the property you want to change. ```yaml -Type: String[] +Type: Int32 Parameter Sets: (All) Aliases: -Required: False -Position: Named -Default value: All Machines +Required: True +Position: 2 +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -Confirm -Prompts you for confirmation before running the cmdlet. +### -Value +The value you want to set the property to. ```yaml -Type: SwitchParameter +Type: String Parameter Sets: (All) -Aliases: cf +Aliases: Required: False -Position: Named +Position: 3 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -WhatIf -Shows what would happen if the cmdlet runs. The cmdlet is not run. +### -Group +Look for the session in these groups. ```yaml -Type: SwitchParameter +Type: String[] Parameter Sets: (All) -Aliases: wi +Aliases: Required: False -Position: Named -Default value: None +Position: 4 +Default value: All Machines Accept pipeline input: False Accept wildcard characters: False ``` -### -Property -The property number of the property you want to change. +### -WhatIf +Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml -Type: Int32 +Type: SwitchParameter Parameter Sets: (All) -Aliases: +Aliases: wi -Required: True +Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -Value -The value you want to set the property to. +### -Confirm +Prompts you for confirmation before running the cmdlet. ```yaml -Type: String +Type: SwitchParameter Parameter Sets: (All) -Aliases: +Aliases: cf Required: False Position: Named diff --git a/Docs/Update-CWCSessionName.md b/Docs/Update-CWCSessionName.md index 43e630d..8493453 100644 --- a/Docs/Update-CWCSessionName.md +++ b/Docs/Update-CWCSessionName.md @@ -13,8 +13,7 @@ Updates the name of a session. ## SYNTAX ``` -Update-CWCSessionName -GUID -NewName [-Group ] - [-WhatIf] [-Confirm] [] +Update-CWCSessionName [-GUID] [-NewName] [[-Group] ] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION @@ -46,7 +45,7 @@ Parameter Sets: (All) Aliases: Required: True -Position: Named +Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -61,7 +60,7 @@ Parameter Sets: (All) Aliases: Required: True -Position: Named +Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -76,19 +75,19 @@ Parameter Sets: (All) Aliases: Required: False -Position: Named +Position: 3 Default value: All Machines Accept pipeline input: False Accept wildcard characters: False ``` -### -Confirm -Prompts you for confirmation before running the cmdlet. +### -WhatIf +Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: SwitchParameter Parameter Sets: (All) -Aliases: cf +Aliases: wi Required: False Position: Named @@ -97,13 +96,13 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -WhatIf -Shows what would happen if the cmdlet runs. The cmdlet is not run. +### -Confirm +Prompts you for confirmation before running the cmdlet. ```yaml Type: SwitchParameter Parameter Sets: (All) -Aliases: wi +Aliases: cf Required: False Position: Named diff --git a/Docs/Update-CWCUser.md b/Docs/Update-CWCUser.md index 9aefbb8..75d4418 100644 --- a/Docs/Update-CWCUser.md +++ b/Docs/Update-CWCUser.md @@ -13,8 +13,9 @@ Update properties of an internal user. ## SYNTAX ``` -Update-CWCUser [-UserToUpdate] [-NewUserName ] [-Password ] [[-OTP] ] - [[-DisplayName] ] [[-Email] ] [[-SecurityGroups] ] [[-ForcePassChange] ] [-WhatIf] [-Confirm] [] +Update-CWCUser [-UserToUpdate] [[-NewUserName] ] [[-Password] ] + [[-OTP] ] [[-DisplayName] ] [[-Email] ] [[-SecurityGroups] ] + [[-ForcePassChange] ] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION @@ -31,29 +32,44 @@ Updates the password for 'ctaylor' and forces a password change at next logon. ## PARAMETERS -### -Confirm -Prompts you for confirmation before running the cmdlet. +### -UserToUpdate +The user account you want to update. ```yaml -Type: SwitchParameter +Type: String Parameter Sets: (All) -Aliases: cf +Aliases: -Required: False -Position: Named +Required: True +Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -DisplayName -The wanted display name for the user. +### -NewUserName +The new username of the user you are updating. ```yaml Type: String Parameter Sets: (All) Aliases: +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Password +The wanted password of the user. + +```yaml +Type: SecureString +Parameter Sets: (All) +Aliases: + Required: False Position: 3 Default value: None @@ -61,8 +77,8 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -Email -The wanted email address for the user. +### -OTP +The wanted MFA option for the user. ```yaml Type: String @@ -76,23 +92,23 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -ForcePassChange -Force the user to change their password at next logon. +### -DisplayName +The wanted display name for the user. ```yaml -Type: Boolean +Type: String Parameter Sets: (All) Aliases: Required: False -Position: 6 +Position: 5 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -OTP -The wanted MFA option for the user. +### -Email +The wanted email address for the user. ```yaml Type: String @@ -100,7 +116,7 @@ Parameter Sets: (All) Aliases: Required: False -Position: 2 +Position: 6 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -115,22 +131,22 @@ Parameter Sets: (All) Aliases: Required: False -Position: 5 +Position: 7 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -UserToUpdate -The user account you want to update. +### -ForcePassChange +Force the user to change their password at next logon. ```yaml -Type: String +Type: Boolean Parameter Sets: (All) Aliases: -Required: True -Position: 0 +Required: False +Position: 8 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -152,28 +168,13 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -NewUserName -The new username of the user you are updating. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Password -The wanted password of the user. +### -Confirm +Prompts you for confirmation before running the cmdlet. ```yaml -Type: SecureString +Type: SwitchParameter Parameter Sets: (All) -Aliases: +Aliases: cf Required: False Position: Named From a352a4e2bdd7d8194c83b3e7fc386bde69580f16 Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Tue, 10 Nov 2026 10:17:22 -0700 Subject: [PATCH 17/30] Fix review round 2 findings - Connect-CWC connects when asked for a different server or auth method even without -Force; it used to keep the old connection with only a warning, so later commands (deletes included) went to the previous server. - HTTP 500 retries only for server faults (no errorType) and rate-limit or timeout errors; application exceptions fail the same way again. - Auth-mode errors name the outermost public command the user ran. - Invoke-CWCCommand stops if queueing the command fails, instead of reporting "queued" or polling until the timeout. - Enter-CWCSession takes SessionType from piped sessions, so piped Support and Meeting sessions use the right group and URL type. - Remove-CWCSessionNote prompts by default (ConfirmImpact High), as its help says. - New-CWCRemoteWorkforceAssignment: comment-based help, nested group paths. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +- .../Private/Invoke-CWCWebRequest.ps1 | 21 +++--- .../Public/Authentication/Connect-CWC.ps1 | 14 ++-- .../New-CWCRemoteWorkforceAssignment.ps1 | 36 +++++++++- .../Public/PageService/Enter-CWCSession.ps1 | 22 ++++-- .../Public/PageService/Invoke-CWCCommand.ps1 | 18 +++-- .../PageService/Remove-CWCSessionNote.ps1 | 3 +- .../en-US/ConnectWiseControlAPI-help.xml | 70 +++++++++---------- Docs/Enter-CWCSession.md | 8 +-- Docs/New-CWCRemoteWorkforceAssignment.md | 27 +++---- Tests/ConnectWiseControlAPI.Private.Tests.ps1 | 15 ++++ Tests/ConnectWiseControlAPI.Public.Tests.ps1 | 35 ++++++++-- 12 files changed, 184 insertions(+), 90 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d50539..ffd1d2c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,8 +23,9 @@ Planned as 0.5.0.0 (the module manifest already carries this version; 0.4.0.0 is (`Invoke-CWCCommand` queues only on API-secret connections; output is not retrieved); other functions return an error naming the required auth method. `-Origin` overrides the Origin header for servers with `RESTfulAllowedOrigin` set -- `Connect-CWC` keeps the previous connection when a `-Force` reconnect fails, and warns when a cached - connection for a different server or auth method is reused +- `Connect-CWC` keeps the previous connection when a reconnect fails. Asking for a different server or + auth method now connects to it even without `-Force`; before, the old connection was silently kept and + later commands went to the previous server - `Find-CWCSession` (`-Filter`/`-Name`/`-GUID`; API secret only), `New-CWCSession`, `Add-CWCSessionNote`, `Send-CWCSessionMessage`, `Send-CWCToolboxItem`. On credentials connections the last three queue session events (AddedNote 32, QueuedMessage 45, QueuedTool 47) and take `-Group` diff --git a/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 b/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 index 62e5c98..d70d578 100644 --- a/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 +++ b/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 @@ -20,9 +20,11 @@ $IsApiSecretConnection = Test-CWCApiSecretConnection $IsRestApiEndpoint = $Arguments.Endpoint -like "App_Extensions/$($script:CWCRestApiExtensionID)/*" if ($IsApiSecretConnection -ne $IsRestApiEndpoint) { - # Name the public function the user called, not the private request helpers. - $Caller = Get-PSCallStack | Select-Object -Skip 1 -ExpandProperty Command | - Where-Object { $_ -notin 'Invoke-CWCServiceMethod', 'Invoke-CWCWebRequest', 'Add-CWCSessionEvent' } | Select-Object -First 1 + # Name the public function the user called: the outermost exported function on the call stack + # (not a private helper, nor a public function it calls internally). + $PublicFunctions = @($ExecutionContext.SessionState.Module.ExportedFunctions.Keys) + $Caller = Get-PSCallStack | Select-Object -ExpandProperty Command | + Where-Object { $_ -in $PublicFunctions } | Select-Object -Last 1 if (-not $Caller -or $Caller -eq '') { $Caller = 'This command' } $Required = if ($IsApiSecretConnection) { 'Credentials' } else { 'ApiSecret' } return Write-Error (Get-CWCAuthModeMessage -Command $Caller -Required $Required) -ErrorId 'CWC.AuthModeMismatch' -Category InvalidOperation @@ -87,11 +89,14 @@ catch { $ServerMessage = $null } } - # Retry on HTTP 500 when the caller allows it (no response yields 0). Control also answers - # permission failures (including a wrong password) with 500 + SecurityException: retrying - # those only delays the error. - $IsPermissionFailure = "$ServerMessage" -match 'SecurityException' - if ($StatusCode -eq 500 -and -not $IsPermissionFailure -and $Retry -lt $MaxRetry) { + # Retry on HTTP 500 when the caller allows it (no response yields 0). Control answers + # application exceptions with 500 + {"errorType": ...}: permission failures (including a wrong + # password), bad arguments, missing sessions. Those fail the same way again, so only retry a + # 500 without an errorType (a server fault) or one that names a rate limit or timeout. + $ServerErrorType = $null + try { $ServerErrorType = ("$ServerMessage" | ConvertFrom-Json -ErrorAction Stop).errorType } catch { $ServerErrorType = $null } + $IsTransient = -not $ServerErrorType -or "$ServerErrorType" -match 'RateLimit|Timeout|Throttl' + if ($StatusCode -eq 500 -and $IsTransient -and $Retry -lt $MaxRetry) { $Retry++ # Exponential backoff: 2, 4, 8 ... seconds $Wait = [math]::Pow(2, $Retry) diff --git a/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 b/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 index 3e04cef..cbcdb60 100644 --- a/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 +++ b/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 @@ -14,7 +14,8 @@ function Connect-CWC { account requires MFA. Only functions backed by that extension are available (see NOTES); other functions return an error telling you to connect with -Credentials. - The connection is validated before it is cached. Without -Force an existing connection is reused. + The connection is validated before it is cached. An existing connection to the same server with + the same method is reused unless -Force is given; a different server or method always reconnects. .PARAMETER Server Control server hostname, e.g. control.example.com. A leading http(s):// is removed. HTTPS is always used. @@ -77,16 +78,17 @@ function Connect-CWC { $Server = $Server -replace("http.*:\/\/",'') $RequestedAuthType = $PSCmdlet.ParameterSetName + # Reuse the cached connection only when it is for the same server and auth method. A request for a + # different one always reconnects: keeping the old one would send later commands (including deletes) + # to the wrong server. if ($script:CWCServerConnection -and !$Force) { $Cached = $script:CWCServerConnection $CachedAuthType = if ($Cached.AuthType) { $Cached.AuthType } else { 'Credentials' } - if ($Cached.Server -ne $Server -or $CachedAuthType -ne $RequestedAuthType) { - Write-Warning "Already connected to '$($Cached.Server)' with $CachedAuthType. Keeping that connection; use -Force to connect to '$Server' with $RequestedAuthType." - } - else { + if ($Cached.Server -eq $Server -and $CachedAuthType -eq $RequestedAuthType) { Write-Verbose "Using cached Authentication information." + return } - return + Write-Verbose "Replacing the connection to '$($Cached.Server)' ($CachedAuthType) with '$Server' ($RequestedAuthType)." } # Kept so a failed -Force reconnect leaves the previous working connection in place diff --git a/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/New-CWCRemoteWorkforceAssignment.ps1 b/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/New-CWCRemoteWorkforceAssignment.ps1 index 8035400..f06879b 100644 --- a/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/New-CWCRemoteWorkforceAssignment.ps1 +++ b/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/New-CWCRemoteWorkforceAssignment.ps1 @@ -1,4 +1,35 @@ function New-CWCRemoteWorkforceAssignment { + <# + .SYNOPSIS + Assigns machines to a Remote Workforce user. + + .DESCRIPTION + Calls the Remote Workforce extension's AddAssignmentNoteToSession, which adds an assignment note + (AddedNote) to each session. The user can then launch the machine from the Remote Workforce page. + + .PARAMETER GUID + One or more session IDs. + + .PARAMETER Username + Control user name of the assignee. + + .PARAMETER DisplayName + Display name of the assignee. + + .PARAMETER Group + Session group containing the sessions: a name, or the path parts of a nested group. Defaults to + 'All Machines'. + + .EXAMPLE + New-CWCRemoteWorkforceAssignment -GUID $SessionID -Username 'jdoe' -DisplayName 'Jane Doe' + + .NOTES + Requires Connect-CWC -Credentials and the Remote Workforce extension. + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> [CmdletBinding(SupportsShouldProcess)] param( [Parameter(Mandatory = $True)] @@ -6,11 +37,12 @@ function New-CWCRemoteWorkforceAssignment { [Parameter(Mandatory = $True)] [string]$Username, [string]$DisplayName, - [string]$Group = 'All Machines' + [string[]]$Group = 'All Machines' ) if ($PSCmdlet.ShouldProcess("$GUID", "Assign to $Username")) { - # Adds an assignment note: not idempotent, so not retried + # AddAssignmentNoteToSession(string[] sessionGroupPath, Guid[] sessionIDs, string hostName). + # Adds notes: not idempotent, so not retried. Invoke-CWCServiceMethod -ExtensionID $script:CWCRemoteWorkforceExtensionID -Method AddAssignmentNoteToSession -Arguments @( @($Group), $GUID, diff --git a/ConnectWiseControlAPI/Public/PageService/Enter-CWCSession.ps1 b/ConnectWiseControlAPI/Public/PageService/Enter-CWCSession.ps1 index dbfff79..4ee957e 100644 --- a/ConnectWiseControlAPI/Public/PageService/Enter-CWCSession.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Enter-CWCSession.ps1 @@ -63,8 +63,12 @@ function Enter-CWCSession { [Alias('SessionID')] [guid]$GUID, - [ValidateSet('Support', 'Meeting', 'Access')] - [string]$Type = 'Access', + # Bound from piped sessions' SessionType, which the server sends as a number (Support 0, + # Meeting 1, Access 2); a name works too. + [Parameter(ValueFromPipelineByPropertyName = $True)] + [Alias('SessionType')] + [ValidateScript({ "$_" -in 'Support', 'Meeting', 'Access', '0', '1', '2' })] + $Type = 'Access', [string[]]$Group, @@ -93,9 +97,13 @@ function Enter-CWCSession { return Write-Error 'Launching the Control client is supported on Windows only. Use -UrlOnly to get the launch URL and open it yourself.' } - # Local copy: a default chosen for one pipeline item must not stick to the next. + # Local copies: values chosen for one pipeline item must not stick to the next. + $TypeName = "$Type" + if ($TypeName -match '^\d$') { + $TypeName = $script:CWCSessionType.Keys | Where-Object { $script:CWCSessionType[$_] -eq [int]$Type } | Select-Object -First 1 + } $SessionGroup = $Group - if (-not $SessionGroup) { $SessionGroup = $script:CWCDefaultSessionGroup[$Type] } + if (-not $SessionGroup) { $SessionGroup = $script:CWCDefaultSessionGroup[$TypeName] } $GroupText = $SessionGroup -join '/' $LaunchContext = Get-CWCHostLaunchContext @@ -110,10 +118,10 @@ function Enter-CWCSession { # as this type in this group. $Title = $Name if (-not $PSBoundParameters.ContainsKey('Name')) { - $Session = Get-CWCSession -Type $Type -Group $SessionGroup -FindSessionID $GUID | + $Session = Get-CWCSession -Type $TypeName -Group $SessionGroup -FindSessionID $GUID | Where-Object { "$($_.SessionID)" -eq "$GUID" } | Select-Object -First 1 if (-not $Session) { - return Write-Error "Session $GUID was not found among $Type sessions in group '$GroupText'. Check -Type and -Group." + return Write-Error "Session $GUID was not found among $TypeName sessions in group '$GroupText'. Check -Type and -Group." } $Title = "$($Session.Name)" } @@ -146,7 +154,7 @@ function Enter-CWCSession { SessionID = $GUID PublicKey = $LaunchContext.PublicKey AccessToken = "$Token" - SessionType = $Type + SessionType = $TypeName Title = $Title } $Url = New-CWCHostLaunchUrl @UrlParameters diff --git a/ConnectWiseControlAPI/Public/PageService/Invoke-CWCCommand.ps1 b/ConnectWiseControlAPI/Public/PageService/Invoke-CWCCommand.ps1 index abf47d0..f191291 100644 --- a/ConnectWiseControlAPI/Public/PageService/Invoke-CWCCommand.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Invoke-CWCCommand.ps1 @@ -66,13 +66,19 @@ function Invoke-CWCCommand { $FormattedCommand = ($CommandLines | Out-String) -replace "`r`n", "`n" # Queueing a command is not idempotent, so it is never retried - if (Test-CWCApiSecretConnection) { - # RESTful API Manager: SendCommandToSession(Guid sessionID, string command) queues the same - # QueuedCommand event. Not scoped by group, so -Group is ignored. - $null = Invoke-CWCServiceMethod -RestApi -Method SendCommandToSession -Arguments @($GUID.ToString(), $FormattedCommand) + try { + if (Test-CWCApiSecretConnection) { + # RESTful API Manager: SendCommandToSession(Guid sessionID, string command) queues the same + # QueuedCommand event. Not scoped by group, so -Group is ignored. + $null = Invoke-CWCServiceMethod -RestApi -Method SendCommandToSession -Arguments @($GUID.ToString(), $FormattedCommand) -ErrorAction Stop + } + else { + Add-CWCSessionEvent -Group $Group -Entry @{ SessionID = $GUID; EventType = $QueuedCommandEventType; Data = $FormattedCommand } -ErrorAction Stop + } } - else { - Add-CWCSessionEvent -Group $Group -Entry @{ SessionID = $GUID; EventType = $QueuedCommandEventType; Data = $FormattedCommand } + catch { + # Not queued: don't report success or poll for output that will never come + return Write-Error $_ } if ($NoWait) { return } diff --git a/ConnectWiseControlAPI/Public/PageService/Remove-CWCSessionNote.ps1 b/ConnectWiseControlAPI/Public/PageService/Remove-CWCSessionNote.ps1 index c2a191d..ab09536 100644 --- a/ConnectWiseControlAPI/Public/PageService/Remove-CWCSessionNote.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Remove-CWCSessionNote.ps1 @@ -42,7 +42,8 @@ function Remove-CWCSessionNote { .LINK https://github.com/christaylorcodes/ConnectWiseControlAPI #> - [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'ById')] + # ConfirmImpact High: removed notes can't be restored, and -All can remove many at once + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High', DefaultParameterSetName = 'ById')] param( [Parameter(Mandatory = $True)] [Alias('SessionID')] diff --git a/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml b/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml index 372a571..4b2ea05 100644 --- a/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml +++ b/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml @@ -456,14 +456,14 @@ None - + Type Session type. Defaults to Access. - String + Object - String + Object Access @@ -518,14 +518,14 @@ None - + Type Session type. Defaults to Access. - String + Object - String + Object Access @@ -2551,7 +2551,7 @@ open $Url # macOS New-CWCRemoteWorkforceAssignment - + GUID GUID of the session you want to assign the user access to. @@ -2563,7 +2563,7 @@ open $Url # macOS None - + Username Username of the account you want to assign remote workforce access to. @@ -2575,7 +2575,7 @@ open $Url # macOS None - + DisplayName Name that is displayed when user is connected to a session. @@ -2587,16 +2587,17 @@ open $Url # macOS None - - Confirm + + Group - Prompts you for confirmation before running the cmdlet. + Session group containing the session(s). Defaults to 'All Machines' where a default exists. + String[] - SwitchParameter + String[] - False + None WhatIf @@ -2609,22 +2610,21 @@ open $Url # macOS False - - Group + + Confirm - Session group containing the session(s). Defaults to 'All Machines' where a default exists. + Prompts you for confirmation before running the cmdlet. - String - String + SwitchParameter - None + False - + GUID GUID of the session you want to assign the user access to. @@ -2636,7 +2636,7 @@ open $Url # macOS None - + Username Username of the account you want to assign remote workforce access to. @@ -2648,7 +2648,7 @@ open $Url # macOS None - + DisplayName Name that is displayed when user is connected to a session. @@ -2660,17 +2660,17 @@ open $Url # macOS None - - Confirm + + Group - Prompts you for confirmation before running the cmdlet. + Session group containing the session(s). Defaults to 'All Machines' where a default exists. - SwitchParameter + String[] - SwitchParameter + String[] - False + None WhatIf @@ -2684,17 +2684,17 @@ open $Url # macOS False - - Group + + Confirm - Session group containing the session(s). Defaults to 'All Machines' where a default exists. + Prompts you for confirmation before running the cmdlet. - String + SwitchParameter - String + SwitchParameter - None + False diff --git a/Docs/Enter-CWCSession.md b/Docs/Enter-CWCSession.md index 2fa391a..a3343ec 100644 --- a/Docs/Enter-CWCSession.md +++ b/Docs/Enter-CWCSession.md @@ -13,7 +13,7 @@ Opens the ConnectWise Control Host client joined to a session, like Join in the ## SYNTAX ``` -Enter-CWCSession [-GUID] [[-Type] ] [[-Group] ] [[-Name] ] [-UrlOnly] [] +Enter-CWCSession [-GUID] [[-Type] ] [[-Group] ] [[-Name] ] [-UrlOnly] [] ``` ## DESCRIPTION @@ -70,14 +70,14 @@ Session type. Defaults to Access. ```yaml -Type: String +Type: Object Parameter Sets: (All) -Aliases: +Aliases: SessionType Required: False Position: 2 Default value: Access -Accept pipeline input: False +Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` diff --git a/Docs/New-CWCRemoteWorkforceAssignment.md b/Docs/New-CWCRemoteWorkforceAssignment.md index 8cdc971..cdb1a36 100644 --- a/Docs/New-CWCRemoteWorkforceAssignment.md +++ b/Docs/New-CWCRemoteWorkforceAssignment.md @@ -13,7 +13,8 @@ Assign a user to machines. ## SYNTAX ``` -New-CWCRemoteWorkforceAssignment -GUID -Username [-DisplayName ] [-Group ] [-WhatIf] [-Confirm] [] +New-CWCRemoteWorkforceAssignment [-GUID] [-Username] [[-DisplayName] ] + [[-Group] ] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION @@ -37,7 +38,7 @@ Parameter Sets: (All) Aliases: Required: True -Position: Named +Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -52,7 +53,7 @@ Parameter Sets: (All) Aliases: Required: True -Position: Named +Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -67,22 +68,22 @@ Parameter Sets: (All) Aliases: Required: False -Position: Named +Position: 3 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -Confirm -Prompts you for confirmation before running the cmdlet. +### -Group +Session group containing the session(s). Defaults to 'All Machines' where a default exists. ```yaml -Type: SwitchParameter +Type: String[] Parameter Sets: (All) -Aliases: cf +Aliases: Required: False -Position: Named +Position: 4 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -103,13 +104,13 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -Group -Session group containing the session(s). Defaults to 'All Machines' where a default exists. +### -Confirm +Prompts you for confirmation before running the cmdlet. ```yaml -Type: String +Type: SwitchParameter Parameter Sets: (All) -Aliases: +Aliases: cf Required: False Position: Named diff --git a/Tests/ConnectWiseControlAPI.Private.Tests.ps1 b/Tests/ConnectWiseControlAPI.Private.Tests.ps1 index dee38ef..285f71f 100644 --- a/Tests/ConnectWiseControlAPI.Private.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Private.Tests.ps1 @@ -337,6 +337,21 @@ Describe 'Invoke-CWCWebRequest' { Mock Start-Sleep -ModuleName 'ConnectWiseControlAPI' {} } + It 'does not retry an application exception (errorType body), and keeps the server message' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest { + $record = & $script:NewHttp500ErrorRecord + $record.ErrorDetails = [System.Management.Automation.ErrorDetails]::new('{"errorType":"SecurityException","message":"Needs permission"}') + throw $record + } + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + $result = Invoke-CWCWebRequest -Arguments $arguments -MaxRetry 3 2>&1 + Should -Invoke Invoke-WebRequest -Times 1 -Exactly + "$result" | Should -Match 'Needs permission' + $result.FullyQualifiedErrorId | Should -BeLike 'CWC.Http500*' + } + } + It 'retries on HTTP 500 and succeeds' { InModuleScope 'ConnectWiseControlAPI' { $script:RetryCallCount = 0 diff --git a/Tests/ConnectWiseControlAPI.Public.Tests.ps1 b/Tests/ConnectWiseControlAPI.Public.Tests.ps1 index 2c4f653..c7ea128 100644 --- a/Tests/ConnectWiseControlAPI.Public.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Public.Tests.ps1 @@ -186,15 +186,24 @@ Describe 'Connect-CWC' { } } - It 'returns early if already connected and Force not set' { + It 'reuses the cached connection for the same server and auth method' { InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { param($cred) - Connect-CWC -Server 'new.server.com' -Credentials $cred + Connect-CWC -Server 'existing.server.com' -Credentials $cred Should -Invoke Invoke-WebRequest -Times 0 $script:CWCServerConnection.Server | Should -Be 'existing.server.com' } } + It 'connects to a different server without -Force, so later commands go to it' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { + param($cred) + Connect-CWC -Server 'new.server.com' -Credentials $cred + Should -Invoke Invoke-WebRequest -Times 1 + $script:CWCServerConnection.Server | Should -Be 'new.server.com' + } + } + It 'reconnects when Force is set' { InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { param($cred) @@ -310,14 +319,14 @@ Describe 'Connect-CWC -ApiSecret' { } } - It 'warns instead of silently reusing a cached connection of another mode or server' { + It 'switches auth method without -Force instead of reusing the other mode' { InModuleScope 'ConnectWiseControlAPI' -Parameters @{ secret = $secret } { param($secret) $script:CWCServerConnection = @{ Server = 'server.example.com'; Headers = @{} } Mock Invoke-CWCWebRequest {} - Connect-CWC -Server 'server.example.com' -ApiSecret $secret -WarningVariable warn -WarningAction SilentlyContinue - ($warn -join ' ') | Should -Match '-Force' - Should -Invoke Invoke-CWCWebRequest -Times 0 + Connect-CWC -Server 'server.example.com' -ApiSecret $secret + Should -Invoke Invoke-CWCWebRequest -Times 1 + $script:CWCServerConnection.AuthType | Should -Be 'ApiSecret' } } @@ -1993,3 +2002,17 @@ Describe 'Remove-CWCSessionNote' { } } } + +Describe 'Enter-CWCSession pipeline binding' { + It 'takes the numeric SessionType of piped sessions (Support = 0) and uses its default group' { + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection = @{ Server = 'test.example.com'; AuthType = 'Credentials'; Headers = @{} } + Mock Get-CWCHostLaunchContext { [PSCustomObject]@{ Scheme = 'sc-test'; RelayHost = 'relay'; RelayPort = 443; PublicKey = 'k' } } + Mock New-CWCAccessToken { 'token' } -ParameterFilter { $Group -eq 'All Sessions' } + Mock Invoke-CWCServiceMethod {} + $Url = [PSCustomObject]@{ SessionID = [guid]::NewGuid(); Name = 'Ticket 1'; SessionType = 0 } | Enter-CWCSession -UrlOnly -WarningAction SilentlyContinue + $Url | Should -Match '/Support/' + Should -Invoke New-CWCAccessToken -Times 1 -ParameterFilter { $Group -eq 'All Sessions' } + } + } +} From c8fdc6cfc49c030c8debaf71effb2c9af2faf412 Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Tue, 10 Nov 2026 10:25:50 -0700 Subject: [PATCH 18/30] Fix review round 3 findings - Connect-CWC reuses a cached connection only for the same server, method and identity (user or API secret); a different user or rotated secret reconnects. A failed switch to another server/method/identity leaves the module disconnected instead of falling back to the old connection, so a script's next command can't hit the previous tenant. A failed -Force refresh of the same connection still keeps it. - Get-CWCLastContact counts only guest events (empty Host), so a technician leaving no longer reads as the machine going offline; requests Events only. - On PS 6+, a failed -Sensitive request's body (e.g. a new user's password) is stripped from the error record along with the auth headers. - Get-CWCAuditLog formats times with the invariant culture. - "Max retries hit" only when the retries actually ran out. - RemoveRedundantSessions example: never-connected sessions sort last, so they are never the copy kept. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 +-- .../Private/Invoke-CWCWebRequest.ps1 | 6 ++- .../Public/AuditService/Get-CWCAuditLog.ps1 | 6 ++- .../Public/Authentication/Connect-CWC.ps1 | 41 ++++++++++----- .../Public/PageService/Get-CWCLastContact.ps1 | 9 ++-- Examples/RemoveRedundantSessions.ps1 | 3 +- Tests/ConnectWiseControlAPI.Public.Tests.ps1 | 51 +++++++++++++++---- 7 files changed, 89 insertions(+), 35 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ffd1d2c..a1df44a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,9 +23,11 @@ Planned as 0.5.0.0 (the module manifest already carries this version; 0.4.0.0 is (`Invoke-CWCCommand` queues only on API-secret connections; output is not retrieved); other functions return an error naming the required auth method. `-Origin` overrides the Origin header for servers with `RESTfulAllowedOrigin` set -- `Connect-CWC` keeps the previous connection when a reconnect fails. Asking for a different server or - auth method now connects to it even without `-Force`; before, the old connection was silently kept and - later commands went to the previous server +- `Connect-CWC` reuses a cached connection only for the same server, auth method and identity (user or + secret); anything else reconnects, even without `-Force`. Before, the old connection was silently kept + and later commands went to the previous server or ran as the previous user. If connecting to a + different server, method or identity fails, the module is left disconnected; a failed `-Force` refresh + of the same connection keeps it - `Find-CWCSession` (`-Filter`/`-Name`/`-GUID`; API secret only), `New-CWCSession`, `Add-CWCSessionNote`, `Send-CWCSessionMessage`, `Send-CWCToolboxItem`. On credentials connections the last three queue session events (AddedNote 32, QueuedMessage 45, QueuedTool 47) and take `-Group` diff --git a/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 b/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 index d70d578..83e2ede 100644 --- a/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 +++ b/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 @@ -78,6 +78,10 @@ foreach ($SecretHeader in 'Authorization', 'CTRLAuthHeader', 'x-anti-forgery-token') { try { $null = $FailedRequest.Headers.Remove($SecretHeader) } catch { Write-Verbose "Could not strip $SecretHeader from the failed request." } } + # PS 6+ also keeps the request body on the HttpRequestMessage (e.g. a new user's password) + if ($SensitiveBody -and $FailedRequest.PSObject.Properties['Content']) { + try { $FailedRequest.Content = $null } catch { Write-Verbose 'Could not strip the body from the failed request.' } + } } # The server's error body, e.g. {"errorType":"SecurityException","message":"Needs permission"} @@ -107,7 +111,7 @@ # Build the error message, keeping the server's error body $ErrorMessage = @() - if ($StatusCode -eq 500 -and $Retry -gt 0) { $ErrorMessage += "Max retries hit ($MaxRetry). Status: 500" } + if ($StatusCode -eq 500 -and $Retry -gt 0 -and $Retry -ge $MaxRetry) { $ErrorMessage += "Max retries hit ($MaxRetry). Status: 500" } elseif ($StatusCode -gt 0) { $ErrorMessage += "HTTP $StatusCode" } if ($ServerMessage) { $ErrorMessage += $ServerMessage } else { $ErrorMessage += "$_" } diff --git a/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditLog.ps1 b/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditLog.ps1 index 13fe9af..86a069c 100644 --- a/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditLog.ps1 +++ b/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditLog.ps1 @@ -49,9 +49,11 @@ function Get-CWCAuditLog { } # Server signature: QueryAuditLog(minTime, maxTime, sessionName, sessionEventTypes[], securityEventTypes[]) + # Invariant culture: some cultures use another calendar (th-TH) or time separator. + $Invariant = [Globalization.CultureInfo]::InvariantCulture Invoke-CWCServiceMethod -Service AuditService -Method QueryAuditLog -Idempotent -Arguments @( - $StartDate.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ'), - $EndDate.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ'), + $StartDate.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ', $Invariant), + $EndDate.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ', $Invariant), $SessionName, $EventTypes, $SecurityTypes diff --git a/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 b/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 index cbcdb60..65bf5d2 100644 --- a/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 +++ b/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 @@ -15,7 +15,8 @@ function Connect-CWC { functions return an error telling you to connect with -Credentials. The connection is validated before it is cached. An existing connection to the same server with - the same method is reused unless -Force is given; a different server or method always reconnects. + the same method and identity (user or secret) is reused unless -Force is given; anything else + reconnects. .PARAMETER Server Control server hostname, e.g. control.example.com. A leading http(s):// is removed. HTTPS is always used. @@ -31,8 +32,9 @@ function Connect-CWC { extension's RESTfulAllowedOrigin setting if that setting is configured. .PARAMETER Force - Replace an existing cached connection. If the new connection fails validation, the previous - connection is kept. + Reconnect even when the cached connection is for the same server, method and identity. If that + refresh fails, the previous connection is kept. A failed connection to a different server, method + or identity leaves the module disconnected, so later commands can't reach the old server. .EXAMPLE Connect-CWC -Server 'control.example.com' -Credentials (Get-Credential) @@ -78,21 +80,34 @@ function Connect-CWC { $Server = $Server -replace("http.*:\/\/",'') $RequestedAuthType = $PSCmdlet.ParameterSetName - # Reuse the cached connection only when it is for the same server and auth method. A request for a - # different one always reconnects: keeping the old one would send later commands (including deletes) - # to the wrong server. - if ($script:CWCServerConnection -and !$Force) { + if ($RequestedAuthType -eq 'Credentials') { + $EncodedCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("$($Credentials.UserName):$($Credentials.GetNetworkCredential().Password)")) + } + + # Is the cached connection the same server, auth method and identity (user or secret) as requested? + $SameAsCached = $False + if ($script:CWCServerConnection) { $Cached = $script:CWCServerConnection $CachedAuthType = if ($Cached.AuthType) { $Cached.AuthType } else { 'Credentials' } if ($Cached.Server -eq $Server -and $CachedAuthType -eq $RequestedAuthType) { - Write-Verbose "Using cached Authentication information." - return + if ($RequestedAuthType -eq 'Credentials') { $SameAsCached = $Cached.Headers.authorization -eq "Basic $EncodedCredentials" } + else { $SameAsCached = (ConvertFrom-CWCSecureString $Cached.ApiSecret) -eq (ConvertFrom-CWCSecureString $ApiSecret) } } - Write-Verbose "Replacing the connection to '$($Cached.Server)' ($CachedAuthType) with '$Server' ($RequestedAuthType)." } - # Kept so a failed -Force reconnect leaves the previous working connection in place - $PreviousConnection = $script:CWCServerConnection + # Reuse the cached connection only for the same server, method and identity. Anything else reconnects: + # keeping the old connection would send later commands (including deletes) to the wrong server, or + # run them as the wrong user. + if ($SameAsCached -and !$Force) { + Write-Verbose "Using cached Authentication information." + return + } + + # On failure, restore the previous connection only when this was a refresh of that same connection + # (-Force). After a failed switch to another server, method or identity, stay disconnected. + $PreviousConnection = $null + if ($SameAsCached) { $PreviousConnection = $script:CWCServerConnection } + $script:CWCServerConnection = $null if ($RequestedAuthType -eq 'ApiSecret') { if ($ApiSecret.Length -eq 0) { @@ -131,7 +146,6 @@ function Connect-CWC { return } - $EncodedCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("$($Credentials.UserName):$($Credentials.GetNetworkCredential().Password)")) $Headers = @{ 'authorization' = "Basic $EncodedCredentials" 'content-type' = "application/json; charset=utf-8" @@ -145,6 +159,7 @@ function Connect-CWC { $FrontPage = Invoke-WebRequest -Uri $Headers.origin -Headers $Headers -UseBasicParsing -SessionVariable 'WebSession' } catch { + $script:CWCServerConnection = $PreviousConnection Write-Error "Failed to connect to Control server 'https://$Server': $_" return } diff --git a/ConnectWiseControlAPI/Public/PageService/Get-CWCLastContact.ps1 b/ConnectWiseControlAPI/Public/PageService/Get-CWCLastContact.ps1 index 82901ce..6db3be4 100644 --- a/ConnectWiseControlAPI/Public/PageService/Get-CWCLastContact.ps1 +++ b/ConnectWiseControlAPI/Public/PageService/Get-CWCLastContact.ps1 @@ -48,7 +48,7 @@ function Get-CWCLastContact { return Write-Error (Get-CWCAuthModeMessage -Command $MyInvocation.MyCommand.Name -Required Credentials) -ErrorId 'CWC.AuthModeMismatch' -Category InvalidOperation } - try { $SessionDetails = Get-CWCSessionDetail -Group $Group -GUID $GUID -Include 'Events', 'Connections' -ErrorAction Stop } + try { $SessionDetails = Get-CWCSessionDetail -Group $Group -GUID $GUID -Include 'Events' -ErrorAction Stop } catch { Write-Error $_ return @@ -59,11 +59,10 @@ function Get-CWCLastContact { return $null } - # The latest connect/disconnect event of a guest connection that is no longer open - $GuestSessionConnections = $SessionDetails.Connections | Where-Object { $_.ParticipantName } + # The guest's latest connect/disconnect event. Guest events have no Host; a technician's carry their + # name, so a technician joining or leaving doesn't count as the machine's last contact. $LatestEvent = $SessionDetails.Events | Where-Object { - $_.EventType -in ($script:CWCSessionEventType.Connected, $script:CWCSessionEventType.Disconnected) -and - $_.ConnectionID -NotIn $GuestSessionConnections.ConnectionID + $_.EventType -in ($script:CWCSessionEventType.Connected, $script:CWCSessionEventType.Disconnected) -and -not $_.Host } | Sort-Object { [double]$_.Time } | Select-Object -First 1 if (-not $LatestEvent) { return Write-Error 'Unable to determine last contact.' } diff --git a/Examples/RemoveRedundantSessions.ps1 b/Examples/RemoveRedundantSessions.ps1 index 784018e..5aad7e2 100644 --- a/Examples/RemoveRedundantSessions.ps1 +++ b/Examples/RemoveRedundantSessions.ps1 @@ -33,7 +33,8 @@ Where-Object -Property Count -gt 1 | ForEach-Object { # LastConnectedEventTime is seconds since the last connection: smallest first, so Skip 1 keeps # the most recently connected session - $_.Group | Sort-Object -Property { [double]$_.LastConnectedEventTime } | + # A session that never connected (no time) sorts last, so it is never the one kept + $_.Group | Sort-Object -Property { if ($null -eq $_.LastConnectedEventTime) { [double]::MaxValue } else { [double]$_.LastConnectedEventTime } } | Select-Object -Skip 1 } diff --git a/Tests/ConnectWiseControlAPI.Public.Tests.ps1 b/Tests/ConnectWiseControlAPI.Public.Tests.ps1 index c7ea128..357c121 100644 --- a/Tests/ConnectWiseControlAPI.Public.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Public.Tests.ps1 @@ -186,15 +186,26 @@ Describe 'Connect-CWC' { } } - It 'reuses the cached connection for the same server and auth method' { + It 'reuses the cached connection for the same server, auth method and user' { InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { param($cred) + $Basic = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$($cred.UserName):$($cred.GetNetworkCredential().Password)")) + $script:CWCServerConnection = @{ Server = 'existing.server.com'; AuthType = 'Credentials'; Headers = @{ authorization = "Basic $Basic" } } Connect-CWC -Server 'existing.server.com' -Credentials $cred Should -Invoke Invoke-WebRequest -Times 0 $script:CWCServerConnection.Server | Should -Be 'existing.server.com' } } + It 'reconnects for a different user on the same server' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { + param($cred) + $script:CWCServerConnection = @{ Server = 'existing.server.com'; AuthType = 'Credentials'; Headers = @{ authorization = 'Basic b3RoZXI6dXNlcg==' } } + Connect-CWC -Server 'existing.server.com' -Credentials $cred + Should -Invoke Invoke-WebRequest -Times 1 + } + } + It 'connects to a different server without -Force, so later commands go to it' { InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { param($cred) @@ -308,17 +319,27 @@ Describe 'Connect-CWC -ApiSecret' { } } - It 'keeps the previous connection when a -Force reconnect fails' { + It 'keeps the previous connection when a -Force refresh of the same connection fails' { InModuleScope 'ConnectWiseControlAPI' -Parameters @{ secret = $secret } { param($secret) - $previous = @{ Server = 'old.example.com'; AuthType = 'Credentials'; Headers = @{} } - $script:CWCServerConnection = $previous + $Copy = $secret.Copy() + $script:CWCServerConnection = @{ Server = 'old.example.com'; AuthType = 'ApiSecret'; ApiSecret = $Copy; Headers = @{} } Mock Invoke-CWCWebRequest { throw 'Unauthorized' } - Connect-CWC -Server 'new.example.com' -ApiSecret $secret -Force -ErrorAction SilentlyContinue + Connect-CWC -Server 'old.example.com' -ApiSecret $secret -Force -ErrorAction SilentlyContinue $script:CWCServerConnection.Server | Should -Be 'old.example.com' } } + It 'is left disconnected when switching to another server fails, so commands cannot reach the old one' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ secret = $secret } { + param($secret) + $script:CWCServerConnection = @{ Server = 'old.example.com'; AuthType = 'Credentials'; Headers = @{} } + Mock Invoke-CWCWebRequest { throw 'Unauthorized' } + Connect-CWC -Server 'new.example.com' -ApiSecret $secret -ErrorAction SilentlyContinue + $script:CWCServerConnection | Should -BeNullOrEmpty + } + } + It 'switches auth method without -Force instead of reusing the other mode' { InModuleScope 'ConnectWiseControlAPI' -Parameters @{ secret = $secret } { param($secret) @@ -498,13 +519,11 @@ Describe 'Session detail polling callers' { BeforeEach { Set-CWCTestConnection } - It 'Get-CWCLastContact requests only Events and Connections' { + It 'Get-CWCLastContact requests only Events' { InModuleScope 'ConnectWiseControlAPI' { - Mock Get-CWCSessionDetail { @{ Events = @(@{ EventType = 10; Time = 0 }); Connections = @() } } + Mock Get-CWCSessionDetail { @{ Events = @(@{ EventType = 10; Time = 0 }) } } $null = Get-CWCLastContact -GUID ([guid]::NewGuid()) -Quiet - Should -Invoke Get-CWCSessionDetail -Times 1 -ParameterFilter { - ($Include | Sort-Object) -join ',' -eq 'Connections,Events' - } + Should -Invoke Get-CWCSessionDetail -Times 1 -ParameterFilter { $Include -eq 'Events' } } } @@ -579,6 +598,18 @@ Describe 'Get-CWCLastContact' { } } + It 'ignores a technician leaving after the guest disconnected' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Get-CWCSessionDetail { + @{ Events = @( + @{ EventType = 11; Time = 5000; Host = 'Technician'; ConnectionID = 'host1' } + @{ EventType = 11; Time = 120000; Host = ''; ConnectionID = 'guest1' } + ) } + } + Get-CWCLastContact -GUID ([guid]::NewGuid()) -Quiet -Seconds 60 | Should -BeFalse + } + } + It 'returns a local time about two minutes ago' { InModuleScope 'ConnectWiseControlAPI' { $result = Get-CWCLastContact -GUID ([guid]::NewGuid()) From 601abc12f0fe9288beb89c2be2e10f3a317fa8aa Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Tue, 10 Nov 2026 10:26:17 -0700 Subject: [PATCH 19/30] Smoke test: record event IDs, check wrong-password handling Records EventID/CorrelationEventID so a live run shows whether RanCommand output points at its QueuedCommand, and checks a wrong password fails within 10 s, names the login causes and leaves the module disconnected. Co-Authored-By: Claude Opus 5.5 --- Tests/Live/Invoke-CWCLiveSmokeTest.ps1 | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Tests/Live/Invoke-CWCLiveSmokeTest.ps1 b/Tests/Live/Invoke-CWCLiveSmokeTest.ps1 index 5b98195..dc81d0b 100644 --- a/Tests/Live/Invoke-CWCLiveSmokeTest.ps1 +++ b/Tests/Live/Invoke-CWCLiveSmokeTest.ps1 @@ -81,6 +81,9 @@ function Select-Event { $Events | ForEach-Object { [ordered]@{ EventType = $_.EventType + # IDs show whether output events (70) point back at their command (44) via CorrelationEventID + EventID = $_.EventID + CorrelationEventID = $_.CorrelationEventID Time = $_.Time TimeType = if ($null -ne $_.Time) { $_.Time.GetType().Name } else { $null } Host = $_.Host @@ -165,6 +168,21 @@ Invoke-Step 'Creds.GetSessionDetail' { [ordered]@{ BaseTime = $Detail.BaseTime; Events = @(Select-Event ($Detail.Events | Select-Object -First 15)) } } Invoke-Step 'Creds.LastContact' { (Get-CWCLastContact -GUID $TestSessionID -Group $Group).ToString('o') } + +# A wrong password must fail fast (no retries) with the login hint, and leave the module disconnected. +Invoke-Step 'Creds.WrongPasswordFailsFast' { + $BadCredential = [pscredential]::new($AdminCredential.UserName, (ConvertTo-SecureString 'definitely-wrong-password' -AsPlainText -Force)) + $Timer = [Diagnostics.Stopwatch]::StartNew() + $Message = $null + try { Connect-CWC -Server $Server -Credentials $BadCredential -WarningAction SilentlyContinue } + catch { $Message = "$_" } + $Timer.Stop() + $Connected = [bool](& (Get-Module ConnectWiseControlAPI) { $script:CWCServerConnection }) + if ($Timer.Elapsed.TotalSeconds -gt 10) { throw "Took $([int]$Timer.Elapsed.TotalSeconds) s; retries are still happening" } + if ($Connected) { throw 'Still connected after a failed login to a different identity' } + [ordered]@{ Seconds = [math]::Round($Timer.Elapsed.TotalSeconds, 1); MentionsLogin = $Message -match 'username and password' } +} +Invoke-Step 'Creds.ReconnectAfterWrongPassword' { Connect-CWC -Server $Server -Credentials $AdminCredential; 'connected' } #endregion #region Limited role (#14) From e89bbb767aa85d334ad93d93d3ff463dd4164319 Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Tue, 10 Nov 2026 10:37:11 -0700 Subject: [PATCH 20/30] Smoke test: test only this checkout's module Unloads any already-imported ConnectWiseControlAPI (e.g. the Gallery version) and keeps the imported module object, instead of Get-Module, which returned two modules and broke the module-scope steps. Co-Authored-By: Claude Opus 5.5 --- Tests/Live/Invoke-CWCLiveSmokeTest.ps1 | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Tests/Live/Invoke-CWCLiveSmokeTest.ps1 b/Tests/Live/Invoke-CWCLiveSmokeTest.ps1 index dc81d0b..7356888 100644 --- a/Tests/Live/Invoke-CWCLiveSmokeTest.ps1 +++ b/Tests/Live/Invoke-CWCLiveSmokeTest.ps1 @@ -50,7 +50,9 @@ param( $ErrorActionPreference = 'Stop' # Module functions report failures with non-terminating Write-Error; make them fail the step. $PSDefaultParameterValues['*-CWC*:ErrorAction'] = 'Stop' -Import-Module (Join-Path $PSScriptRoot '..\..\ConnectWiseControlAPI\ConnectWiseControlAPI.psd1') -Force +# Unload every copy first (e.g. a Gallery install imported earlier), so the script tests this checkout only +Get-Module ConnectWiseControlAPI | Remove-Module -Force +$CWCModule = Import-Module (Join-Path $PSScriptRoot '..\..\ConnectWiseControlAPI\ConnectWiseControlAPI.psd1') -Force -PassThru $Results = [ordered]@{ PSVersion = $PSVersionTable.PSVersion.ToString() @@ -73,7 +75,7 @@ function Invoke-Step { } } -function Disconnect-Test { $Module = Get-Module ConnectWiseControlAPI; & $Module { $script:CWCServerConnection = $null } } +function Disconnect-Test { & $CWCModule { $script:CWCServerConnection = $null } } # Events with only the fields we need; Data/Host trimmed so output stays small. function Select-Event { @@ -142,7 +144,7 @@ Invoke-Step 'Creds.Connect' { Connect-CWC -Server $Server -Credentials $AdminCre Invoke-Step 'Creds.SessionEventTypeEnum' { # The enum only exists in the web client's scripts; grab the text around each mention. - $Connection = & (Get-Module ConnectWiseControlAPI) { $script:CWCServerConnection } + $Connection = & $CWCModule { $script:CWCServerConnection } $Front = Invoke-WebRequest -Uri "https://$Server" -WebSession $Connection.WebSession -UseBasicParsing $ScriptUrls = [regex]::Matches($Front.Content, ']+src="([^"]+)"') | ForEach-Object { $_.Groups[1].Value } | Where-Object { $_ -notmatch '^https?://' -or $_ -match [regex]::Escape($Server) } @@ -177,7 +179,7 @@ Invoke-Step 'Creds.WrongPasswordFailsFast' { try { Connect-CWC -Server $Server -Credentials $BadCredential -WarningAction SilentlyContinue } catch { $Message = "$_" } $Timer.Stop() - $Connected = [bool](& (Get-Module ConnectWiseControlAPI) { $script:CWCServerConnection }) + $Connected = [bool](& $CWCModule { $script:CWCServerConnection }) if ($Timer.Elapsed.TotalSeconds -gt 10) { throw "Took $([int]$Timer.Elapsed.TotalSeconds) s; retries are still happening" } if ($Connected) { throw 'Still connected after a failed login to a different identity' } [ordered]@{ Seconds = [math]::Round($Timer.Elapsed.TotalSeconds, 1); MentionsLogin = $Message -match 'username and password' } From 59407b85296cd93e9431a1675e1e24cf88ddea67 Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Tue, 10 Nov 2026 10:42:16 -0700 Subject: [PATCH 21/30] API-secret note/message/toolbox: no output; document RESTfulUserName - Add-CWCSessionNote, Send-CWCSessionMessage and Send-CWCToolboxItem no longer output the extension's empty {} response (the credentials path outputs nothing; seen in the live smoke test). - Help: the extension attributes notes, commands and toolbox runs to its RESTfulUserName setting, which can be renamed; Send-CWCSessionMessage -From defaults to 'RESTful API' and must be passed to match a renamed setting. Co-Authored-By: Claude Opus 5.5 --- ConnectWiseControlAPI/Public/RestApi/Add-CWCSessionNote.ps1 | 2 +- .../Public/RestApi/Send-CWCSessionMessage.ps1 | 6 ++++-- .../Public/RestApi/Send-CWCToolboxItem.ps1 | 6 ++++-- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/ConnectWiseControlAPI/Public/RestApi/Add-CWCSessionNote.ps1 b/ConnectWiseControlAPI/Public/RestApi/Add-CWCSessionNote.ps1 index 36e1aa1..11f8723 100644 --- a/ConnectWiseControlAPI/Public/RestApi/Add-CWCSessionNote.ps1 +++ b/ConnectWiseControlAPI/Public/RestApi/Add-CWCSessionNote.ps1 @@ -50,7 +50,7 @@ function Add-CWCSessionNote { # Adding an event is not idempotent: never retried if (Test-CWCApiSecretConnection) { # AddNoteToSession(Guid sessionID, string noteBody) - Invoke-CWCServiceMethod -RestApi -Method AddNoteToSession -Arguments @($GUID.ToString(), $Note) + $null = Invoke-CWCServiceMethod -RestApi -Method AddNoteToSession -Arguments @($GUID.ToString(), $Note) } else { Add-CWCSessionEvent -Group $Group -Entry @{ SessionID = $GUID; EventType = $script:CWCSessionEventType.AddedNote; Data = $Note } diff --git a/ConnectWiseControlAPI/Public/RestApi/Send-CWCSessionMessage.ps1 b/ConnectWiseControlAPI/Public/RestApi/Send-CWCSessionMessage.ps1 index 2f9027f..70a49f8 100644 --- a/ConnectWiseControlAPI/Public/RestApi/Send-CWCSessionMessage.ps1 +++ b/ConnectWiseControlAPI/Public/RestApi/Send-CWCSessionMessage.ps1 @@ -20,7 +20,9 @@ function Send-CWCSessionMessage { Message text. .PARAMETER From - Sender name shown to the guest (API secret connections only). + Sender name shown to the guest (API secret connections only). Defaults to 'RESTful API', the + extension's default RESTfulUserName. The extension uses this value, not its RESTfulUserName + setting, so pass -From to match a renamed setting (or any name you want the guest to see). .PARAMETER Group Session group containing the session (credentials connections only). Defaults to 'All Machines'. @@ -57,7 +59,7 @@ function Send-CWCSessionMessage { # Adding an event is not idempotent: never retried if (Test-CWCApiSecretConnection) { # SendMessageToSession(Guid sessionID, string byHost, string message) - Invoke-CWCServiceMethod -RestApi -Method SendMessageToSession -Arguments @($GUID.ToString(), $From, $Message) + $null = Invoke-CWCServiceMethod -RestApi -Method SendMessageToSession -Arguments @($GUID.ToString(), $From, $Message) } else { # The server sets the sender to the connected user's display name. diff --git a/ConnectWiseControlAPI/Public/RestApi/Send-CWCToolboxItem.ps1 b/ConnectWiseControlAPI/Public/RestApi/Send-CWCToolboxItem.ps1 index 26754d7..9e41d4c 100644 --- a/ConnectWiseControlAPI/Public/RestApi/Send-CWCToolboxItem.ps1 +++ b/ConnectWiseControlAPI/Public/RestApi/Send-CWCToolboxItem.ps1 @@ -9,7 +9,9 @@ function Send-CWCToolboxItem { Credentials connections: PageService.AddSessionEvents; the user needs the RunSharedTool permission in -Group. - API secret connections: the RESTful API Manager extension's SendToolboxItemToSession; -Group is ignored. + API secret connections: the RESTful API Manager extension's SendToolboxItemToSession. The event + is attributed to the extension's RESTfulUserName setting ("RESTful API" unless renamed); -Group + is ignored. .PARAMETER GUID Session ID. @@ -49,7 +51,7 @@ function Send-CWCToolboxItem { # Adding an event is not idempotent: never retried if (Test-CWCApiSecretConnection) { # SendToolboxItemToSession(Guid sessionID, string toolboxItemName) - Invoke-CWCServiceMethod -RestApi -Method SendToolboxItemToSession -Arguments @($GUID.ToString(), $Name) + $null = Invoke-CWCServiceMethod -RestApi -Method SendToolboxItemToSession -Arguments @($GUID.ToString(), $Name) } else { Add-CWCSessionEvent -Group $Group -Entry @{ SessionID = $GUID; EventType = $script:CWCSessionEventType.QueuedTool; Data = $Name } From 274bd848433ec9a39f868282c6e2715e0a5408d9 Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Tue, 10 Nov 2026 11:33:26 -0700 Subject: [PATCH 22/30] MFA login for Connect-CWC (#12) Connect-CWC -Credentials with -Mfa (prompts for the code; authenticator, email or SMS), -OneTimeCode or -TotpSecret (computes the authenticator code; the secret is not stored) signs in through AuthenticationService.TryLogin and uses the .ASPXAUTH cookie: no Basic auth, no stored password. - Cached MFA logins match on a salted hash of user and password and are re-checked with GetEligibleHosts; an expired one is never restored. - A replaced MFA login is logged out (best effort). - ErrorIds CWC.MfaRequired, CWC.MfaCodeRejected, CWC.LoginFailed, CWC.LoginThrottled; logins are never retried. - TOTP waits for a fresh step near the window end and never reuses a step for the same server and user. - Expired-login hint on permission/anti-forgery errors over MFA connections. - Failed requests no longer keep the Cookie header or cookie jar on $Error. - Smoke test: module-level MFA steps, optional TOTP and expired-login check; raw failed-login probes behind -MfaNegativeProbes. Co-Authored-By: Claude Opus 5.5 --- .github/SECURITY.md | 5 +- CHANGELOG.md | 12 +- CLAUDE.md | 5 +- .../Private/ConvertFrom-CWCBase32.ps1 | 41 +++ .../Private/Get-CWCAntiForgeryToken.ps1 | 20 ++ .../Private/Get-CWCAuthModeMessage.ps1 | 2 +- .../Private/Get-CWCIdentityHash.ps1 | 34 ++ .../Private/Get-CWCTotpCode.ps1 | 64 ++++ .../Private/Get-CWCTotpLoginCode.ps1 | 42 +++ .../Private/Get-CWCUnixTime.ps1 | 13 + .../Private/Invoke-CWCLogout.ps1 | 26 ++ .../Private/Invoke-CWCMfaLogin.ps1 | 164 ++++++++++ .../Private/Invoke-CWCServiceMethod.ps1 | 2 +- .../Private/Invoke-CWCWebRequest.ps1 | 14 +- .../Public/Authentication/Connect-CWC.ps1 | 252 ++++++++++---- .../en-US/ConnectWiseControlAPI-help.xml | 256 ++++++++++++++- ConnectWiseControlAPI_Functions.md | 2 +- Docs/Connect-CWC.md | 156 ++++++++- README.md | 17 +- Tests/ConnectWiseControlAPI.Private.Tests.ps1 | 205 ++++++++++++ Tests/ConnectWiseControlAPI.Public.Tests.ps1 | 309 ++++++++++++++++++ Tests/Live/Invoke-CWCLiveSmokeTest.ps1 | 160 +++++---- 22 files changed, 1630 insertions(+), 171 deletions(-) create mode 100644 ConnectWiseControlAPI/Private/ConvertFrom-CWCBase32.ps1 create mode 100644 ConnectWiseControlAPI/Private/Get-CWCAntiForgeryToken.ps1 create mode 100644 ConnectWiseControlAPI/Private/Get-CWCIdentityHash.ps1 create mode 100644 ConnectWiseControlAPI/Private/Get-CWCTotpCode.ps1 create mode 100644 ConnectWiseControlAPI/Private/Get-CWCTotpLoginCode.ps1 create mode 100644 ConnectWiseControlAPI/Private/Get-CWCUnixTime.ps1 create mode 100644 ConnectWiseControlAPI/Private/Invoke-CWCLogout.ps1 create mode 100644 ConnectWiseControlAPI/Private/Invoke-CWCMfaLogin.ps1 diff --git a/.github/SECURITY.md b/.github/SECURITY.md index 5136b9e..603a0cf 100644 --- a/.github/SECURITY.md +++ b/.github/SECURITY.md @@ -71,7 +71,10 @@ When using this module, please: 1. **Secure Your Credentials** - Never commit API credentials or passwords to source control - Use PowerShell `[PSCredential]` objects, not plaintext passwords - - The module requires a non-MFA account; use a complex username and password + - Use a complex username and password; accounts that require MFA sign in with `-Mfa`, + `-OneTimeCode` or `-TotpSecret` + - A TOTP secret for unattended logins (`-TotpSecret`) is a second password: keep it in a secret + store, apart from the account password where you can, and replace it if the computer is compromised 2. **Use HTTPS** - The module requires your Control server to use HTTPS diff --git a/CHANGELOG.md b/CHANGELOG.md index a1df44a..890edce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,15 @@ Planned as 0.5.0.0 (the module manifest already carries this version; 0.4.0.0 is (`Invoke-CWCCommand` queues only on API-secret connections; output is not retrieved); other functions return an error naming the required auth method. `-Origin` overrides the Origin header for servers with `RESTfulAllowedOrigin` set +- MFA login (#12): `Connect-CWC -Credentials` with `-Mfa` (asks for the one-time code; works with + authenticator-app, email and SMS codes), `-OneTimeCode` or `-TotpSecret` (computes the authenticator + code for unattended scripts; the secret is not stored). Signs in through + `AuthenticationService.TryLogin` and uses the login cookie; no Basic auth, and the password is not kept. + A cached MFA login is checked with one call and replaced when it has expired; a replaced MFA login is + logged out. Errors carry ErrorIds `CWC.MfaRequired`, `CWC.MfaCodeRejected`, `CWC.LoginFailed`, + `CWC.LoginThrottled`. Logins are never retried. Requests that fail on an MFA connection with a + permission or anti-forgery error say the login may have expired +- Failed requests no longer keep the login cookie on the request object stored in `$Error` - `Connect-CWC` reuses a cached connection only for the same server, auth method and identity (user or secret); anything else reconnects, even without `-Force`. Before, the old connection was silently kept and later commands went to the previous server or ran as the previous user. If connecting to a @@ -32,7 +41,8 @@ Planned as 0.5.0.0 (the module manifest already carries this version; 0.4.0.0 is `Add-CWCSessionNote`, `Send-CWCSessionMessage`, `Send-CWCToolboxItem`. On credentials connections the last three queue session events (AddedNote 32, QueuedMessage 45, QueuedTool 47) and take `-Group` - Live smoke test script `Tests/Live/Invoke-CWCLiveSmokeTest.ps1` (read-only by default; `-AllowWrites` - acts on one chosen test session and cleans up its notes; `-MfaUserName` probes the MFA login flow) + acts on one chosen test session and cleans up its notes; `-MfaUserName` tests the MFA login, optionally with a TOTP secret; `-MfaNegativeProbes` records the raw + failed-login codes) - `Get-CWCRemoteWorkforceLaunchURL` (by `-GUID`, pipeline, or `-SessionName`), replacing `Get-CWCLauncURL` - `Get-CWCRemoteWorkforceSession` lists the calling user's assigned machines (`GetRemoteWorkforceSessions`) - `Initialize-CWCRemoteWorkforceSessionGroup` creates/repairs the extension's session group diff --git a/CLAUDE.md b/CLAUDE.md index 89931cc..95c3400 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,9 +4,10 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Overview -PowerShell module wrapping the ConnectWise Control (ScreenConnect) web API; published to the PowerShell Gallery and used by MSPs. Version lives in `ConnectWiseControlAPI/ConnectWiseControlAPI.psd1` (history in `CHANGELOG.md`). Two auth modes via `Connect-CWC`: +PowerShell module wrapping the ConnectWise Control (ScreenConnect) web API; published to the PowerShell Gallery and used by MSPs. Version lives in `ConnectWiseControlAPI/ConnectWiseControlAPI.psd1` (history in `CHANGELOG.md`). Three auth modes via `Connect-CWC` (stored as `AuthType`): -- `-Credentials`: Basic auth, non-MFA account. Reaches the built-in `Services/*.ashx` and extensions. +- `-Credentials` (`Credentials`): Basic auth, non-MFA account. Reaches the built-in `Services/*.ashx` and extensions. +- `-Credentials` plus `-Mfa`, `-OneTimeCode` or `-TotpSecret` (`Mfa`): `Private/Invoke-CWCMfaLogin.ps1` signs in with `AuthenticationService.TryLogin` and the connection uses the `.ASPXAUTH` cookie, with no Authorization header and no stored password. Reaches the same endpoints as `Credentials`. The login expires; a cache hit is re-checked with `GetEligibleHosts`. - `-ApiSecret`: RESTful API Manager extension secret. Reaches only that extension's methods: `Public/RestApi/` functions plus the dual-mode ones (`Get-CWCSessionDetail`, `Update-CWCSessionName`, `Invoke-CWCCommand`), which branch on `Test-CWCApiSecretConnection`. ## Commands diff --git a/ConnectWiseControlAPI/Private/ConvertFrom-CWCBase32.ps1 b/ConnectWiseControlAPI/Private/ConvertFrom-CWCBase32.ps1 new file mode 100644 index 0000000..b3ac6eb --- /dev/null +++ b/ConnectWiseControlAPI/Private/ConvertFrom-CWCBase32.ps1 @@ -0,0 +1,41 @@ +function ConvertFrom-CWCBase32 { + <# + .SYNOPSIS + Decodes RFC 4648 Base32 text to bytes. Ignores case, whitespace, dashes and '=' padding. + Errors never echo the input (it is a secret). + #> + [CmdletBinding()] + [OutputType([byte[]])] + param( + [Parameter(Mandatory = $True)] + [AllowEmptyString()] + [string]$Text + ) + + $Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567' + $Clean = ($Text -replace '[\s=-]', '').ToUpperInvariant() + $Length = [int][math]::Floor($Clean.Length * 5 / 8) + if ($Length -eq 0) { throw 'The TOTP secret is empty or too short.' } + + $Bytes = New-Object byte[] $Length + $Index = 0 + $Buffer = 0 + $Bits = 0 + foreach ($Char in $Clean.ToCharArray()) { + $Value = $Alphabet.IndexOf($Char) + if ($Value -lt 0) { + [array]::Clear($Bytes, 0, $Bytes.Length) + throw 'The TOTP secret is not valid Base32 (letters A-Z and digits 2-7, optionally prefixed with "ms:").' + } + $Buffer = ($Buffer -shl 5) -bor $Value + $Bits += 5 + if ($Bits -ge 8) { + $Bits -= 8 + if ($Index -lt $Length) { $Bytes[$Index] = [byte](($Buffer -shr $Bits) -band 0xFF) } + $Index++ + # Keep only the bits not yet written + $Buffer = $Buffer -band ((1 -shl $Bits) - 1) + } + } + , $Bytes +} diff --git a/ConnectWiseControlAPI/Private/Get-CWCAntiForgeryToken.ps1 b/ConnectWiseControlAPI/Private/Get-CWCAntiForgeryToken.ps1 new file mode 100644 index 0000000..9a10e6f --- /dev/null +++ b/ConnectWiseControlAPI/Private/Get-CWCAntiForgeryToken.ps1 @@ -0,0 +1,20 @@ +function Get-CWCAntiForgeryToken { + <# + .SYNOPSIS + Returns the anti-forgery token from the Control front page HTML, or $null. + + .DESCRIPTION + Matches only a token-shaped value, so a change in the page's JSON key order can't break the + capture (an old pattern required "isUserAdministrator" to follow) and no other page content is taken. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [AllowNull()] + [AllowEmptyString()] + [string]$Content + ) + + $Match = [regex]::Match("$Content", 'antiForgeryToken":"([A-Za-z0-9+/=_-]{16,512})"') + if ($Match.Success) { $Match.Groups[1].Value } else { $null } +} diff --git a/ConnectWiseControlAPI/Private/Get-CWCAuthModeMessage.ps1 b/ConnectWiseControlAPI/Private/Get-CWCAuthModeMessage.ps1 index b63aa1c..47558f7 100644 --- a/ConnectWiseControlAPI/Private/Get-CWCAuthModeMessage.ps1 +++ b/ConnectWiseControlAPI/Private/Get-CWCAuthModeMessage.ps1 @@ -21,7 +21,7 @@ function Get-CWCAuthModeMessage { ) if ($Required -eq 'Credentials') { - return "$Command is not available when connected with -ApiSecret (RESTful API Manager). Connect with 'Connect-CWC -Credentials' to use it." + return "$Command is not available when connected with -ApiSecret (RESTful API Manager). Connect with 'Connect-CWC -Credentials' to use it (for an account that requires MFA, add -Mfa, -OneTimeCode or -TotpSecret)." } "$Command requires the RESTful API Manager extension. Connect with 'Connect-CWC -ApiSecret' to use it." } diff --git a/ConnectWiseControlAPI/Private/Get-CWCIdentityHash.ps1 b/ConnectWiseControlAPI/Private/Get-CWCIdentityHash.ps1 new file mode 100644 index 0000000..e31daef --- /dev/null +++ b/ConnectWiseControlAPI/Private/Get-CWCIdentityHash.ps1 @@ -0,0 +1,34 @@ +function Get-CWCIdentityHash { + <# + .SYNOPSIS + Salted SHA-256 of a username and password, so Connect-CWC can tell whether a cached MFA login + belongs to the same credentials without keeping the password. + + .DESCRIPTION + The salt is random per module load and never leaves memory, so the hash can't be compared + against hashes from anywhere else. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory = $True)] + [pscredential]$Credentials + ) + + if (-not $script:CWCIdentitySalt) { + $Salt = New-Object byte[] 32 + $Rng = [System.Security.Cryptography.RandomNumberGenerator]::Create() + try { $Rng.GetBytes($Salt) } finally { $Rng.Dispose() } + $script:CWCIdentitySalt = [Convert]::ToBase64String($Salt) + } + + $Sha = [System.Security.Cryptography.SHA256]::Create() + try { + # Usernames are case-insensitive in Control; passwords are not + $Text = "$($script:CWCIdentitySalt)`n$($Credentials.UserName.ToLowerInvariant())`n$($Credentials.GetNetworkCredential().Password)" + [Convert]::ToBase64String($Sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($Text))) + } + finally { + $Sha.Dispose() + } +} diff --git a/ConnectWiseControlAPI/Private/Get-CWCTotpCode.ps1 b/ConnectWiseControlAPI/Private/Get-CWCTotpCode.ps1 new file mode 100644 index 0000000..fcd4569 --- /dev/null +++ b/ConnectWiseControlAPI/Private/Get-CWCTotpCode.ps1 @@ -0,0 +1,64 @@ +function Get-CWCTotpCode { + <# + .SYNOPSIS + Computes an RFC 6238 TOTP code (HMAC-SHA1, 30-second step) from a Base32 seed. + + .DESCRIPTION + Pure function: the time is passed in, so callers and tests control it. Accepts the seed as + Control stores it for authenticator apps ("ms:", e.g. from New-CWCMFA) or as bare Base32; + case, spaces, dashes and '=' padding are ignored. + + The decoded key bytes are zeroed afterwards. The plain-text seed string taken from the + SecureString can't be wiped (.NET strings are immutable); it is left for garbage collection. + + .PARAMETER Secret + The TOTP seed. + + .PARAMETER UnixTime + Seconds since 1970-01-01 UTC. + + .PARAMETER Digits + Code length. Control uses 6. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory = $True)] + [securestring]$Secret, + + [Parameter(Mandatory = $True)] + [int64]$UnixTime, + + [ValidateRange(6, 8)] + [int]$Digits = 6 + ) + + $Key = $null + $Hash = $null + $Hmac = $null + try { + $Key = ConvertFrom-CWCBase32 -Text ((ConvertFrom-CWCSecureString $Secret) -replace '^\s*ms:', '') + + # The counter is the 30-second step number as a big-endian 64-bit integer + $Counter = [BitConverter]::GetBytes([int64][math]::Floor($UnixTime / 30)) + if ([BitConverter]::IsLittleEndian) { [array]::Reverse($Counter) } + + # (,$Key) passes the byte array as one argument instead of one argument per byte + $Hmac = New-Object System.Security.Cryptography.HMACSHA1 (, $Key) + $Hash = $Hmac.ComputeHash($Counter) + + # Dynamic truncation (RFC 4226 section 5.3) + $Offset = $Hash[$Hash.Length - 1] -band 0x0F + $Binary = (([int64]($Hash[$Offset] -band 0x7F)) -shl 24) -bor + (([int64]$Hash[$Offset + 1]) -shl 16) -bor + (([int64]$Hash[$Offset + 2]) -shl 8) -bor + ([int64]$Hash[$Offset + 3]) + $Modulus = [int64][math]::Pow(10, $Digits) + ($Binary % $Modulus).ToString().PadLeft($Digits, '0') + } + finally { + if ($Key) { [array]::Clear($Key, 0, $Key.Length) } + if ($Hash) { [array]::Clear($Hash, 0, $Hash.Length) } + if ($Hmac) { $Hmac.Dispose() } + } +} diff --git a/ConnectWiseControlAPI/Private/Get-CWCTotpLoginCode.ps1 b/ConnectWiseControlAPI/Private/Get-CWCTotpLoginCode.ps1 new file mode 100644 index 0000000..9a2e7ee --- /dev/null +++ b/ConnectWiseControlAPI/Private/Get-CWCTotpLoginCode.ps1 @@ -0,0 +1,42 @@ +function Get-CWCTotpLoginCode { + <# + .SYNOPSIS + The TOTP code to send for one login, waiting for a fresh time step when needed. + + .DESCRIPTION + Waits for the next 30-second step when: + - fewer than 3 seconds are left in this one, so the code doesn't expire in flight; + - this step was already used for the same server and user, because the server may reject a + code it has already accepted. + Only the step number is remembered (not secret); the code and the seed are never stored. + + .PARAMETER Key + Identifies the server and user, e.g. "server|user". + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory = $True)] + [securestring]$Secret, + + [Parameter(Mandatory = $True)] + [string]$Key + ) + + if (-not $script:CWCLastTotpStep) { $script:CWCLastTotpStep = @{} } + $Key = $Key.ToLowerInvariant() + + $Now = Get-CWCUnixTime + $Remaining = 30 - ($Now % 30) + $Step = [int64][math]::Floor($Now / 30) + if ($Remaining -lt 3 -or $script:CWCLastTotpStep[$Key] -eq $Step) { + Write-Verbose "Waiting $Remaining s for a new one-time code." + Start-Sleep -Seconds $Remaining + # Computed rather than read again, so the result doesn't depend on how long the sleep took + $Now += $Remaining + $Step++ + } + + $script:CWCLastTotpStep[$Key] = $Step + Get-CWCTotpCode -Secret $Secret -UnixTime $Now +} diff --git a/ConnectWiseControlAPI/Private/Get-CWCUnixTime.ps1 b/ConnectWiseControlAPI/Private/Get-CWCUnixTime.ps1 new file mode 100644 index 0000000..7c58020 --- /dev/null +++ b/ConnectWiseControlAPI/Private/Get-CWCUnixTime.ps1 @@ -0,0 +1,13 @@ +function Get-CWCUnixTime { + <# + .SYNOPSIS + Seconds since 1970-01-01 UTC. Its own function so tests can mock the clock. + (DateTimeOffset.ToUnixTimeSeconds needs .NET 4.6.) + #> + [CmdletBinding()] + [OutputType([int64])] + param() + + $Epoch = New-Object DateTime 1970, 1, 1, 0, 0, 0, ([DateTimeKind]::Utc) + [int64][math]::Floor(([DateTime]::UtcNow - $Epoch).TotalSeconds) +} diff --git a/ConnectWiseControlAPI/Private/Invoke-CWCLogout.ps1 b/ConnectWiseControlAPI/Private/Invoke-CWCLogout.ps1 new file mode 100644 index 0000000..562b80a --- /dev/null +++ b/ConnectWiseControlAPI/Private/Invoke-CWCLogout.ps1 @@ -0,0 +1,26 @@ +function Invoke-CWCLogout { + <# + .SYNOPSIS + Best-effort AuthenticationService.TryLogout for an MFA connection the module no longer uses, so + its login cookie stops working on the server too. Never fails the caller. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory = $True)] + [hashtable]$Connection + ) + + # Invoke-CWCServiceMethod sends on the module's connection: point it at the old one briefly + $Current = $script:CWCServerConnection + try { + $script:CWCServerConnection = $Connection + $null = Invoke-CWCServiceMethod -Service AuthenticationService -Method TryLogout -ErrorAction Stop + Write-Verbose "Logged out the previous MFA login to https://$($Connection.Server)." + } + catch { + Write-Verbose "Could not log out the previous MFA login: $($_.Exception.Message)" + } + finally { + $script:CWCServerConnection = $Current + } +} diff --git a/ConnectWiseControlAPI/Private/Invoke-CWCMfaLogin.ps1 b/ConnectWiseControlAPI/Private/Invoke-CWCMfaLogin.ps1 new file mode 100644 index 0000000..ae6f6cb --- /dev/null +++ b/ConnectWiseControlAPI/Private/Invoke-CWCMfaLogin.ps1 @@ -0,0 +1,164 @@ +function Invoke-CWCMfaLogin { + <# + .SYNOPSIS + Logs in the way the web client does (AuthenticationService.TryLogin with a one-time code) and + stores a cookie-based connection in $script:CWCServerConnection. Used by Connect-CWC. + + .DESCRIPTION + 1. Front page with a new WebRequestSession: cookies and the pre-login anti-forgery token. + 2. TryLogin(userName, password, oneTimePassword, shouldTrust = false, securityNonce = null). + Live-verified results: 1 = success (sets .ASPXAUTH), 11 = one-time code required, 10 = wrong code. + 3. Front page again: the anti-forgery token changes after login. + 4. Validation with PageService.GetEligibleHosts. + No Authorization header is sent; the .ASPXAUTH cookie carries the login. The password is used only + in the TryLogin body and is not stored. + + On failure it throws an ErrorRecord with one of these ErrorIds and leaves + $script:CWCServerConnection set to the half-built connection; Connect-CWC restores the state. + CWC.MfaRequired, CWC.MfaCodeRejected, CWC.LoginFailed, CWC.LoginThrottled, CWC.NoResponse. + + .PARAMETER Prompt + If the server asks for a one-time code (11), read it from the console. Covers email and SMS codes, + which the server sends only after this first TryLogin. + #> + [CmdletBinding(DefaultParameterSetName = 'Prompt')] + param( + [Parameter(Mandatory = $True)] + [string]$Server, + + [Parameter(Mandatory = $True)] + [pscredential]$Credentials, + + [Parameter(Mandatory = $True)] + [string]$IdentityHash, + + [Parameter(Mandatory = $True, ParameterSetName = 'Prompt')] + [switch]$Prompt, + + [Parameter(Mandatory = $True, ParameterSetName = 'OneTimeCode')] + [string]$OneTimeCode, + + [Parameter(Mandatory = $True, ParameterSetName = 'TotpSecret')] + [securestring]$TotpSecret + ) + + $Origin = "https://$Server" + $UserName = $Credentials.UserName + + function New-LoginError { + param([string]$Message, [string]$ErrorId, [System.Management.Automation.ErrorCategory]$Category) + New-Object System.Management.Automation.ErrorRecord ((New-Object Exception $Message), $ErrorId, $Category, $null) + } + + # GET the front page with the shared cookie jar; returns its anti-forgery token + function Get-FrontPageToken { + try { + $Page = Invoke-WebRequest -Uri $Origin -WebSession $WebSession -UseBasicParsing -ErrorAction Stop + } + catch { + throw (New-LoginError "Failed to connect to Control server '$Origin': $($_.Exception.Message)" 'CWC.NoResponse' ConnectionError) + } + Get-CWCAntiForgeryToken -Content $Page.Content + } + + # One TryLogin call. Never retried: each attempt counts toward the server's login limits. + function Invoke-TryLogin { + param([AllowNull()][string]$Code) + $Password = $Credentials.GetNetworkCredential().Password + try { + $Arguments = @($UserName, $Password, $Code, $False, $null) + Invoke-CWCServiceMethod -Service AuthenticationService -Method TryLogin -Arguments $Arguments -Sensitive -ErrorAction Stop + } + catch { + $Message = $_.Exception.Message + if ($_.FullyQualifiedErrorId -like 'CWC.Http*') { + if ($Message -match 'OperationLimit|RateLimit|Throttl|Too many') { + throw (New-LoginError "Login to '$Origin' was refused because of too many attempts. Wait before trying again. $Message" 'CWC.LoginThrottled' LimitsExceeded) + } + throw (New-LoginError "Login to '$Origin' failed: $Message" 'CWC.LoginFailed' AuthenticationError) + } + throw (New-LoginError "Connecting to '$Origin' failed before authentication could be checked: $Message" 'CWC.NoResponse' ConnectionError) + } + finally { + $Password = $null + $Arguments = $null + } + } + + $WebSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession + $Headers = @{ + 'content-type' = 'application/json; charset=utf-8' + 'origin' = $Origin + } + $Token = Get-FrontPageToken + if ($Token) { $Headers.'x-anti-forgery-token' = $Token } + + $script:CWCServerConnection = @{ + Server = $Server + AuthType = 'Mfa' + UserName = $UserName + IdentityHash = $IdentityHash + Headers = $Headers + WebSession = $WebSession + } + + switch ($PSCmdlet.ParameterSetName) { + 'Prompt' { + $Result = Invoke-TryLogin -Code $null + if ("$Result" -eq '11') { + $SecureCode = $null + try { $SecureCode = Read-Host -AsSecureString -Prompt "One-time code for $UserName" } + catch { Write-Verbose "Could not prompt for the one-time code: $($_.Exception.Message)" } + $Code = $null + if ($SecureCode -and $SecureCode.Length -gt 0) { $Code = (ConvertFrom-CWCSecureString $SecureCode).Trim() } + if (-not $Code) { + throw (New-LoginError ("The account '$UserName' requires a one-time code and none was entered. " + + 'In scripts, use -OneTimeCode or -TotpSecret.') 'CWC.MfaRequired' AuthenticationError) + } + $Result = Invoke-TryLogin -Code $Code + $Code = $null + } + } + 'OneTimeCode' { + $Result = Invoke-TryLogin -Code $OneTimeCode + } + 'TotpSecret' { + $Result = Invoke-TryLogin -Code (Get-CWCTotpLoginCode -Secret $TotpSecret -Key "$Server|$UserName") + } + } + + # SecurityOperationResult comes back as a bare number. Compare as text: Int32 on PS 5.1, Int64 on 7. + switch ("$Result") { + { $_ -in '1', 'Success' } { break } + '11' { + throw (New-LoginError "The account '$UserName' requires a one-time code. Use -Mfa, -OneTimeCode or -TotpSecret." 'CWC.MfaRequired' AuthenticationError) + } + '10' { + throw (New-LoginError ("The one-time code for '$UserName' was rejected: wrong, expired or already used. " + + 'With -TotpSecret, check that the secret is right and the computer clock is accurate.') 'CWC.MfaCodeRejected' AuthenticationError) + } + default { + throw (New-LoginError "Login to '$Origin' failed (result '$Result'). Check the username and password." 'CWC.LoginFailed' AuthenticationError) + } + } + + # The anti-forgery token is issued per login: fetch the new one + $Token = Get-FrontPageToken + if ($Token) { $Headers.'x-anti-forgery-token' = $Token } + else { + $Headers.Remove('x-anti-forgery-token') + Write-Warning 'Unable to find the anti-forgery token on the server front page. Commands that change sessions may fail with "Invalid anti-forgery token".' + } + + try { + # GetEligibleHosts requires any permission, so it validates non-admin accounts too + $null = Invoke-CWCServiceMethod -Service PageService -Method GetEligibleHosts -Idempotent -ErrorAction Stop + } + catch { + if ($_.FullyQualifiedErrorId -like 'CWC.Http*') { + throw (New-LoginError ("Logged in to '$Origin' as '$UserName', but the account can't use the API. " + + "Check that its role grants at least one permission. $($_.Exception.Message)") 'CWC.LoginFailed' AuthenticationError) + } + throw (New-LoginError "Connecting to '$Origin' failed after login: $($_.Exception.Message)" 'CWC.NoResponse' ConnectionError) + } +} diff --git a/ConnectWiseControlAPI/Private/Invoke-CWCServiceMethod.ps1 b/ConnectWiseControlAPI/Private/Invoke-CWCServiceMethod.ps1 index 9e2e336..cce3238 100644 --- a/ConnectWiseControlAPI/Private/Invoke-CWCServiceMethod.ps1 +++ b/ConnectWiseControlAPI/Private/Invoke-CWCServiceMethod.ps1 @@ -25,7 +25,7 @@ function Invoke-CWCServiceMethod { [CmdletBinding(DefaultParameterSetName = 'Service')] param( [Parameter(Mandatory = $True, ParameterSetName = 'Service')] - [ValidateSet('PageService', 'SecurityService', 'AuditService', 'SessionGroupService')] + [ValidateSet('PageService', 'SecurityService', 'AuditService', 'SessionGroupService', 'AuthenticationService')] [string]$Service, [Parameter(Mandatory = $True, ParameterSetName = 'RestApi')] diff --git a/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 b/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 index 83e2ede..b169682 100644 --- a/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 +++ b/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 @@ -75,9 +75,14 @@ # Type-name check: a [System.Net.Http.HttpRequestMessage] literal fails on PS 5.1 when the assembly isn't loaded. $FailedRequest = $_.TargetObject if ($FailedRequest -and $FailedRequest.GetType().FullName -in 'System.Net.Http.HttpRequestMessage', 'System.Net.HttpWebRequest') { - foreach ($SecretHeader in 'Authorization', 'CTRLAuthHeader', 'x-anti-forgery-token') { + # Cookie: the .ASPXAUTH login cookie of MFA and credentials connections + foreach ($SecretHeader in 'Authorization', 'CTRLAuthHeader', 'x-anti-forgery-token', 'Cookie') { try { $null = $FailedRequest.Headers.Remove($SecretHeader) } catch { Write-Verbose "Could not strip $SecretHeader from the failed request." } } + # PS 5.1's HttpWebRequest also references the whole cookie jar + if ($FailedRequest.PSObject.Properties['CookieContainer']) { + try { $FailedRequest.CookieContainer = $null } catch { Write-Verbose 'Could not strip the cookies from the failed request.' } + } # PS 6+ also keeps the request body on the HttpRequestMessage (e.g. a new user's password) if ($SensitiveBody -and $FailedRequest.PSObject.Properties['Content']) { try { $FailedRequest.Content = $null } catch { Write-Verbose 'Could not strip the body from the failed request.' } @@ -116,6 +121,13 @@ if ($ServerMessage) { $ErrorMessage += $ServerMessage } else { $ErrorMessage += "$_" } + # An expired MFA login makes requests run as an anonymous user: they fail with a permission + # error, or an anti-forgery error because the token belonged to the login. + if ($StatusCode -gt 0 -and $script:CWCServerConnection.AuthType -eq 'Mfa' -and + ("$ServerErrorType" -match 'Security' -or "$ServerMessage" -match 'anti-?forgery|Needs permission')) { + $ErrorMessage += 'If the MFA login has expired, run Connect-CWC again.' + } + if ($StatusCode -gt 0) { $ErrorId = "CWC.Http$StatusCode"; $Category = 'InvalidResult' } else { $ErrorId = 'CWC.NoResponse'; $Category = 'ConnectionError' } return Write-Error ($ErrorMessage -join ' ') -ErrorId $ErrorId -Category $Category diff --git a/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 b/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 index 65bf5d2..0c78240 100644 --- a/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 +++ b/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 @@ -4,10 +4,15 @@ function Connect-CWC { Connects to a ConnectWise Control server. .DESCRIPTION - Two authentication methods are supported: + Three ways to sign in: - -Credentials (default): Basic auth with a Control user account that does not use MFA. Gives - access to every function in the module, limited by that user's permissions. + -Credentials alone (default): Basic auth with a Control user account that does not use MFA. Gives + access to every function in the module, limited by that user's permissions. Never expires. + + -Credentials with -Mfa, -OneTimeCode or -TotpSecret: signs in the way the web page does, with a + one-time code, for accounts that require MFA. Gives the same access as -Credentials alone. The + login is a cookie that the server expires; when it does, commands fail with a permission error + and you run Connect-CWC again. The password and TOTP secret are not kept after the login. -ApiSecret: the authentication secret configured in the RESTful API Manager extension's RESTfulAuthenticationSecret setting, sent as the CTRLAuthHeader header. Works when every user @@ -15,14 +20,35 @@ function Connect-CWC { functions return an error telling you to connect with -Credentials. The connection is validated before it is cached. An existing connection to the same server with - the same method and identity (user or secret) is reused unless -Force is given; anything else - reconnects. + the same method and identity (user and password, or secret) is reused unless -Force is given; + anything else reconnects. A cached MFA login is checked with one call first and replaced with a + new login if it has expired. .PARAMETER Server Control server hostname, e.g. control.example.com. A leading http(s):// is removed. HTTPS is always used. .PARAMETER Credentials - Credentials for a Control user account without MFA. + Username and password of a Control user account. + + .PARAMETER Mfa + Sign in for an account that requires MFA, asking for the one-time code at the console when the + server requests it. Works with authenticator apps and with codes the server sends by email or + SMS (they are sent at this point). For interactive use only. + + .PARAMETER OneTimeCode + The current one-time code (6 to 8 digits) for an account that requires MFA. Quote it, so a + leading zero is kept. + + .PARAMETER TotpSecret + The account's authenticator-app (TOTP) secret, for unattended scripts. The current code is + computed from it at each login; the secret itself is not stored. Accepts the value Control stores + for authenticator apps ("ms:" followed by Base32, as New-CWCMFA creates) or bare Base32. + Not for email or SMS codes. + + Keep it in a secret store, e.g. Microsoft.PowerShell.SecretManagement: -TotpSecret (Get-Secret ...). + A TOTP secret stored next to the password turns MFA into a single factor: keep them in separate + vaults where you can, prefer -ApiSecret when its functions are enough, and replace the secret if + the computer is compromised. .PARAMETER ApiSecret The RESTful API Manager extension's RESTfulAuthenticationSecret value. @@ -39,6 +65,26 @@ function Connect-CWC { .EXAMPLE Connect-CWC -Server 'control.example.com' -Credentials (Get-Credential) + Connects with an account that does not use MFA. + + .EXAMPLE + Connect-CWC -Server 'control.example.com' -Credentials (Get-Credential) -Mfa + + Connects with an account that requires MFA and asks for the one-time code. + + .EXAMPLE + Connect-CWC -Server 'control.example.com' -Credentials $Credential -OneTimeCode (Read-Host 'One-time code') + + Connects with an account that requires MFA, using a code you supply. Reading it with Read-Host + keeps it out of the command history. + + .EXAMPLE + $Credential = Get-Secret -Name 'CWC-Login' + Connect-CWC -Server 'control.example.com' -Credentials $Credential -TotpSecret (Get-Secret -Name 'CWC-TOTP') + + Unattended login for an account that requires MFA. Run it again before each batch of work: when + the cached login is still valid it costs one call, and when it has expired it logs in again. + .EXAMPLE $Secret = Read-Host -AsSecureString -Prompt 'RESTful API secret' Connect-CWC -Server 'control.example.com' -ApiSecret $Secret @@ -53,6 +99,10 @@ function Connect-CWC { session group scoping, so it can act on every session. Treat it like an administrator password. Requires the RESTful API Manager extension (2d558935-686a-4bd0-9991-07539f5fe749). + MFA logins are never retried automatically: each attempt counts toward the server's login limits. + Errors carry an ErrorId: CWC.MfaRequired, CWC.MfaCodeRejected, CWC.LoginFailed, CWC.LoginThrottled + or CWC.NoResponse. The device is never marked as trusted, and the login is never saved to disk. + Author: Chris Taylor .LINK @@ -65,8 +115,21 @@ function Connect-CWC { [string]$Server, [Parameter(Mandatory = $True, ParameterSetName = 'Credentials')] + [Parameter(Mandatory = $True, ParameterSetName = 'Mfa')] + [Parameter(Mandatory = $True, ParameterSetName = 'OneTimeCode')] + [Parameter(Mandatory = $True, ParameterSetName = 'TotpSecret')] [pscredential]$Credentials, + [Parameter(Mandatory = $True, ParameterSetName = 'Mfa')] + [switch]$Mfa, + + [Parameter(Mandatory = $True, ParameterSetName = 'OneTimeCode')] + [ValidatePattern('^\d{6,8}$')] + [string]$OneTimeCode, + + [Parameter(Mandatory = $True, ParameterSetName = 'TotpSecret')] + [securestring]$TotpSecret, + [Parameter(Mandatory = $True, ParameterSetName = 'ApiSecret')] [securestring]$ApiSecret, @@ -77,21 +140,35 @@ function Connect-CWC { [switch]$Force ) - $Server = $Server -replace("http.*:\/\/",'') - $RequestedAuthType = $PSCmdlet.ParameterSetName + $Server = $Server -replace ("http.*:\/\/", '') + # The three MFA parameter sets are one auth method + $RequestedAuthType = switch ($PSCmdlet.ParameterSetName) { + 'Credentials' { 'Credentials' } + 'ApiSecret' { 'ApiSecret' } + default { 'Mfa' } + } + + if ($RequestedAuthType -eq 'ApiSecret' -and $ApiSecret.Length -eq 0) { throw 'ApiSecret cannot be empty.' } + if ($PSCmdlet.ParameterSetName -eq 'TotpSecret' -and $TotpSecret.Length -eq 0) { throw 'TotpSecret cannot be empty.' } if ($RequestedAuthType -eq 'Credentials') { $EncodedCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("$($Credentials.UserName):$($Credentials.GetNetworkCredential().Password)")) } + if ($RequestedAuthType -eq 'Mfa') { + $IdentityHash = Get-CWCIdentityHash -Credentials $Credentials + } - # Is the cached connection the same server, auth method and identity (user or secret) as requested? + # Is the cached connection the same server, auth method and identity as requested? $SameAsCached = $False - if ($script:CWCServerConnection) { - $Cached = $script:CWCServerConnection + $Cached = $script:CWCServerConnection + if ($Cached) { $CachedAuthType = if ($Cached.AuthType) { $Cached.AuthType } else { 'Credentials' } if ($Cached.Server -eq $Server -and $CachedAuthType -eq $RequestedAuthType) { - if ($RequestedAuthType -eq 'Credentials') { $SameAsCached = $Cached.Headers.authorization -eq "Basic $EncodedCredentials" } - else { $SameAsCached = (ConvertFrom-CWCSecureString $Cached.ApiSecret) -eq (ConvertFrom-CWCSecureString $ApiSecret) } + switch ($RequestedAuthType) { + 'Credentials' { $SameAsCached = $Cached.Headers.authorization -eq "Basic $EncodedCredentials" } + 'ApiSecret' { $SameAsCached = (ConvertFrom-CWCSecureString $Cached.ApiSecret) -eq (ConvertFrom-CWCSecureString $ApiSecret) } + 'Mfa' { $SameAsCached = [bool]$Cached.IdentityHash -and $Cached.IdentityHash -eq $IdentityHash } + } } } @@ -99,20 +176,33 @@ function Connect-CWC { # keeping the old connection would send later commands (including deletes) to the wrong server, or # run them as the wrong user. if ($SameAsCached -and !$Force) { - Write-Verbose "Using cached Authentication information." - return + if ($RequestedAuthType -ne 'Mfa') { + Write-Verbose 'Using cached Authentication information.' + return + } + # An MFA login is a cookie the server expires: check it is still accepted + try { + $null = Invoke-CWCServiceMethod -Service PageService -Method GetEligibleHosts -ErrorAction Stop + Write-Verbose 'Using the cached MFA login.' + return + } + catch { + Write-Verbose "The cached MFA login is no longer accepted; logging in again. $($_.Exception.Message)" + # Never restore an expired login + $SameAsCached = $False + } } # On failure, restore the previous connection only when this was a refresh of that same connection # (-Force). After a failed switch to another server, method or identity, stay disconnected. $PreviousConnection = $null - if ($SameAsCached) { $PreviousConnection = $script:CWCServerConnection } + if ($SameAsCached) { $PreviousConnection = $Cached } + # An MFA login this replaces is logged out at the end, so its cookie stops working on the server too + $OldMfaConnection = $null + if ($Cached -and $Cached.AuthType -eq 'Mfa') { $OldMfaConnection = $Cached } $script:CWCServerConnection = $null if ($RequestedAuthType -eq 'ApiSecret') { - if ($ApiSecret.Length -eq 0) { - throw 'ApiSecret cannot be empty.' - } if (-not $Origin) { $Origin = "https://$Server" } # Own copy, so the caller disposing their SecureString doesn't break later requests @@ -126,7 +216,7 @@ function Connect-CWC { AuthType = 'ApiSecret' ApiSecret = $StoredSecret Headers = @{ - 'content-type' = "application/json; charset=utf-8" + 'content-type' = 'application/json; charset=utf-8' 'origin' = $Origin } } @@ -143,61 +233,83 @@ function Connect-CWC { "extension is installed, its RESTfulAuthenticationSecret matches, and RESTfulAllowedOrigin is empty " + "or equals '$Origin' (see -Origin). $_") } - return } - - $Headers = @{ - 'authorization' = "Basic $EncodedCredentials" - 'content-type' = "application/json; charset=utf-8" - 'origin' = "https://$Server" + elseif ($RequestedAuthType -eq 'Mfa') { + $LoginParameters = @{ Server = $Server; Credentials = $Credentials; IdentityHash = $IdentityHash } + switch ($PSCmdlet.ParameterSetName) { + 'Mfa' { $LoginParameters.Prompt = $True } + 'OneTimeCode' { $LoginParameters.OneTimeCode = $OneTimeCode } + 'TotpSecret' { $LoginParameters.TotpSecret = $TotpSecret } + } + try { + Invoke-CWCMfaLogin @LoginParameters + Write-Verbose "Connected to Control server with an MFA login: https://$Server" + } + catch { + $script:CWCServerConnection = $PreviousConnection + Write-Verbose 'Authentication failed.' + # Keeps the ErrorId (CWC.MfaRequired, CWC.MfaCodeRejected, ...) for callers + $PSCmdlet.WriteError($_) + } } + else { + $Headers = @{ + 'authorization' = "Basic $EncodedCredentials" + 'content-type' = 'application/json; charset=utf-8' + 'origin' = "https://$Server" + } - # The WebRequestSession keeps the cookies the server sets (e.g. .ASPXAUTH) and sends them back on - # every later request, the way a browser does. The anti-forgery token is issued alongside them. - $WebSession = $null - try { - $FrontPage = Invoke-WebRequest -Uri $Headers.origin -Headers $Headers -UseBasicParsing -SessionVariable 'WebSession' - } - catch { - $script:CWCServerConnection = $PreviousConnection - Write-Error "Failed to connect to Control server 'https://$Server': $_" - return - } + # The WebRequestSession keeps the cookies the server sets (e.g. .ASPXAUTH) and sends them back on + # every later request, the way a browser does. The anti-forgery token is issued alongside them. + $WebSession = $null + $FrontPage = $null + try { + $FrontPage = Invoke-WebRequest -Uri $Headers.origin -Headers $Headers -UseBasicParsing -SessionVariable 'WebSession' + } + catch { + $script:CWCServerConnection = $PreviousConnection + Write-Error "Failed to connect to Control server 'https://$Server': $_" + } - # Match only a token-shaped value, so a change in the page's JSON key order can't break the - # capture (the old pattern required "isUserAdministrator" to follow) and no other page content is taken. - $Regex = [Regex]'antiForgeryToken":"([A-Za-z0-9+/=_-]{16,512})"' - $Match = $Regex.Match($FrontPage.content) - if ($Match.Success) { $Headers.'x-anti-forgery-token' = $Match.Groups[1].Value } - else { Write-Warning 'Unable to find the anti-forgery token on the server front page. Commands that change sessions may fail with "Invalid anti-forgery token".' } - - $script:CWCServerConnection = @{ - Server = $Server - AuthType = 'Credentials' - Headers = $Headers - WebSession = $WebSession - } - Write-Verbose "Connected to Control server: https://$Server" + if ($FrontPage) { + $Token = Get-CWCAntiForgeryToken -Content $FrontPage.content + if ($Token) { $Headers.'x-anti-forgery-token' = $Token } + else { Write-Warning 'Unable to find the anti-forgery token on the server front page. Commands that change sessions may fail with "Invalid anti-forgery token".' } - try{ - # GetEligibleHosts requires any permission, so it validates auth for non-admin accounts too - # (Get-CWCSessionGroup requires ManageSessionGroups). - $null = Invoke-CWCServiceMethod -Service PageService -Method GetEligibleHosts -Idempotent -ErrorAction Stop - Write-Verbose '$CWCServerConnection, variable initialized.' - } - catch{ - $script:CWCServerConnection = $PreviousConnection - Write-Verbose 'Authentication failed.' - if ($_.FullyQualifiedErrorId -like 'CWC.Http*') { - # The server answered and rejected the call. Bad credentials are not rejected with a 401: the - # request runs as an anonymous user and fails with "Needs permission", so name the likely causes. - Write-Error ("Authentication to 'https://$Server' failed. Check the username and password, that the " + - "account does not require MFA, and that its role grants at least one permission. $_") - } - else { - # No answer from the server (DNS, TLS, network) or a local PowerShell error: says nothing - # about the credentials. - Write-Error "Connecting to 'https://$Server' failed before authentication could be checked: $_" + $script:CWCServerConnection = @{ + Server = $Server + AuthType = 'Credentials' + Headers = $Headers + WebSession = $WebSession + } + Write-Verbose "Connected to Control server: https://$Server" + + try { + # GetEligibleHosts requires any permission, so it validates auth for non-admin accounts too + # (Get-CWCSessionGroup requires ManageSessionGroups). + $null = Invoke-CWCServiceMethod -Service PageService -Method GetEligibleHosts -Idempotent -ErrorAction Stop + Write-Verbose '$CWCServerConnection, variable initialized.' + } + catch { + $script:CWCServerConnection = $PreviousConnection + Write-Verbose 'Authentication failed.' + if ($_.FullyQualifiedErrorId -like 'CWC.Http*') { + # The server answered and rejected the call. Bad credentials are not rejected with a 401: the + # request runs as an anonymous user and fails with "Needs permission", so name the likely causes. + Write-Error ("Authentication to 'https://$Server' failed. Check the username and password, " + + 'that the account does not require MFA (for one that does, add -Mfa, -OneTimeCode or ' + + "-TotpSecret), and that its role grants at least one permission. $_") + } + else { + # No answer from the server (DNS, TLS, network) or a local PowerShell error: says nothing + # about the credentials. + Write-Error "Connecting to 'https://$Server' failed before authentication could be checked: $_" + } + } } } + + if ($OldMfaConnection -and -not [object]::ReferenceEquals($script:CWCServerConnection, $OldMfaConnection)) { + Invoke-CWCLogout -Connection $OldMfaConnection + } } diff --git a/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml b/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml index 4b2ea05..8c92bea 100644 --- a/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml +++ b/ConnectWiseControlAPI/en-US/ConnectWiseControlAPI-help.xml @@ -251,11 +251,15 @@ Connect CWC - Initializes the connection parameters for the module. + Connects to a ConnectWise Control server. - Initializes the connection parameters used by other commands in the module. + Three ways to sign in: + -Credentials alone (default): Basic auth with a Control user account that does not use MFA. Gives access to every function in the module, limited by that user's permissions. Never expires. + -Credentials with -Mfa, -OneTimeCode or -TotpSecret: signs in the way the web page does, with a one-time code, for accounts that require MFA. Gives the same access as -Credentials alone. The login is a cookie that the server expires; when it does, commands fail with a permission error and you run Connect-CWC again. The password and TOTP secret are not kept after the login. + -ApiSecret: the authentication secret configured in the RESTful API Manager extension's RESTfulAuthenticationSecret setting, sent as the CTRLAuthHeader header. Works when every user account requires MFA. Only functions backed by that extension are available (see NOTES); other functions return an error telling you to connect with -Credentials. + The connection is validated before it is cached. An existing connection to the same server with the same method and identity (user and password, or secret) is reused unless -Force is given; anything else reconnects. A cached MFA login is checked with one call first and replaced with a new login if it has expired. @@ -263,7 +267,7 @@ Server - The URL to your control server. + Control server hostname, e.g. control.example.com. A leading http(s):// is removed. HTTPS is always used. String @@ -275,7 +279,7 @@ Credentials - Credentials used to authenticate with the control server. + Username and password of a Control user account. PSCredential @@ -287,7 +291,7 @@ Force - Used to overwrite any information already loaded in the session. + Reconnect even when the cached connection is for the same server, method and identity. If that refresh fails, the previous connection is kept. A failed connection to a different server, method or identity leaves the module disconnected, so later commands can't reach the old server. SwitchParameter @@ -301,7 +305,157 @@ Server - The URL to your control server. + Control server hostname, e.g. control.example.com. A leading http(s):// is removed. HTTPS is always used. + + String + + String + + + None + + + Credentials + + Username and password of a Control user account. + + PSCredential + + PSCredential + + + None + + + TotpSecret + + The account's authenticator-app (TOTP) secret, for unattended scripts. The current code is computed from it at each login; the secret itself is not stored. Accepts the value Control stores for authenticator apps ("ms:" followed by Base32, as New-CWCMFA creates) or bare Base32. Not for email or SMS codes. + Keep it in a secret store, e.g. Microsoft.PowerShell.SecretManagement: -TotpSecret (Get-Secret ...). A TOTP secret stored next to the password turns MFA into a single factor: keep them in separate vaults where you can, prefer -ApiSecret when its functions are enough, and replace the secret if the computer is compromised. + + SecureString + + SecureString + + + None + + + Force + + Reconnect even when the cached connection is for the same server, method and identity. If that refresh fails, the previous connection is kept. A failed connection to a different server, method or identity leaves the module disconnected, so later commands can't reach the old server. + + + SwitchParameter + + + False + + + + Connect-CWC + + Server + + Control server hostname, e.g. control.example.com. A leading http(s):// is removed. HTTPS is always used. + + String + + String + + + None + + + Credentials + + Username and password of a Control user account. + + PSCredential + + PSCredential + + + None + + + OneTimeCode + + The current one-time code (6 to 8 digits) for an account that requires MFA. Quote it, so a leading zero is kept. + + String + + String + + + None + + + Force + + Reconnect even when the cached connection is for the same server, method and identity. If that refresh fails, the previous connection is kept. A failed connection to a different server, method or identity leaves the module disconnected, so later commands can't reach the old server. + + + SwitchParameter + + + False + + + + Connect-CWC + + Server + + Control server hostname, e.g. control.example.com. A leading http(s):// is removed. HTTPS is always used. + + String + + String + + + None + + + Credentials + + Username and password of a Control user account. + + PSCredential + + PSCredential + + + None + + + Mfa + + Sign in for an account that requires MFA, asking for the one-time code at the console when the server requests it. Works with authenticator apps and with codes the server sends by email or SMS (they are sent at this point). For interactive use only. + + + SwitchParameter + + + False + + + Force + + Reconnect even when the cached connection is for the same server, method and identity. If that refresh fails, the previous connection is kept. A failed connection to a different server, method or identity leaves the module disconnected, so later commands can't reach the old server. + + + SwitchParameter + + + False + + + + Connect-CWC + + Server + + Control server hostname, e.g. control.example.com. A leading http(s):// is removed. HTTPS is always used. String @@ -337,7 +491,7 @@ Force - Used to overwrite any information already loaded in the session. + Reconnect even when the cached connection is for the same server, method and identity. If that refresh fails, the previous connection is kept. A failed connection to a different server, method or identity leaves the module disconnected, so later commands can't reach the old server. SwitchParameter @@ -351,7 +505,7 @@ Server - The URL to your control server. + Control server hostname, e.g. control.example.com. A leading http(s):// is removed. HTTPS is always used. String @@ -363,7 +517,7 @@ Credentials - Credentials used to authenticate with the control server. + Username and password of a Control user account. PSCredential @@ -372,6 +526,43 @@ None + + Mfa + + Sign in for an account that requires MFA, asking for the one-time code at the console when the server requests it. Works with authenticator apps and with codes the server sends by email or SMS (they are sent at this point). For interactive use only. + + SwitchParameter + + SwitchParameter + + + False + + + OneTimeCode + + The current one-time code (6 to 8 digits) for an account that requires MFA. Quote it, so a leading zero is kept. + + String + + String + + + None + + + TotpSecret + + The account's authenticator-app (TOTP) secret, for unattended scripts. The current code is computed from it at each login; the secret itself is not stored. Accepts the value Control stores for authenticator apps ("ms:" followed by Base32, as New-CWCMFA creates) or bare Base32. Not for email or SMS codes. + Keep it in a secret store, e.g. Microsoft.PowerShell.SecretManagement: -TotpSecret (Get-Secret ...). A TOTP secret stored next to the password turns MFA into a single factor: keep them in separate vaults where you can, prefer -ApiSecret when its functions are enough, and replace the secret if the computer is compromised. + + SecureString + + SecureString + + + None + ApiSecret @@ -399,7 +590,7 @@ Force - Used to overwrite any information already loaded in the session. + Reconnect even when the cached connection is for the same server, method and identity. If that refresh fails, the previous connection is kept. A failed connection to a different server, method or identity leaves the module disconnected, so later commands can't reach the old server. SwitchParameter @@ -413,19 +604,56 @@ - + Functions available with -ApiSecret: Get-CWCSessionDetail, Update-CWCSessionName, Invoke-CWCCommand (queues the command; output is not retrieved), Find-CWCSession, New-CWCSession, Add-CWCSessionNote, Send-CWCSessionMessage, Send-CWCToolboxItem. Only calls that are safe to repeat (reads, "set to value" updates) are retried on HTTP 500. + The API secret is not tied to a Control user: the extension does not apply role permissions or session group scoping, so it can act on every session. Treat it like an administrator password. Requires the RESTful API Manager extension (2d558935-686a-4bd0-9991-07539f5fe749). + MFA logins are never retried automatically: each attempt counts toward the server's login limits. Errors carry an ErrorId: CWC.MfaRequired, CWC.MfaCodeRejected, CWC.LoginFailed, CWC.LoginThrottled or CWC.NoResponse. The device is never marked as trusted, and the login is never saved to disk. -------------------------- Example 1 -------------------------- - PS C:\> Connect-CWC -Server 'control.christaylor.codes' -Credentials $Credentials -Force + PS C:\> Connect-CWC -Server 'control.example.com' -Credentials (Get-Credential) - Sets connection information used by the module and overwrites any previously set information. + Connects with an account that does not use MFA. + + + + -------------------------- Example 2 -------------------------- + PS C:\> Connect-CWC -Server 'control.example.com' -Credentials (Get-Credential) -Mfa + + Connects with an account that requires MFA and asks for the one-time code. + + + + -------------------------- Example 3 -------------------------- + PS C:\> Connect-CWC -Server 'control.example.com' -Credentials $Credential -OneTimeCode (Read-Host 'One-time code') + + Connects with an account that requires MFA, using a code you supply. Reading it with Read-Host keeps it out of the command history. + + + + -------------------------- Example 4 -------------------------- + PS C:\> $Credential = Get-Secret -Name 'CWC-Login' +PS C:\> Connect-CWC -Server 'control.example.com' -Credentials $Credential -TotpSecret (Get-Secret -Name 'CWC-TOTP') + + Unattended login for an account that requires MFA. Run it again before each batch of work: when the cached login is still valid it costs one call, and when it has expired it logs in again. + + + + -------------------------- Example 5 -------------------------- + PS C:\> $Secret = Read-Host -AsSecureString -Prompt 'RESTful API secret' +PS C:\> Connect-CWC -Server 'control.example.com' -ApiSecret $Secret + + Connects with the RESTful API Manager extension's secret. - + + + https://github.com/christaylorcodes/ConnectWiseControlAPI + https://github.com/christaylorcodes/ConnectWiseControlAPI + + diff --git a/ConnectWiseControlAPI_Functions.md b/ConnectWiseControlAPI_Functions.md index 49b1a4b..adfa650 100644 --- a/ConnectWiseControlAPI_Functions.md +++ b/ConnectWiseControlAPI_Functions.md @@ -18,7 +18,7 @@ Create a new Remote Workforce security role Adds a note to a session. ### [Connect-CWC](Docs/Connect-CWC.md) -Initializes the connection parameters for the module. +Connects to a ConnectWise Control server. ### [Enter-CWCSession](Docs/Enter-CWCSession.md) Opens the ConnectWise Control Host client joined to a session, like Join in the web UI. diff --git a/Docs/Connect-CWC.md b/Docs/Connect-CWC.md index 64d1fb4..edc50a5 100644 --- a/Docs/Connect-CWC.md +++ b/Docs/Connect-CWC.md @@ -8,7 +8,7 @@ schema: 2.0.0 # Connect-CWC ## SYNOPSIS -Initializes the connection parameters for the module. +Connects to a ConnectWise Control server. ## SYNTAX @@ -18,27 +18,94 @@ Connect-CWC -Server -Credentials [-Force] [] ``` +### TotpSecret +``` +Connect-CWC -Server -Credentials -TotpSecret [-Force] [] +``` + +### OneTimeCode +``` +Connect-CWC -Server -Credentials -OneTimeCode [-Force] [] +``` + +### Mfa +``` +Connect-CWC -Server -Credentials [-Mfa] [-Force] + [] +``` + ### ApiSecret ``` Connect-CWC -Server -ApiSecret [-Origin ] [-Force] [] ``` ## DESCRIPTION -Initializes the connection parameters used by other commands in the module. +Three ways to sign in: + +-Credentials alone (default): Basic auth with a Control user account that does not use MFA. +Gives access to every function in the module, limited by that user's permissions. Never expires. + +-Credentials with -Mfa, -OneTimeCode or -TotpSecret: signs in the way the web page does, with a one-time +code, for accounts that require MFA. Gives the same access as -Credentials alone. The login is a cookie +that the server expires; when it does, commands fail with a permission error and you run Connect-CWC +again. The password and TOTP secret are not kept after the login. + +-ApiSecret: the authentication secret configured in the RESTful API Manager extension's +RESTfulAuthenticationSecret setting, sent as the CTRLAuthHeader header. Works when every user account +requires MFA. Only functions backed by that extension are available (see NOTES); other functions return +an error telling you to connect with -Credentials. + +The connection is validated before it is cached. An existing connection to the same server with the same +method and identity (user and password, or secret) is reused unless -Force is given; anything else +reconnects. A cached MFA login is checked with one call first and replaced with a new login if it has +expired. ## EXAMPLES ### Example 1 ```powershell -PS C:\> Connect-CWC -Server 'control.christaylor.codes' -Credentials $Credentials -Force +PS C:\> Connect-CWC -Server 'control.example.com' -Credentials (Get-Credential) +``` + +Connects with an account that does not use MFA. + +### Example 2 +```powershell +PS C:\> Connect-CWC -Server 'control.example.com' -Credentials (Get-Credential) -Mfa ``` -Sets connection information used by the module and overwrites any previously set information. +Connects with an account that requires MFA and asks for the one-time code. + +### Example 3 +```powershell +PS C:\> Connect-CWC -Server 'control.example.com' -Credentials $Credential -OneTimeCode (Read-Host 'One-time code') +``` + +Connects with an account that requires MFA, using a code you supply. +Reading it with Read-Host keeps it out of the command history. + +### Example 4 +```powershell +PS C:\> $Credential = Get-Secret -Name 'CWC-Login' +PS C:\> Connect-CWC -Server 'control.example.com' -Credentials $Credential -TotpSecret (Get-Secret -Name 'CWC-TOTP') +``` + +Unattended login for an account that requires MFA. +Run it again before each batch of work: when the cached login is still valid it costs one call, and when +it has expired it logs in again. + +### Example 5 +```powershell +PS C:\> $Secret = Read-Host -AsSecureString -Prompt 'RESTful API secret' +PS C:\> Connect-CWC -Server 'control.example.com' -ApiSecret $Secret +``` + +Connects with the RESTful API Manager extension's secret. ## PARAMETERS ### -Server -The URL to your control server. +Control server hostname, e.g. control.example.com. A leading http(s):// is removed. HTTPS is always used. ```yaml Type: String @@ -53,11 +120,67 @@ Accept wildcard characters: False ``` ### -Credentials -Credentials used to authenticate with the control server. +Username and password of a Control user account. ```yaml Type: PSCredential -Parameter Sets: Credentials +Parameter Sets: Credentials, TotpSecret, OneTimeCode, Mfa +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Mfa +Sign in for an account that requires MFA, asking for the one-time code at the console when the server +requests it. Works with authenticator apps and with codes the server sends by email or SMS (they are sent +at this point). For interactive use only. + +```yaml +Type: SwitchParameter +Parameter Sets: Mfa +Aliases: + +Required: True +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -OneTimeCode +The current one-time code (6 to 8 digits) for an account that requires MFA. +Quote it, so a leading zero is kept. + +```yaml +Type: String +Parameter Sets: OneTimeCode +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TotpSecret +The account's authenticator-app (TOTP) secret, for unattended scripts. +The current code is computed from it at each login; the secret itself is not stored. +Accepts the value Control stores for authenticator apps ("ms:" followed by Base32, as New-CWCMFA creates) +or bare Base32. Not for email or SMS codes. + +Keep it in a secret store, e.g. Microsoft.PowerShell.SecretManagement: -TotpSecret (Get-Secret ...). +A TOTP secret stored next to the password turns MFA into a single factor: keep them in separate vaults +where you can, prefer -ApiSecret when its functions are enough, and replace the secret if the computer is +compromised. + +```yaml +Type: SecureString +Parameter Sets: TotpSecret Aliases: Required: True @@ -99,7 +222,10 @@ Accept wildcard characters: False ``` ### -Force -Used to overwrite any information already loaded in the session. +Reconnect even when the cached connection is for the same server, method and identity. +If that refresh fails, the previous connection is kept. +A failed connection to a different server, method or identity leaves the module disconnected, so later +commands can't reach the old server. ```yaml Type: SwitchParameter @@ -122,5 +248,19 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## OUTPUTS ## NOTES +Functions available with -ApiSecret: Get-CWCSessionDetail, Update-CWCSessionName, Invoke-CWCCommand +(queues the command; output is not retrieved), Find-CWCSession, New-CWCSession, Add-CWCSessionNote, +Send-CWCSessionMessage, Send-CWCToolboxItem. +Only calls that are safe to repeat (reads, "set to value" updates) are retried on HTTP 500. + +The API secret is not tied to a Control user: the extension does not apply role permissions or session +group scoping, so it can act on every session. Treat it like an administrator password. +Requires the RESTful API Manager extension (2d558935-686a-4bd0-9991-07539f5fe749). + +MFA logins are never retried automatically: each attempt counts toward the server's login limits. +Errors carry an ErrorId: CWC.MfaRequired, CWC.MfaCodeRejected, CWC.LoginFailed, CWC.LoginThrottled or +CWC.NoResponse. The device is never marked as trusted, and the login is never saved to disk. ## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) diff --git a/README.md b/README.md index ce71aaf..e376895 100644 --- a/README.md +++ b/README.md @@ -50,11 +50,26 @@ Install-Module 'ConnectWiseControlAPI' * Requires your Control server to use https. -* One of two authentication methods: +* One of three authentication methods: * **Credentials** (`Connect-CWC -Credentials`): an account without MFA. Use a complex username and password. All functions except `Find-CWCSession` are available, limited by the account's permissions. + * **Credentials with MFA** (`Connect-CWC -Credentials` plus `-Mfa`, `-OneTimeCode` or `-TotpSecret`): + an account that requires MFA, signed in the way the web page does. Same functions as credentials. + `-Mfa` asks for the code at the console (authenticator app, email or SMS). `-TotpSecret` computes the + authenticator-app code for unattended scripts from the account's TOTP secret (`ms:...` or Base32); + keep that secret in a secret store, and note that storing it next to the password makes MFA a + single factor. The login expires on the server; run `Connect-CWC` again before each batch of work + (a still-valid login is reused with one check call). + + ```powershell + Connect-CWC -Server 'control.example.com' -Credentials (Get-Credential) -Mfa + + # Unattended, with Microsoft.PowerShell.SecretManagement + Connect-CWC -Server 'control.example.com' -Credentials (Get-Secret 'CWC-Login') -TotpSecret (Get-Secret 'CWC-TOTP') + ``` + * **API secret** (`Connect-CWC -ApiSecret`): install the **RESTful API Manager** extension and set its `RESTfulAuthenticationSecret` setting to a long random value. Works when every account requires MFA. Available functions: `Find-CWCSession`, `New-CWCSession`, `Get-CWCSessionDetail`, diff --git a/Tests/ConnectWiseControlAPI.Private.Tests.ps1 b/Tests/ConnectWiseControlAPI.Private.Tests.ps1 index 285f71f..4ea022f 100644 --- a/Tests/ConnectWiseControlAPI.Private.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Private.Tests.ps1 @@ -392,6 +392,211 @@ Describe 'Invoke-CWCWebRequest' { } } } + + Context 'MFA connection (#12)' { + BeforeAll { + InModuleScope 'ConnectWiseControlAPI' { + # HTTP 500 with a server error body; the failed request (with a login cookie) as TargetObject + $script:NewServerErrorRecord = { + param([string]$Body, $Request) + $exception = [System.Net.WebException]::new('Server Error') + $exception | Add-Member -NotePropertyName Response -NotePropertyValue ([PSCustomObject]@{ StatusCode = 500 }) -Force + $record = [System.Management.Automation.ErrorRecord]::new($exception, 'WebError', 'InvalidResult', $Request) + $record.ErrorDetails = [System.Management.Automation.ErrorDetails]::new($Body) + $record + } + } + } + + BeforeEach { + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection = @{ + Server = 'test.example.com' + AuthType = 'Mfa' + Headers = @{ 'origin' = 'https://test.example.com' } + WebSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession + } + } + } + + It 'sends the WebSession and no Authorization header' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest { [PSCustomObject]@{ Content = '{}' } } + $arguments = @{ Endpoint = 'Services/PageService.ashx/GetEligibleHosts'; Method = 'Post' } + $null = Invoke-CWCWebRequest -Arguments $arguments + Should -Invoke Invoke-WebRequest -Times 1 -ParameterFilter { $null -ne $WebSession } + $arguments.Headers.Keys | Should -Not -Contain 'authorization' + } + } + + It 'says the login may have expired on a permission error' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest { throw (& $script:NewServerErrorRecord '{"errorType":"SecurityException","message":"Needs permission"}' $null) } + $result = Invoke-CWCWebRequest -Arguments @{ Endpoint = 'Services/PageService.ashx/GetSessionDetails'; Method = 'Post' } -ErrorAction SilentlyContinue -ErrorVariable err + "$err" | Should -Match 'MFA login has expired' + @($err | Where-Object { $_.FullyQualifiedErrorId -like 'CWC.Http500*' }).Count | Should -BeGreaterThan 0 + } + } + + It 'says the login may have expired on an anti-forgery error' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest { throw (& $script:NewServerErrorRecord '{"errorType":"InvalidOperationException","message":"Invalid anti-forgery token"}' $null) } + $null = Invoke-CWCWebRequest -Arguments @{ Endpoint = 'Services/PageService.ashx/AddSessionEvents'; Method = 'Post' } -ErrorAction SilentlyContinue -ErrorVariable err + "$err" | Should -Match 'MFA login has expired' + } + } + + It 'does not add the hint on a credentials connection' { + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection.AuthType = 'Credentials' + Mock Invoke-WebRequest { throw (& $script:NewServerErrorRecord '{"errorType":"SecurityException","message":"Needs permission"}' $null) } + $null = Invoke-CWCWebRequest -Arguments @{ Endpoint = 'Services/PageService.ashx/GetSessionDetails'; Method = 'Post' } -ErrorAction SilentlyContinue -ErrorVariable err + "$err" | Should -Not -Match 'MFA login' + } + } + + It 'strips the login cookie from the failed request kept on the error record' { + InModuleScope 'ConnectWiseControlAPI' { + $script:FailedRequest = [System.Net.WebRequest]::Create('https://test.example.com/Services/PageService.ashx/GetSessionDetails') + $script:FailedRequest.Headers.Add('Cookie', '.ASPXAUTH=cookiesecretvalue') + $script:FailedRequest.CookieContainer = New-Object System.Net.CookieContainer + Mock Invoke-WebRequest { throw (& $script:NewServerErrorRecord '{"errorType":"SecurityException","message":"Needs permission"}' $script:FailedRequest) } + $null = Invoke-CWCWebRequest -Arguments @{ Endpoint = 'Services/PageService.ashx/GetSessionDetails'; Method = 'Post' } -ErrorAction SilentlyContinue + $script:FailedRequest.Headers['Cookie'] | Should -BeNullOrEmpty + $script:FailedRequest.CookieContainer | Should -BeNullOrEmpty + } + } + } +} + +# ============================================================================= +# MFA helpers (#12) +# ============================================================================= +Describe 'Get-CWCTotpCode' { + + # RFC 6238 appendix B test key "12345678901234567890" in Base32 + It 'matches the RFC 6238 SHA-1 test vector at T=