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

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