-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocessor_agent.ps1
More file actions
3375 lines (2893 loc) · 144 KB
/
Copy pathprocessor_agent.ps1
File metadata and controls
3375 lines (2893 loc) · 144 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
param(
[string]$ConfigPath,
[switch]$SingleRun
)
if (-not $ConfigPath) {
$scriptPath = $MyInvocation.MyCommand.Path
if (-not $scriptPath) {
$scriptPath = (Get-Location).ProviderPath
}
$ConfigPath = Join-Path (Split-Path -Parent $scriptPath) "config/agent.json"
}
function Resolve-RelativePath {
param(
[string]$BasePath,
[string]$PathValue
)
if ([string]::IsNullOrWhiteSpace($PathValue)) {
return $BasePath
}
if ([System.IO.Path]::IsPathRooted($PathValue)) {
return [System.IO.Path]::GetFullPath($PathValue)
}
$combined = Join-Path $BasePath $PathValue
return [System.IO.Path]::GetFullPath($combined)
}
function Get-OneDriveBasePath {
param(
[object]$Config
)
# If autoDetect is disabled, use fallback
if ($Config.oneDrive -and -not $Config.oneDrive.autoDetect) {
$fallback = $Config.oneDrive.fallbackRoot
if ($fallback -and $Config.oneDrive.relativePath) {
$fullPath = Join-Path $fallback $Config.oneDrive.relativePath
Write-Host "[OneDrive] AutoDetect disabled - using configured fallback: $fullPath" -ForegroundColor Cyan
return $fullPath
}
}
# Build list of all relative paths to try (primary relativePath + any extraFallbackPaths)
# extraFallbackPaths entries are treated as additional relative paths tried against every
# strategy root, allowing different SharePoint folder layouts across machines.
$relativePathsToTry = @($Config.oneDrive.relativePath)
if ($Config.oneDrive.extraFallbackPaths) {
$relativePathsToTry += @($Config.oneDrive.extraFallbackPaths)
}
$relativePathsToTry = $relativePathsToTry | Where-Object { $_ }
# Strategy 1: Environment variables (per PRD line 13)
Write-Host "[OneDrive] Strategy 1: Environment variables" -ForegroundColor Gray
# OneDriveCommercial (business account - highest priority)
if ($env:OneDriveCommercial) {
foreach ($relPath in $relativePathsToTry) {
$testPath = Join-Path $env:OneDriveCommercial $relPath
if (Test-Path $testPath) {
Write-Host "[OneDrive] ✓ Found via OneDriveCommercial: $testPath" -ForegroundColor Green
return $testPath
}
}
Write-Host "[OneDrive] OneDriveCommercial exists but no relative path matched" -ForegroundColor Yellow
}
# OneDrive (personal account)
if ($env:OneDrive) {
foreach ($relPath in $relativePathsToTry) {
$testPath = Join-Path $env:OneDrive $relPath
if (Test-Path $testPath) {
Write-Host "[OneDrive] ✓ Found via OneDrive: $testPath" -ForegroundColor Green
return $testPath
}
}
}
# Strategy 2: Registry keys (per PRD line 13)
Write-Host "[OneDrive] Strategy 2: Registry keys" -ForegroundColor Gray
$regPaths = @(
@{ Path = "HKCU:\Software\Microsoft\OneDrive\Accounts\Business1"; Name = "UserFolder" },
@{ Path = "HKCU:\Software\Microsoft\OneDrive\Commercial"; Name = "UserFolder" },
@{ Path = "HKLM:\Software\Microsoft\OneDrive"; Name = "UserFolder" }
)
foreach ($reg in $regPaths) {
try {
if (Test-Path $reg.Path) {
$regValue = Get-ItemProperty -Path $reg.Path -Name $reg.Name -ErrorAction SilentlyContinue
if ($regValue -and $regValue.($reg.Name)) {
# Check if this is already the full path or just the root
$regRoot = $regValue.($reg.Name)
# Try direct use first (in case it's already the project root)
if (Test-Path $regRoot) {
foreach ($relPath in $relativePathsToTry) {
$testPath = Join-Path $regRoot $relPath
if (Test-Path $testPath) {
Write-Host "[OneDrive] ✓ Found via registry ($($reg.Path)): $testPath" -ForegroundColor Green
return $testPath
}
}
}
}
}
} catch {
# Silently continue to next registry path
}
}
# Strategy 3: User Profile root
Write-Host "[OneDrive] Strategy 3: User profile root" -ForegroundColor Gray
$userProfile = [Environment]::GetFolderPath('UserProfile')
if ($userProfile) {
foreach ($relPath in $relativePathsToTry) {
$testPath = Join-Path $userProfile $relPath
if (Test-Path $testPath) {
Write-Host "[OneDrive] ✓ Found via user profile: $testPath" -ForegroundColor Green
return $testPath
}
}
}
# Strategy 4: Common OneDrive locations
Write-Host "[OneDrive] Strategy 4: Common OneDrive locations" -ForegroundColor Gray
$commonPaths = @(
"$userProfile\OneDrive - The Education University of Hong Kong",
"$userProfile\OneDrive for Business"
)
foreach ($commonPath in $commonPaths) {
if (Test-Path $commonPath -ErrorAction SilentlyContinue) {
foreach ($relPath in $relativePathsToTry) {
$testPath = Join-Path $commonPath $relPath
if (Test-Path $testPath) {
Write-Host "[OneDrive] ✓ Found via common location: $testPath" -ForegroundColor Green
return $testPath
}
}
}
}
# Strategy 5: Script location analysis
Write-Host "[OneDrive] Strategy 5: Script location analysis" -ForegroundColor Gray
$scriptPath = $PSScriptRoot
if (-not $scriptPath) {
$scriptPath = (Get-Location).ProviderPath
}
# Try to extract root from script path
if ($scriptPath -match '(.*?)(\\The Education University of Hong Kong.*)') {
$extractedRoot = $Matches[1]
foreach ($relPath in $relativePathsToTry) {
$testPath = Join-Path $extractedRoot $relPath
if (Test-Path $testPath) {
Write-Host "[OneDrive] ✓ Found via script path analysis: $testPath" -ForegroundColor Green
return $testPath
}
}
}
# Strategy 6: Configured fallback (final resort)
# Tries every relative path against fallbackRoot
Write-Host "[OneDrive] Strategy 6: Configured fallback" -ForegroundColor Yellow
if ($Config.oneDrive -and $Config.oneDrive.fallbackRoot) {
foreach ($relPath in $relativePathsToTry) {
$fullPath = Join-Path $Config.oneDrive.fallbackRoot $relPath
Write-Host "[OneDrive] Using fallback path: $fullPath" -ForegroundColor Yellow
return $fullPath
}
}
# Absolute final fallback: script directory
Write-Host "[OneDrive] All detection failed - using script directory: $scriptPath" -ForegroundColor Red
return $scriptPath
}
# Get-ComputerNumber function removed - computer number now comes from web upload metadata
$script:AgentSecrets = $null
$script:SupabaseUrl = $null
$script:SupabaseServiceKey = $null
$script:SupabaseLogTable = $null
$script:HostName = [Environment]::MachineName
function Convert-SecureStringToPlainText {
param([System.Security.SecureString]$SecureString)
if (-not $SecureString) {
return ""
}
$bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString)
try {
return [Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr)
} finally {
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)
}
}
function Write-Log {
<#
.SYNOPSIS
Thread-safe logging function with file locking retry mechanism
.DESCRIPTION
Writes log entries to CSV file using StreamWriter with FileShare.ReadWrite
to allow concurrent reads while writing. Implements retry logic with
exponential backoff to handle file locking conflicts.
Fixed Issue: "The process cannot access the file because it is being used by another process"
- Excel, log viewer, or other processes reading the CSV file
- Multiple concurrent PDF processing threads
.PARAMETER Message
Log message content
.PARAMETER Level
Log level (INFO, WARN, ERROR, REJECT, UPLOAD, FILED, etc.)
.PARAMETER File
PDF filename being processed (optional)
#>
param(
[string]$Message,
[string]$Level = "INFO",
[string]$File = ""
)
# Check if this log level is enabled
if ($script:LogLevels -and $script:LogLevels.PSObject.Properties[$Level]) {
$enabled = $script:LogLevels.$Level
if (-not $enabled) {
return # Level is explicitly disabled
}
}
if (-not $script:LogFile) {
return
}
$timestamp = Get-Date -Format "o"
# Sanitize message: remove line breaks and extra spaces
$cleanMessage = $Message -replace '[\r\n]+', ' ' -replace '\s+', ' ' -replace '"', '""'
$logEntry = '{0},{1},"{2}","{3}"' -f $timestamp, $Level, $File, $cleanMessage
# Retry mechanism for file locking conflicts
$maxRetries = 5
$retryDelayMs = 50
$attempt = 0
while ($attempt -lt $maxRetries) {
try {
# Use StreamWriter with FileShare.ReadWrite to allow concurrent reads
$fileStream = [System.IO.File]::Open(
$script:LogFile,
[System.IO.FileMode]::Append,
[System.IO.FileAccess]::Write,
[System.IO.FileShare]::ReadWrite
)
$streamWriter = New-Object System.IO.StreamWriter($fileStream, [System.Text.Encoding]::UTF8)
$streamWriter.WriteLine($logEntry)
$streamWriter.Flush()
$streamWriter.Close()
$fileStream.Close()
Write-SupabaseLog -Timestamp $timestamp -Level $Level -File $File -Message $cleanMessage
break # Success, exit retry loop
}
catch {
$attempt++
if ($attempt -ge $maxRetries) {
# Final attempt failed - write to console as fallback
Write-Warning "Failed to write to log file after $maxRetries attempts: $_"
Write-Host "[LOG FALLBACK] $logEntry"
break
}
# Wait before retry with exponential backoff
Start-Sleep -Milliseconds ($retryDelayMs * $attempt)
}
}
}
function Write-SupabaseLog {
<#
.SYNOPSIS
Writes log entries to Supabase (conditional on enableSupabaseLogging config)
.DESCRIPTION
Uploads log entries to Supabase pdf_upload_log table if enabled in config/log_check_config.json.
Silently skips if disabled or if Supabase credentials are not configured.
.PARAMETER Timestamp
ISO 8601 timestamp
.PARAMETER Level
Log level (INFO, WARN, ERROR, etc.)
.PARAMETER File
PDF filename being processed
.PARAMETER Message
Log message content
#>
param(
[string]$Timestamp,
[string]$Level,
[string]$File,
[string]$Message
)
# Check if Supabase logging is enabled in config
$logCheckConfigPath = Join-Path $PSScriptRoot "config/log_check_config.json"
$supabaseEnabled = $true # Default to true for backward compatibility
if (Test-Path $logCheckConfigPath) {
try {
$logCheckConfig = Get-Content $logCheckConfigPath -Raw | ConvertFrom-Json
if ($logCheckConfig.PSObject.Properties['enableSupabaseLogging']) {
$supabaseEnabled = $logCheckConfig.enableSupabaseLogging
}
} catch {
# Silently continue if config can't be read
}
}
# Exit early if disabled
if (-not $supabaseEnabled) {
return
}
# Exit early if required variables not set
if (-not $script:SupabaseUrl -or -not $script:SupabaseServiceKey -or -not $script:SupabaseLogTable) {
return
}
try {
# Prepare log entry for Supabase
$logEntry = @{
timestamp = $Timestamp
level = $Level
file = $File
message = $Message
hostname = $script:HostName
}
$headers = @{
"apikey" = $script:SupabaseServiceKey
"Authorization" = "Bearer $script:SupabaseServiceKey"
"Content-Type" = "application/json"
"Prefer" = "return=minimal"
}
$body = $logEntry | ConvertTo-Json -Compress
$url = "$script:SupabaseUrl/rest/v1/$script:SupabaseLogTable"
# Fire and forget - don't wait for response or handle errors
# Use -TimeoutSec 2 to avoid blocking too long
Invoke-RestMethod -Uri $url -Method Post -Headers $headers -Body $body -TimeoutSec 2 -ErrorAction SilentlyContinue | Out-Null
} catch {
# Silently ignore any Supabase upload errors to avoid impacting main processing
}
}
function Get-MasterKeyFromCredentialManager {
param([string]$Target)
$password = $null
if (Get-Command -Name Get-StoredCredential -ErrorAction SilentlyContinue) {
$credential = Get-StoredCredential -Target $Target -ErrorAction SilentlyContinue
if ($credential -and $credential.Password) {
$plain = Convert-SecureStringToPlainText -SecureString $credential.Password
if (-not [string]::IsNullOrWhiteSpace($plain)) {
return $plain
}
}
}
try {
Import-Module CredentialManager -ErrorAction Stop
$credential = Get-StoredCredential -Target $Target -ErrorAction SilentlyContinue
if ($credential -and $credential.Password) {
$plain = Convert-SecureStringToPlainText -SecureString $credential.Password
if (-not [string]::IsNullOrWhiteSpace($plain)) {
return $plain
}
}
} catch {
try {
Import-Module CredentialManager -UseWindowsPowerShell -ErrorAction Stop
$credential = Get-StoredCredential -Target $Target -ErrorAction SilentlyContinue
if ($credential -and $credential.Password) {
$plain = Convert-SecureStringToPlainText -SecureString $credential.Password
if (-not [string]::IsNullOrWhiteSpace($plain)) {
return $plain
}
}
} catch {
# Fall through to native API
}
}
if (-not ("NativeCred.CredMan" -as [Type])) {
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
namespace NativeCred {
public enum CredType : int { Generic = 1 }
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct Credential {
public uint Flags;
public uint Type;
public IntPtr TargetName;
public IntPtr Comment;
public long LastWritten;
public uint CredentialBlobSize;
public IntPtr CredentialBlob;
public uint Persist;
public uint AttributeCount;
public IntPtr Attributes;
public IntPtr TargetAlias;
public IntPtr UserName;
}
public static class CredMan {
[DllImport("advapi32", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool CredRead(string target, int type, int reservedFlag, out IntPtr credentialPtr);
[DllImport("advapi32", SetLastError = true)]
public static extern void CredFree(IntPtr cred);
}
}
'@ -Language CSharp
}
$credPtr = [IntPtr]::Zero
if (-not [NativeCred.CredMan]::CredRead($Target, [int][NativeCred.CredType]::Generic, 0, [ref]$credPtr)) {
$errorCode = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
throw "Master key '$Target' not found in Credential Manager (CredRead error $errorCode)."
}
try {
$cred = [Runtime.InteropServices.Marshal]::PtrToStructure($credPtr, [type]([NativeCred.Credential]))
$blobBytes = @()
if ($cred.CredentialBlobSize -gt 0) {
$blobBytes = New-Object byte[] $cred.CredentialBlobSize
[Runtime.InteropServices.Marshal]::Copy($cred.CredentialBlob, $blobBytes, 0, $cred.CredentialBlobSize)
}
$password = [System.Text.Encoding]::Unicode.GetString($blobBytes)
} finally {
if ($credPtr -ne [IntPtr]::Zero) {
[NativeCred.CredMan]::CredFree($credPtr)
}
}
if ([string]::IsNullOrWhiteSpace($password)) {
throw "Master key '$Target' retrieved but empty."
}
return $password
}
function Unlock-AgentBundle {
param(
[byte[]]$EncryptedBytes,
[string]$Passphrase
)
$saltLength = 16
$ivLength = 12
$tagLength = 16
if (-not $EncryptedBytes -or $EncryptedBytes.Length -lt ($saltLength + $ivLength + $tagLength + 1)) {
throw "Encrypted credential bundle is invalid or empty."
}
$offset = 0
$salt = New-Object byte[] $saltLength
[Array]::Copy($EncryptedBytes, $offset, $salt, 0, $saltLength)
$offset += $saltLength
$iv = New-Object byte[] $ivLength
[Array]::Copy($EncryptedBytes, $offset, $iv, 0, $ivLength)
$offset += $ivLength
$remaining = $EncryptedBytes.Length - $offset
if ($remaining -le $tagLength) {
throw "Encrypted credential bundle is missing authentication tag."
}
$cipherLength = $remaining - $tagLength
$cipherBytes = New-Object byte[] $cipherLength
[Array]::Copy($EncryptedBytes, $offset, $cipherBytes, 0, $cipherLength)
$offset += $cipherLength
$tagBytes = New-Object byte[] $tagLength
[Array]::Copy($EncryptedBytes, $offset, $tagBytes, 0, $tagLength)
$keyBytes = $null
try {
$candidate = [Convert]::FromBase64String($Passphrase)
if ($candidate.Length -eq 32) {
$keyBytes = $candidate
}
} catch {
# passphrase is not base64, fall back to PBKDF2
}
if (-not $keyBytes) {
$passphraseBytes = [System.Text.Encoding]::UTF8.GetBytes($Passphrase)
$pbkdf2 = [System.Security.Cryptography.Rfc2898DeriveBytes]::new($passphraseBytes, $salt, 100000, [System.Security.Cryptography.HashAlgorithmName]::SHA256)
$keyBytes = $pbkdf2.GetBytes(32)
}
$plaintext = New-Object byte[] $cipherBytes.Length
try {
$aesGcm = [System.Security.Cryptography.AesGcm]::new($keyBytes)
$aesGcm.Decrypt($iv, $cipherBytes, $tagBytes, $plaintext)
} catch [System.Management.Automation.RuntimeException] {
if ($_.Exception.Message -like "*Unable to find type*AesGcm*") {
throw "AES-GCM encryption requires PowerShell 7 or later. Please install PowerShell 7: https://aka.ms/powershell-release?tag=stable"
}
throw "Failed to decrypt credential bundle: $($_.Exception.Message)"
} catch {
throw "Failed to decrypt credential bundle: $($_.Exception.Message)"
}
$text = [System.Text.Encoding]::UTF8.GetString($plaintext)
return $text
}
function Invoke-PdfParser {
param(
[string]$PdfPath,
[string]$OutputJsonPath
)
$result = @{
success = $false
error = ""
jsonPath = ""
}
try {
$parserScript = Join-Path $PSScriptRoot "parser/parse_pdf_cli.py"
if (-not (Test-Path $parserScript)) {
throw "Python parser not found: $parserScript"
}
# Parsing started - no log (too verbose)
$pythonCmd = $null
$pythonCandidates = Get-Command "python","python3" -ErrorAction SilentlyContinue | Where-Object { $_.Source -notlike "*WindowsApps*" }
if ($pythonCandidates) {
$pythonCmd = $pythonCandidates[0].Source
} else {
$fallbackPaths = Get-ChildItem "C:\Python*\python.exe" -ErrorAction SilentlyContinue
if ($fallbackPaths) {
$pythonCmd = $fallbackPaths[0].FullName
}
}
if (-not $pythonCmd) {
throw "Python executable not found. Please install Python 3.7+ and ensure it's in PATH (not Windows Store stub)."
}
$processInfo = New-Object System.Diagnostics.ProcessStartInfo
$processInfo.FileName = $pythonCmd
$processInfo.Arguments = "`"$parserScript`" `"$PdfPath`" `"$OutputJsonPath`""
$processInfo.RedirectStandardOutput = $true
$processInfo.RedirectStandardError = $true
$processInfo.UseShellExecute = $false
$processInfo.CreateNoWindow = $true
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $processInfo
$process.Start() | Out-Null
$stderr = $process.StandardError.ReadToEnd()
$process.WaitForExit()
if ($process.ExitCode -eq 0) {
$result.success = $true
$result.jsonPath = $OutputJsonPath
# Parser succeeded - no log (too verbose)
} else {
$result.error = "Python parser failed (exit code $($process.ExitCode)): $stderr"
Write-Log -Message "Python parser failed: $stderr" -Level "ERROR" -File ([System.IO.Path]::GetFileName($PdfPath))
}
return $result
} catch {
$result.error = $_.Exception.Message
Write-Log -Message "Parser invocation failed: $($_.Exception.Message)" -Level "ERROR" -File ([System.IO.Path]::GetFileName($PdfPath))
return $result
}
}
function Extract-PdfMetadata {
param([string]$JsonPath)
$result = @{
success = $false
error = ""
coreId = ""
schoolId = ""
sessionkey = ""
fields = @{}
}
try {
if (-not (Test-Path $JsonPath)) {
$result.error = "JSON file not found: $JsonPath"
return $result
}
$json = Get-Content -Path $JsonPath -Raw | ConvertFrom-Json
# Field names now match jotformquestions.json (lowercase with hyphens)
$studentId = $json.data.'student-id'
if (-not $studentId) { $studentId = $json.data.'Student ID' } # Fallback for old format
$schoolId = $json.data.'school-id'
if (-not $schoolId) { $schoolId = $json.data.'School ID' } # Fallback for old format
$sessionkey = $json.data.'sessionkey'
if (-not $sessionkey) { $sessionkey = $json.data.'Sessionkey' } # Fallback for old format
if ($studentId) {
$cleanId = $studentId -replace '[^\d]', ''
$result.coreId = "C" + $cleanId
}
if ($schoolId) {
$cleanSchoolId = $schoolId -replace '[^\d]', ''
$result.schoolId = "S" + $cleanSchoolId.PadLeft(3, '0')
}
if ($sessionkey) {
$result.sessionkey = $sessionkey.Trim()
}
if ([string]::IsNullOrWhiteSpace($result.coreId)) {
$result.error = "Could not extract Core ID from JSON data"
return $result
}
$result.fields = $json.data
$result.success = $true
return $result
} catch {
$result.error = $_.Exception.Message
return $result
}
}
function Load-AgentSecrets {
param(
[string]$SecretsPath,
[string]$KeyIdentifier
)
if ($script:AgentSecrets) {
return $script:AgentSecrets
}
$bundle = $null
try {
$masterKey = Get-MasterKeyFromCredentialManager -Target $KeyIdentifier
$encryptedBytes = [System.IO.File]::ReadAllBytes($SecretsPath)
$bundleText = Unlock-AgentBundle -EncryptedBytes $encryptedBytes -Passphrase $masterKey
$bundle = $bundleText | ConvertFrom-Json
$systemPassword = $bundle.systemPassword
if ($systemPassword) {
$coreidPath = Join-Path (Split-Path $SecretsPath) "coreid.enc"
$schoolidPath = Join-Path (Split-Path $SecretsPath) "schoolid.enc"
if (Test-Path $coreidPath) {
$coreidBytes = [System.IO.File]::ReadAllBytes($coreidPath)
$coreidText = Unlock-AgentBundle -EncryptedBytes $coreidBytes -Passphrase $systemPassword
if ($coreidText.TrimStart().StartsWith('{') -or $coreidText.TrimStart().StartsWith('[')) {
$coreidData = $coreidText | ConvertFrom-Json
} else {
$coreidData = $coreidText | ConvertFrom-Csv
$coreidMap = @{}
foreach ($row in $coreidData) {
$coreId = $row.'Core ID'
if (-not $coreId.StartsWith('C')) {
$coreId = "C" + $coreId
}
$coreidMap[$coreId] = $row
}
$coreidData = $coreidMap
}
$bundle | Add-Member -NotePropertyName "coreIdMap" -NotePropertyValue $coreidData -Force
}
if (Test-Path $schoolidPath) {
$schoolidBytes = [System.IO.File]::ReadAllBytes($schoolidPath)
$schoolidText = Unlock-AgentBundle -EncryptedBytes $schoolidBytes -Passphrase $systemPassword
if ($schoolidText.TrimStart().StartsWith('{') -or $schoolidText.TrimStart().StartsWith('[')) {
$schoolidData = $schoolidText | ConvertFrom-Json
} else {
$schoolidData = $schoolidText | ConvertFrom-Csv
# Convert to hashtable for easier lookup by School ID
$schoolidMap = @{}
foreach ($row in $schoolidData) {
$schoolKey = $row.'School ID'
if (-not [string]::IsNullOrWhiteSpace($schoolKey)) {
$schoolidMap[$schoolKey] = $row
}
}
$schoolidData = $schoolidMap
}
$bundle | Add-Member -NotePropertyName "schoolIdMap" -NotePropertyValue $schoolidData -Force
}
$classidPath = Join-Path (Split-Path $SecretsPath) "classid.enc"
if (Test-Path $classidPath) {
$classidBytes = [System.IO.File]::ReadAllBytes($classidPath)
$classidText = Unlock-AgentBundle -EncryptedBytes $classidBytes -Passphrase $systemPassword
if ($classidText.TrimStart().StartsWith('{') -or $classidText.TrimStart().StartsWith('[')) {
$classidData = $classidText | ConvertFrom-Json
} else {
$classidData = $classidText | ConvertFrom-Csv
# Convert to hashtable for easier lookup by Class ID
$classidMap = @{}
foreach ($row in $classidData) {
$classKey = $row.'Class ID'
if (-not [string]::IsNullOrWhiteSpace($classKey)) {
$classidMap[$classKey] = $row
}
}
$classidData = $classidMap
}
$bundle | Add-Member -NotePropertyName "classIdMap" -NotePropertyValue $classidData -Force
}
# Load jotformquestions.json mapping (from assets root)
$jotformQuestionsPath = Join-Path (Split-Path $SecretsPath) "jotformquestions.json"
if (Test-Path $jotformQuestionsPath) {
$jotformQuestionsText = Get-Content $jotformQuestionsPath -Raw
$jotformQuestionsData = $jotformQuestionsText | ConvertFrom-Json
# Convert to hashtable for easy lookup (field name → QID)
$jotformMap = @{}
foreach ($prop in $jotformQuestionsData.PSObject.Properties) {
$jotformMap[$prop.Name] = $prop.Value
}
$bundle | Add-Member -NotePropertyName "jotformQuestions" -NotePropertyValue $jotformMap -Force
}
}
} catch {
Write-Log -Message ("Failed to load secrets: {0}" -f $_.Exception.Message) -Level "ERROR"
$script:AgentSecrets = @{
CredentialBundlePath = $SecretsPath
MasterKeyReference = $KeyIdentifier
LoadedAt = (Get-Date -Format o)
Error = $_.Exception.Message
Bundle = $null
}
return $script:AgentSecrets
}
$script:AgentSecrets = @{
CredentialBundlePath = $SecretsPath
MasterKeyReference = $KeyIdentifier
LoadedAt = (Get-Date -Format o)
Bundle = $bundle
}
return $script:AgentSecrets
}
function Invoke-Phase2Validation {
param(
[string]$FilePath,
[string]$FileName,
[hashtable]$AgentSecrets,
[string]$CoreId,
[datetime]$ParsedDate,
[int]$Hour,
[int]$Minute
)
$result = [pscustomobject]@{
IsValid = $true
Reason = ""
ReasonCode = ""
Metadata = @{}
}
if (-not $AgentSecrets) {
$result.IsValid = $false
$result.Reason = "Agent secrets unavailable; cannot perform mapping lookup."
$result.ReasonCode = "secrets_unavailable"
return $result
}
$bundle = $AgentSecrets.Bundle
if (-not $bundle) {
Write-Log -Message "Phase2: AgentSecrets exists but Bundle is null" -Level "ERROR" -File $FileName
$result.IsValid = $false
$result.Reason = "Secrets bundle not available; mapping data missing."
$result.ReasonCode = "secrets_unavailable"
return $result
}
# Validation bundle loaded
$pdfData = Extract-PdfMetadata -JsonPath $FilePath
if (-not $pdfData.success) {
Write-Log -Message "Phase2: PDF extraction failed - $($pdfData.error)" -Level "ERROR" -File $FileName
$result.IsValid = $false
$result.Reason = "PDF extraction failed: $($pdfData.error)"
$result.ReasonCode = "pdf_extraction_failed"
return $result
}
$extractedCoreId = $pdfData.coreId
$extractedSchoolId = $pdfData.schoolId
$extractedSessionkey = $pdfData.sessionkey
if ([string]::IsNullOrWhiteSpace($extractedCoreId)) {
Write-Log -Message "Phase2: Could not extract Core ID from JSON" -Level "ERROR" -File $FileName
$result.IsValid = $false
$result.Reason = "Core ID missing in parsed data"
$result.ReasonCode = "coreid_missing_in_pdf"
return $result
}
# CRITICAL VALIDATION 1: Construct and compare sessionkey (FULL match including date/time)
# PDF's sessionkey field format: "YYYY/MM/DD HH:MM" (e.g., "2025/09/04 14:07")
# Filename format: "coreID_YYYYMMDD_HH_MM" (e.g., "13268_20250904_14_07")
# We must CONSTRUCT the canonical sessionkey from BOTH PDF and filename components
# Construct canonical filename sessionkey from validated components
# This ensures we compare canonical forms, not raw strings with extra symbols
$filenameSessionkey = "{0}_{1}_{2:D2}_{3:D2}" -f $CoreId, $ParsedDate.ToString("yyyyMMdd"), $Hour, $Minute
# Extract Core ID digits from PDF (remove "C" prefix)
$pdfCoreIdDigits = $extractedCoreId -replace '^C', ''
# Parse PDF's sessionkey field to construct canonical format
# Expected format: "YYYY/MM/DD HH:MM" or "YYYY/M/D H:M"
$pdfConstructedSessionkey = $null
if (-not [string]::IsNullOrWhiteSpace($extractedSessionkey)) {
try {
# Try parsing common datetime formats (PowerShell syntax)
$parsedDateTime = $null
$formats = @(
'yyyy/MM/dd HH:mm',
'yyyy/M/d H:m',
'yyyy/MM/dd H:mm',
'yyyy/M/dd HH:mm',
'yyyy-MM-dd HH:mm',
'yyyy-M-d H:m'
)
foreach ($format in $formats) {
try {
# PowerShell DateTime parsing
$parsedDateTime = [DateTime]::ParseExact($extractedSessionkey, $format, [System.Globalization.CultureInfo]::InvariantCulture)
# Successfully parsed - construct canonical sessionkey
$pdfConstructedSessionkey = "{0}_{1}_{2:D2}_{3:D2}" -f $pdfCoreIdDigits, $parsedDateTime.ToString("yyyyMMdd"), $parsedDateTime.Hour, $parsedDateTime.Minute
# Sessionkey constructed - no log (too verbose)
break
} catch {
# Try next format
continue
}
}
if (-not $pdfConstructedSessionkey) {
Write-Log -Message "Phase2: Could not parse PDF sessionkey timestamp: '$extractedSessionkey' (tried $($formats.Count) formats)" -Level "WARN" -File $FileName
}
} catch {
Write-Log -Message "Phase2: Error parsing PDF sessionkey: $($_.Exception.Message)" -Level "WARN" -File $FileName
}
}
# Compare constructed PDF sessionkey with filename
if ($pdfConstructedSessionkey -and $pdfConstructedSessionkey -ne $filenameSessionkey) {
# Break down the mismatch to show exactly what's different
$filenameParts = $filenameSessionkey -split '_'
$pdfParts = $pdfConstructedSessionkey -split '_'
$mismatchDetails = @()
if ($filenameParts[0] -ne $pdfParts[0]) {
$mismatchDetails += "Core ID (filename: '$($filenameParts[0])' vs PDF: '$($pdfParts[0])')"
}
if ($filenameParts[1] -ne $pdfParts[1]) {
$mismatchDetails += "Date (filename: '$($filenameParts[1])' vs PDF: '$($pdfParts[1])')"
}
if ($filenameParts[2] -ne $pdfParts[2]) {
$mismatchDetails += "Hour (filename: '$($filenameParts[2])' vs PDF: '$($pdfParts[2])')"
}
if ($filenameParts[3] -ne $pdfParts[3]) {
$mismatchDetails += "Minute (filename: '$($filenameParts[3])' vs PDF: '$($pdfParts[3])')"
}
$mismatchSummary = $mismatchDetails -join ', '
Write-Log -Message "Sessionkey mismatch: $mismatchSummary" -Level "REJECT" -File $FileName
Write-Log -Message "Details: Filename='$filenameSessionkey' vs PDF='$pdfConstructedSessionkey' (from student-id='$pdfCoreIdDigits' + timestamp='$extractedSessionkey')" -Level "REJECT" -File $FileName
$result.IsValid = $false
$result.Reason = "Sessionkey mismatch: $mismatchSummary"
$result.ReasonCode = "sessionkey_filename_mismatch"
return $result
}
# Fallback: If we couldn't construct full sessionkey, at least validate Core ID
if (-not $pdfConstructedSessionkey) {
$filenameCoreId = $CoreId
if ($pdfCoreIdDigits -ne $filenameCoreId) {
Write-Log -Message "Core ID mismatch: Filename='$filenameCoreId' vs PDF='$pdfCoreIdDigits'" -Level "REJECT" -File $FileName
$result.IsValid = $false
$result.Reason = "PDF Core ID Mismatch: Filename indicates '$filenameCoreId' but PDF contains '$pdfCoreIdDigits'. This indicates data corruption or incorrect filing."
$result.ReasonCode = "coreid_filename_mismatch"
return $result
}
}
# Log successful match
# Validation passed - no log (logged as SUCCESS at end)
# Extracted Core ID, School ID, and Sessionkey from JSON validated
$result.Metadata = @{
coreId = $extractedCoreId
extractedCoreId = $extractedCoreId
extractedSchoolId = $extractedSchoolId
extractedSessionkey = $extractedSessionkey
pdfConstructedSessionkey = $pdfConstructedSessionkey
filenameSessionkey = $filenameSessionkey
date = if ($ParsedDate) { $ParsedDate.ToString("yyyy-MM-dd") } else { $null }
hour = $Hour
minute = $Minute
bundlePath = $AgentSecrets.CredentialBundlePath
}
$coreMap = $null
if ($bundle.coreIdMap) {
$coreMap = $bundle.coreIdMap
} elseif ($bundle.coreMappings) {
$coreMap = $bundle.coreMappings
}
if (-not $coreMap) {
Write-Log -Message "No mapping data available, skipping school ID cross-validation" -Level "WARN" -File $FileName
return $result
}
$studentRecord = $coreMap.$extractedCoreId
if (-not $studentRecord) {
Write-Log -Message "Phase2: Core ID $extractedCoreId not found in mapping" -Level "WARN" -File $FileName
$result.IsValid = $false
$result.Reason = "Core ID '$extractedCoreId' not found in mapping data."
$result.ReasonCode = "coreid_missing_in_mapping"
return $result
}
$mappedSchoolId = if ($studentRecord.'School ID') { $studentRecord.'School ID' } else { $studentRecord.schoolId }
if (-not $mappedSchoolId) {
$mappedSchoolId = $studentRecord.SchoolId
}
if ($extractedSchoolId -and $mappedSchoolId -and ($mappedSchoolId -ne $extractedSchoolId)) {
Write-Log -Message "School ID mismatch: PDF='$extractedSchoolId' vs Mapping='$mappedSchoolId'" -Level "REJECT" -File $FileName
$result.IsValid = $false
$result.Reason = "School ID mismatch: JSON shows '$extractedSchoolId' but mapping expects '$mappedSchoolId' for Core ID '$extractedCoreId'."
$result.ReasonCode = "coreid_schoolid_mismatch"
return $result
}
$result.Metadata.schoolId = $mappedSchoolId
$result.Metadata.mappedSchoolId = $mappedSchoolId
$result.Metadata.studentName = $studentRecord.studentName
if (-not $result.Metadata.studentName) {
$result.Metadata.studentName = $studentRecord.StudentName
}
# Validation passed