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

fix/a02-atomic-excel-master-merge-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
js 341 lines 14.6 KB
Raw
1 // ============================================================
2 // Auth — احراز هویت محلی
3 // - رمزها با PBKDF2-SHA256 هش می‌شوند (هرگز متن خام ذخیره نمی‌شود)
4 // - بدون ورود موفق، برنامه بارگذاری نمی‌شود (صفحه قفل)
5 // - نشست فقط شناسه کاربر را نگه می‌دارد، نه رمز و هش
6 // توجه: این لایه جلوی دسترسی معمولی را می‌گیرد؛ داده‌های IndexedDB
7 // رمزگذاری نمی‌شوند و کسی که به فایل‌های کامپیوتر دسترسی دارد می‌تواند آن‌ها را بخواند.
8 // ============================================================
9
10 import { StorageService, CREDENTIAL_FIELDS } from './StorageService.js';
11 import { EventBus } from './EventBus.js';
12 import { LicenseService } from './LicenseService.js';
13
14 const PBKDF2_ITERATIONS = 600000;
15 const MIN_PASSWORD_LENGTH = 8;
16 const LEGACY_DEFAULT_PASSWORD = 'admin123';
17 const AUTH_ERROR = 'نام کاربری یا رمز عبور اشتباه است';
18
19 const encoder = new TextEncoder();
20 const toB64 = (bytes) => btoa(String.fromCharCode(...bytes));
21 const fromB64 = (b64) => Uint8Array.from(atob(b64), c => c.charCodeAt(0));
22 const sleep = (ms) => new Promise(r => setTimeout(r, ms));
23
24 async function derive(password, salt, iterations) {
25 const key = await crypto.subtle.importKey('raw', encoder.encode(password), 'PBKDF2', false, ['deriveBits']);
26 const bits = await crypto.subtle.deriveBits({ name: 'PBKDF2', hash: 'SHA-256', salt, iterations }, key, 256);
27 return new Uint8Array(bits);
28 }
29
30 function timingSafeEqual(a, b) {
31 if (a.length !== b.length) return false;
32 let diff = 0;
33 for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
34 return diff === 0;
35 }
36
37 export async function hashPassword(password) {
38 const salt = crypto.getRandomValues(new Uint8Array(16));
39 const hash = await derive(password, salt, PBKDF2_ITERATIONS);
40 return {
41 pwAlgo: 'pbkdf2-sha256',
42 pwIter: PBKDF2_ITERATIONS,
43 pwSalt: toB64(salt),
44 pwHash: toB64(hash)
45 };
46 }
47
48 export async function verifyPassword(password, user) {
49 if (!user || !user.pwHash || !user.pwSalt) return false;
50 const hash = await derive(String(password ?? ''), fromB64(user.pwSalt), user.pwIter || PBKDF2_ITERATIONS);
51 return timingSafeEqual(hash, fromB64(user.pwHash));
52 }
53
54 const needsPassword = (user) => !!user.mustSetPassword || !user.pwHash;
55
56 class AuthImpl {
57 constructor() {
58 this.currentUser = null;
59 this.sessionKey = 'finora_pro_session';
60 this._failures = 0;
61 }
62
63 // ---------- راه‌اندازی ----------
64
65 async init() {
66 await this._migrateLegacyPasswords();
67 await this._migrateDefaultManagerUsername();
68
69 let users = await StorageService.getAll('users');
70 if (users.length === 0) {
71 // اولین اجرا: کاربر مدیر بدون رمز ساخته می‌شود و صفحه قفل از او رمز می‌گیرد
72 const admin = await StorageService.put('users', {
73 id: 'user_admin',
74 username: 'مدیر',
75 role: 'admin',
76 displayName: 'مدیر',
77 mustSetPassword: true,
78 createdAt: new Date().toISOString()
79 });
80 users = [admin];
81 }
82
83 let user = this._restoreSession(users);
84 if (!user) user = await this._showLockScreen(users);
85
86 this._startSession(user);
87 this._updateUI();
88 EventBus.emit('auth:ready', this.currentUser);
89 return this.currentUser;
90 }
91
92 // رمزهای متن خام نسخه‌های قبلی را هش می‌کند. رمز پیش‌فرض عمومی admin123 بی‌اعتبار
93 // می‌شود و کاربر باید رمز جدید تعیین کند.
94 async _migrateLegacyPasswords() {
95 const users = await StorageService.getAll('users');
96 for (const u of users) {
97 if (u.pass === undefined) continue;
98 const legacy = u.pass;
99 const next = { ...u };
100 delete next.pass;
101 if (typeof legacy !== 'string' || legacy === '' || legacy === LEGACY_DEFAULT_PASSWORD) {
102 next.mustSetPassword = true;
103 } else {
104 Object.assign(next, await hashPassword(legacy));
105 delete next.mustSetPassword;
106 }
107 await StorageService.put('users', next);
108 }
109 }
110
111 // فقط حساب مدیر پیش‌فرض قدیمی را تغییر نام می‌دهد؛ رمز، شناسه و مجوزها حفظ می‌شوند.
112 async _migrateDefaultManagerUsername() {
113 const users = await StorageService.getAll('users');
114 const manager = users.find(u => u.id === 'user_admin' && u.role === 'admin' && u.username === 'admin');
115 if (!manager || users.some(u => u.username === 'مدیر' && u.id !== manager.id)) return;
116 await StorageService.put('users', { ...manager, username: 'مدیر', displayName: 'مدیر' });
117 }
118
119 _restoreSession(users) {
120 const raw = sessionStorage.getItem(this.sessionKey);
121 if (!raw) return null;
122 let id = raw;
123 try {
124 const parsed = JSON.parse(raw); // نشست قدیمی کل شیء کاربر بود
125 if (parsed && typeof parsed === 'object' && parsed.id) id = parsed.id;
126 } catch (_) { /* نشست جدید فقط شناسه است */ }
127 const user = users.find(u => u.id === id);
128 if (!user || needsPassword(user)) return null;
129 return user;
130 }
131
132 _publicUser(user) {
133 const copy = { ...user };
134 CREDENTIAL_FIELDS.forEach(f => delete copy[f]);
135 delete copy.mustSetPassword;
136 return copy;
137 }
138
139 _startSession(user) {
140 this.currentUser = this._publicUser(user);
141 sessionStorage.setItem(this.sessionKey, user.id);
142 }
143
144 async _setPassword(user, password) {
145 const next = { ...user, ...(await hashPassword(password)), mustSetPassword: false };
146 delete next.pass;
147 return StorageService.put('users', next);
148 }
149
150 // ---------- صفحه قفل ----------
151
152 _showLockScreen(users) {
153 return new Promise((resolve) => {
154 const splash = document.getElementById('splash');
155 const splashDisplay = splash ? splash.style.display : '';
156 if (splash) splash.style.display = 'none';
157
158 const root = document.createElement('div');
159 root.id = 'finoraAuthOverlay';
160 root.setAttribute('dir', 'rtl');
161 root.style.cssText = 'position:fixed;inset:0;z-index:2147483000;display:flex;align-items:center;justify-content:center;background:#0f172a;font-family:inherit;';
162 root.innerHTML = `
163 <form id="finoraAuthForm" autocomplete="on" style="width:min(92vw,380px);background:#fff;color:#0f172a;border-radius:16px;padding:28px;box-shadow:0 20px 60px rgba(0,0,0,.4);display:flex;flex-direction:column;gap:12px;">
164 <div id="faTitle" style="font-size:20px;font-weight:700;"></div>
165 <div id="faHint" style="font-size:13px;color:#475569;line-height:1.7;"></div>
166 <input id="faUser" name="username" type="text" placeholder="نام کاربری" autocomplete="username" style="padding:12px;border:1px solid #cbd5e1;border-radius:10px;font:inherit;">
167 <input id="faPass" name="password" type="password" placeholder="رمز عبور" autocomplete="current-password" style="padding:12px;border:1px solid #cbd5e1;border-radius:10px;font:inherit;">
168 <input id="faPass2" name="password2" type="password" placeholder="تکرار رمز عبور" autocomplete="new-password" style="padding:12px;border:1px solid #cbd5e1;border-radius:10px;font:inherit;display:none;">
169 <div id="faError" role="alert" style="min-height:20px;font-size:13px;color:#b91c1c;"></div>
170 <button id="faSubmit" type="submit" style="padding:12px;border:0;border-radius:10px;background:#2563eb;color:#fff;font:inherit;font-weight:700;cursor:pointer;">ورود</button>
171 </form>`;
172 document.body.appendChild(root);
173
174 const $ = (id) => root.querySelector('#' + id);
175 const form = $('finoraAuthForm');
176 const el = {
177 title: $('faTitle'), hint: $('faHint'), user: $('faUser'),
178 pass: $('faPass'), pass2: $('faPass2'), error: $('faError'), submit: $('faSubmit')
179 };
180
181 let mode = 'login';
182 let busy = false;
183 const showError = (msg) => { el.error.textContent = msg || ''; };
184
185 const setMode = (next, user) => {
186 mode = next;
187 showError('');
188 el.pass.value = '';
189 el.pass2.value = '';
190 if (next === 'setup') {
191 el.title.textContent = 'تعیین رمز مدیر';
192 el.hint.textContent = `برای حساب «مدیر» رمز عبور حداقل ${MIN_PASSWORD_LENGTH} کاراکتری انتخاب کنید.`;
193 el.user.value = user.username;
194 el.user.readOnly = true;
195 el.pass.placeholder = 'رمز عبور جدید';
196 el.pass.autocomplete = 'new-password';
197 el.pass2.style.display = '';
198 el.submit.textContent = 'ذخیره و ورود';
199 el.pass.focus();
200 } else {
201 el.title.textContent = 'ورود به Factor-easyPro';
202 el.hint.textContent = 'برای ادامه وارد Factor-easyPro شوید.';
203 el.user.readOnly = false;
204 el.pass.placeholder = 'رمز عبور';
205 el.pass.autocomplete = 'current-password';
206 el.pass2.style.display = 'none';
207 el.submit.textContent = 'ورود';
208 (el.user.value ? el.pass : el.user).focus();
209 }
210 };
211
212 const finish = (user) => {
213 root.remove();
214 if (splash) splash.style.display = splashDisplay;
215 this._failures = 0;
216 resolve(user);
217 };
218
219 // اگر فقط یک کاربر هست، نام کاربری پر می‌شود؛ اگر او رمز ندارد مستقیم به تعیین رمز می‌رویم
220 if (users.length === 1) {
221 el.user.value = users[0].username;
222 if (needsPassword(users[0])) setMode('setup', users[0]);
223 else setMode('login');
224 } else {
225 setMode('login');
226 }
227
228 form.addEventListener('submit', async (e) => {
229 e.preventDefault();
230 if (busy) return;
231 busy = true;
232 el.submit.disabled = true;
233 showError('');
234 try {
235 const username = el.user.value.trim();
236 const password = el.pass.value;
237 const user = users.find(u => u.username === username);
238
239 if (mode === 'setup') {
240 if (password.length < MIN_PASSWORD_LENGTH) {
241 showError(`رمز عبور باید حداقل ${MIN_PASSWORD_LENGTH} کاراکتر باشد`);
242 } else if (password !== el.pass2.value) {
243 showError('تکرار رمز عبور با رمز وارد‌شده یکسان نیست');
244 } else if (password === LEGACY_DEFAULT_PASSWORD) {
245 showError('این رمز پیش‌فرض و ناامن است؛ رمز دیگری انتخاب کنید');
246 } else {
247 finish(await this._setPassword(user, password));
248 }
249 } else if (user && needsPassword(user)) {
250 setMode('setup', user);
251 } else if (user && await verifyPassword(password, user)) {
252 finish(user);
253 } else {
254 this._failures++;
255 await sleep(Math.min(500 * 2 ** (this._failures - 1), 15000));
256 showError(AUTH_ERROR);
257 }
258 } catch (err) {
259 showError(err && err.message ? err.message : 'خطای ناشناخته');
260 } finally {
261 busy = false;
262 el.submit.disabled = false;
263 }
264 });
265 });
266 }
267
268 // ---------- رابط عمومی ----------
269
270 _updateUI() {
271 const u = this.currentUser;
272 if (!u) return;
273 const avatar = document.getElementById('userAvatar');
274 const name = document.getElementById('userName');
275 const role = document.getElementById('userRole');
276 if (avatar) avatar.textContent = (u.displayName || u.username || 'م').charAt(0);
277 if (name) name.textContent = u.displayName || u.username;
278 if (role) role.textContent = u.role === 'admin' ? 'مدیر' : 'کاربر';
279 }
280
281 current() { return this.currentUser; }
282 isAdmin() { return this.currentUser?.role === 'admin'; }
283
284 async login(username, password) {
285 await this._migrateLegacyPasswords();
286 const users = await StorageService.getAll('users');
287 const user = users.find(u => u.username === username);
288 if (!user || needsPassword(user) || !(await verifyPassword(password, user))) {
289 throw new Error(AUTH_ERROR);
290 }
291 this._startSession(user);
292 this._updateUI();
293 EventBus.emit('auth:login', this.currentUser);
294 return this.currentUser;
295 }
296
297 logout() {
298 if (!confirm('از حساب کاربری خارج می‌شوید؟')) return;
299 this.currentUser = null;
300 sessionStorage.removeItem(this.sessionKey);
301 EventBus.emit('auth:logout');
302 window.location.reload(); // پس از بارگذاری دوباره، صفحه قفل نمایش داده می‌شود
303 }
304
305 async changePassword(oldPassword, newPassword) {
306 if (!this.currentUser) throw new Error('ابتدا وارد شوید');
307 const user = await StorageService.get('users', this.currentUser.id);
308 if (!(await verifyPassword(oldPassword, user))) throw new Error('رمز عبور فعلی اشتباه است');
309 if (typeof newPassword !== 'string' || newPassword.length < MIN_PASSWORD_LENGTH) {
310 throw new Error(`رمز عبور باید حداقل ${MIN_PASSWORD_LENGTH} کاراکتر باشد`);
311 }
312 await this._setPassword(user, newPassword);
313 return true;
314 }
315
316 async createUser({ username, password, displayName, role = 'user' } = {}) {
317 if (!this.isAdmin()) throw new Error('فقط مدیر می‌تواند کاربر بسازد');
318 const name = String(username ?? '').trim();
319 if (!name) throw new Error('نام کاربری الزامی است');
320 if (typeof password !== 'string' || password.length < MIN_PASSWORD_LENGTH) {
321 throw new Error(`رمز عبور باید حداقل ${MIN_PASSWORD_LENGTH} کاراکتر باشد`);
322 }
323 if (LicenseService.state) LicenseService.assertWritable();
324 const limit=LicenseService.state
325 ? Math.min(4,LicenseService.status().maxUsers)
326 : 4;
327 const users = await StorageService.getAll('users');
328 if (users.length >= limit) throw new Error('حداکثر تعداد کاربر مجاز در اشتراک تکمیل شده است');
329 if (role === 'admin' && users.some(u => u.role === 'admin')) throw new Error('فقط یک مدیر سیستم مجاز است');
330 if (users.some(u => u.username === name)) throw new Error('این نام کاربری قبلاً ثبت شده است');
331 const created = await StorageService.put('users', {
332 username: name,
333 displayName: displayName || name,
334 role: role === 'admin' ? 'admin' : 'user',
335 ...(await hashPassword(password))
336 });
337 return this._publicUser(created);
338 }
339 }
340
341 export const Auth = new AuthImpl();