فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
feat(A06): verify signed license at startup and support protected offline activation
davoodmehraban89 committed
Oct 15, 2026 at 20:45 UTC
b4ddff5bfd649c0d52da5b4739b83516cf8aaf1d
1 file changed
+111
-23
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();