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

feat(A06): add safe installation-bound signed offline license activation

* feat(A06): verify installation-bound signed offline lease with trusted build key * feat(A06): verify signed license at startup and support protected offline activation * feat(A06): expose admin-only offline license activation and device identifier in settings * test(A06): prove ECDSA signature, device binding, offline lease and tamper rejection

davoodmehraban89 committed Oct 15, 2026 at 20:53 UTC 385e65d8394e20f9658e5bba885407255c0a9ab1
4 files changed +280 -23
src/core/LicenseActivationCore.mjs new
+38
@@ -0,0 +1,38 @@
1 +import { validateEntitlementPayload, verifyEntitlement } from './EntitlementVerifier.mjs';
2 +import { OFFLINE_LEASE_DAYS } from './LicensePolicy.mjs';
3 +
4 +export function loadProductionLicensePublicKey(rawValue) {
5 + if (typeof rawValue !== 'string' || !rawValue.trim()) return null;
6 + try {
7 + const jwk = JSON.parse(rawValue);
8 + if (!jwk || jwk.kty !== 'EC' || jwk.crv !== 'P-256' ||
9 + typeof jwk.x !== 'string' || typeof jwk.y !== 'string' ||
10 + !jwk.x || !jwk.y || 'd' in jwk ||
11 + (jwk.key_ops && JSON.stringify(jwk.key_ops) !== '["verify"]')) {
12 + return null;
13 + }
14 + return jwk;
15 + } catch { return null; }
16 +}
17 +
18 +/**
19 + * Verify a signed, installation-bound offline lease.
20 + * NEVER pass a public key from the token itself; the trusted key is only
21 + * supplied by the application build configuration.
22 + */
23 +export async function validateOfflineActivation(token, publicJwk, installationId, nowMs = Date.now()) {
24 + if (!publicJwk || !token || typeof token !== 'object' ||
25 + !validateEntitlementPayload(token.payload, installationId, nowMs)) return false;
26 + const lease = token.payload.lastOnlineCheckAt;
27 + if (typeof lease !== 'string' || !lease.trim()) return false;
28 + const checkedAtMs = Date.parse(lease);
29 + if (!Number.isFinite(checkedAtMs) ||
30 + checkedAtMs > nowMs + 5 * 60 * 1000 ||
31 + nowMs - checkedAtMs > OFFLINE_LEASE_DAYS * 86400000) return false;
32 + // Prevent using a token ostensibly signed after its offline lease timestamp.
33 + const issuedAt = token.payload.issuedAt;
34 + if (typeof issuedAt !== 'string' || !Number.isFinite(Date.parse(issuedAt)) ||
35 + Date.parse(issuedAt) > checkedAtMs ||
36 + Date.parse(issuedAt) > nowMs + 5 * 60 * 1000) return false;
37 + return verifyEntitlement(token, publicJwk);
38 +}
src/core/LicenseService.js
+111 -23
@@ -1,26 +1,114 @@
1 import { SecureState } from './SecureState.js';
2 import { trialStatus, licensedStatus } from './LicensePolicy.mjs';
3 -const KEY='finora_pro_entitlement_v2',LEGACY_KEY='finora_pro_entitlement_v1';
4 -class LicenseServiceImpl{
5 - constructor(){this.state=null;}
6 - async init(){
7 - let stored=await SecureState.get(KEY);
8 - if(!stored){try{stored=JSON.parse(localStorage.getItem(LEGACY_KEY)||'null')}catch(_){}}
9 - stored=stored||{}; const now=new Date();
10 - if(!stored.trialStartedAt)stored.trialStartedAt=now.toISOString();
11 - if(!Number.isFinite(stored.issuedInvoiceCount))stored.issuedInvoiceCount=0;
12 - if(!stored.installationId)stored.installationId=crypto.randomUUID();
13 - this.state=stored; await this._save(); localStorage.removeItem(LEGACY_KEY); return this.status();
14 - }
15 - async _save(){await SecureState.set(KEY,this.state);}
16 - status(){
17 - const s=this.state||{};
18 - // Never accept a locally editable `active` flag as proof of a paid entitlement.
19 - // Signed entitlement verification must succeed before licensed mode is enabled.
20 - return trialStatus(s); // Until server-issued signatures are verified at startup, remain in trial mode.
21 - }
22 - assertWritable(){if(this.status().readOnly)throw new Error('دوره استفاده یا مجوز به پایان رسیده است؛ اطلاعات فقط قابل مشاهده‌اند.');}
23 - async recordIssuedInvoice(){this.assertWritable();this.state.issuedInvoiceCount=(Number(this.state.issuedInvoiceCount)||0)+1;await this._save();return this.status();}
24 - installationId(){return this.state?.installationId||null;}
3 +import { validateEntitlementPayload } from './EntitlementVerifier.mjs';
4 +import { loadProductionLicensePublicKey, validateOfflineActivation } from './LicenseActivationCore.mjs';
5 +
6 +const KEY = 'finora_pro_entitlement_v2';
7 +const LEGACY_KEY = 'finora_pro_entitlement_v1';
8 +// This public key is embedded by the release build. No private signing key
9 +// exists in the application, its repository, or any public artifact.
10 +const trustedPublicKey = loadProductionLicensePublicKey(
11 + import.meta.env?.VITE_LICENSE_PUBLIC_JWK || ''
12 +);
13 +
14 +class LicenseServiceImpl {
15 + constructor() {
16 + this.state = null;
17 + this.verifiedPayload = null;
18 + this.clockRollback = false;
19 + }
20 +
21 + async init() {
22 + let stored = await SecureState.get(KEY);
23 + if (!stored) {
24 + try { stored = JSON.parse(localStorage.getItem(LEGACY_KEY) || 'null'); }
25 + catch (_) { /* Invalid legacy state is not an entitlement. */ }
26 + }
27 + stored = stored && typeof stored === 'object' && !Array.isArray(stored) ? stored : {};
28 + const now = Date.now();
29 + if (!stored.trialStartedAt || !Number.isFinite(Date.parse(stored.trialStartedAt))) {
30 + stored.trialStartedAt = new Date(now).toISOString();
31 + }
32 + if (!Number.isSafeInteger(stored.issuedInvoiceCount) || stored.issuedInvoiceCount < 0) {
33 + stored.issuedInvoiceCount = 0;
34 + }
35 + if (!stored.installationId || typeof stored.installationId !== 'string') {
36 + stored.installationId = crypto.randomUUID();
37 + }
38 + const previousClock = Date.parse(stored.lastSeenAt || '');
39 + this.clockRollback = Number.isFinite(previousClock) && now + 5 * 60 * 1000 < previousClock;
40 + this.state = stored;
41 + this.verifiedPayload = null;
42 + if (!this.clockRollback && await validateOfflineActivation(
43 + stored.signedEntitlement, trustedPublicKey, stored.installationId, now
44 + )) {
45 + this.verifiedPayload = structuredClone(stored.signedEntitlement.payload);
46 + }
47 + // Preserve a previous future timestamp on rollback; do not overwrite proof.
48 + if (!this.clockRollback) stored.lastSeenAt = new Date(now).toISOString();
49 + await this._save();
50 + localStorage.removeItem(LEGACY_KEY);
51 + return this.status();
52 + }
53 +
54 + async _save() { await SecureState.set(KEY, this.state); }
55 + hasTrustedIssuer() { return Boolean(trustedPublicKey); }
56 + installationId() { return this.state?.installationId || null; }
57 +
58 + status() {
59 + const s = this.state || {};
60 + const now = Date.now();
61 + const previousClock = Date.parse(s.lastSeenAt || '');
62 + const rollback = this.clockRollback ||
63 + (Number.isFinite(previousClock) && now + 5 * 60 * 1000 < previousClock);
64 + if (this.verifiedPayload && validateEntitlementPayload(
65 + this.verifiedPayload, s.installationId, now
66 + )) {
67 + return { ...licensedStatus(this.verifiedPayload, now),
68 + readOnly: rollback || licensedStatus(this.verifiedPayload, now).readOnly,
69 + installationId: s.installationId };
70 + }
71 + if (s.signedEntitlement) {
72 + // Never treat a bad/expired signature as a renewed free trial.
73 + return { ...trialStatus(s, now), mode: 'license-invalid', readOnly: true,
74 + installationId: s.installationId };
75 + }
76 + const trial = trialStatus(s, now);
77 + return { ...trial, readOnly: rollback || trial.readOnly,
78 + installationId: s.installationId };
79 + }
80 +
81 + async activateSignedLicense(rawToken) {
82 + if (!this.state) throw new Error('سامانه مجوز هنوز راه‌اندازی نشده است');
83 + if (!trustedPublicKey) {
84 + throw new Error('کلید عمومی صادرکننده معتبر در این نسخه پیکربندی نشده است');
85 + }
86 + let token = rawToken;
87 + if (typeof rawToken === 'string') {
88 + try { token = JSON.parse(rawToken); }
89 + catch { throw new Error('ساختار فایل یا متن مجوز نامعتبر است'); }
90 + }
91 + if (!await validateOfflineActivation(token, trustedPublicKey,
92 + this.state.installationId)) {
93 + throw new Error('امضا، تاریخ یا شناسه دستگاه در مجوز معتبر نیست');
94 + }
95 + const next = { ...this.state, signedEntitlement: structuredClone(token) };
96 + await SecureState.set(KEY, next);
97 + this.state = next;
98 + this.verifiedPayload = structuredClone(token.payload);
99 + return this.status();
100 + }
101 +
102 + assertWritable() {
103 + if (this.status().readOnly) {
104 + throw new Error('دوره استفاده یا مجوز به پایان رسیده است؛ اطلاعات فقط قابل مشاهده‌اند.');
105 + }
106 + }
107 + async recordIssuedInvoice() {
108 + this.assertWritable();
109 + this.state.issuedInvoiceCount = (this.state.issuedInvoiceCount || 0) + 1;
110 + await this._save();
111 + return this.status();
112 + }
113 }
26 -export const LicenseService=new LicenseServiceImpl();
114 +export const LicenseService = new LicenseServiceImpl();
src/views/SettingsView.js
+63
@@ -13,6 +13,7 @@ import { Auth } from '../core/Auth.js';
13 import { ExcelController } from '../controllers/ExcelController.js';
14 import { inspectSettlementConsistency } from '../core/FinancialDiagnosticsService.js';
15 import { AuditService } from '../core/AuditService.js';
16 +import { LicenseService } from '../core/LicenseService.js';
17
18 let cache = { company: {}, stats: {}, invoiceSettings: { numberingMode: 'auto', nextNumber: 1 } };
19
@@ -31,6 +32,7 @@ class SettingsViewImpl {
32 ${this._renderExcelCard()}
33 ${this._renderShortcutsCard()}
34 ${this._renderBackupCard()}
35 + ${Auth.isAdmin() ? this._renderLicenseCard() : ''}
36 ${this._renderStatsCard()}
37 ${Auth.isAdmin() ? this._renderHealthCard() : ''}
38 ${Auth.isAdmin() ? this._renderAuditCard() : ''}
@@ -693,12 +695,73 @@ class SettingsViewImpl {
695 `;
696 }
697
698 + _renderLicenseCard() {
699 + const state = LicenseService.status();
700 + const mode = state.mode === 'licensed' ? 'مجوز امضاشده معتبر' :
701 + state.mode === 'license-invalid' ? 'مجوز نامعتبر یا منقضی' : 'نسخه آزمایشی';
702 + const machine = this._esc(LicenseService.installationId() || 'نامشخص');
703 + const readiness = LicenseService.hasTrustedIssuer()
704 + ? 'کلید عمومی صادرکننده فعال است'
705 + : 'فعلاً کلید عمومی صدور مجوز در نسخه نصب‌شده تنظیم نشده است';
706 + return `
707 + <div class="card settings-card">
708 + <div class="settings-card-header">
709 + <div class="settings-card-icon">🔐</div>
710 + <div>
711 + <h3 class="settings-card-title">مجوز آفلاین نرم‌افزار</h3>
712 + <p class="settings-card-desc">وضعیت: ${this._esc(mode)} — ${state.readOnly ? 'فقط مشاهده' : 'قابل ثبت'}</p>
713 + </div>
714 + </div>
715 + <div style="font-size:12px;line-height:2">
716 + <div>شناسه نصب: <code dir="ltr" style="overflow-wrap:anywhere">${machine}</code></div>
717 + <div>${this._esc(readiness)}</div>
718 + </div>
719 + <button class="btn btn-secondary" onclick="window.SettingsView.openSignedLicenseModal()" ${LicenseService.hasTrustedIssuer() ? '' : 'disabled'}>
720 + فعال‌سازی با مجوز امضاشده
721 + </button>
722 + <small style="display:block;margin-top:8px">برای فعال‌سازی، مجوز صادرشده مخصوص همین شناسه نصب لازم است؛ اطلاعات حسابداری در صورت انقضا حذف نمی‌شود.</small>
723 + </div>
724 + `;
725 + }
726 +
727 + openSignedLicenseModal() {
728 + if (!Auth.isAdmin()) { Toast.error('فقط مدیر مجاز است'); return; }
729 + if (!LicenseService.hasTrustedIssuer()) {
730 + Toast.error('کلید معتبر صادرکننده در این نسخه نصب نشده است'); return;
731 + }
732 + Modal.open({
733 + title: 'فعال‌سازی مجوز آفلاین',
734 + body: '<label for="signedLicenseToken">متن JSON مجوز امضاشده</label>' +
735 + '<textarea id="signedLicenseToken" class="form-control" rows="8" spellcheck="false" dir="ltr"></textarea>' +
736 + '<p style="font-size:12px">امضای دیجیتال و شناسه دستگاه پیش از هر تغییر اعتبارسنجی می‌شوند.</p>',
737 + footer: '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>' +
738 + '<button class="btn" onclick="window.SettingsView.applySignedLicense()">اعتبارسنجی و فعال‌سازی</button>',
739 + size: 'md'
740 + });
741 + }
742 +
743 + async applySignedLicense() {
744 + if (!Auth.isAdmin()) { Toast.error('فقط مدیر مجاز است'); return; }
745 + const token = document.getElementById('signedLicenseToken')?.value;
746 + if (!token?.trim()) { Toast.error('متن مجوز خالی است'); return; }
747 + try {
748 + await LicenseService.activateSignedLicense(token.trim());
749 + Modal.close();
750 + const grid = document.querySelector('.settings-grid');
751 + if (grid) grid.innerHTML = this._renderAllCards();
752 + Toast.success('مجوز آفلاین معتبر با موفقیت فعال شد');
753 + } catch (error) {
754 + Toast.error(error.message);
755 + }
756 + }
757 +
758 _renderAllCards() {
759 return this._renderCompanyCard()
760 + this._renderInvoiceSettingsCard()
761 + this._renderExcelCard()
762 + this._renderShortcutsCard()
763 + this._renderBackupCard()
764 + + (Auth.isAdmin() ? this._renderLicenseCard() : '')
765 + this._renderStatsCard()
766 + (Auth.isAdmin() ? this._renderHealthCard() : '')
767 + (Auth.isAdmin() ? this._renderAuditCard() : '')
tests/a06-signed-license-integration.test.mjs new
+68
@@ -0,0 +1,68 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { canonical } from '../src/core/EntitlementVerifier.mjs';
4 +import { loadProductionLicensePublicKey, validateOfflineActivation }
5 + from '../src/core/LicenseActivationCore.mjs';
6 +
7 +const NOW = Date.UTC(2026, 9, 15);
8 +async function newSignedExample() {
9 + const keys = await crypto.subtle.generateKey({
10 + name: 'ECDSA', namedCurve: 'P-256'
11 + }, true, ['sign', 'verify']);
12 + const pub = await crypto.subtle.exportKey('jwk', keys.publicKey);
13 + const payload = {
14 + product: 'Factor-easyPro',
15 + installationId: 'device-hardware-1', perpetual: true,
16 + issuedAt: '2026-10-15T00:00:00.000Z',
17 + lastOnlineCheckAt: '2026-10-15T00:00:00.000Z',
18 + maxCompanies: 5, maxUsers: 4, maxDevices: 1
19 + };
20 + const sign = async value => {
21 + const sig = await crypto.subtle.sign({
22 + name: 'ECDSA', hash: 'SHA-256'
23 + }, keys.privateKey, new TextEncoder().encode(canonical(value)));
24 + return { payload: value, signature: Buffer.from(sig).toString('base64url') };
25 + };
26 + return { pub, payload, sign };
27 +}
28 +
29 +test('A06: only a trusted public P-256 key without private scalar is accepted', async () => {
30 + const { pub } = await newSignedExample();
31 + assert.deepEqual(loadProductionLicensePublicKey(JSON.stringify(pub)), pub);
32 + assert.equal(loadProductionLicensePublicKey(null), null);
33 + assert.equal(loadProductionLicensePublicKey('{}'), null);
34 + assert.equal(loadProductionLicensePublicKey('{invalid-json'), null);
35 + assert.equal(loadProductionLicensePublicKey(JSON.stringify({ ...pub, d: 'secret' })), null);
36 +});
37 +
38 +test('A06: locally generated signed license verifies when bound to this exact installation', async () => {
39 + const { pub, payload, sign } = await newSignedExample();
40 + const token = await sign(payload);
41 + assert.equal(await validateOfflineActivation(token, pub, 'device-hardware-1', NOW), true);
42 + assert.equal(await validateOfflineActivation(token, pub, 'another-device', NOW), false);
43 + assert.equal(await validateOfflineActivation(
44 + { ...token, payload: { ...payload, maxUsers: 8 } }, pub, 'device-hardware-1', NOW
45 + ), false);
46 + assert.equal(await validateOfflineActivation(
47 + { ...token, signature: 'tampered' }, pub, 'device-hardware-1', NOW
48 + ), false);
49 +});
50 +
51 +test('A06: signed lease fails closed after 30 days, before activation, or on future timestamps', async () => {
52 + const { pub, payload, sign } = await newSignedExample();
53 + const token = await sign(payload);
54 + const DAY = 86400000;
55 + assert.equal(await validateOfflineActivation(token, pub, payload.installationId, NOW + 31 * DAY), false);
56 + assert.equal(await validateOfflineActivation(token, pub, payload.installationId, NOW - DAY), false);
57 + const future = await sign({
58 + ...payload, issuedAt: '2026-10-20T00:00:00.000Z',
59 + lastOnlineCheckAt: '2026-10-20T00:00:00.000Z'
60 + });
61 + assert.equal(await validateOfflineActivation(future, pub, payload.installationId, NOW), false);
62 +});
63 +
64 +test('A06: a caller-supplied forged public key is not automatically trusted by the application', async () => {
65 + const { payload, sign } = await newSignedExample();
66 + const attackerToken = await sign(payload);
67 + assert.equal(await validateOfflineActivation(attackerToken, null, payload.installationId, NOW), false);
68 +});