-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1st-RdpMonSecurityAnalyzer.ps1
More file actions
executable file
·4036 lines (3393 loc) · 131 KB
/
Copy path1st-RdpMonSecurityAnalyzer.ps1
File metadata and controls
executable file
·4036 lines (3393 loc) · 131 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#requires -Version 7.5
#requires -PSEdition Core
<#
.SYNOPSIS
1st rdpmon Security Analyzer
Advanced RDP Monitor Analyzer for Cameyo RdpMon LiteDB database with auto-installation
Reads and analyzes RDP authentication attempts with professional reporting
.DESCRIPTION
PowerShell module to query and analyze RDP login attempts stored in Cameyo RdpMon LiteDB database.
Provides comprehensive filtering, multiple output formats, modern HTML reporting with auto-refresh,
and automatic LiteDB installation from GitHub releases.
.AUTHOR
Mikhail Deynekin [deynekin.com]
GitHub Repository: https://github.com/paulmann/1st-rdpmon
.VERSION
1.0.0
.LICENSE
MIT License
.NOTES
Requires PowerShell 7.5+ and LiteDB 5.0.21+ assembly
Compatible with Windows 7+/Server 2008R2+
Modern HTML reports use Tailwind CSS CDN for responsive design
Features automatic LiteDB installation from GitHub releases
.PARAMETER DbPath
Path to RdpMon LiteDB database file (.db)
.PARAMETER LiteDbPath
Custom path to LiteDB assembly (LiteDB.dll) or installation directory
.PARAMETER LiteDbInstallPath
Custom installation path for LiteDB auto-installation (default: $PSScriptRoot\LiteDB)
.PARAMETER AutoInstallLiteDb
Automatically install LiteDB from GitHub if not found (requires internet)
.PARAMETER LiteDbVersion
Specific LiteDB version to install (e.g., "4.1.4"). Default: 4.1.4 - Used in cameyo rdpmon
.PARAMETER ForceLiteDbInstall
Force reinstallation of LiteDB even if already present
.PARAMETER SkipLiteDbInstall
Skip automatic LiteDB installation even if not found
.PARAMETER Type
Filter by connection type: All, Attack, Legit, Unknown
.PARAMETER MinFails
Minimum failed attempts threshold for filtering
.PARAMETER From
Start date/time filter (local time)
.PARAMETER To
End date/time filter (local time)
.PARAMETER OutputFormat
Output format: Table, List, Json, Csv, Xml, Html, Text, Yaml, Markdown, Object
.PARAMETER ExportPath
Export results to specified file path
.PARAMETER SortBy
Sort output by specified property
.PARAMETER Descending
Sort in descending order
.PARAMETER Limit
Limit number of results returned
.PARAMETER IncludeResolved
Include DNS-resolved hostnames for IP addresses
.PARAMETER AutoRefreshInterval
Auto-refresh interval in seconds for HTML reports (default: 30)
.PARAMETER HtmlTemplatePath
Path to custom HTML template file
.PARAMETER DebugMode
Enable detailed debugging output showing start, result, and end of each step
.PARAMETER NoProgress
Disable progress bars during LiteDB installation
.PARAMETER GitHubToken
GitHub API token for higher rate limits (optional)
.EXAMPLE
.\1st-RdpMonSecurityAnalyzer.ps1 -DbPath 'C:\Monitoring\RdpMon.db' -AutoInstallLiteDb
.EXAMPLE
.\1st-RdpMonSecurityAnalyzer.ps1 -DbPath 'C:\RdpMon.db' -LiteDbInstallPath 'C:\Libraries\LiteDB' -ForceLiteDbInstall
.EXAMPLE
.\1st-RdpMonSecurityAnalyzer.ps1 -DbPath 'C:\RdpMon.db' -LiteDbVersion "5.0.21" -OutputFormat Html -ExportPath 'report.html'
.EXAMPLE
.\1st-RdpMonSecurityAnalyzer.ps1 -DbPath 'C:\RdpMon.db' -AutoInstallLiteDb -DebugMode
.LINK
https://github.com/cameyo/rdpmon
https://deynekin.com
https://github.com/mbdavid/LiteDB
#>
using namespace System.IO
using namespace System.Collections.Generic
using namespace System.Collections.Specialized
using namespace System.Net.Http
using namespace System.Text.Json
using namespace System.Text.Encodings.Web
using namespace System.Text.Json
[CmdletBinding(DefaultParameterSetName = 'Default')]
param(
# Path to RdpMon LiteDB database file (.db)
[Parameter(Mandatory, Position = 0)]
[ValidateScript({
if (-not (Test-Path -Path $_ -PathType Leaf)) {
throw "Database file not found: $_"
}
if ($_ -notmatch '\.db$') {
throw "File must have .db extension: $_"
}
$true
})]
[Alias('Database', 'Path')]
[string]$DbPath,
# Custom path to LiteDB assembly (LiteDB.dll) or installation directory
[Parameter()]
[ValidateScript({
if ($_ -and -not (Test-Path -Path $_)) {
throw "Path not found: $_"
}
$true
})]
[string]$LiteDbPath,
# Add these parameters after existing ones in the param() block
[Parameter()]
[switch]$RepairDatabase,
[Parameter()]
[switch]$ExportRawData,
[Parameter()]
[string]$RepairOutputPath,
[Parameter()]
[string]$RawExportPath = "RdpMon_RawExport.csv",
# Custom installation path for LiteDB auto-installation
[Parameter()]
[string]$LiteDbInstallPath,
# Automatically install LiteDB from GitHub if not found
[Parameter()]
[switch]$AutoInstallLiteDb,
# Specific LiteDB version to install
[Parameter()]
[ValidatePattern('^(\d+\.\d+\.\d+|latest)$')]
[string]$LiteDbVersion = 'latest',
# Force reinstallation of LiteDB even if already present
[Parameter()]
[switch]$ForceLiteDbInstall,
# Skip automatic LiteDB installation even if not found
[Parameter()]
[switch]$SkipLiteDbInstall,
# Filter by connection type: All, Attack, Legit, Unknown
[Parameter(Position = 1)]
[ValidateSet('All', 'Attack', 'Legit', 'Unknown')]
[string]$Type = 'All',
# Minimum failed attempts threshold for filtering
[Parameter()]
[ValidateRange(0, [int]::MaxValue)]
[int]$MinFails = 0,
# Start date/time filter (local time)
[Parameter()]
[datetime]$From = [datetime]::MinValue,
# End date/time filter (local time)
[Parameter()]
[datetime]$To = [datetime]::MaxValue,
# Filter by IP address (single IPv4/IPv6 or string key in Addr._id)
[Parameter()]
[ValidatePattern('^[0-9a-fA-F\.:]+$')]
[string]$IpAddress,
# Output format: Table, List, Json, Csv, Xml, Html, Text, Yaml, Markdown, Object
[Parameter()]
[ValidateSet('Table', 'List', 'Json', 'Csv', 'Xml', 'Html', 'Text', 'Yaml', 'Markdown', 'Object')]
[string]$OutputFormat = 'Table',
# Export results to specified file path
[Parameter()]
[string]$ExportPath,
# Sort output by specified property
[Parameter()]
[ValidateSet('IP', 'FailCount', 'SuccessCount', 'FirstLocal', 'LastLocal', 'Duration')]
[string]$SortBy = 'LastLocal',
# Sort in descending order
[Parameter()]
[switch]$Descending,
# Limit number of results returned
[Parameter()]
[ValidateRange(1, 1000)]
[int]$Limit = [int]::MaxValue,
# Include DNS-resolved hostnames for IP addresses
[Parameter()]
[switch]$IncludeResolved,
# Auto-refresh interval in seconds for HTML reports
[Parameter()]
[ValidateRange(5, 3600)]
[int]$AutoRefreshInterval = 30,
# Path to custom HTML template file
[Parameter()]
[string]$HtmlTemplatePath,
# Enable detailed debugging output showing start, result, and end of each step
[Parameter()]
[switch]$DebugMode,
# Disable progress bars during LiteDB installation
[Parameter()]
[switch]$NoProgress,
# GitHub API token for higher rate limits
[Parameter()]
[string]$GitHubToken
)
#region Global Configuration
# ============================================================================
# GLOBAL CONFIGURATION SECTION
# ============================================================================
# LiteDB installation configuration
$global:LiteDbConfig = @{
# Default installation path (relative to script directory)
DefaultInstallPath = Join-Path -Path $PSScriptRoot -ChildPath "LiteDB"
# GitHub repository information
GitHubRepoOwner = "mbdavid"
GitHubRepoName = "LiteDB"
# GitHub API configuration
GitHubApiBaseUrl = "https://api.github.com"
GitHubReleasesUrl = "https://api.github.com/repos/{0}/{1}/releases"
GitHubRawBaseUrl = "https://github.com"
# LiteDB assembly names (in order of preference)
AssemblyNames = @("LiteDB.dll", "LiteDB.v5.dll", "LiteDB.NET.dll", "LiteDB.5.dll")
# Asset name patterns to look for
AssetPatterns = @(
"LiteDB.*.zip", # Source code archives
"LiteDB.*.nupkg", # NuGet packages
"LiteDB.*win*.zip", # Windows binaries
"*.zip" # Generic zip files
)
# Required .NET versions
RequiredNetVersions = @("netstandard2.0", "netcoreapp3.1", "net5.0", "net6.0", "net7.0", "net8.0")
# Cache directory for downloads
CacheDirectory = Join-Path -Path $env:TEMP -ChildPath "LiteDBCache"
}
# Script execution configuration
$global:ScriptConfig = @{
Name = "1st-RdpMonSecurityAnalyzer.ps1"
Version = "1.0.0"
MinimumPowerShellVersion = [Version]"7.5.0"
MinimumLiteDbVersion = [Version]"4.1.4"
Git = "https://github.com/paulmann/1st-rdpmon"
UserAgent = "RdpMon-PowerShell/3.0.0 (+https://github.com/paulmann/1st-rdpmon)"
HTMLTemplate = "1st-RdpMonSecurityAnalyzer.html"
TimeoutSeconds = 30
RetryAttempts = 3
RetryDelayMs = 1000
}
# Performance and cache configuration
$global:PerformanceConfig = @{
EnableAssemblyCache = $true
MaxAssemblyCacheSize = 5
EnableDnsCache = $true
MaxDnsCacheSize = 100
EnableDownloadCache = $true
MaxCacheAgeDays = 7
}
# UI and output configuration
$global:UiConfig = @{
ProgressStyle = 'Detailed' # Simple, Detailed, Minimal, None
ColorOutput = $true
EnableUnicode = $true
ShowBanner = $true
ShowSummary = $true
}
# Debug and logging configuration
$global:DebugConfig = @{
Enabled = $DebugMode
LogLevel = 'Verbose' # Error, Warning, Info, Verbose, Debug
LogToFile = $false
LogFilePath = Join-Path -Path $env:TEMP -ChildPath "RdpMonAnalyzer.log"
}
# Initialize global variables
$global:ScriptStartTime = Get-Date
$global:ScriptPhase = "Initialization"
$global:LiteDbAssembly = $null
$global:DatabaseConnection = $null
$global:DatabaseCollection = $null
$global:TotalRecordsProcessed = 0
$global:FilteredRecords = 0
$global:ResultsCollection = @()
$global:ResolvedHostnamesCache = @{}
$global:StepCounter = 0
$global:LastOperationStatus = "Not Started"
$global:OperationStartTime = $null
# Apply parameter overrides
if ($DebugMode) { $global:DebugConfig.Enabled = $true }
if ($NoProgress) { $global:UiConfig.ProgressStyle = 'None' }
if ($LiteDbInstallPath) { $global:LiteDbConfig.DefaultInstallPath = $LiteDbInstallPath }
#endregion
#region Core Functions
function Write-DebugStep {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$Phase,
[Parameter(Mandatory)]
[string]$Message,
[Parameter()]
[object]$Data = $null,
[Parameter()]
[ValidateSet('Start', 'Progress', 'Complete', 'Error', 'Warning', 'Info')]
[string]$Type = 'Progress'
)
if (-not $global:DebugConfig.Enabled) {
return
}
$global:StepCounter++
$timestamp = Get-Date -Format "HH:mm:ss.fff"
$stepFormatted = $global:StepCounter.ToString("D3")
switch ($Type) {
'Start' {
$global:OperationStartTime = Get-Date
$global:ScriptPhase = $Phase
$global:LastOperationStatus = "Starting: $Message"
Write-Host "`n[$timestamp] ┌── STEP ${stepFormatted}: $Phase" -ForegroundColor Cyan
Write-Host "[$timestamp] │ START: $Message" -ForegroundColor Cyan
if ($Data) {
Write-Host "[$timestamp] │ DATA: $($Data | ConvertTo-Json -Depth 2 -Compress)" -ForegroundColor DarkCyan
}
}
'Progress' {
Write-Host "[$timestamp] │ INFO: $Message" -ForegroundColor Gray
if ($Data) {
Write-Host "[$timestamp] │ DATA: $($Data | ConvertTo-Json -Depth 2 -Compress)" -ForegroundColor DarkGray
}
}
'Complete' {
$duration = if ($global:OperationStartTime) {
[math]::Round(((Get-Date) - $global:OperationStartTime).TotalMilliseconds, 2)
}
else { 0 }
Write-Host "[$timestamp] │ COMPLETE: $Message" -ForegroundColor Green
Write-Host "[$timestamp] │ DURATION: ${duration}ms" -ForegroundColor DarkGreen
Write-Host "[$timestamp] └──" -ForegroundColor Cyan
$global:LastOperationStatus = "Completed: $Message"
}
'Error' {
Write-Host "[$timestamp] │ ERROR: $Message" -ForegroundColor Red
if ($Data) {
Write-Host "[$timestamp] │ DATA: $($Data | ConvertTo-Json -Depth 2 -Compress)" -ForegroundColor DarkRed
}
Write-Host "[$timestamp] └── [FAILED]" -ForegroundColor Red
$global:LastOperationStatus = "Failed: $Message"
}
'Warning' {
Write-Host "[$timestamp] │ WARNING: $Message" -ForegroundColor Yellow
if ($Data) {
Write-Host "[$timestamp] │ DATA: $($Data | ConvertTo-Json -Depth 2 -Compress)" -ForegroundColor DarkYellow
}
}
'Info' {
Write-Host "[$timestamp] │ INFO: $Message" -ForegroundColor Blue
if ($Data) {
Write-Host "[$timestamp] │ DATA: $($Data | ConvertTo-Json -Depth 2 -Compress)" -ForegroundColor DarkBlue
}
}
}
}
#region Database Diagnostics
function Get-RdpMonDatabaseStructure {
[CmdletBinding()]
param()
return Measure-Operation -Name "DatabaseDiagnostics" -ScriptBlock {
Write-DebugStep -Phase "DatabaseDiagnostics" -Message "Analyzing RdpMon database structure (safe mode)" -Type 'Start'
try {
# Get all collections using safe method
$collectionNames = @()
try {
$collectionNames = $global:DatabaseConnection.GetCollectionNames()
}
catch {
Write-DebugStep -Phase "DatabaseDiagnostics" -Message "Failed to get collection names, trying alternative method" -Type 'Warning' -Data @{ Error = $_.Exception.Message }
# Try to read directly from system collection
$systemCollection = $global:DatabaseConnection.GetCollection("_collections")
if ($systemCollection) {
foreach ($col in $systemCollection.FindAll()) {
if ($col.ContainsKey('name')) {
$collectionNames += $col['name']
}
}
}
}
if (-not $collectionNames -or $collectionNames.Count -eq 0) {
# If still no collections, try known RdpMon collections
$collectionNames = @("Addr", "Session", "Prop", "Process")
}
Write-DebugStep -Phase "DatabaseDiagnostics" -Message "Collections to analyze: $($collectionNames -join ', ')" -Type 'Info'
$structure = @{}
$errors = @()
foreach ($collectionName in $collectionNames) {
Write-DebugStep -Phase "DatabaseDiagnostics" -Message "Analyzing collection: $collectionName" -Type 'Progress'
try {
$collection = $null
try {
$collection = $global:DatabaseConnection.GetCollection($collectionName)
}
catch {
Write-DebugStep -Phase "DatabaseDiagnostics" -Message "Cannot access collection ${collectionName}, skipping" -Type 'Warning'
$errors += "Cannot access collection ${collectionName}: ${_}"
continue
}
$count = 0
try {
$count = $collection.Count()
}
catch {
Write-DebugStep -Phase "DatabaseDiagnostics" -Message "Cannot count collection $collectionName" -Type 'Warning'
$count = -1
}
if ($count -gt 0) {
# Get first record only for analysis - avoid reading damaged data
$sampleRecords = @()
try {
$firstRecord = $collection.FindById(1) # Try by ID first
if (-not $firstRecord) {
# Try to get any record
$enumerator = $collection.FindAll().GetEnumerator()
if ($enumerator.MoveNext()) {
$firstRecord = $enumerator.Current
}
}
if ($firstRecord) {
$recordAnalysis = @{}
foreach ($key in $firstRecord.Keys) {
if ($key -ne 'RawRecord' -and $key -ne '_raw') {
# Avoid circular references
$value = $firstRecord[$key]
$recordAnalysis[$key] = @{
Type = if ($value) { $value.GetType().Name } else { 'Null' }
Value = if ($value) { $value.ToString().Substring(0, [math]::Min(50, $value.ToString().Length)) } else { 'null' }
IsNull = $value -eq $null
}
}
}
$sampleRecords += $recordAnalysis
}
}
catch {
Write-DebugStep -Phase "DatabaseDiagnostics" -Message "Cannot read sample from ${collectionName}" -Type 'Warning'
$sampleRecords = @()
}
$structure[$collectionName] = @{
Count = $count
Sample = $sampleRecords
Fields = if ($sampleRecords.Count -gt 0) { ($sampleRecords[0].Keys | Sort-Object) -join ', ' } else { "Cannot read fields" }
Status = "OK"
}
}
elseif ($count -eq 0) {
$structure[$collectionName] = @{
Count = 0
Sample = @()
Fields = "Empty collection"
Status = "Empty"
}
}
else {
$structure[$collectionName] = @{
Count = -1
Sample = @()
Fields = "Cannot count"
Status = "Error"
}
}
}
catch {
Write-DebugStep -Phase "DatabaseDiagnostics" -Message "Failed to analyze collection ${collectionName}" -Type 'Error' -Data @{ Error = $_.Exception.Message }
$structure[$collectionName] = @{
Count = -1
Sample = @()
Fields = "Error"
Status = "Failed: $_"
}
$errors += "Collection ${collectionName}: ${_}"
}
}
Write-DebugStep -Phase "DatabaseDiagnostics" -Message "Database structure analysis completed (with errors)" -Type 'Complete' -Data @{
Collections = $collectionNames
Structure = $structure
ErrorCount = $errors.Count
}
if ($errors.Count -gt 0) {
Write-Host "WARNING: Database has $($errors.Count) errors. Some data may be corrupted." -ForegroundColor Yellow
foreach ($error in $errors) {
Write-Host " - $error" -ForegroundColor DarkYellow
}
}
return @{
Collections = $collectionNames
Structure = $structure
Errors = $errors
IsCorrupted = ($errors.Count -gt 0)
}
}
catch {
Write-DebugStep -Phase "DatabaseDiagnostics" -Message "Failed to analyze database structure completely" -Type 'Error' -Data @{ Error = $_.Exception.Message }
# Return minimal structure
return @{
Collections = @("Addr", "Session", "Prop", "Process")
Structure = @{}
Errors = @("Complete analysis failed: $_")
IsCorrupted = $true
}
}
}
}
#endregion
function Measure-Operation {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$Name,
[Parameter(Mandatory)]
[ScriptBlock]$ScriptBlock,
[Parameter()]
[object[]]$ArgumentList = @(),
[Parameter()]
[switch]$SuppressDebug
)
if (-not $SuppressDebug) {
Write-DebugStep -Phase $Name -Message "Starting operation" -Type 'Start'
}
try {
$result = & $ScriptBlock @ArgumentList
if (-not $SuppressDebug) {
Write-DebugStep -Phase $Name -Message "Operation completed successfully" -Type 'Complete'
}
return $result
}
catch {
if (-not $SuppressDebug) {
Write-DebugStep -Phase $Name -Message "Operation failed: $_" -Type 'Error' -Data @{ Error = $_.Exception.Message }
}
throw
}
}
function Show-Progress {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$Activity,
[Parameter()]
[string]$Status,
[Parameter()]
[int]$PercentComplete = -1,
[Parameter()]
[int]$SecondsRemaining = -1,
[Parameter()]
[switch]$Completed
)
if ($global:UiConfig.ProgressStyle -eq 'None') {
return
}
switch ($global:UiConfig.ProgressStyle) {
'Detailed' {
if ($Completed) {
Write-Progress -Activity $Activity -Completed
}
else {
$params = @{
Activity = $Activity
Status = $Status
}
if ($PercentComplete -ge 0) {
$params.PercentComplete = $PercentComplete
}
if ($SecondsRemaining -ge 0) {
$params.SecondsRemaining = $SecondsRemaining
}
Write-Progress @params
}
}
'Simple' {
if (-not $Completed) {
Write-Host "[$(Get-Date -Format 'HH:mm:ss')] ${Activity}: ${Status}" -ForegroundColor Gray
}
}
'Minimal' {
if (-not $Completed) {
Write-Host "." -NoNewline -ForegroundColor Gray
}
else {
Write-Host ""
}
}
}
}
#endregion
#region LiteDB Installation Functions
function Install-LiteDbAutomatically {
[CmdletBinding()]
param(
[Parameter()]
[string]$InstallPath = $global:LiteDbConfig.DefaultInstallPath,
[Parameter()]
[string]$Version = 'latest',
[Parameter()]
[switch]$Force,
[Parameter()]
[switch]$NoProgress
)
return Measure-Operation -Name "AutoInstallLiteDb" -ScriptBlock {
Write-DebugStep -Phase "AutoInstallLiteDb" -Message "Starting automatic LiteDB installation" -Type 'Start' -Data @{
InstallPath = $InstallPath
Version = $Version
Force = $Force
}
# Check if already installed
$existingInstall = Test-LiteDbInstallation -InstallPath $InstallPath
if ($existingInstall.Installed -and -not $Force) {
Write-DebugStep -Phase "AutoInstallLiteDb" -Message "LiteDB already installed, skipping installation" -Type 'Info' -Data @{
Version = $existingInstall.Version
Path = $existingInstall.AssemblyPath
}
return $existingInstall.AssemblyPath
}
# Ensure install directory exists
if (-not (Test-Path -Path $InstallPath)) {
Write-DebugStep -Phase "AutoInstallLiteDb" -Message "Creating installation directory" -Type 'Progress' -Data @{ Path = $InstallPath }
New-Item -ItemType Directory -Path $InstallPath -Force | Out-Null
}
# Step 1: Get release information from GitHub
Write-DebugStep -Phase "AutoInstallLiteDb" -Message "Fetching LiteDB release information from GitHub" -Type 'Progress'
$releaseInfo = Get-LiteDbGitHubRelease -Version $Version
if (-not $releaseInfo) {
throw "Failed to get LiteDB release information from GitHub"
}
Write-DebugStep -Phase "AutoInstallLiteDb" -Message "Found release: $($releaseInfo.TagName)" -Type 'Info' -Data @{
Version = $releaseInfo.TagName
Assets = $releaseInfo.Assets.Count
}
# Step 2: Download and extract the release
Write-DebugStep -Phase "AutoInstallLiteDb" -Message "Downloading and extracting LiteDB release" -Type 'Progress'
$extractedPath = Install-LiteDbFromGitHubRelease -Release $releaseInfo -InstallPath $InstallPath -NoProgress:$NoProgress
if (-not $extractedPath -or -not (Test-Path -Path $extractedPath)) {
throw "Failed to download and extract LiteDB release"
}
# Step 3: Find and verify LiteDB assembly
Write-DebugStep -Phase "AutoInstallLiteDb" -Message "Locating LiteDB assembly in extracted files" -Type 'Progress'
$assemblyPath = Find-LiteDbAssembly -SearchPath $extractedPath
if (-not $assemblyPath) {
throw "Could not find LiteDB assembly in the downloaded release"
}
# Step 4: Copy assembly to install directory
Write-DebugStep -Phase "AutoInstallLiteDb" -Message "Copying LiteDB assembly to installation directory" -Type 'Progress' -Data @{
Source = $assemblyPath
Destination = $InstallPath
}
$targetAssemblyPath = Join-Path -Path $InstallPath -ChildPath (Split-Path -Leaf $assemblyPath)
Copy-Item -Path $assemblyPath -Destination $targetAssemblyPath -Force
# Step 5: Verify the assembly can be loaded
Write-DebugStep -Phase "AutoInstallLiteDb" -Message "Verifying assembly can be loaded" -Type 'Progress'
try {
$assembly = Add-Type -Path $targetAssemblyPath -ErrorAction Stop -PassThru
Write-DebugStep -Phase "AutoInstallLiteDb" -Message "Assembly loaded successfully" -Type 'Info' -Data @{
FullName = $assembly.FullName
Location = $assembly.Location
}
}
catch {
Write-DebugStep -Phase "AutoInstallLiteDb" -Message "Failed to load assembly" -Type 'Warning' -Data @{ Error = $_.Exception.Message }
# Try to load via reflection as fallback
$assemblyBytes = [System.IO.File]::ReadAllBytes($targetAssemblyPath)
[System.Reflection.Assembly]::Load($assemblyBytes) | Out-Null
Write-DebugStep -Phase "AutoInstallLiteDb" -Message "Assembly loaded via reflection" -Type 'Info'
}
# Step 6: Create version file
$versionFile = Join-Path -Path $InstallPath -ChildPath "version.txt"
Set-Content -Path $versionFile -Value $releaseInfo.TagName -Encoding UTF8
Write-DebugStep -Phase "AutoInstallLiteDb" -Message "LiteDB installation completed successfully" -Type 'Complete' -Data @{
Version = $releaseInfo.TagName
InstallPath = $InstallPath
AssemblyPath = $targetAssemblyPath
}
return $targetAssemblyPath
}
}
function Get-LiteDbGitHubRelease {
[CmdletBinding()]
param(
[Parameter()]
[string]$Version = 'latest'
)
return Measure-Operation -Name "GetGitHubRelease" -ScriptBlock {
$owner = $global:LiteDbConfig.GitHubRepoOwner
$repo = $global:LiteDbConfig.GitHubRepoName
Write-DebugStep -Phase "GetGitHubRelease" -Message "Fetching LiteDB release from GitHub" -Type 'Progress' -Data @{
Owner = $owner
Repo = $repo
Version = $Version
}
# Build GitHub API URL
$apiUrl = if ($Version -eq 'latest') {
"$($global:LiteDbConfig.GitHubApiBaseUrl)/repos/$owner/$repo/releases/latest"
}
else {
"$($global:LiteDbConfig.GitHubApiBaseUrl)/repos/$owner/$repo/releases/tags/$Version"
}
# Prepare headers
$headers = @{
'Accept' = 'application/vnd.github+json'
'User-Agent' = $global:ScriptConfig.UserAgent
'X-GitHub-Api-Version' = '2022-11-28'
}
# Add token if provided
if ($GitHubToken) {
$headers.Authorization = "Bearer $GitHubToken"
}
try {
Show-Progress -Activity "Fetching LiteDB Release" -Status "Connecting to GitHub API..." -PercentComplete 25
# Make API request with retry logic
$maxRetries = $global:ScriptConfig.RetryAttempts
$retryCount = 0
while ($true) {
try {
$response = Invoke-RestMethod -Uri $apiUrl -Method Get -Headers $headers -TimeoutSec $global:ScriptConfig.TimeoutSeconds
break
}
catch {
$retryCount++
if ($retryCount -ge $maxRetries) {
throw "Failed to fetch GitHub release after $maxRetries attempts: $_"
}
Write-DebugStep -Phase "GetGitHubRelease" -Message "Request failed, retrying ($retryCount/$maxRetries)" -Type 'Warning' -Data @{ Error = $_.Exception.Message }
Start-Sleep -Milliseconds ($global:ScriptConfig.RetryDelayMs * $retryCount)
}
}
Show-Progress -Activity "Fetching LiteDB Release" -Status "Processing release data..." -PercentComplete 75
# Parse response
$releaseInfo = @{
TagName = $response.tag_name
Name = $response.name
PublishedAt = $response.published_at
Assets = $response.assets
Body = $response.body
Url = $response.html_url
IsPrerelease = $response.prerelease
AssetsCount = $response.assets.Count
}
Show-Progress -Activity "Fetching LiteDB Release" -Status "Completed" -PercentComplete 100 -Completed
Write-DebugStep -Phase "GetGitHubRelease" -Message "Successfully fetched release information" -Type 'Progress' -Data @{
TagName = $releaseInfo.TagName
AssetsCount = $releaseInfo.AssetsCount
}
return $releaseInfo
}
catch {
Show-Progress -Activity "Fetching LiteDB Release" -Status "Failed" -Completed
# Fallback: Try to get releases list and find the latest
if ($Version -eq 'latest') {
Write-DebugStep -Phase "GetGitHubRelease" -Message "Trying fallback method to get latest release" -Type 'Warning'
try {
$releasesUrl = "$($global:LiteDbConfig.GitHubApiBaseUrl)/repos/$owner/$repo/releases"
$allReleases = Invoke-RestMethod -Uri $releasesUrl -Method Get -Headers $headers -TimeoutSec $global:ScriptConfig.TimeoutSeconds
$latestRelease = $allReleases | Where-Object { -not $_.prerelease } | Select-Object -First 1
if ($latestRelease) {
$releaseInfo = @{
TagName = $latestRelease.tag_name
Name = $latestRelease.name
PublishedAt = $latestRelease.published_at
Assets = $latestRelease.assets
Body = $latestRelease.body
Url = $latestRelease.html_url
IsPrerelease = $latestRelease.prerelease
AssetsCount = $latestRelease.assets.Count
}
return $releaseInfo
}
}
catch {
# If all fails, throw the original error
throw "Failed to fetch LiteDB release from GitHub: $_"
}
}
throw "Failed to fetch LiteDB release from GitHub: $_"
}
}
}
function Install-LiteDbFromGitHubRelease {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[hashtable]$Release,
[Parameter()]
[string]$InstallPath,
[Parameter()]
[switch]$NoProgress
)
return Measure-Operation -Name "InstallFromGitHub" -ScriptBlock {
Write-DebugStep -Phase "InstallFromGitHub" -Message "Installing LiteDB from GitHub release" -Type 'Progress' -Data @{
Release = $Release.TagName
InstallPath = $InstallPath
}
# Step 1: Find appropriate asset
$asset = Find-SuitableAsset -Assets $Release.Assets
if (-not $asset) {
throw "No suitable asset found in the release. Available assets: $($Release.Assets | ForEach-Object { $_.name })"
}
Write-DebugStep -Phase "InstallFromGitHub" -Message "Selected asset for download" -Type 'Info' -Data @{
AssetName = $asset.name
Size = "$([math]::Round($asset.size / 1MB, 2)) MB"
DownloadUrl = $asset.browser_download_url
}
# Step 2: Download the asset
$downloadPath = Download-GitHubAsset -Asset $asset -CacheDir $global:LiteDbConfig.CacheDirectory -NoProgress:$NoProgress
if (-not $downloadPath -or -not (Test-Path -Path $downloadPath)) {
throw "Failed to download asset: $($asset.name)"
}
# Step 3: Extract the asset
$extractPath = Extract-Asset -AssetPath $downloadPath -ExtractPath $InstallPath -AssetName $asset.name
if (-not $extractPath -or -not (Test-Path -Path $extractPath)) {
throw "Failed to extract asset: $($asset.name)"
}
Write-DebugStep -Phase "InstallFromGitHub" -Message "Asset extracted successfully" -Type 'Progress' -Data @{ ExtractPath = $extractPath }
return $extractPath
}
}
function Find-SuitableAsset {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[object[]]$Assets
)
Write-DebugStep -Phase "FindSuitableAsset" -Message "Finding suitable asset from release" -Type 'Progress' -Data @{ AssetCount = $Assets.Count }
# Define asset preferences in order of priority
$preferredPatterns = @(
# Windows binaries (prefer ZIP archives)