chore: merge main into PR #19

This commit is contained in:
igor04091968
2026-05-07 07:33:53 +03:00
43 changed files with 1969 additions and 29 deletions
+3 -3
View File
@@ -541,7 +541,7 @@ function Send-DlpIncidentHeartbeat {
} + $captureData
} | ConvertTo-Json -Depth 5 -Compress
Invoke-RestMethod -Method Post -Uri "$($script:ApiBase)/buckets/$bucketId/heartbeat?pulsetime=$resolvedPulseSeconds" -ContentType 'application/json' -Body $event | Out-Null
Invoke-RestMethod -Method Post -Uri "$($script:ApiBase)/buckets/$bucketId/heartbeat?pulsetime=$resolvedPulseSeconds" -ContentType 'application/json' -Body $event -TimeoutSec 15 -DisableKeepAlive | Out-Null
}
function Get-FileSha256Hex {
@@ -746,7 +746,7 @@ function Send-Heartbeat {
}
} | ConvertTo-Json -Depth 4 -Compress
Invoke-RestMethod -Method Post -Uri "$($script:ApiBase)/buckets/$BucketId/heartbeat?pulsetime=$resolvedPulseSeconds" -ContentType 'application/json' -Body $event | Out-Null
Invoke-RestMethod -Method Post -Uri "$($script:ApiBase)/buckets/$BucketId/heartbeat?pulsetime=$resolvedPulseSeconds" -ContentType 'application/json' -Body $event -TimeoutSec 15 -DisableKeepAlive | Out-Null
}
function Send-CategoryHeartbeat {
@@ -783,7 +783,7 @@ function Send-CategoryHeartbeat {
}
} | ConvertTo-Json -Depth 4 -Compress
Invoke-RestMethod -Method Post -Uri "$($script:ApiBase)/buckets/$bucketId/heartbeat?pulsetime=$resolvedPulseSeconds" -ContentType 'application/json' -Body $event | Out-Null
Invoke-RestMethod -Method Post -Uri "$($script:ApiBase)/buckets/$bucketId/heartbeat?pulsetime=$resolvedPulseSeconds" -ContentType 'application/json' -Body $event -TimeoutSec 15 -DisableKeepAlive | Out-Null
}
Load-CustomCategoryRules -Path $resolvedRulesPath
+113 -10
View File
@@ -40,7 +40,7 @@ function Invoke-AwJsonPost {
)
$bytes = [Text.Encoding]::UTF8.GetBytes($Json)
Invoke-RestMethod -Method Post -Uri $Uri -ContentType 'application/json; charset=utf-8' -Body $bytes | Out-Null
Invoke-RestMethod -Method Post -Uri $Uri -ContentType 'application/json; charset=utf-8' -Body $bytes -TimeoutSec 15 -DisableKeepAlive | Out-Null
}
function Ensure-Bucket {
@@ -243,6 +243,10 @@ function Show-EnforcementNotification {
[Parameter(Mandatory = $true)][string]$Title,
[Parameter(Mandatory = $true)][string]$Body
)
if ($script:HeadlessMode) {
Write-EndpointLog ("headless mode: skip notification title={0}" -f $Title)
return $false
}
try {
Add-Type -AssemblyName System.Windows.Forms -ErrorAction SilentlyContinue
$icon = New-Object System.Windows.Forms.NotifyIcon
@@ -254,9 +258,11 @@ function Show-EnforcementNotification {
$icon.ShowBalloonTip(5000)
Start-Sleep -Milliseconds 200
$icon.Dispose()
return $true
}
catch {
Write-EndpointLog ("notification failed: {0}" -f $_.Exception.Message)
return $false
}
}
@@ -340,6 +346,44 @@ function Get-StringHash {
}
}
function Get-ClipboardTextSafe {
[OutputType([string])]
param()
try {
$v = Get-Clipboard -Raw -ErrorAction Stop
if ($null -ne $v) { return [string]$v }
}
catch {
Write-EndpointLog ("clipboard direct read failed: {0}" -f $_.Exception.Message)
}
# Fallback: read clipboard in a dedicated STA thread for RDP/user-session edge cases.
try {
Add-Type -AssemblyName System.Windows.Forms -ErrorAction SilentlyContinue | Out-Null
$result = [string]::Empty
$thread = [System.Threading.Thread]{
try {
$script:__aw_clip = [System.Windows.Forms.Clipboard]::GetText()
}
catch {
$script:__aw_clip = $null
}
}
$thread.SetApartmentState([System.Threading.ApartmentState]::STA)
$thread.Start()
$thread.Join(3000) | Out-Null
if ($thread.IsAlive) { $thread.Abort() }
$result = [string]$script:__aw_clip
Remove-Variable -Name __aw_clip -Scope Script -ErrorAction SilentlyContinue
return $result
}
catch {
Write-EndpointLog ("clipboard STA read failed: {0}" -f $_.Exception.Message)
return $null
}
}
function Load-DlpPolicy {
param([string]$Path)
@@ -405,6 +449,9 @@ function Evaluate-ClipboardRules {
[string]$ClipboardText,
[string]$ClipboardHash
)
if ([string]::IsNullOrEmpty($ClipboardText) -or [string]::IsNullOrEmpty($ClipboardHash)) {
return
}
foreach ($rule in @($script:Policy.endpoint.clipboard)) {
if (-not $rule) { continue }
@@ -435,8 +482,13 @@ function Evaluate-ClipboardRules {
$enforced = $false
if ($action -eq 'block') {
$enforced = Invoke-ClipboardEnforcement
Show-EnforcementNotification -Title 'DLP: буфер обмена очищен' -Body $message
if ($script:HeadlessMode) {
Write-EndpointLog ("headless fallback: clipboard rule={0} requires block, skipped interactive enforcement" -f $ruleId)
}
else {
$enforced = Invoke-ClipboardEnforcement
[void](Show-EnforcementNotification -Title 'DLP: буфер обмена очищен' -Body $message)
}
}
Send-DlpIncidentHeartbeat -RuleId $ruleId -Action $action -Severity $severity -Message $message -SignalType 'clipboard' -Data @{
@@ -470,8 +522,13 @@ function Evaluate-UsbRules {
$enforced = $false
if ($action -eq 'block') {
$enforced = Invoke-UsbWriteBlockEnforcement -DriveLetter $DriveLetter
Show-EnforcementNotification -Title 'DLP: USB заблокирован для записи' -Body $message
if ($script:HeadlessMode) {
Write-EndpointLog ("headless fallback: usb rule={0} requires block, skipped interactive enforcement drive={1}" -f $ruleId, $DriveLetter)
}
else {
$enforced = Invoke-UsbWriteBlockEnforcement -DriveLetter $DriveLetter
[void](Show-EnforcementNotification -Title 'DLP: USB заблокирован для записи' -Body $message)
}
}
Send-DlpIncidentHeartbeat -RuleId $ruleId -Action $action -Severity $severity -Message $message -SignalType 'usb_insert' -Data @{
@@ -515,8 +572,13 @@ function Evaluate-PrintRules {
$enforced = $false
if ($action -eq 'block') {
$enforced = Invoke-PrintJobEnforcement -PrinterName $PrinterName -DocumentName $DocumentName -Owner $Owner
Show-EnforcementNotification -Title 'DLP: печать заблокирована' -Body $message
if ($script:HeadlessMode) {
Write-EndpointLog ("headless fallback: print rule={0} requires block, skipped interactive enforcement printer={1}" -f $ruleId, $PrinterName)
}
else {
$enforced = Invoke-PrintJobEnforcement -PrinterName $PrinterName -DocumentName $DocumentName -Owner $Owner
[void](Show-EnforcementNotification -Title 'DLP: печать заблокирована' -Body $message)
}
}
Send-DlpIncidentHeartbeat -RuleId $ruleId -Action $action -Severity $severity -Message $message -SignalType 'print_job' -Data @{
@@ -535,6 +597,17 @@ function Test-LooksLikeMojibakeQuestionMarks {
return $Value -match '\?{2,}'
}
function Test-LooksLikeRussianTitleMaskedAsQuestionMarks {
param([AllowNull()][string]$Value)
if ([string]::IsNullOrWhiteSpace($Value)) { return $false }
$trimmed = $Value.Trim()
if ($trimmed -match '[A-Za-zА-Яа-я0-9]') { return $false }
# Typical broken Cyrillic print title shape: multiple words of question marks.
return $trimmed -match '^\?{3,}(\s+\?{3,})+$'
}
function Normalize-OwnerForMatch {
param([AllowNull()][string]$Value)
if ([string]::IsNullOrWhiteSpace($Value)) { return '' }
@@ -743,6 +816,7 @@ function Get-BetterDocumentNameFromPrintServiceEvents {
}
}
catch {
Write-EndpointLog ("printservice fallback failed: {0}" -f $_.Exception.Message)
}
return $null
@@ -779,9 +853,13 @@ $script:LogPath = $resolvedLogPath
$script:IncidentArtifactsRoot = $resolvedIncidentArtifactsRoot
$script:IncidentScreenshotEnabled = $resolvedIncidentScreenshotEnabled
$script:ScreenshotTypesLoaded = $false
$script:HeadlessMode = ($env:SESSIONNAME -eq 'Service') -or (-not [Environment]::UserInteractive)
Load-DlpPolicy -Path $resolvedPolicyPath
Write-EndpointLog ("endpoint collector started against {0}" -f $script:ApiBase)
if ($script:HeadlessMode) {
Write-EndpointLog "headless mode enabled: enforcement UI is disabled, incident heartbeat and logs only"
}
while ($true) {
try {
@@ -791,7 +869,7 @@ while ($true) {
}
try {
$clipboardText = Get-Clipboard -Raw -ErrorAction SilentlyContinue
$clipboardText = Get-ClipboardTextSafe
if ($clipboardText) {
$clipboardHash = Get-StringHash -Value $clipboardText
if ($clipboardHash -and $clipboardHash -ne $script:LastClipboardHash) {
@@ -805,6 +883,7 @@ while ($true) {
}
}
catch {
Write-EndpointLog ("clipboard poll failed: {0}" -f $_.Exception.Message)
}
try {
@@ -832,6 +911,7 @@ while ($true) {
}
}
catch {
Write-EndpointLog ("usb poll failed: {0}" -f $_.Exception.Message)
}
try {
@@ -842,23 +922,33 @@ while ($true) {
if ($script:SeenPrintJob.ContainsKey($jobId)) { continue }
$script:SeenPrintJob[$jobId] = (Get-Date).ToUniversalTime()
$printerName = [string]$job.Name
$printerName = Normalize-PrinterForMatch -Value ([string]$job.Name)
$documentName = [string]$job.Document
$owner = [string]$job.Owner
$documentNameOriginal = $documentName
if (Test-LooksLikeMojibakeQuestionMarks -Value $documentName) {
if (Test-LooksLikeRussianTitleMaskedAsQuestionMarks -Value $documentName) {
$eventDocumentName = Get-BetterDocumentNameFromPrintServiceEvents -Owner $owner -PrinterName $printerName
if ($eventDocumentName) {
$documentName = $eventDocumentName
}
}
$printDocumentNorm = if ($documentName) { [string]$documentName } else { '' }
$printSignalKey = ('{0}|{1}|{2}|{3}' -f
(Normalize-PrinterForMatch -Value $printerName),
(Normalize-OwnerForMatch -Value $owner),
$printDocumentNorm.ToLowerInvariant(),
'print_job')
if (-not (Should-EmitByCooldown -Fingerprint $printSignalKey -CooldownSeconds 90)) {
continue
}
Send-EndpointSignalHeartbeat -SignalType 'print_job' -Data @{
printerName = $printerName
documentName = $documentName
documentNameOriginal = $documentNameOriginal
owner = $owner
eventSource = 'win32_printjob'
}
Evaluate-PrintRules -PrinterName $printerName -DocumentName $documentName -Owner $owner
}
@@ -872,6 +962,7 @@ while ($true) {
}
}
catch {
Write-EndpointLog ("printjob poll failed: {0}" -f $_.Exception.Message)
}
try {
@@ -899,6 +990,17 @@ while ($true) {
continue
}
$effectiveDocument = if ($resolvedDocument) { [string]$resolvedDocument } else { [string]$documentName }
$printSignalKey = ('{0}|{1}|{2}|{3}' -f
(Normalize-PrinterForMatch -Value $printerName),
(Normalize-OwnerForMatch -Value $owner),
$effectiveDocument.ToLowerInvariant(),
'print_job')
if (-not (Should-EmitByCooldown -Fingerprint $printSignalKey -CooldownSeconds 90)) {
Write-PrintServiceEventTrace -EventSummary $summary -Phase 'skip' -MatchReason 'dedupe-recent-printjob' -ResolvedDocument $resolvedDocument
continue
}
Send-EndpointSignalHeartbeat -SignalType 'print_job' -Data @{
printerName = $printerName
documentName = if ($resolvedDocument) { $resolvedDocument } else { $documentName }
@@ -919,6 +1021,7 @@ while ($true) {
}
}
catch {
Write-EndpointLog ("printservice poll failed: {0}" -f $_.Exception.Message)
}
}
catch {
+21 -1
View File
@@ -48,13 +48,23 @@ function Invoke-AwJsonPost {
[Parameter(Mandatory = $true)][string]$Uri,
[Parameter(Mandatory = $true)][string]$Json
)
$httpClient = $null
try {
$httpClient = New-Object System.Net.Http.HttpClient
$content = New-Object System.Net.Http.StringContent($Json, [System.Text.Encoding]::UTF8, "application/json")
$response = $httpClient.PostAsync($Uri, $content).Result
$httpClient.Dispose()
if (-not $response.IsSuccessStatusCode) {
$status = [int]$response.StatusCode
$reason = [string]$response.ReasonPhrase
$body = $response.Content.ReadAsStringAsync().Result
Write-FileCollectorLog ("POST failed: uri={0} status={1} reason={2} body={3}" -f $Uri, $status, $reason, $body)
}
} catch {
Write-FileCollectorLog "POST Error: $($_.Exception.Message)"
} finally {
if ($null -ne $httpClient) {
$httpClient.Dispose()
}
}
}
@@ -168,6 +178,7 @@ if ($resolvedPaths.Count -eq 0) {
Write-FileCollectorLog "Starting watch on paths: $($resolvedPaths -join ', ')"
$watchers = @()
$subscriptions = @()
foreach ($path in $resolvedPaths) {
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $path
@@ -188,6 +199,7 @@ foreach ($path in $resolvedPaths) {
}
$watchers += $watcher
$subscriptions += @($onChanged, $onDeleted, $onRenamed)
}
Write-FileCollectorLog "Collector started. Waiting for events..."
@@ -199,6 +211,14 @@ try {
}
finally {
Write-FileCollectorLog "Stopping collector..."
foreach ($sub in @($subscriptions)) {
try {
if ($sub -and $sub.Id) {
Unregister-Event -SubscriptionId $sub.Id -ErrorAction SilentlyContinue
Remove-Job -Id $sub.Id -Force -ErrorAction SilentlyContinue
}
} catch {}
}
foreach ($w in $watchers) {
$w.EnableRaisingEvents = $false
$w.Dispose()
@@ -4,6 +4,7 @@
#define AwDefaultServerHost "10.10.10.13"
#define AwDefaultServerPort "5600"
#define AwDefaultWorktimeReportBase "http://10.10.10.13:5610"
#define AwDefaultUsers "user1,user2,user3,user4,user5"
#define AwDefaultInstallRoot "C:\\Program Files\\AWatch-rus\\bin"
#define AwDefaultStateRoot "C:\\ProgramData\\AWatch-rus"
@@ -42,6 +43,7 @@ Source: "..\..\migrate-awatch-rus-paths.ps1"; DestDir: "{app}\windows"; Flags: i
Source: "..\..\worktime-session-collector.ps1"; DestDir: "{app}\windows"; Flags: ignoreversion
Source: "..\..\browser-domains-native-collector.ps1"; DestDir: "{app}\windows"; Flags: ignoreversion
Source: "..\..\dlp-endpoint-signals-collector.ps1"; DestDir: "{app}\windows"; Flags: ignoreversion
Source: "..\..\file-operations-collector.ps1"; DestDir: "{app}\windows"; Flags: ignoreversion
Source: "..\..\web-category-rules.example.json"; DestDir: "{app}\windows"; Flags: ignoreversion
Source: "..\..\dlp-policy.example.json"; DestDir: "{app}\windows"; Flags: ignoreversion
; Offline payload (optional): place ZIP into windows/installkit/innosetup/payload/ before compiling.
@@ -147,6 +149,8 @@ begin
'Укажите сервер ActivityWatch (куда агенты будут отправлять данные).',
'Если нужно, измените host/port. По умолчанию — наша конфигурация.'
);
{ Worktime CSV/JSON reports are served by aw-worktime-api on :5610 (AwDefaultWorktimeReportBase).
Standard AW "Сегодня" is backed by server-side aw-worktime-ui-bridge timer on AW host. }
ServerHostPage.Add('ServerHost', False);
ServerHostPage.Add('ServerPort', False);
ServerHostPage.Values[0] := '{#AwDefaultServerHost}';