فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
fix/a02-disable-destructive-excel-replace-20261031
a02/strict-export-preflight-20261018
audit/a01-readonly-invoice-metadata-20261101
ci/a06-require-trusted-issuer-for-release
ci/main-postmerge-phase-a-validation-20261020
ci/phase-a-controlled-public-release
design/issue-5-commercial-corrections-adr
docs/a01-a02-a05-oct23-verified-evidence
docs/a01-cheque-endorsement-evidence-20261022
docs/a01-cheque-event-date-evidence-20261021
docs/a01-explicit-refund-reason-evidence-20261021
docs/a01-refund-auth-status-20261020
docs/a01-refund-trace-evidence-20261020
docs/a02-102-evidence-20261018
docs/a02-pr104-evidence-20261018
docs/a02-pr106-evidence-20261019
docs/a02-pr108-ten-tests-20261019
docs/a02-private-sql-backup-evidence-20261111
docs/a03-merge-status-sync-20261020
docs/a04-software-gate-acceptance-20261020
docs/feature-matrix-20261014
docs/finora-master-execution-playbook
docs/four-phase-execution-20261014
docs/four-phase-roadmap-20261014
docs/holoo-lab-stabilization-phase1-20261111
docs/holoo-runtime-schema-audit-20261111
docs/ops-142-governance-5-1-3-20261030
docs/phase-a-a01-a02-a06-a08-verified-evidence-20261023
docs/phase-a-a01-a05-a06-evidence-20261023
docs/phase-a-independent-acceptance-evidence
docs/phase-a-pr110-evidence-20261019
docs/project-status-phase-a-20261014
feat/a01-referenced-return-corrections
feat/a01-referenced-returns-on-main
feat/a02-atomic-opening-ledger-preflight
feat/a02-holoo-compatibility-preflight
feat/a02-holoo-declared-control-totals
feat/a02-holoo-explicit-csv-gate
feat/a02-holoo-safe-zip-intake-offline-webview2-20261030
feat/a02-offline-sql-server-provisioning-20261030
feat/a02-opening-balance-dry-run
feat/a02-opening-ledger-admin-ui
feat/a02-opt-in-isolated-sql-restore-executor-20261030
feat/a02-private-holoo-zip-staging-20261030
feat/a02-safe-isolated-restore-plan-20261030
feat/a02-sql-backup-header-verifyonly-20261030
feat/a03-audit-schema-atomic-events
feat/a03-complete-manual-journal-audit
feat/a05-cheque-treasury-reconciliation
feat/a06-signed-offline-license-activation
feat/a08-synthetic-performance-baseline
feat/phase-a-accounting-benchmark-return-preview
feat/phase-a-ledger-settlement-diagnostics
feature/v2-reconciliation-20261013
fix/a01-atomic-confirm-ui-one-shot-20261031
fix/a01-cheque-clearance-explicit-account-20261023
fix/a01-cheque-contractual-due-date-validity-20261023
fix/a01-cheque-endorsement-counterparty-20261022
fix/a01-cheque-event-date-open-period-20261021
fix/a01-cumulative-return-amount-cap
fix/a01-explicit-refund-reason-approval-20261021
fix/a01-manager-authorized-customer-refunds-20261020
fix/a01-no-implicit-refund
fix/a01-one-shot-confirm-on-atomic-import-20261031
fix/a01-refund-and-overcollection-net-cash
fix/a01-refund-correction-trace-20261020
fix/a02-atomic-excel-master-merge-20261031
fix/a02-canonical-mapping-contract-20261018
fix/a02-disable-destructive-excel-replace-20261031
fix/a02-holoo-invoice-line-coverage-20261023
fix/a02-holoo-preflight-required-invoice-lines-20261023
fix/a02-mapping-contract-20261018
fix/a02-opening-preflight-unbalanced-report
fix/a02-orphan-mapping-20261018
fix/a02-private-excel-import-session-20261031
fix/a02-strict-export-input-20261019
fix/a03-append-only-full-backup-import
fix/a03-append-only-write-guard
fix/a03-block-transaction-clear-append-only-20261016
fix/a03-chain-validation-20261020
fix/a03-company-scoped-audit-data-access
fix/a03-deny-direct-audit-write-20261019
fix/a03-escaped-expense-list-20261031
fix/a03-escaped-financial-record-ids-20261031
fix/a03-financial-ledger-actions-and-print-20261031
fix/a04-backup-checksum-preflight
fix/a04-company-audit-replay-stable-compare
fix/a04-company-backup-source-isolation-20261020
fix/a04-full-restore-posted-financial-integrity
fix/a04-reject-mixed-company-backup-20261019
fix/a04-replace-immutable-posted-ledger
fix/a04-restore-financial-journal-references
fix/a04-service-source-company-boundary-20261020
fix/a05-block-inactive-treasury-settlements
fix/a05-cheque-cash-evidence-reconciliation-20261023
fix/a05-cheque-ledger-and-bank-reconciliation-20261023
fix/a05-fiscal-close-invariant-gates
fix/a06-backup-restore-user-privileges
fix/a06-license-user-company-quota-20261023
fix/a06-malformed-trial-state-fail-closed
fix/a06-offline-clock-fail-closed-20261019
fix/a07-indexeddb-blocked-startup
fix/a07-offline-bundled-assets
fix/a07-version-and-startup-banner
fix/issue-7-company-backup-isolation
fix/p0-deterministic-fractional-invoice-money-20261031
fix/p0-fractional-quantity-input-20261031
fix/p0-fractional-quantity-integrated-20261031
fix/p0-invoice-posting-invariants-20261031
fix/p0-legacy-stock-and-product-inputs-20261031
fix/p0-reports-immutable-cogs-20261101
fix/p0-verified-financial-percent-20261031
fix/p0-zero-discount-report-revenue-20261101
fix/phase-a-backup-app-version
fix/phase-a-backup-integrity-checksum
fix/phase-a-backup-record-id-validation-20261014
fix/phase-a-backup-version-validation-20261014
fix/phase-a-closure-pack3-20261101
fix/phase-a-entitlement-payload-validation
fix/phase-a-gate-exact-evidence-20261019
fix/phase-a-pack4-stock-scope-20261101
fix/phase-a-pack5-integrated-evidence-20261101
fix/phase-a-pack6-atomic-legacy-20261101
fix/phase-a-restore-envelope-and-rollback
fix/phase-a-settings-admin-gate
fix/print-browser-header-footer-20261014
fix/q01-expense-security-probe-exact-option-20261031
fix/q01-financial-grid-labels-20261031
fix/q01-form-label-association-20261031
fix/q01-native-evidence-integrity-20261030
fix/q01-number-input-persian-decimal-20261031
fix/q01-responsive-dashboard-and-cheque-table-20261031
fix/q01-safe-ui-action-audit-coverage-20261031
fix/q01-visible-desktop-sidebar-and-safe-confirm-20261030
fix/roadmap-metadata-sync-20261014
gate/a03-audit-metadata-validation-20261019
integration/a02-windows-holoo-setup-candidate-20261030
license-server
main
perf/a07-lazy-load-excel
perf/a08-cheque-reconciliation-account-index-20261023
perf/a08-paginated-reports-20261101
phase1-restore-hardening
planning/holoo-execution-20261013
planning/roadmap-project-management-20261014
qa/native-click-coverage-audit-20261030
release/v2.0.0
test/a01-native-endorsement-mandatory-20261023
test/a01-native-purchase-return-guardrails
test/a01-native-sale-return-financial-guardrails
test/a01-safe-integer-boundary-20261019
test/a02-native-opening-dry-run-rejections
test/a02-native-positive-opening-ledger
test/a04-native-corrupt-fbackup-20261016
test/a04-native-encrypted-company-backup
test/a04-native-encrypted-company-backup-main
test/a04-native-late-transaction-rollback
test/a04-native-windows-backup-recovery
test/a04-real-edge-v6-v7-migration
test/a04-real-native-interrupted-restore
test/a05-native-draft-ledger-and-repeat-close-20261016
test/a05-native-fiscal-close-guardrails
test/a07-native-multipage-print-engine
test/a07-native-origin-provenance
test/a07-native-webview2-offline-routes
test/a07-windows-offline-startup-smoke
test/a08-installed-webview2-60k-baseline
test/a08-native-webview2-heap-metrics
test/a08-windows-synthetic-performance-baseline
test/github-write-access-20261009
test/native-win-ui-routes-after-finance-backup
test/phase-a-combined-a01-a05-a08-final-evidence
test/phase-a-combined-native-acceptance-matrix
test/phase-a-ledger-invariants-20261014
test/phase-a-native-all-routes-on-merged-lab
test/phase-a-native-encrypted-backup
test/phase-a-native-finance-backup-matrix
test/phase-a-native-ui-and-backup-smoke
test/phase-a-windows-native-installer-lab
work/a08-dispatch-activation-20261123
work/a08-memory-stability-20261123
work/finance-curated-20261123
| 1 | #requires -Version 5.1 |
| 2 | <# |
| 3 | A02: read-only SQL schema inventory for a restored, isolated database. |
| 4 | Inspect prints counts/hash only. PrivateManifest writes schema metadata only, |
| 5 | encrypted with Windows DPAPI CurrentUser and a restrictive local file ACL. |
| 6 | DecryptManifest creates a local ACL-restricted plaintext schema-only JSON file. |
| 7 | No application/business rows are queried. No database writes are performed. |
| 8 | #> |
| 9 | [CmdletBinding()] |
| 10 | param( |
| 11 | [ValidateSet('Test','Inspect','PrivateManifest','DecryptManifest')] |
| 12 | [string]$Mode='Test', |
| 13 | [string]$InstanceName='FINORAMIG', |
| 14 | [string]$DatabaseName='', |
| 15 | [string]$OutputPath='', |
| 16 | [string]$InputPath='' |
| 17 | ) |
| 18 | Set-StrictMode -Version Latest |
| 19 | $ErrorActionPreference='Stop' |
| 20 | $script:ManifestHeader='FEP-A02-DPAPI-V1' |
| 21 | $script:ManifestEntropy=[Text.Encoding]::UTF8.GetBytes('FactorEasyPro|A02|SchemaManifest|v1') |
| 22 | |
| 23 | function Assert-Target([string]$instance,[string]$database){ |
| 24 | if($instance -ceq 'FINORAMIG'){ |
| 25 | if($database -cnotmatch '^FinoraHoloo_[0-9a-f]{32}$'){throw 'A02_ISOLATED_DB_REQUIRED'} |
| 26 | }elseif($instance -cmatch '^FinoraA02_([0-9a-f]{12})$'){ |
| 27 | if($database -cne ('A02Restore_'+$Matches[1])){throw 'A02_TEST_DB_PAIR_MISMATCH'} |
| 28 | }else{throw 'A02_LOCAL_INSTANCE_ONLY'} |
| 29 | } |
| 30 | function Frame([string]$v){if($null -eq $v){$v=''};return ([string]$v.Length)+':'+$v} |
| 31 | function Fingerprint([object[]]$rows){ |
| 32 | if($rows.Count -gt 200000){throw 'A02_TOO_MANY_COLUMNS'} |
| 33 | $lines=[Collections.Generic.List[string]]::new() |
| 34 | foreach($row in $rows){ |
| 35 | $parts=@((Frame ([string]$row.SchemaName)),(Frame ([string]$row.TableName)), |
| 36 | (Frame ([string]$row.ColumnName)),(Frame ([string]$row.DataType)), |
| 37 | (Frame ([string]$row.Ordinal)),(Frame ([string]$row.MaxLength)), |
| 38 | (Frame ([string]$row.Precision)),(Frame ([string]$row.Scale)), |
| 39 | (Frame ([string]$row.IsNullable)),(Frame ([string]$row.IsIdentity)), |
| 40 | (Frame ([string]$row.IsComputed))) |
| 41 | $lines.Add(($parts -join '|')) |
| 42 | } |
| 43 | $lines.Sort([StringComparer]::Ordinal) |
| 44 | $sha=[Security.Cryptography.SHA256]::Create() |
| 45 | try{ |
| 46 | $bytes=[Text.Encoding]::UTF8.GetBytes(($lines -join [Environment]::NewLine)) |
| 47 | return [BitConverter]::ToString($sha.ComputeHash($bytes)).Replace('-','').ToLowerInvariant() |
| 48 | }finally{$sha.Dispose()} |
| 49 | } |
| 50 | function Assert-LocalFilePath([string]$value,[bool]$mustExist){ |
| 51 | if([string]::IsNullOrWhiteSpace($value) -or |
| 52 | $value -notmatch '^[A-Za-z]:\\' -or |
| 53 | $value -match '[/\x00-\x1f<>\"|?*]' -or |
| 54 | $value.Substring(2).Contains(':')){throw 'A02_PRIVATE_PATH_NOT_LOCAL'} |
| 55 | foreach($segment in $value.Substring(3).Split('\')){ |
| 56 | if([string]::IsNullOrWhiteSpace($segment) -or $segment -eq '.' -or |
| 57 | $segment -eq '..' -or $segment.EndsWith(' ') -or $segment.EndsWith('.')){ |
| 58 | throw 'A02_PRIVATE_PATH_AMBIGUOUS' |
| 59 | } |
| 60 | } |
| 61 | $full=[IO.Path]::GetFullPath($value) |
| 62 | $drive=[IO.DriveInfo]::new($full.Substring(0,1)) |
| 63 | if($drive.DriveType -ne [IO.DriveType]::Fixed -or -not $drive.IsReady){ |
| 64 | throw 'A02_PRIVATE_PATH_REQUIRES_FIXED_LOCAL_DISK' |
| 65 | } |
| 66 | $directory=[IO.DirectoryInfo]::new([IO.Path]::GetDirectoryName($full)) |
| 67 | if(-not $directory.Exists){throw 'A02_PRIVATE_PARENT_DIRECTORY_MISSING'} |
| 68 | $cursor=$directory |
| 69 | while($null -ne $cursor){ |
| 70 | if(($cursor.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0){ |
| 71 | throw 'A02_PRIVATE_PATH_REPARSE_POINT' |
| 72 | } |
| 73 | $cursor=$cursor.Parent |
| 74 | } |
| 75 | if($mustExist){ |
| 76 | $file=[IO.FileInfo]::new($full) |
| 77 | if(-not $file.Exists -or $file.Length -lt 1 -or $file.Length -gt 67108864){ |
| 78 | throw 'A02_PRIVATE_INPUT_FILE_INVALID' |
| 79 | } |
| 80 | if(($file.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0){ |
| 81 | throw 'A02_PRIVATE_INPUT_REPARSE_POINT' |
| 82 | } |
| 83 | }else{ |
| 84 | if([IO.File]::Exists($full) -or [IO.Directory]::Exists($full)){ |
| 85 | throw 'A02_PRIVATE_OUTPUT_ALREADY_EXISTS' |
| 86 | } |
| 87 | } |
| 88 | return $full |
| 89 | } |
| 90 | function Write-RestrictedFile([string]$path,[byte[]]$bytes){ |
| 91 | if($bytes.Length -lt 1 -or $bytes.Length -gt 67108864){throw 'A02_PRIVATE_OUTPUT_SIZE_INVALID'} |
| 92 | $full=Assert-LocalFilePath $path $false |
| 93 | $directory=[IO.Path]::GetDirectoryName($full) |
| 94 | $temporary=[IO.Path]::Combine($directory,'.a02-'+[guid]::NewGuid().ToString('N')+'.tmp') |
| 95 | try{ |
| 96 | $stream=[IO.File]::Open($temporary,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::None) |
| 97 | $stream.Dispose() |
| 98 | $current=[Security.Principal.WindowsIdentity]::GetCurrent().User |
| 99 | $sidValues=@($current.Value,'S-1-5-18','S-1-5-32-544') | Select-Object -Unique |
| 100 | $acl=[Security.AccessControl.FileSecurity]::new() |
| 101 | $acl.SetAccessRuleProtection($true,$false) |
| 102 | $acl.SetOwner($current) |
| 103 | foreach($sidValue in $sidValues){ |
| 104 | $sid=[Security.Principal.SecurityIdentifier]::new([string]$sidValue) |
| 105 | $rule=[Security.AccessControl.FileSystemAccessRule]::new( |
| 106 | $sid,[Security.AccessControl.FileSystemRights]::FullControl, |
| 107 | [Security.AccessControl.AccessControlType]::Allow) |
| 108 | [void]$acl.AddAccessRule($rule) |
| 109 | } |
| 110 | [IO.File]::SetAccessControl($temporary,$acl) |
| 111 | [IO.File]::WriteAllBytes($temporary,$bytes) |
| 112 | $check=[IO.File]::GetAccessControl($temporary) |
| 113 | if(-not $check.AreAccessRulesProtected){throw 'A02_PRIVATE_ACL_NOT_PROTECTED'} |
| 114 | $rules=@($check.GetAccessRules($true,$false,[Security.Principal.SecurityIdentifier])) |
| 115 | if($rules.Count -ne $sidValues.Count){throw 'A02_PRIVATE_ACL_RULE_COUNT_INVALID'} |
| 116 | foreach($entry in $rules){ |
| 117 | if($entry.AccessControlType -ne [Security.AccessControl.AccessControlType]::Allow -or |
| 118 | $entry.FileSystemRights -ne [Security.AccessControl.FileSystemRights]::FullControl -or |
| 119 | $entry.IdentityReference.Value -notin $sidValues){ |
| 120 | throw 'A02_PRIVATE_ACL_RULE_INVALID' |
| 121 | } |
| 122 | } |
| 123 | [IO.File]::Move($temporary,$full) |
| 124 | }finally{ |
| 125 | if([IO.File]::Exists($temporary)){[IO.File]::Delete($temporary)} |
| 126 | } |
| 127 | } |
| 128 | function Get-SchemaData($connection){ |
| 129 | $columnSql=@' |
| 130 | SELECT s.name AS SchemaName,t.name AS TableName,c.name AS ColumnName, |
| 131 | ts.name AS TypeSchemaName,ty.name AS DataType, |
| 132 | c.column_id AS Ordinal,c.max_length AS MaxLength, |
| 133 | c.precision AS Precision,c.scale AS Scale,c.is_nullable AS IsNullable, |
| 134 | c.is_identity AS IsIdentity,c.is_computed AS IsComputed, |
| 135 | c.collation_name AS CollationName,c.is_rowguidcol AS IsRowGuid, |
| 136 | c.is_sparse AS IsSparse,c.is_filestream AS IsFileStream |
| 137 | FROM sys.tables AS t |
| 138 | JOIN sys.schemas AS s ON s.schema_id=t.schema_id |
| 139 | JOIN sys.columns AS c ON c.object_id=t.object_id |
| 140 | JOIN sys.types AS ty ON ty.user_type_id=c.user_type_id |
| 141 | JOIN sys.schemas AS ts ON ts.schema_id=ty.schema_id |
| 142 | WHERE t.is_ms_shipped=0 |
| 143 | ORDER BY s.name,t.name,c.column_id; |
| 144 | '@ |
| 145 | $indexSql=@' |
| 146 | SELECT s.name AS SchemaName,t.name AS TableName,i.index_id AS IndexId, |
| 147 | i.name AS IndexName,i.is_primary_key AS IsPrimaryKey, |
| 148 | i.is_unique AS IsUnique,i.type_desc AS IndexType, |
| 149 | i.is_disabled AS IsDisabled,i.has_filter AS HasFilter, |
| 150 | ic.key_ordinal AS KeyOrdinal,ic.index_column_id AS IndexColumnId, |
| 151 | ic.is_included_column AS IsIncludedColumn, |
| 152 | ic.is_descending_key AS IsDescendingKey,c.name AS ColumnName |
| 153 | FROM sys.indexes AS i |
| 154 | JOIN sys.tables AS t ON t.object_id=i.object_id |
| 155 | JOIN sys.schemas AS s ON s.schema_id=t.schema_id |
| 156 | JOIN sys.index_columns AS ic ON ic.object_id=i.object_id AND ic.index_id=i.index_id |
| 157 | JOIN sys.columns AS c ON c.object_id=ic.object_id AND c.column_id=ic.column_id |
| 158 | WHERE t.is_ms_shipped=0 AND i.index_id>0 AND i.is_hypothetical=0 |
| 159 | AND (i.is_primary_key=1 OR i.is_unique=1) |
| 160 | ORDER BY s.name,t.name,i.index_id,ic.index_column_id; |
| 161 | '@ |
| 162 | $foreignSql=@' |
| 163 | SELECT fk.object_id AS ForeignKeyId,fk.name AS ForeignKeyName, |
| 164 | ps.name AS ParentSchema,pt.name AS ParentTable, |
| 165 | pc.name AS ParentColumn,rs.name AS ReferencedSchema, |
| 166 | rt.name AS ReferencedTable,rc.name AS ReferencedColumn, |
| 167 | fkc.constraint_column_id AS Ordinal, |
| 168 | fk.is_disabled AS IsDisabled,fk.is_not_trusted AS IsNotTrusted, |
| 169 | fk.delete_referential_action_desc AS DeleteAction, |
| 170 | fk.update_referential_action_desc AS UpdateAction, |
| 171 | fk.is_not_for_replication AS IsNotForReplication |
| 172 | FROM sys.foreign_keys AS fk |
| 173 | JOIN sys.foreign_key_columns AS fkc ON fkc.constraint_object_id=fk.object_id |
| 174 | JOIN sys.tables AS pt ON pt.object_id=fk.parent_object_id |
| 175 | JOIN sys.schemas AS ps ON ps.schema_id=pt.schema_id |
| 176 | JOIN sys.columns AS pc ON pc.object_id=pt.object_id AND pc.column_id=fkc.parent_column_id |
| 177 | JOIN sys.tables AS rt ON rt.object_id=fk.referenced_object_id |
| 178 | JOIN sys.schemas AS rs ON rs.schema_id=rt.schema_id |
| 179 | JOIN sys.columns AS rc ON rc.object_id=rt.object_id AND rc.column_id=fkc.referenced_column_id |
| 180 | ORDER BY ps.name,pt.name,fk.object_id,fkc.constraint_column_id; |
| 181 | '@ |
| 182 | $metaSql=@' |
| 183 | SELECT CAST(SERVERPROPERTY('ProductMajorVersion') AS int) AS EngineMajorVersion, |
| 184 | d.compatibility_level AS CompatibilityLevel,d.collation_name AS DatabaseCollation, |
| 185 | d.is_read_only AS IsReadOnly,d.recovery_model_desc AS RecoveryModel |
| 186 | FROM sys.databases AS d WHERE d.name=DB_NAME(); |
| 187 | '@ |
| 188 | $columnTable=$null;$indexTable=$null;$foreignTable=$null;$metaTable=$null |
| 189 | try{ |
| 190 | foreach($spec in @( |
| 191 | @{Name='columnTable';Sql=$columnSql}, |
| 192 | @{Name='indexTable';Sql=$indexSql}, |
| 193 | @{Name='foreignTable';Sql=$foreignSql}, |
| 194 | @{Name='metaTable';Sql=$metaSql} |
| 195 | )){ |
| 196 | $cmd=$connection.CreateCommand();$cmd.CommandText=$spec.Sql;$cmd.CommandTimeout=120 |
| 197 | $adapter=[Data.SqlClient.SqlDataAdapter]::new($cmd);$result=[Data.DataTable]::new() |
| 198 | try{[void]$adapter.Fill($result)}finally{$adapter.Dispose();$cmd.Dispose()} |
| 199 | Set-Variable -Name $spec.Name -Value $result -Scope Local |
| 200 | } |
| 201 | if($columnTable.Rows.Count -lt 1 -or $columnTable.Rows.Count -gt 200000 -or |
| 202 | $metaTable.Rows.Count -ne 1){throw 'A02_SCHEMA_SIZE_OR_METADATA_INVALID'} |
| 203 | $tableMap=[Collections.Generic.Dictionary[string,object]]::new([StringComparer]::Ordinal);$tableOrder=[Collections.Generic.List[string]]::new() |
| 204 | foreach($r in $columnTable.Rows){ |
| 205 | $schema=[string]$r['SchemaName'];$name=[string]$r['TableName'] |
| 206 | $key=(Frame $schema)+(Frame $name) |
| 207 | if(-not $tableMap.ContainsKey($key)){ |
| 208 | $tableMap[$key]=[ordered]@{ |
| 209 | schema=$schema;name=$name |
| 210 | columns=[Collections.Generic.List[object]]::new() |
| 211 | indexes=[Collections.Generic.List[object]]::new() |
| 212 | foreignKeys=[Collections.Generic.List[object]]::new() |
| 213 | } |
| 214 | $tableOrder.Add($key) |
| 215 | } |
| 216 | $tableMap[$key].columns.Add([pscustomobject][ordered]@{ |
| 217 | name=[string]$r['ColumnName'];typeSchema=[string]$r['TypeSchemaName'] |
| 218 | dataType=[string]$r['DataType'];ordinal=[int]$r['Ordinal'] |
| 219 | maxLength=[int]$r['MaxLength'];precision=[int]$r['Precision'] |
| 220 | scale=[int]$r['Scale'];nullable=([int]$r['IsNullable'] -eq 1) |
| 221 | identity=([int]$r['IsIdentity'] -eq 1);computed=([int]$r['IsComputed'] -eq 1) |
| 222 | collation=if($r['CollationName'] -is [DBNull]){$null}else{[string]$r['CollationName']} |
| 223 | rowGuid=([int]$r['IsRowGuid'] -eq 1);sparse=([int]$r['IsSparse'] -eq 1) |
| 224 | fileStream=([int]$r['IsFileStream'] -eq 1) |
| 225 | }) |
| 226 | } |
| 227 | $indexMap=[Collections.Generic.Dictionary[string,object]]::new([StringComparer]::Ordinal) |
| 228 | foreach($r in $indexTable.Rows){ |
| 229 | $tableKey=(Frame ([string]$r['SchemaName']))+(Frame ([string]$r['TableName'])) |
| 230 | $idxKey=$tableKey+(Frame ([string]$r['IndexId'])) |
| 231 | if(-not $tableMap.ContainsKey($tableKey)){throw 'A02_SCHEMA_INDEX_PARENT_MISSING'} |
| 232 | if(-not $indexMap.ContainsKey($idxKey)){ |
| 233 | $indexMap[$idxKey]=[ordered]@{ |
| 234 | name=[string]$r['IndexName'];indexId=[int]$r['IndexId'] |
| 235 | primaryKey=([int]$r['IsPrimaryKey'] -eq 1) |
| 236 | unique=([int]$r['IsUnique'] -eq 1);type=[string]$r['IndexType'] |
| 237 | disabled=([int]$r['IsDisabled'] -eq 1);filtered=([int]$r['HasFilter'] -eq 1) |
| 238 | keyColumns=[Collections.Generic.List[object]]::new() |
| 239 | includedColumns=[Collections.Generic.List[string]]::new() |
| 240 | } |
| 241 | $tableMap[$tableKey].indexes.Add($indexMap[$idxKey]) |
| 242 | } |
| 243 | if([int]$r['IsIncludedColumn'] -eq 1){ |
| 244 | $indexMap[$idxKey].includedColumns.Add([string]$r['ColumnName']) |
| 245 | }elseif([int]$r['KeyOrdinal'] -gt 0){ |
| 246 | $indexMap[$idxKey].keyColumns.Add([pscustomobject]@{ |
| 247 | name=[string]$r['ColumnName'];ordinal=[int]$r['KeyOrdinal'] |
| 248 | descending=([int]$r['IsDescendingKey'] -eq 1) |
| 249 | }) |
| 250 | } |
| 251 | } |
| 252 | $foreignMap=[Collections.Generic.Dictionary[string,object]]::new([StringComparer]::Ordinal) |
| 253 | foreach($r in $foreignTable.Rows){ |
| 254 | $parentKey=(Frame ([string]$r['ParentSchema']))+(Frame ([string]$r['ParentTable'])) |
| 255 | $fkKey=$parentKey+(Frame ([string]$r['ForeignKeyId'])) |
| 256 | if(-not $tableMap.ContainsKey($parentKey)){throw 'A02_SCHEMA_FOREIGN_KEY_PARENT_MISSING'} |
| 257 | if(-not $foreignMap.ContainsKey($fkKey)){ |
| 258 | $foreignMap[$fkKey]=[ordered]@{ |
| 259 | name=[string]$r['ForeignKeyName'] |
| 260 | referencedSchema=[string]$r['ReferencedSchema'] |
| 261 | referencedTable=[string]$r['ReferencedTable'] |
| 262 | disabled=([int]$r['IsDisabled'] -eq 1) |
| 263 | notTrusted=([int]$r['IsNotTrusted'] -eq 1) |
| 264 | deleteAction=[string]$r['DeleteAction'];updateAction=[string]$r['UpdateAction'] |
| 265 | notForReplication=([int]$r['IsNotForReplication'] -eq 1) |
| 266 | columns=[Collections.Generic.List[object]]::new() |
| 267 | } |
| 268 | $tableMap[$parentKey].foreignKeys.Add($foreignMap[$fkKey]) |
| 269 | } |
| 270 | $foreignMap[$fkKey].columns.Add([pscustomobject]@{ |
| 271 | ordinal=[int]$r['Ordinal'];column=[string]$r['ParentColumn'] |
| 272 | referencedColumn=[string]$r['ReferencedColumn'] |
| 273 | }) |
| 274 | } |
| 275 | $tables=[Collections.Generic.List[object]]::new() |
| 276 | foreach($key in $tableOrder){$tables.Add($tableMap[$key])} |
| 277 | $schemaObject=[ordered]@{tables=$tables} |
| 278 | $canonical=ConvertTo-Json -InputObject $schemaObject -Depth 20 -Compress |
| 279 | $sha=[Security.Cryptography.SHA256]::Create() |
| 280 | try{ |
| 281 | $fingerprint=[BitConverter]::ToString($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($canonical))).Replace('-','').ToLowerInvariant() |
| 282 | }finally{$sha.Dispose()} |
| 283 | $columnCount=[int]$columnTable.Rows.Count |
| 284 | $tableCount=[int]$tables.Count |
| 285 | $indexCount=0;$primaryCount=0;$foreignCount=0 |
| 286 | foreach($t in $tables){ |
| 287 | foreach($idx in $t.indexes){$indexCount++;if($idx.primaryKey){$primaryCount++}} |
| 288 | $foreignCount+=$t.foreignKeys.Count |
| 289 | } |
| 290 | $manifest=[pscustomobject][ordered]@{ |
| 291 | format='factor-easypro-a02-schema-manifest';formatVersion=1 |
| 292 | generatedUtc=[DateTime]::UtcNow.ToString('o') |
| 293 | engineMajorVersion=[int]$metaTable.Rows[0]['EngineMajorVersion'] |
| 294 | compatibilityLevel=[int]$metaTable.Rows[0]['CompatibilityLevel'] |
| 295 | databaseCollation=[string]$metaTable.Rows[0]['DatabaseCollation'] |
| 296 | isReadOnly=([int]$metaTable.Rows[0]['IsReadOnly'] -eq 1) |
| 297 | recoveryModel=[string]$metaTable.Rows[0]['RecoveryModel'] |
| 298 | schemaFingerprintSha256=$fingerprint |
| 299 | tableCount=$tableCount;columnCount=$columnCount |
| 300 | uniqueIndexCount=$indexCount;primaryKeyCount=$primaryCount |
| 301 | foreignKeyCount=$foreignCount |
| 302 | userRowsRead=$false;databaseModified=$false;canImport=$false |
| 303 | tables=$tables |
| 304 | } |
| 305 | return $manifest |
| 306 | }finally{ |
| 307 | foreach($item in @($columnTable,$indexTable,$foreignTable,$metaTable)){ |
| 308 | if($null -ne $item){$item.Dispose()} |
| 309 | } |
| 310 | } |
| 311 | } |
| 312 | function Read-EncryptedManifest([string]$path){ |
| 313 | $full=Assert-LocalFilePath $path $true |
| 314 | $raw=[IO.File]::ReadAllBytes($full) |
| 315 | $headerBytes=[Text.Encoding]::ASCII.GetBytes($script:ManifestHeader) |
| 316 | if($raw.Length -le ($headerBytes.Length+1)){throw 'A02_PRIVATE_MANIFEST_TRUNCATED'} |
| 317 | $header=[Text.Encoding]::ASCII.GetString($raw,0,$headerBytes.Length) |
| 318 | if($header -cne $script:ManifestHeader -or $raw[$headerBytes.Length] -ne 10){ |
| 319 | throw 'A02_PRIVATE_MANIFEST_HEADER_INVALID' |
| 320 | } |
| 321 | $cipherLength=$raw.Length-$headerBytes.Length-1 |
| 322 | $cipher=New-Object byte[] $cipherLength |
| 323 | [Buffer]::BlockCopy($raw,$headerBytes.Length+1,$cipher,0,$cipherLength) |
| 324 | Add-Type -AssemblyName System.Security -ErrorAction Stop |
| 325 | $plain=[Security.Cryptography.ProtectedData]::Unprotect( |
| 326 | $cipher,$script:ManifestEntropy,[Security.Cryptography.DataProtectionScope]::CurrentUser) |
| 327 | $json=[Text.Encoding]::UTF8.GetString($plain) |
| 328 | $manifest=$json | ConvertFrom-Json |
| 329 | if($null -eq $manifest.tables){throw 'A02_PRIVATE_MANIFEST_TABLES_MISSING'} |
| 330 | $schemaObject=[ordered]@{tables=$manifest.tables} |
| 331 | $canonical=ConvertTo-Json -InputObject $schemaObject -Depth 20 -Compress |
| 332 | $sha=[Security.Cryptography.SHA256]::Create() |
| 333 | try{ |
| 334 | $actualFingerprint=[BitConverter]::ToString($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($canonical))).Replace('-','').ToLowerInvariant() |
| 335 | }finally{$sha.Dispose()} |
| 336 | if($actualFingerprint -cne [string]$manifest.schemaFingerprintSha256){ |
| 337 | throw 'A02_PRIVATE_MANIFEST_FINGERPRINT_MISMATCH' |
| 338 | } |
| 339 | if($manifest.format -cne 'factor-easypro-a02-schema-manifest' -or |
| 340 | [int]$manifest.formatVersion -ne 1 -or |
| 341 | [string]$manifest.schemaFingerprintSha256 -cnotmatch '^[0-9a-f]{64}$' -or |
| 342 | [int]$manifest.tableCount -lt 1 -or |
| 343 | [int]$manifest.columnCount -lt 1 -or |
| 344 | $manifest.userRowsRead -ne $false -or |
| 345 | $manifest.databaseModified -ne $false -or |
| 346 | $manifest.canImport -ne $false){ |
| 347 | throw 'A02_PRIVATE_MANIFEST_CONTRACT_INVALID' |
| 348 | } |
| 349 | return ,$plain |
| 350 | } |
| 351 | |
| 352 | if($Mode -eq 'Test'){ |
| 353 | Assert-Target 'FINORAMIG' 'FinoraHoloo_0123456789abcdef0123456789abcdef' |
| 354 | Assert-Target 'FinoraA02_0123456789ab' 'A02Restore_0123456789ab' |
| 355 | foreach($pair in @(@('FINORAMIG','master'),@('FINORAMIG','Holoo1'), |
| 356 | @('master','FinoraHoloo_0123456789abcdef0123456789abcdef'), |
| 357 | @('FinoraA02_0123456789ab','A02Restore_aaaaaaaaaaaa'))){ |
| 358 | $blocked=$false |
| 359 | try{Assert-Target $pair[0] $pair[1]}catch{$blocked=$true} |
| 360 | if(-not $blocked){throw 'A02_UNSAFE_TARGET_ACCEPTED'} |
| 361 | } |
| 362 | $rows=@( |
| 363 | [pscustomobject]@{SchemaName='dbo';TableName='Synthetic';ColumnName='id';DataType='int';Ordinal=1;MaxLength=4;Precision=10;Scale=0;IsNullable=0;IsIdentity=0;IsComputed=0}, |
| 364 | [pscustomobject]@{SchemaName='dbo';TableName='Synthetic';ColumnName='amount';DataType='bigint';Ordinal=2;MaxLength=8;Precision=19;Scale=0;IsNullable=0;IsIdentity=0;IsComputed=0} |
| 365 | ) |
| 366 | $h=Fingerprint $rows;[array]::Reverse($rows) |
| 367 | if((Fingerprint $rows) -cne $h){throw 'A02_FINGERPRINT_NOT_ORDER_INDEPENDENT'} |
| 368 | $rows[0].ColumnName='changed' |
| 369 | if((Fingerprint $rows) -ceq $h){throw 'A02_FINGERPRINT_NOT_CHANGE_SENSITIVE'} |
| 370 | [pscustomobject]@{ |
| 371 | status='schema-fingerprint-selftest-passed';sqlOpened=$false |
| 372 | userRowsRead=$false;databaseModified=$false;canImport=$false |
| 373 | }|ConvertTo-Json -Compress |
| 374 | return |
| 375 | } |
| 376 | |
| 377 | if($Mode -eq 'DecryptManifest'){ |
| 378 | try{ |
| 379 | if([string]::IsNullOrWhiteSpace($InputPath) -or [string]::IsNullOrWhiteSpace($OutputPath)){ |
| 380 | throw 'A02_PRIVATE_MANIFEST_PATHS_REQUIRED' |
| 381 | } |
| 382 | $plain=Read-EncryptedManifest $InputPath |
| 383 | Write-RestrictedFile $OutputPath $plain |
| 384 | [pscustomobject]@{status='private-schema-manifest-decrypted';plaintextFileAclRestricted=$true;userRowsRead=$false;databaseModified=$false;canImport=$false}|ConvertTo-Json -Compress |
| 385 | }catch{Write-Error 'A02_PRIVATE_MANIFEST_DECRYPT_FAILED';exit 2} |
| 386 | return |
| 387 | } |
| 388 | |
| 389 | $conn=$null |
| 390 | try{ |
| 391 | Assert-Target $InstanceName $DatabaseName |
| 392 | $source=if($InstanceName -ceq 'FINORAMIG'){'lpc:.\FINORAMIG'}else{'(localdb)\'+$InstanceName} |
| 393 | $connectionString='Data Source='+$source+';Initial Catalog=master;Integrated Security=True;Connect Timeout=15;Encrypt=False;Pooling=False;' |
| 394 | $conn=[Data.SqlClient.SqlConnection]::new($connectionString);$conn.Open() |
| 395 | $check=$conn.CreateCommand() |
| 396 | $check.CommandText='SELECT state_desc FROM sys.databases WHERE name=@db;' |
| 397 | [void]$check.Parameters.Add('@db',[Data.SqlDbType]::NVarChar,128) |
| 398 | $check.Parameters['@db'].Value=$DatabaseName |
| 399 | $status=$check.ExecuteScalar();$check.Dispose() |
| 400 | if($null -eq $status -or [string]$status -cne 'ONLINE'){throw 'A02_RESTORE_NOT_ONLINE'} |
| 401 | $conn.ChangeDatabase($DatabaseName) |
| 402 | $manifest=Get-SchemaData $conn |
| 403 | if($Mode -eq 'Inspect'){ |
| 404 | [pscustomobject]@{ |
| 405 | status='isolated-schema-inventoried' |
| 406 | fingerprintSha256=$manifest.schemaFingerprintSha256 |
| 407 | tableCount=$manifest.tableCount;columnCount=$manifest.columnCount |
| 408 | primaryKeyCount=$manifest.primaryKeyCount;foreignKeyCount=$manifest.foreignKeyCount |
| 409 | userRowsRead=$false;databaseModified=$false;canImport=$false |
| 410 | }|ConvertTo-Json -Compress |
| 411 | }else{ |
| 412 | if([string]::IsNullOrWhiteSpace($OutputPath)){throw 'A02_PRIVATE_OUTPUT_PATH_REQUIRED'} |
| 413 | $json=ConvertTo-Json -InputObject $manifest -Depth 20 |
| 414 | $plain=[Text.Encoding]::UTF8.GetBytes($json) |
| 415 | if($plain.Length -gt 33554432){throw 'A02_PRIVATE_MANIFEST_TOO_LARGE'} |
| 416 | Add-Type -AssemblyName System.Security -ErrorAction Stop |
| 417 | $cipher=[Security.Cryptography.ProtectedData]::Protect( |
| 418 | $plain,$script:ManifestEntropy,[Security.Cryptography.DataProtectionScope]::CurrentUser) |
| 419 | $header=[Text.Encoding]::ASCII.GetBytes($script:ManifestHeader) |
| 420 | $payload=New-Object byte[] ($header.Length+1+$cipher.Length) |
| 421 | [Buffer]::BlockCopy($header,0,$payload,0,$header.Length) |
| 422 | $payload[$header.Length]=10 |
| 423 | [Buffer]::BlockCopy($cipher,0,$payload,$header.Length+1,$cipher.Length) |
| 424 | Write-RestrictedFile $OutputPath $payload |
| 425 | [pscustomobject]@{ |
| 426 | status='private-schema-manifest-encrypted' |
| 427 | tableCount=$manifest.tableCount;columnCount=$manifest.columnCount |
| 428 | primaryKeyCount=$manifest.primaryKeyCount;foreignKeyCount=$manifest.foreignKeyCount |
| 429 | dpapiScope='CurrentUser';fileAclRestricted=$true |
| 430 | userRowsRead=$false;databaseModified=$false;canImport=$false |
| 431 | }|ConvertTo-Json -Compress |
| 432 | } |
| 433 | }catch{ |
| 434 | Write-Error 'A02_SCHEMA_INVENTORY_OR_PRIVATE_EXPORT_FAILED' |
| 435 | exit 2 |
| 436 | }finally{if($null -ne $conn){$conn.Dispose()}} |