فینورا پرو - سامانه جامع حسابداری و صدور فاکتور

integrate(a02): carry reviewed scripts/a02-isolated-sql-restore.ps1 into combined candidate

davoodmehraban89 committed Oct 30, 2026 at 19:44 UTC 7bae2a85a8ea7909a77711eedc28ca25482a19f0
1 file changed +374
scripts/a02-isolated-sql-restore.ps1 new
+374
@@ -0,0 +1,374 @@
1 +#requires -Version 5.1
2 +<#
3 +A02: owner-approved, LOCAL-only, isolated SQL Server RESTORE. Not the public wizard.
4 +No SQL install, data mapping/import, remote instance access, WITH REPLACE or DROP.
5 +Use only on a dedicated disposable SQL instance named FINORAMIG.
6 +No owner backup is ever used by public GitHub CI; -Mode Test uses synthetic rows.
7 +#>
8 +[CmdletBinding()]
9 +param(
10 + [ValidateSet('Test', 'Inspect', 'Restore')]
11 + [string]$Mode = 'Test',
12 + [string]$BackupPath = '',
13 + [ValidatePattern('^FINORAMIG$')]
14 + [string]$InstanceName = 'FINORAMIG',
15 + [string]$ConsentPhrase = ''
16 +)
17 +Set-StrictMode -Version Latest
18 +$ErrorActionPreference = 'Stop'
19 +
20 +function Sql-Literal([string]$Value) {
21 + if ([string]::IsNullOrWhiteSpace($Value) -or $Value.IndexOf([char]0) -ge 0) {
22 + throw 'A02_INVALID_SQL_LITERAL'
23 + }
24 + return "N'" + $Value.Replace("'", "''") + "'"
25 +}
26 +
27 +function Assert-LocalPathShape([string]$Value) {
28 + if ([string]::IsNullOrWhiteSpace($Value) -or
29 + $Value -notmatch '^[A-Za-z]:\\' -or
30 + $Value -match '[/\x00-\x1f<>"|?*]' -or
31 + $Value.Substring(2).Contains(':')) {
32 + throw 'A02_UNSAFE_LOCAL_PATH'
33 + }
34 + foreach ($segment in $Value.Substring(3).Split('\')) {
35 + if ([string]::IsNullOrWhiteSpace($segment) -or
36 + $segment -eq '.' -or $segment -eq '..' -or
37 + $segment.EndsWith(' ') -or $segment.EndsWith('.')) {
38 + throw 'A02_AMBIGUOUS_PATH'
39 + }
40 + }
41 + return $Value
42 +}
43 +
44 +function Assert-LocalFilesystemSource([string]$Value) {
45 + $path = Assert-LocalPathShape $Value
46 + $drive = [System.IO.DriveInfo]::new($path.Substring(0, 1))
47 + if ($drive.DriveType -ne [System.IO.DriveType]::Fixed -and
48 + $drive.DriveType -ne [System.IO.DriveType]::Removable) {
49 + throw 'A02_SOURCE_NOT_LOCAL_DISK'
50 + }
51 + $file = New-Object System.IO.FileInfo($path)
52 + if (-not $file.Exists -or $file.Length -le 0 -or $file.Length -gt 4GB) {
53 + throw 'A02_SOURCE_FILE_OR_SIZE_INVALID'
54 + }
55 + if (($file.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) {
56 + throw 'A02_SOURCE_LINK_DISALLOWED'
57 + }
58 + $parent = $file.Directory
59 + while ($null -ne $parent) {
60 + if (($parent.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) {
61 + throw 'A02_SOURCE_PARENT_LINK_DISALLOWED'
62 + }
63 + $parent = $parent.Parent
64 + }
65 + return $file.FullName
66 +}
67 +
68 +function New-RandomDatabaseName {
69 + $rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
70 + try {
71 + [byte[]]$bytes = New-Object byte[] 16
72 + $rng.GetBytes($bytes)
73 + return 'FinoraHoloo_' + [BitConverter]::ToString($bytes).Replace('-', '').ToLowerInvariant()
74 + } finally { $rng.Dispose() }
75 +}
76 +
77 +function New-LocalRestorePlan(
78 + [string]$BackupFile, [string]$DataDirectory, [string]$LogDirectory,
79 + [string]$DatabaseName, [object[]]$Files
80 +) {
81 + $null = Assert-LocalPathShape $BackupFile
82 + $null = Assert-LocalPathShape $DataDirectory
83 + $null = Assert-LocalPathShape $LogDirectory
84 + if ($DatabaseName -cnotmatch '^FinoraHoloo_[0-9a-f]{32}$') {
85 + throw 'A02_INVALID_DATABASE_NAME'
86 + }
87 + if ($null -eq $Files -or $Files.Count -lt 2 -or $Files.Count -gt 16) {
88 + throw 'A02_FILELIST_COUNT_UNSUPPORTED'
89 + }
90 + $seen = [System.Collections.Generic.HashSet[string]]::new(
91 + [System.StringComparer]::OrdinalIgnoreCase
92 + )
93 + $moves = @()
94 + $data = 0
95 + $logs = 0
96 + $totalBytes = [long]0
97 + foreach ($file in $Files) {
98 + $logical = [string]$file.LogicalName
99 + $type = [string]$file.Type
100 + [long]$size = $file.Size
101 + if ([string]::IsNullOrWhiteSpace($logical) -or $logical.Length -gt 128 -or
102 + $logical -match '[\x00-\x1f]' -or
103 + -not $seen.Add($logical) -or
104 + $size -le 0 -or $size -gt 2TB) {
105 + throw 'A02_FILELIST_UNSAFE_ENTRY'
106 + }
107 + if ($type -eq 'D') {
108 + $data++
109 + $ext = if ($data -eq 1) { '.mdf' } else { '.ndf' }
110 + $directory = $DataDirectory
111 + } elseif ($type -eq 'L') {
112 + $logs++
113 + $ext = '.ldf'
114 + $directory = $LogDirectory
115 + } else { throw 'A02_UNSUPPORTED_SQL_FILE_TYPE' }
116 + if ($totalBytes -gt [long]::MaxValue - $size) {
117 + throw 'A02_FILELIST_SIZE_OVERFLOW'
118 + }
119 + $totalBytes += $size
120 + $filename = $DatabaseName + '_file' + ($moves.Count + 1).ToString('00') + $ext
121 + $target = [System.IO.Path]::Combine($directory, $filename)
122 + $null = Assert-LocalPathShape $target
123 + $moves += [pscustomobject]@{
124 + Logical = $logical; Target = $target; Type = $type; Bytes = $size
125 + }
126 + }
127 + if ($data -eq 0 -or $logs -eq 0) {
128 + throw 'A02_DATA_AND_LOG_FILES_REQUIRED'
129 + }
130 + $clauses = @($moves | ForEach-Object {
131 + 'MOVE ' + (Sql-Literal $_.Logical) + ' TO ' + (Sql-Literal $_.Target)
132 + })
133 + $sourceSql = 'FROM DISK = ' + (Sql-Literal $BackupFile) +
134 + ' WITH FILE = 1, ' + ($clauses -join ', ')
135 + $guard = 'IF DB_ID(' + (Sql-Literal $DatabaseName) +
136 + ") IS NOT NULL THROW 51001, 'A02_DATABASE_COLLISION', 1;"
137 + $verify = 'RESTORE VERIFYONLY ' + $sourceSql + ';'
138 + $restore = $guard + [Environment]::NewLine +
139 + 'RESTORE DATABASE [' + $DatabaseName + '] ' +
140 + $sourceSql + ', RECOVERY, STATS = 10;'
141 + return [pscustomobject]@{
142 + DatabaseName = $DatabaseName
143 + Moves = @($moves)
144 + TotalBytes = $totalBytes
145 + VerifySql = $verify
146 + RestoreSql = $restore
147 + RestoreExecuted = $false
148 + CanImport = $false
149 + }
150 +}
151 +
152 +function Invoke-SqlRows($Connection, [string]$Sql) {
153 + $cmd = $Connection.CreateCommand()
154 + $cmd.CommandText = $Sql
155 + $cmd.CommandTimeout = 300
156 + $adapter = New-Object System.Data.SqlClient.SqlDataAdapter($cmd)
157 + $rows = New-Object System.Data.DataTable
158 + try {
159 + [void]$adapter.Fill($rows)
160 + return ,$rows
161 + } finally {
162 + $adapter.Dispose()
163 + $cmd.Dispose()
164 + }
165 +}
166 +
167 +function Invoke-SqlCommand($Connection, [string]$Sql, [int]$Timeout = 1800) {
168 + $cmd = $Connection.CreateCommand()
169 + $cmd.CommandText = $Sql
170 + $cmd.CommandTimeout = $Timeout
171 + try { [void]$cmd.ExecuteNonQuery() }
172 + finally { $cmd.Dispose() }
173 +}
174 +
175 +function Assert-PlanCollisionFree($Connection, $Plan) {
176 + # Only read system catalogs; no CREATE/DROP/ALTER.
177 + $catalog = Invoke-SqlRows $Connection 'SELECT physical_name FROM sys.master_files'
178 + $names = Invoke-SqlRows $Connection 'SELECT name FROM sys.databases'
179 + try {
180 + foreach ($r in $names.Rows) {
181 + if ([string]::Equals([string]$r['name'], $Plan.DatabaseName,
182 + [System.StringComparison]::OrdinalIgnoreCase)) {
183 + throw 'A02_DATABASE_COLLISION'
184 + }
185 + }
186 + foreach ($move in $Plan.Moves) {
187 + if ([System.IO.File]::Exists($move.Target) -or
188 + [System.IO.Directory]::Exists($move.Target)) {
189 + throw 'A02_DESTINATION_FILE_COLLISION'
190 + }
191 + foreach ($row in $catalog.Rows) {
192 + if ([string]::Equals([string]$row['physical_name'], $move.Target,
193 + [System.StringComparison]::OrdinalIgnoreCase)) {
194 + throw 'A02_EXISTING_SQL_FILE_COLLISION'
195 + }
196 + }
197 + }
198 + } finally {
199 + $catalog.Dispose()
200 + $names.Dispose()
201 + }
202 +}
203 +
204 +function Assert-DestinationDiskSpace($Plan) {
205 + # Require at least 2 GiB reserve beyond the logical file sizes per drive.
206 + $required = @{}
207 + foreach ($move in $Plan.Moves) {
208 + $drive = $move.Target.Substring(0, 1).ToUpperInvariant()
209 + if (-not $required.ContainsKey($drive)) { $required[$drive] = [long]0 }
210 + $required[$drive] += [long]$move.Bytes
211 + }
212 + foreach ($drive in $required.Keys) {
213 + $info = [System.IO.DriveInfo]::new($drive)
214 + if ($info.DriveType -ne [System.IO.DriveType]::Fixed -or
215 + -not $info.IsReady -or
216 + $info.AvailableFreeSpace -lt ($required[$drive] + 2GB)) {
217 + throw 'A02_DESTINATION_DISK_INSUFFICIENT'
218 + }
219 + }
220 +}
221 +
222 +function Invoke-SelfTest {
223 + $name = 'FinoraHoloo_0123456789abcdef0123456789abcdef'
224 + $files = @(
225 + [pscustomobject]@{ LogicalName = "Data';DROP DATABASE master;--"; Type = 'D'; Size = 1024 },
226 + [pscustomobject]@{ LogicalName = 'Log'; Type = 'L'; Size = 2048 }
227 + )
228 + $p = New-LocalRestorePlan "D:\Private\O'Connor.bak" 'C:\SqlData' 'C:\SqlLog' $name $files
229 + if (-not $p.VerifySql.Contains("O''Connor.bak") -or
230 + -not $p.RestoreSql.Contains("Data'';DROP DATABASE master;--") -or
231 + $p.RestoreSql -match '(?i)\bWITH\s+REPLACE\b' -or
232 + ($p.RestoreSql.Split([string[]]@('RESTORE DATABASE'), [System.StringSplitOptions]::None)).Count -ne 2 -or
233 + $p.Moves.Count -ne 2) { throw 'A02_SELFTEST_SQL_PLAN' }
234 + foreach ($bad in @('relative\file.bak', '\\server\share\a.bak',
235 + 'C:\Private\..\file.bak', 'C:\Private\file.bak:ads', 'C:/Private/file.bak')) {
236 + $rejected = $false
237 + try { $null = Assert-LocalPathShape $bad }
238 + catch { $rejected = $true }
239 + if (-not $rejected) { throw 'A02_SELFTEST_UNSAFE_PATH' }
240 + }
241 + $badType = @(
242 + [pscustomobject]@{ LogicalName = 'Data'; Type = 'D'; Size = 1024 },
243 + [pscustomobject]@{ LogicalName = 'Fs'; Type = 'S'; Size = 1024 }
244 + )
245 + $rejected = $false
246 + try { $null = New-LocalRestorePlan 'D:\copy.bak' 'C:\Data' 'C:\Log' $name $badType }
247 + catch { $rejected = $true }
248 + if (-not $rejected) { throw 'A02_SELFTEST_FILE_TYPE' }
249 + [pscustomobject]@{
250 + status = 'selftest-passed'; sqlConnectionOpened = $false
251 + backupOpened = $false; databaseModified = $false; canImport = $false
252 + } | ConvertTo-Json -Compress
253 +}
254 +
255 +if ($Mode -eq 'Test') {
256 + Invoke-SelfTest
257 + return
258 +}
259 +
260 +# A02: explicit consent required before potentially creating a new database.
261 +if ($Mode -eq 'Restore' -and
262 + $ConsentPhrase -cne 'I_AUTHORIZE_A_NEW_ISOLATED_SQL_DATABASE') {
263 + Write-Error 'A02_EXPLICIT_OWNER_CONSENT_REQUIRED'
264 + exit 2
265 +}
266 +$connection = $null
267 +try {
268 + $localBackup = Assert-LocalFilesystemSource $BackupPath
269 + # Bind metadata/VERIFYONLY and eventual restore to unchanged file bytes.
270 + # Never output this private source fingerprint to console or CI.
271 + $sourceHash = (Get-FileHash -LiteralPath $localBackup -Algorithm SHA256).Hash
272 + $builder = New-Object System.Data.SqlClient.SqlConnectionStringBuilder
273 + $builder.DataSource = 'lpc:.\FINORAMIG'
274 + $builder.InitialCatalog = 'master'
275 + $builder.IntegratedSecurity = $true
276 + $builder.Encrypt = $true
277 + $builder.TrustServerCertificate = $true
278 + $builder.ConnectTimeout = 10
279 + $builder.Pooling = $false
280 + $connection = New-Object System.Data.SqlClient.SqlConnection($builder.ToString())
281 + $connection.Open()
282 + $version = Invoke-SqlRows $connection @"
283 +SELECT TRY_CAST(SERVERPROPERTY('ProductMajorVersion') AS int) AS Major,
284 + CAST(SERVERPROPERTY('InstanceName') AS nvarchar(128)) AS InstanceName,
285 + CAST(SERVERPROPERTY('InstanceDefaultDataPath') AS nvarchar(4000)) AS DataDir,
286 + CAST(SERVERPROPERTY('InstanceDefaultLogPath') AS nvarchar(4000)) AS LogDir;
287 +"@
288 + if ($version.Rows.Count -ne 1 -or
289 + [string]$version.Rows[0]['InstanceName'] -ine 'FINORAMIG') {
290 + throw 'A02_SQL_INSTANCE_NOT_DEDICATED'
291 + }
292 + [int]$serverMajor = $version.Rows[0]['Major']
293 + if ($serverMajor -lt 11) { throw 'A02_SQL_INSTANCE_TOO_OLD' }
294 + $dataPath = [string]$version.Rows[0]['DataDir']
295 + $logPath = [string]$version.Rows[0]['LogDir']
296 + if ($dataPath.EndsWith('\')) { $dataPath = $dataPath.TrimEnd('\') }
297 + if ($logPath.EndsWith('\')) { $logPath = $logPath.TrimEnd('\') }
298 + $null = Assert-LocalPathShape $dataPath
299 + $null = Assert-LocalPathShape $logPath
300 + foreach ($folder in @($dataPath, $logPath)) {
301 + if (-not [System.IO.Directory]::Exists($folder)) {
302 + throw 'A02_SQL_DEFAULT_DIRECTORY_MISSING'
303 + }
304 + }
305 + $sourceLiteral = Sql-Literal $localBackup
306 + $header = Invoke-SqlRows $connection ('RESTORE HEADERONLY FROM DISK = ' + $sourceLiteral)
307 + if ($header.Rows.Count -ne 1 -or
308 + [int]$header.Rows[0]['BackupType'] -ne 1 -or
309 + [int]$header.Rows[0]['Position'] -ne 1) {
310 + throw 'A02_NOT_SINGLE_STANDALONE_FULL_BACKUP'
311 + }
312 + if ($header.Columns.Contains('IsDamaged') -and
313 + $header.Rows[0]['IsDamaged'] -ne [DBNull]::Value -and
314 + [bool]$header.Rows[0]['IsDamaged']) {
315 + throw 'A02_SOURCE_HEADER_DAMAGED'
316 + }
317 + [int]$sourceMajor = $header.Rows[0]['SoftwareVersionMajor']
318 + if ($sourceMajor -lt 9 -or $sourceMajor -gt $serverMajor) {
319 + throw 'A02_SOURCE_SQL_VERSION_INCOMPATIBLE'
320 + }
321 + $files = Invoke-SqlRows $connection ('RESTORE FILELISTONLY FROM DISK = ' + $sourceLiteral)
322 + $plan = New-LocalRestorePlan $localBackup $dataPath $logPath (
323 + New-RandomDatabaseName
324 + ) @($files.Rows)
325 + Assert-DestinationDiskSpace $plan
326 + Assert-PlanCollisionFree $connection $plan
327 + Invoke-SqlCommand $connection $plan.VerifySql 1800
328 + if ((Get-FileHash -LiteralPath $localBackup -Algorithm SHA256).Hash -cne $sourceHash) {
329 + throw 'A02_SOURCE_BACKUP_CHANGED_AFTER_VERIFY'
330 + }
331 + if ($Mode -eq 'Inspect') {
332 + [pscustomobject]@{
333 + status = 'backup-verifyonly-passed'
334 + sourceSqlMajor = $sourceMajor; engineSqlMajor = $serverMajor
335 + fileCount = $plan.Moves.Count; canImport = $false
336 + restoreExecuted = $false; financialReconciled = $false
337 + } | ConvertTo-Json -Compress
338 + return
339 + }
340 + # Recheck to narrow races; SQL itself also refuses existing database
341 + # without WITH REPLACE. This cannot prove true exclusive use of instance.
342 + Assert-PlanCollisionFree $connection $plan
343 + if ((Get-FileHash -LiteralPath $localBackup -Algorithm SHA256).Hash -cne $sourceHash) {
344 + throw 'A02_SOURCE_BACKUP_CHANGED_BEFORE_RESTORE'
345 + }
346 + Invoke-SqlCommand $connection $plan.RestoreSql 3600
347 + $online = Invoke-SqlRows $connection (
348 + 'SELECT state_desc FROM sys.databases WHERE name = ' +
349 + (Sql-Literal $plan.DatabaseName)
350 + )
351 + if ($online.Rows.Count -ne 1 -or [string]$online.Rows[0]['state_desc'] -ne 'ONLINE') {
352 + throw 'A02_ISOLATED_DATABASE_NOT_ONLINE'
353 + }
354 + $schema = Invoke-SqlRows $connection (
355 + 'SELECT (SELECT COUNT(*) FROM [' + $plan.DatabaseName +
356 + '].sys.tables) AS TableCount, (SELECT COUNT(*) FROM [' +
357 + $plan.DatabaseName + '].sys.columns) AS ColumnCount'
358 + )
359 + [pscustomobject]@{
360 + status = 'isolated-restore-completed-needs-mapping-and-reconciliation'
361 + databaseName = $plan.DatabaseName
362 + tableCount = [int]$schema.Rows[0]['TableCount']
363 + columnCount = [int]$schema.Rows[0]['ColumnCount']
364 + canImport = $false; financialReconciled = $false
365 + importPerformed = $false
366 + } | ConvertTo-Json -Compress
367 +} catch {
368 + # Do not leak source paths, company names, SQL logical names, credentials,
369 + # raw SQL errors or source financial data into logs/public CI.
370 + Write-Error 'A02_SQL_ISOLATED_RESTORE_OR_PREFLIGHT_FAILED_CHECK_PRIVATE_LOGS'
371 + exit 3
372 +} finally {
373 + if ($null -ne $connection) { $connection.Dispose() }
374 +}