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

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
cs 280 lines 13.3 KB
Raw
1 // A02: private local Holoo ZIP staging. Compiles with Windows PowerShell 5.1 / .NET Framework.
2 // Do not log owner ZIP names, input paths, extracted bytes or per-record data.
3 using System;
4 using System.IO;
5 using System.IO.Compression;
6 using System.Text;
7 namespace Finora.Migration {
8 public sealed class HolooZipReport {
9 public long ArchiveBytes { get; internal set; }
10 public long BackupBytes { get; internal set; }
11 public long CompressedBytes { get; internal set; }
12 public bool EnvelopeValid { get; internal set; }
13 public bool CrcVerified { get; internal set; }
14 public bool SqlTapeHeaderVerified { get; internal set; }
15 public bool CanImport { get { return false; } }
16 }
17
18 public static class SafeHolooZip {
19 private const long MaxArchive = 2L * 1024 * 1024 * 1024;
20 private const long MaxBackup = 4L * 1024 * 1024 * 1024 - 1;
21 private const long MaxRatio = 1000;
22 private static readonly uint[] CrcTable = BuildCrcTable();
23 private sealed class ZipMeta {
24 public uint Crc, Compressed, Uncompressed;
25 public ushort Flags, Method;
26 public string EntryName;
27 }
28 private static uint[] BuildCrcTable() {
29 uint[] values = new uint[256];
30 for (uint i = 0; i < 256; i++) {
31 uint c = i;
32 for (int j = 0; j < 8; j++) c = (c & 1) != 0 ? 0xedb88320u ^ (c >> 1) : c >> 1;
33 values[i] = c;
34 }
35 return values;
36 }
37 private static uint UpdateCrc(uint crc, byte[] bytes, int length) {
38 for (int i = 0; i < length; i++) crc = CrcTable[(int)((crc ^ bytes[i]) & 0xff)] ^ (crc >> 8);
39 return crc;
40 }
41 private static void Require(bool valid, string code) {
42 if (!valid) throw new InvalidDataException(code);
43 }
44 private static string SafeName(byte[] bytes, ushort flags) {
45 Require(bytes.Length > 0 && bytes.Length <= 255, "A02_ENTRY_NAME_LENGTH");
46 string name = ((flags & 0x0800) != 0
47 ? new UTF8Encoding(false, true)
48 : Encoding.GetEncoding(437)).GetString(bytes);
49 Require(name.Length > 0 && name.Length <= 255 &&
50 name.IndexOf('/') < 0 && name.IndexOf('\\') < 0 &&
51 name.IndexOf(':') < 0 && name.IndexOf("..", StringComparison.Ordinal) < 0 &&
52 name.TrimEnd(' ', '.') == name, "A02_UNSAFE_ENTRY_NAME");
53 foreach (char c in name) Require(!Char.IsControl(c), "A02_UNSAFE_ENTRY_NAME");
54 return name;
55 }
56 private static ZipMeta ParseCentral(FileStream stream) {
57 Require(stream.Length >= 52 && stream.Length <= MaxArchive, "A02_ZIP_SIZE_UNSUPPORTED");
58 const int maxEnd = 22 + 65535;
59 int n = (int)Math.Min(stream.Length, maxEnd);
60 byte[] tail = new byte[n];
61 stream.Seek(-n, SeekOrigin.End);
62 Require(stream.Read(tail, 0, n) == n, "A02_ZIP_TRAILER_UNREADABLE");
63 int p = -1;
64 for (int i = n - 22; i >= 0; i--) {
65 if (BitConverter.ToUInt32(tail, i) == 0x06054b50u &&
66 i + 22 + BitConverter.ToUInt16(tail, i + 20) == n) { p = i; break; }
67 }
68 Require(p >= 0, "A02_ZIP_END_MISSING");
69 Require(BitConverter.ToUInt16(tail, p + 4) == 0 &&
70 BitConverter.ToUInt16(tail, p + 6) == 0 &&
71 BitConverter.ToUInt16(tail, p + 8) == 1 &&
72 BitConverter.ToUInt16(tail, p + 10) == 1, "A02_ZIP_SINGLE_ENTRY_REQUIRED");
73 uint directorySize = BitConverter.ToUInt32(tail, p + 12);
74 uint directoryOffset = BitConverter.ToUInt32(tail, p + 16);
75 long directoryEnd = stream.Length - n + p;
76 Require(directorySize >= 46 && directorySize != uint.MaxValue &&
77 directoryOffset != uint.MaxValue &&
78 ((long)directoryOffset + directorySize) == directoryEnd,
79 "A02_ZIP_CENTRAL_INVALID");
80 stream.Position = directoryOffset;
81 byte[] header = new byte[46];
82 Require(stream.Read(header, 0, header.Length) == 46 &&
83 BitConverter.ToUInt32(header, 0) == 0x02014b50u,
84 "A02_ZIP_CENTRAL_INVALID");
85 ushort flags = BitConverter.ToUInt16(header, 8);
86 ushort method = BitConverter.ToUInt16(header, 10);
87 uint crc = BitConverter.ToUInt32(header, 16);
88 uint compressed = BitConverter.ToUInt32(header, 20);
89 uint uncompressed = BitConverter.ToUInt32(header, 24);
90 ushort nameSize = BitConverter.ToUInt16(header, 28);
91 ushort extraSize = BitConverter.ToUInt16(header, 30);
92 ushort commentSize = BitConverter.ToUInt16(header, 32);
93 uint externalAttributes = BitConverter.ToUInt32(header, 38);
94 uint localOffset = BitConverter.ToUInt32(header, 42);
95 Require((flags & 0x0041) == 0 && (method == 0 || method == 8),
96 "A02_ZIP_ENCRYPTED_OR_UNSUPPORTED_METHOD");
97 Require(compressed > 0 && uncompressed >= 4 && uncompressed <= MaxBackup &&
98 uncompressed <= (long)compressed * MaxRatio &&
99 compressed != uint.MaxValue && uncompressed != uint.MaxValue,
100 "A02_ZIP_UNPACK_LIMIT");
101 Require(localOffset == 0 && nameSize > 0 && nameSize <= 255 &&
102 (long)46 + nameSize + extraSize + commentSize == directorySize &&
103 (externalAttributes >> 28) != 0xA, "A02_ZIP_LAYOUT_UNSUPPORTED");
104 byte[] nameBytes = new byte[nameSize];
105 Require(stream.Read(nameBytes, 0, nameSize) == nameSize,
106 "A02_ZIP_NAME_TRUNCATED");
107 string name = SafeName(nameBytes, flags);
108 stream.Position = 0;
109 byte[] local = new byte[30];
110 Require(stream.Read(local, 0, 30) == 30 &&
111 BitConverter.ToUInt32(local, 0) == 0x04034b50u &&
112 BitConverter.ToUInt16(local, 6) == flags &&
113 BitConverter.ToUInt16(local, 8) == method &&
114 BitConverter.ToUInt16(local, 26) == nameSize,
115 "A02_ZIP_LOCAL_MISMATCH");
116 ushort localExtra = BitConverter.ToUInt16(local, 28);
117 byte[] localName = new byte[nameSize];
118 Require(stream.Read(localName, 0, nameSize) == nameSize,
119 "A02_ZIP_LOCAL_NAME_TRUNCATED");
120 for (int i = 0; i < nameSize; i++) {
121 Require(nameBytes[i] == localName[i], "A02_ZIP_NAMES_DIFFER");
122 }
123 Require(30L + nameSize + localExtra + compressed <= directoryOffset,
124 "A02_ZIP_DATA_BOUNDS_INVALID");
125 return new ZipMeta {
126 Crc = crc, Compressed = compressed, Uncompressed = uncompressed,
127 Flags = flags, Method = method, EntryName = name
128 };
129 }
130 private static ZipArchiveEntry OpenValidatedEntry(FileStream file, ZipMeta meta, out ZipArchive zip) {
131 file.Position = 0;
132 zip = new ZipArchive(file, ZipArchiveMode.Read, true);
133 Require(zip.Entries.Count == 1, "A02_ZIP_MULTIPLE_ENTRIES");
134 ZipArchiveEntry entry = zip.Entries[0];
135 Require(entry.FullName == meta.EntryName && entry.Name == meta.EntryName &&
136 entry.Length == meta.Uncompressed && entry.CompressedLength == meta.Compressed,
137 "A02_ZIP_ENTRY_DISAGREEMENT");
138 return entry;
139 }
140 public static HolooZipReport Probe(string source) {
141 using (FileStream file = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read)) {
142 ZipMeta meta = ParseCentral(file);
143 ZipArchive zip = null;
144 try {
145 OpenValidatedEntry(file, meta, out zip);
146 return new HolooZipReport {
147 ArchiveBytes = file.Length, BackupBytes = meta.Uncompressed,
148 CompressedBytes = meta.Compressed, EnvelopeValid = true,
149 CrcVerified = false, SqlTapeHeaderVerified = false
150 };
151 } finally { if (zip != null) zip.Dispose(); }
152 }
153 }
154 public static HolooZipReport Stage(string source, string destination) {
155 // Stage NEVER overwrites a destination and locks the source against
156 // concurrent writers for the duration of verification and extraction.
157 using (FileStream file = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read)) {
158 ZipMeta meta = ParseCentral(file);
159 ZipArchive zip = null;
160 bool destinationCreated = false;
161 try {
162 ZipArchiveEntry entry = OpenValidatedEntry(file, meta, out zip);
163 using (Stream input = entry.Open()) {
164 using (FileStream output = new FileStream(destination, FileMode.CreateNew,
165 FileAccess.Write, FileShare.None, 1024 * 1024, FileOptions.SequentialScan)) {
166 destinationCreated = true;
167 byte[] buffer = new byte[1024 * 1024];
168 byte[] tape = new byte[4];
169 int tapeRead = 0;
170 uint crc = 0xffffffffu;
171 long total = 0;
172 while (true) {
173 int count = input.Read(buffer, 0, buffer.Length);
174 if (count == 0) break;
175 total += count;
176 Require(total <= meta.Uncompressed && total <= MaxBackup,
177 "A02_UNCOMPRESSED_LIMIT_EXCEEDED");
178 for (int i = 0; i < count && tapeRead < 4; i++) tape[tapeRead++] = buffer[i];
179 crc = UpdateCrc(crc, buffer, count);
180 output.Write(buffer, 0, count);
181 }
182 Require(total == meta.Uncompressed && (crc ^ 0xffffffffu) == meta.Crc,
183 "A02_ZIP_CRC_OR_LENGTH_MISMATCH");
184 Require(tapeRead == 4 && tape[0] == (byte)'T' && tape[1] == (byte)'A' &&
185 tape[2] == (byte)'P' && tape[3] == (byte)'E',
186 "A02_SQL_TAPE_SIGNATURE_MISSING");
187 output.Flush(true);
188 }
189 }
190 return new HolooZipReport {
191 ArchiveBytes = file.Length, BackupBytes = meta.Uncompressed,
192 CompressedBytes = meta.Compressed, EnvelopeValid = true,
193 CrcVerified = true, SqlTapeHeaderVerified = true
194 };
195 } catch {
196 if (destinationCreated) {
197 // Delete only the new file this operation itself created.
198 try { File.Delete(destination); } catch { }
199 }
200 throw;
201 } finally { if (zip != null) zip.Dispose(); }
202 }
203 }
204 public static void SelfTest() {
205 string root = Path.Combine(Path.GetTempPath(), "FinoraHolooSynthetic_" +
206 Guid.NewGuid().ToString("N"));
207 Directory.CreateDirectory(root);
208 try {
209 string good = Path.Combine(root, "synthetic.zip");
210 using (FileStream f = new FileStream(good, FileMode.CreateNew)) {
211 using (ZipArchive zip = new ZipArchive(f, ZipArchiveMode.Create, true)) {
212 using (Stream s = zip.CreateEntry("Holoo1", CompressionLevel.Optimal).Open()) {
213 byte[] sample = Encoding.ASCII.GetBytes("TAPE-SYNTHETIC-DATA");
214 s.Write(sample, 0, sample.Length);
215 }
216 }
217 }
218 HolooZipReport probe = Probe(good);
219 Require(probe.EnvelopeValid && !probe.CrcVerified &&
220 !probe.SqlTapeHeaderVerified && !probe.CanImport,
221 "A02_SYNTHETIC_PROBE_FAILED");
222 string outFile = Path.Combine(root, "extracted.bak");
223 HolooZipReport staged = Stage(good, outFile);
224 Require(staged.CrcVerified && staged.SqlTapeHeaderVerified &&
225 !staged.CanImport && File.Exists(outFile) &&
226 Encoding.ASCII.GetString(File.ReadAllBytes(outFile)) == "TAPE-SYNTHETIC-DATA",
227 "A02_SYNTHETIC_STAGE_FAILED");
228 bool refusedOverwrite = false;
229 try { Stage(good, outFile); }
230 catch (IOException) { refusedOverwrite = true; }
231 Require(refusedOverwrite, "A02_OVERWRITE_ALLOWED");
232 // Mutate ONLY central CRC, leaving compressed source bytes intact:
233 // probing must not claim CRC, and staging must fail and clean up.
234 string damaged = Path.Combine(root, "bad_crc.zip");
235 byte[] corrupt = File.ReadAllBytes(good);
236 int central = -1;
237 for (int i = 0; i <= corrupt.Length - 46; i++) {
238 if (BitConverter.ToUInt32(corrupt, i) == 0x02014b50u) { central = i; break; }
239 }
240 Require(central >= 0, "A02_SYNTHETIC_CENTRAL_MISSING");
241 corrupt[central + 16] ^= 0x80;
242 File.WriteAllBytes(damaged, corrupt);
243 HolooZipReport badProbe = Probe(damaged);
244 Require(badProbe.EnvelopeValid && !badProbe.CrcVerified,
245 "A02_PROBE_MUST_NOT_CLAIM_CRC");
246 string damagedOut = Path.Combine(root, "bad_crc.bak");
247 bool crcBlocked = false;
248 try { Stage(damaged, damagedOut); }
249 catch (InvalidDataException) { crcBlocked = true; }
250 Require(crcBlocked && !File.Exists(damagedOut),
251 "A02_CORRUPTED_CRC_ACCEPTED_OR_OUTPUT_LEFT");
252 string wrong = Path.Combine(root, "not_sql.zip");
253 using (FileStream f = new FileStream(wrong, FileMode.CreateNew)) {
254 using (ZipArchive zip = new ZipArchive(f, ZipArchiveMode.Create, true)) {
255 using (Stream s = zip.CreateEntry("Holoo1").Open()) {
256 byte[] sample = Encoding.ASCII.GetBytes("NOPE");
257 s.Write(sample, 0, sample.Length);
258 }
259 }
260 }
261 string badOut = Path.Combine(root, "bad.bak");
262 bool blocked = false;
263 try { Stage(wrong, badOut); } catch (InvalidDataException) { blocked = true; }
264 Require(blocked && !File.Exists(badOut), "A02_BAD_SIGNATURE_LEFT_FILE");
265 string multi = Path.Combine(root, "multi.zip");
266 using (FileStream f = new FileStream(multi, FileMode.CreateNew)) {
267 using (ZipArchive zip = new ZipArchive(f, ZipArchiveMode.Create, true)) {
268 zip.CreateEntry("Holoo1");
269 zip.CreateEntry("Another");
270 }
271 }
272 blocked = false;
273 try { Probe(multi); } catch (InvalidDataException) { blocked = true; }
274 Require(blocked, "A02_MULTIENTRY_ACCEPTED");
275 } finally {
276 Directory.Delete(root, true);
277 }
278 }
279 }
280 }