فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
feat(a02): read-only SQL backup header, filelist and verify-only diagnostic
davoodmehraban89 committed
Oct 30, 2026 at 17:11 UTC
98edfe13d205594817dcbf1f55ecee3cda0130c6
1 file changed
+171
scripts/a02-sql-backup-readonly-preflight.ps1
new
+171
@@ -0,0 +1,171 @@
1
+#requires -Version 5.1
2
+<#
3
+A02: optional read-only SQL Server BACKUP metadata preflight.
4
+- Existing *local named* SQL Server instance only. No network/remote credentials.
5
+- No CREATE DATABASE, RESTORE DATABASE, service controls, setup or import.
6
+- Owner's source backup stays on their device. No source metadata is logged.
7
+- This is a developer/diagnostic bridge, not the final user-facing wizard.
8
+#>
9
+[CmdletBinding()]
10
+param(
11
+ [string]$BackupPath = '',
12
+ [ValidatePattern('^[A-Za-z][A-Za-z0-9_]{0,31}$')]
13
+ [string]$InstanceName = 'FINORAMIG',
14
+ [switch]$SelfTest
15
+)
16
+Set-StrictMode -Version Latest
17
+$ErrorActionPreference = 'Stop'
18
+
19
+function ConvertTo-SqlUnicodeLiteral([string]$Value) {
20
+ # T-SQL RESTORE FROM DISK cannot bind a normal SQL parameter.
21
+ # Quote the complete absolute filename as one unicode string literal.
22
+ return "N'" + $Value.Replace("'", "''") + "'"
23
+}
24
+
25
+function New-SafeBackupCommands([string]$AbsolutePath) {
26
+ $literal = ConvertTo-SqlUnicodeLiteral $AbsolutePath
27
+ return @{
28
+ Header = 'RESTORE HEADERONLY FROM DISK = ' + $literal
29
+ FileList = 'RESTORE FILELISTONLY FROM DISK = ' + $literal
30
+ Verify = 'RESTORE VERIFYONLY FROM DISK = ' + $literal
31
+ }
32
+}
33
+
34
+function Assert-PrivateLocalBackupFile([string]$PathValue) {
35
+ if ([string]::IsNullOrWhiteSpace($PathValue)) {
36
+ throw 'BACKUP_FILE_REQUIRED'
37
+ }
38
+ if (-not [System.IO.Path]::IsPathRooted($PathValue)) {
39
+ throw 'BACKUP_ABSOLUTE_PATH_REQUIRED'
40
+ }
41
+ $fullPath = [System.IO.Path]::GetFullPath($PathValue)
42
+ if ($fullPath.StartsWith('\\') -or $fullPath.StartsWith('//') -or
43
+ $fullPath -match '^\\\\\?\\' -or $fullPath.Substring(2).Contains(':')) {
44
+ throw 'BACKUP_NONLOCAL_OR_ALTERNATE_STREAM_BLOCKED'
45
+ }
46
+ $info = New-Object System.IO.FileInfo($fullPath)
47
+ if (-not $info.Exists) {
48
+ throw 'BACKUP_FILE_NOT_FOUND'
49
+ }
50
+ if (($info.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) {
51
+ throw 'BACKUP_REPARSE_POINT_BLOCKED'
52
+ }
53
+ if ($info.Length -le 0 -or $info.Length -gt 4GB) {
54
+ throw 'BACKUP_SIZE_OUTSIDE_PREFLIGHT_LIMIT'
55
+ }
56
+ return $fullPath
57
+}
58
+
59
+function Invoke-SqlTable($Connection, [string]$Query) {
60
+ $command = $Connection.CreateCommand()
61
+ $command.CommandText = $Query
62
+ $command.CommandTimeout = 300
63
+ $table = New-Object System.Data.DataTable
64
+ $adapter = New-Object System.Data.SqlClient.SqlDataAdapter($command)
65
+ try {
66
+ [void]$adapter.Fill($table)
67
+ return $table
68
+ } finally {
69
+ $adapter.Dispose()
70
+ $command.Dispose()
71
+ }
72
+}
73
+
74
+if ($SelfTest) {
75
+ # Pure parser/quoting contract; no SQL connection or disk access.
76
+ $testPath = "C:\Sample\copy'; DROP DATABASE master;--.bak"
77
+ $commands = New-SafeBackupCommands $testPath
78
+ if ($commands.Header -notlike "*copy''; DROP DATABASE master;--.bak'*") {
79
+ throw 'SELFTEST_LITERAL_ESCAPE_FAILED'
80
+ }
81
+ if ($commands.Header -notlike 'RESTORE HEADERONLY FROM DISK = N*' -or
82
+ $commands.FileList -notlike 'RESTORE FILELISTONLY FROM DISK = N*' -or
83
+ $commands.Verify -notlike 'RESTORE VERIFYONLY FROM DISK = N*') {
84
+ throw 'SELFTEST_COMMAND_SCOPE_FAILED'
85
+ }
86
+ if (($commands.Values | Where-Object {
87
+ $_ -match '(?i)\b(CREATE|DROP|ALTER|REPLACE|ATTACH|DETACH)\s+(DATABASE|TABLE)\b'
88
+ }).Count -gt 0) {
89
+ # Synthetic injection string is inside a quoted SQL literal; this
90
+ # test must instead establish proper doubled quote escape above.
91
+ throw 'SELFTEST_UNEXPECTED_SQL'
92
+ }
93
+ @{ status = 'selftest-passed'; sourceRead = $false; connectionOpened = $false;
94
+ databaseModified = $false; canImport = $false } |
95
+ ConvertTo-Json -Compress
96
+ return
97
+}
98
+
99
+try {
100
+ $localFile = Assert-PrivateLocalBackupFile $BackupPath
101
+} catch {
102
+ # No path or other personal/source metadata in diagnostic output.
103
+ Write-Error 'HOLOO_BACKUP_PREFLIGHT_INVALID_LOCAL_SOURCE'
104
+ exit 2
105
+}
106
+
107
+$connection = $null
108
+try {
109
+ # Local shared-memory endpoint only, Windows authentication only.
110
+ # Server version, actual backup format and permissions are checked live.
111
+ $builder = New-Object System.Data.SqlClient.SqlConnectionStringBuilder
112
+ $builder.DataSource = 'lpc:.\' + $InstanceName
113
+ $builder.IntegratedSecurity = $true
114
+ $builder.Encrypt = $true
115
+ $builder.TrustServerCertificate = $true
116
+ $builder.Pooling = $false
117
+ $builder.ConnectTimeout = 10
118
+ $connection = New-Object System.Data.SqlClient.SqlConnection($builder.ToString())
119
+ $connection.Open()
120
+ $versionQuery = $connection.CreateCommand()
121
+ $versionQuery.CommandText = "SELECT TRY_CAST(SERVERPROPERTY('ProductMajorVersion') AS int)"
122
+ $versionQuery.CommandTimeout = 10
123
+ $serverMajor = [int]$versionQuery.ExecuteScalar()
124
+ $versionQuery.Dispose()
125
+ if ($serverMajor -lt 10) {
126
+ throw 'SQL_VERSION_UNDETERMINED'
127
+ }
128
+
129
+ $sql = New-SafeBackupCommands $localFile
130
+ $header = Invoke-SqlTable $connection $sql.Header
131
+ if ($header.Rows.Count -ne 1) {
132
+ # Multiple backup sets need explicit FILE number/version handling.
133
+ throw 'BACKUP_SET_COUNT_UNSUPPORTED'
134
+ }
135
+ $sourceMajor = [int]$header.Rows[0]['SoftwareVersionMajor']
136
+ if ($sourceMajor -lt 9 -or $sourceMajor -gt $serverMajor) {
137
+ throw 'SQL_BACKUP_VERSION_INCOMPATIBLE'
138
+ }
139
+ $fileList = Invoke-SqlTable $connection $sql.FileList
140
+ if ($fileList.Rows.Count -lt 1) {
141
+ throw 'SQL_BACKUP_EMPTY_FILE_LIST'
142
+ }
143
+ $verify = $connection.CreateCommand()
144
+ $verify.CommandText = $sql.Verify
145
+ $verify.CommandTimeout = 1800
146
+ [void]$verify.ExecuteNonQuery()
147
+ $verify.Dispose()
148
+
149
+ # Deliberately no database name, file path, logical file name,
150
+ # instance name, account data, raw SQL errors or source hash in output.
151
+ @{
152
+ status = 'sql-backup-verifyonly-passed'
153
+ backupSetCount = $header.Rows.Count
154
+ fileCount = $fileList.Rows.Count
155
+ sourceSqlMajor = $sourceMajor
156
+ installedSqlMajor = $serverMajor
157
+ verifyOnlyPassed = $true
158
+ restoreAttempted = $false
159
+ schemaVerified = $false
160
+ financialReconciled = $false
161
+ importPerformed = $false
162
+ canImport = $false
163
+ } | ConvertTo-Json -Compress
164
+} catch {
165
+ Write-Error 'HOLOO_SQL_BACKUP_METADATA_OR_VERIFY_FAILED'
166
+ exit 3
167
+} finally {
168
+ if ($null -ne $connection) {
169
+ $connection.Dispose()
170
+ }
171
+}