@extenshi/pay 0.9.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +138 -17
- package/dist/api/mock.d.ts +4 -0
- package/dist/api/mock.d.ts.map +1 -1
- package/dist/api/pay-api.d.ts +9 -4
- package/dist/api/pay-api.d.ts.map +1 -1
- package/dist/core/config.d.ts.map +1 -1
- package/dist/core/extenshi-pay.d.ts +60 -5
- package/dist/core/extenshi-pay.d.ts.map +1 -1
- package/dist/core/index.d.ts +3 -1
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/storage.d.ts +6 -0
- package/dist/core/storage.d.ts.map +1 -1
- package/dist/core.d.mts +271 -26
- package/dist/core.d.ts +271 -26
- package/dist/core.js +589 -49
- package/dist/core.js.map +1 -1
- package/dist/core.mjs +584 -50
- package/dist/core.mjs.map +1 -1
- package/dist/extenshi-pay-lite.js +577 -49
- package/dist/extenshi-pay-lite.js.map +1 -1
- package/dist/extenshi-pay-lite.min.js +3 -3
- package/dist/extenshi-pay-lite.min.js.map +1 -1
- package/dist/extenshi-pay-lite.mjs +577 -49
- package/dist/extenshi-pay-lite.mjs.map +1 -1
- package/dist/extenshi-pay.cjs.js +694 -61
- package/dist/extenshi-pay.cjs.js.map +1 -1
- package/dist/extenshi-pay.d.ts +11 -1
- package/dist/extenshi-pay.d.ts.map +1 -1
- package/dist/extenshi-pay.js +694 -61
- package/dist/extenshi-pay.js.map +1 -1
- package/dist/extenshi-pay.min.js +3 -3
- package/dist/extenshi-pay.min.js.map +1 -1
- package/dist/extenshi-pay.min.mjs +3 -3
- package/dist/extenshi-pay.min.mjs.map +1 -1
- package/dist/extenshi-pay.mjs +689 -62
- package/dist/extenshi-pay.mjs.map +1 -1
- package/dist/index.d.mts +288 -26
- package/dist/index.d.ts +288 -26
- package/dist/lite.d.mts +214 -13
- package/dist/lite.d.ts +214 -13
- package/dist/lite.d.ts.map +1 -1
- package/dist/payment/cloud-backup.d.ts +35 -0
- package/dist/payment/cloud-backup.d.ts.map +1 -0
- package/dist/payment/entitlement.d.ts +21 -5
- package/dist/payment/entitlement.d.ts.map +1 -1
- package/dist/payment/recovery.d.ts +4 -2
- package/dist/payment/recovery.d.ts.map +1 -1
- package/dist/payment/signature.d.ts +29 -3
- package/dist/payment/signature.d.ts.map +1 -1
- package/dist/payment/trial.d.ts +55 -0
- package/dist/payment/trial.d.ts.map +1 -0
- package/dist/paywall/i18n.d.ts +3 -0
- package/dist/paywall/i18n.d.ts.map +1 -1
- package/dist/paywall/renderer.d.ts +7 -0
- package/dist/paywall/renderer.d.ts.map +1 -1
- package/dist/paywall.d.mts +7 -0
- package/dist/paywall.d.ts +7 -0
- package/dist/paywall.js +54 -14
- package/dist/paywall.js.map +1 -1
- package/dist/paywall.mjs +54 -14
- package/dist/paywall.mjs.map +1 -1
- package/dist/types/config.d.ts +27 -1
- package/dist/types/config.d.ts.map +1 -1
- package/dist/types/contract.d.ts +36 -0
- package/dist/types/contract.d.ts.map +1 -1
- package/dist/types/entitlement.d.ts +39 -1
- package/dist/types/entitlement.d.ts.map +1 -1
- package/dist/types/events.d.ts +5 -1
- package/dist/types/events.d.ts.map +1 -1
- package/dist/types/paywall.d.ts +10 -0
- package/dist/types/paywall.d.ts.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.d.ts.map +1 -1
- package/package.json +3 -2
package/dist/extenshi-pay.cjs.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* ExtenshiPay SDK v0.
|
|
2
|
+
* ExtenshiPay SDK v0.12.0
|
|
3
3
|
* (c) 2026 Extenshi.io
|
|
4
4
|
* Released under the MIT License.
|
|
5
|
-
* commit
|
|
5
|
+
* commit 7f4b4e98165b3c8eb11e100b3855fee1ade7aaab · built by `rollup -c`
|
|
6
6
|
*/
|
|
7
7
|
'use strict';
|
|
8
8
|
|
|
@@ -50,6 +50,8 @@ const PAY_SKU_RE = /^[a-z0-9][a-z0-9_-]{1,39}$/;
|
|
|
50
50
|
* none — never had it
|
|
51
51
|
*/
|
|
52
52
|
const PAY_ENTITLEMENT_STATUSES = ['active', 'grace', 'expired', 'none'];
|
|
53
|
+
// Outside the seller SKU grammar. Issued only in a signed projection, never in the sales ledger.
|
|
54
|
+
const PAY_REGIONAL_ACCESS_SKU = '@regional-free';
|
|
53
55
|
/**
|
|
54
56
|
* Version of the buyer-facing withdrawal waiver text the paywall shows (EU/EEA
|
|
55
57
|
* digital content, Directive 2011/83/EU art. 16(m); UK CCR 2013 reg. 37). The
|
|
@@ -90,6 +92,14 @@ function canonicalJson(value) {
|
|
|
90
92
|
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
91
93
|
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`;
|
|
92
94
|
}
|
|
95
|
+
/**
|
|
96
|
+
* `storage`: the buyer turns on the cloud copy of the extension's settings. The
|
|
97
|
+
* hosted page shows the storage disclosure; the claim records consent. Additive:
|
|
98
|
+
* a session without a purpose is a plain restore.
|
|
99
|
+
*/
|
|
100
|
+
const PAY_RESTORE_PURPOSES = ['restore', 'storage'];
|
|
101
|
+
/** From `shared-types/storage.ts`: `est_` + 32 random bytes, base64url. */
|
|
102
|
+
const STORAGE_TOKEN_RE = /^est_[A-Za-z0-9_-]{43}$/;
|
|
93
103
|
|
|
94
104
|
const ERROR_CODES = {
|
|
95
105
|
INVALID_CONFIG: 'INVALID_CONFIG',
|
|
@@ -161,7 +171,7 @@ async function getOrCreateEndUserRef(storage) {
|
|
|
161
171
|
* developed with no backend: offers and entitlements come from `mockData`, a
|
|
162
172
|
* mock checkout completes after `claimAfterPolls` polls and grants the SKU.
|
|
163
173
|
*/
|
|
164
|
-
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
174
|
+
const DAY_MS$1 = 24 * 60 * 60 * 1000;
|
|
165
175
|
/** Accepts the same optional `withdrawalWaiver` input as the BFF; anything else is no consent. */
|
|
166
176
|
function mockConsent(value) {
|
|
167
177
|
const consent = value;
|
|
@@ -179,6 +189,10 @@ class MockTransport {
|
|
|
179
189
|
this.claimAfterPolls = data.claimAfterPolls ?? 1;
|
|
180
190
|
this.withdrawalWaiver =
|
|
181
191
|
data.withdrawalWaiver === undefined ? { version: PAY_WITHDRAWAL_WAIVER_VERSION } : data.withdrawalWaiver;
|
|
192
|
+
this.seller = data.seller;
|
|
193
|
+
this.trial = null;
|
|
194
|
+
if (data.trial)
|
|
195
|
+
this.setTrial(data.trial.days, data.trial.startedAt);
|
|
182
196
|
}
|
|
183
197
|
async call(procedure, _kind, input) {
|
|
184
198
|
switch (procedure) {
|
|
@@ -200,6 +214,14 @@ class MockTransport {
|
|
|
200
214
|
setEntitlements(items) {
|
|
201
215
|
this.entitlements = [...items];
|
|
202
216
|
}
|
|
217
|
+
/** Previews a server trial of `days` from `startedAt` (default now); `null` removes it. */
|
|
218
|
+
setTrial(days, startedAt = new Date().toISOString()) {
|
|
219
|
+
const start = Date.parse(startedAt);
|
|
220
|
+
this.trial =
|
|
221
|
+
days === null || !Number.isFinite(start)
|
|
222
|
+
? null
|
|
223
|
+
: { startedAt: new Date(start).toISOString(), endsAt: new Date(start + days * DAY_MS$1).toISOString() };
|
|
224
|
+
}
|
|
203
225
|
cancelSession(sessionId) {
|
|
204
226
|
const session = this.sessions.get(sessionId);
|
|
205
227
|
if (session)
|
|
@@ -219,6 +241,7 @@ class MockTransport {
|
|
|
219
241
|
offers: [...this.offers],
|
|
220
242
|
entitlementPublicKey: null,
|
|
221
243
|
withdrawalWaiver: this.withdrawalWaiver ? { ...this.withdrawalWaiver } : null,
|
|
244
|
+
...(this.seller !== undefined && { seller: this.seller ? { ...this.seller } : null }),
|
|
222
245
|
};
|
|
223
246
|
}
|
|
224
247
|
createCheckout(sku, withdrawalWaiver) {
|
|
@@ -256,7 +279,7 @@ class MockTransport {
|
|
|
256
279
|
grant(sku) {
|
|
257
280
|
const offer = this.offers.find((o) => o.sku === sku);
|
|
258
281
|
const expiresAt = offer?.kind === 'subscription'
|
|
259
|
-
? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS).toISOString()
|
|
282
|
+
? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS$1).toISOString()
|
|
260
283
|
: null;
|
|
261
284
|
this.entitlements = [
|
|
262
285
|
...this.entitlements.filter((item) => item.sku !== sku),
|
|
@@ -278,6 +301,7 @@ class MockTransport {
|
|
|
278
301
|
endUserRef,
|
|
279
302
|
entitlements: [...this.entitlements],
|
|
280
303
|
issuedAt: new Date().toISOString(),
|
|
304
|
+
...(this.trial ? { trial: { ...this.trial } } : {}),
|
|
281
305
|
},
|
|
282
306
|
signature: null,
|
|
283
307
|
alg: null,
|
|
@@ -291,12 +315,17 @@ class PayApi {
|
|
|
291
315
|
this.transport = transport;
|
|
292
316
|
this.publishableKey = publishableKey;
|
|
293
317
|
}
|
|
294
|
-
/**
|
|
295
|
-
|
|
318
|
+
/**
|
|
319
|
+
* `locale` opens the hosted recovery page (and its email) in the user's language.
|
|
320
|
+
* `purpose` is sent only for `storage`: a plain restore keeps the request older
|
|
321
|
+
* BFFs know, and their non-strict zod input strips the key anyway.
|
|
322
|
+
*/
|
|
323
|
+
createRestoreSession(claimChallenge, locale, purpose) {
|
|
296
324
|
return this.transport.call('pay.createRestoreSession', 'mutation', {
|
|
297
325
|
publishableKey: this.publishableKey,
|
|
298
326
|
claimChallenge,
|
|
299
327
|
...(locale ? { locale } : {}),
|
|
328
|
+
...(purpose === 'storage' ? { purpose } : {}),
|
|
300
329
|
});
|
|
301
330
|
}
|
|
302
331
|
claimRestoreSession(sessionId, claimSecret) {
|
|
@@ -335,10 +364,12 @@ class PayApi {
|
|
|
335
364
|
endUserRef,
|
|
336
365
|
});
|
|
337
366
|
}
|
|
338
|
-
|
|
367
|
+
/** `trialStartedHint`: the trial start kept in storage.sync; the server only lets it move a start earlier. */
|
|
368
|
+
getEntitlement(endUserRef, trialStartedHint) {
|
|
339
369
|
return this.transport.call('pay.getEntitlement', 'query', {
|
|
340
370
|
publishableKey: this.publishableKey,
|
|
341
371
|
endUserRef,
|
|
372
|
+
...(trialStartedHint ? { trialStartedHint } : {}),
|
|
342
373
|
});
|
|
343
374
|
}
|
|
344
375
|
getPortalUrl(endUserRef, customerId, locale) {
|
|
@@ -736,6 +767,118 @@ var checkout = /*#__PURE__*/Object.freeze({
|
|
|
736
767
|
openInNewTab: openInNewTab
|
|
737
768
|
});
|
|
738
769
|
|
|
770
|
+
/**
|
|
771
|
+
* Cloud copy of the extension's settings (`@extenshi/storage`). Pay owns the
|
|
772
|
+
* token: only a verified restore claim issues it; this module keeps it in the
|
|
773
|
+
* SDK's storage (`storage.local`) and revokes it. `@extenshi/storage` reads it
|
|
774
|
+
* through `cloudBackupToken()`. The token is never logged and never answered to
|
|
775
|
+
* a content script: route those calls to the background.
|
|
776
|
+
*/
|
|
777
|
+
const REQUEST_TIMEOUT_MS = 10000;
|
|
778
|
+
/** True in a content script, where the token must not be handed out. */
|
|
779
|
+
function inContentScript() {
|
|
780
|
+
const g = globalThis;
|
|
781
|
+
return !!(g.chrome?.runtime?.id || g.browser?.runtime?.id) && !(g.chrome?.tabs || g.browser?.tabs);
|
|
782
|
+
}
|
|
783
|
+
class CloudBackup {
|
|
784
|
+
constructor(options) {
|
|
785
|
+
this.options = options;
|
|
786
|
+
this.fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));
|
|
787
|
+
}
|
|
788
|
+
get storageKey() {
|
|
789
|
+
return `extenshi-pay:${this.options.publishableKey}:storageToken`;
|
|
790
|
+
}
|
|
791
|
+
/** Stores or clears the token from a verified claim. Never throws: the licence is already restored. */
|
|
792
|
+
async accept(grant) {
|
|
793
|
+
if (!grant || typeof grant !== 'object')
|
|
794
|
+
return undefined;
|
|
795
|
+
try {
|
|
796
|
+
if (grant.state === 'granted') {
|
|
797
|
+
if (typeof grant.token !== 'string' || !STORAGE_TOKEN_RE.test(grant.token))
|
|
798
|
+
return undefined;
|
|
799
|
+
await this.options.storage.set(this.storageKey, grant.token);
|
|
800
|
+
return 'on';
|
|
801
|
+
}
|
|
802
|
+
if (grant.state === 'unavailable') {
|
|
803
|
+
await this.options.storage.remove(this.storageKey);
|
|
804
|
+
return grant.reason === 'LICENSE_REQUIRED' ? 'license_required' : 'no_consent';
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
catch {
|
|
808
|
+
logger.warn('cloud backup state could not be saved');
|
|
809
|
+
}
|
|
810
|
+
return undefined;
|
|
811
|
+
}
|
|
812
|
+
async token() {
|
|
813
|
+
this.assertTrustedContext();
|
|
814
|
+
const value = await this.options.storage.get(this.storageKey);
|
|
815
|
+
return typeof value === 'string' && STORAGE_TOKEN_RE.test(value) ? value : null;
|
|
816
|
+
}
|
|
817
|
+
/** Revokes this installation's token. A token the server no longer knows (401) is forgotten too. */
|
|
818
|
+
async disable() {
|
|
819
|
+
const token = await this.token();
|
|
820
|
+
if (!token)
|
|
821
|
+
return;
|
|
822
|
+
if (!this.options.mock) {
|
|
823
|
+
const status = await this.request('/v1/storage/grant', token);
|
|
824
|
+
if (status !== 401)
|
|
825
|
+
this.throwUnlessOk(status);
|
|
826
|
+
}
|
|
827
|
+
await this.options.storage.remove(this.storageKey);
|
|
828
|
+
}
|
|
829
|
+
/** Deletes the buyer's cloud copy and turns the backup off on every device. */
|
|
830
|
+
async delete() {
|
|
831
|
+
const token = await this.token();
|
|
832
|
+
if (!token)
|
|
833
|
+
throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Cloud backup is off on this installation; turn it on to delete the cloud copy');
|
|
834
|
+
if (!this.options.mock) {
|
|
835
|
+
const status = await this.request('/v1/storage/data', token);
|
|
836
|
+
if (status === 401) {
|
|
837
|
+
// The server no longer accepts this token, so it is useless here; the copy was not deleted.
|
|
838
|
+
await this.options.storage.remove(this.storageKey);
|
|
839
|
+
throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Cloud backup is off on the server; turn it on again to delete the cloud copy', { httpStatus: 401 });
|
|
840
|
+
}
|
|
841
|
+
this.throwUnlessOk(status);
|
|
842
|
+
}
|
|
843
|
+
await this.options.storage.remove(this.storageKey);
|
|
844
|
+
}
|
|
845
|
+
assertTrustedContext() {
|
|
846
|
+
if (inContentScript())
|
|
847
|
+
throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Use cloud backup from an extension page or background context');
|
|
848
|
+
}
|
|
849
|
+
throwUnlessOk(status) {
|
|
850
|
+
if (status >= 200 && status < 300)
|
|
851
|
+
return;
|
|
852
|
+
if (status === 429)
|
|
853
|
+
throw new ExtenshiPayError(ERROR_CODES.RATE_LIMITED, 'Too many requests', { httpStatus: status });
|
|
854
|
+
if (status >= 500)
|
|
855
|
+
throw new ExtenshiPayError(ERROR_CODES.GATEWAY_UNAVAILABLE, `HTTP ${status}`, { httpStatus: status });
|
|
856
|
+
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, `HTTP ${status}`, { httpStatus: status });
|
|
857
|
+
}
|
|
858
|
+
async request(path, token) {
|
|
859
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
|
860
|
+
const timer = controller ? setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS) : null;
|
|
861
|
+
try {
|
|
862
|
+
const response = await this.fetchImpl(`${this.options.apiUrl}${path}`, {
|
|
863
|
+
method: 'DELETE',
|
|
864
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
865
|
+
credentials: 'omit',
|
|
866
|
+
signal: controller?.signal,
|
|
867
|
+
});
|
|
868
|
+
return response.status;
|
|
869
|
+
}
|
|
870
|
+
catch (error) {
|
|
871
|
+
if (controller?.signal.aborted)
|
|
872
|
+
throw new ExtenshiPayError(ERROR_CODES.TIMEOUT, `Request timed out after ${REQUEST_TIMEOUT_MS}ms`);
|
|
873
|
+
throw new ExtenshiPayError(ERROR_CODES.NETWORK_ERROR, 'Network request failed', { cause: error });
|
|
874
|
+
}
|
|
875
|
+
finally {
|
|
876
|
+
if (timer !== null)
|
|
877
|
+
clearTimeout(timer);
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
|
|
739
882
|
/** Pure helpers over the entitlement projection. Features come from the items' `features[]`. */
|
|
740
883
|
const LIVE_STATUSES = new Set(['active', 'grace']);
|
|
741
884
|
function isLive(item) {
|
|
@@ -790,9 +933,17 @@ Object.freeze(EMPTY_ENTITLEMENT.features);
|
|
|
790
933
|
/**
|
|
791
934
|
* Ed25519 verification of the entitlement projection.
|
|
792
935
|
*
|
|
793
|
-
* Tamper resistance, not DRM.
|
|
794
|
-
*
|
|
795
|
-
*
|
|
936
|
+
* Tamper resistance, not DRM. Callers must deny access for both invalid and
|
|
937
|
+
* unverified envelopes outside explicit mocks.
|
|
938
|
+
*
|
|
939
|
+
* Which keys are trusted, in order (`PublicKeySource`, built in core/extenshi-pay.ts):
|
|
940
|
+
* 1. the key the server returned over HTTPS in this session;
|
|
941
|
+
* 2. the bundled `entitlementPublicKey`, when the developer configured one. It pins
|
|
942
|
+
* verification without a round-trip: a key read from extension storage is then never used;
|
|
943
|
+
* 3. without a bundled key, the server key saved in `storage.local` next to the
|
|
944
|
+
* license cache, so a restart with no network can still verify the cache.
|
|
945
|
+
* When none of them verifies an envelope the server is asked for its current key once
|
|
946
|
+
* (a rotated key), and that answer decides.
|
|
796
947
|
*/
|
|
797
948
|
function base64ToBytes(base64) {
|
|
798
949
|
const binary = atob(base64);
|
|
@@ -827,6 +978,156 @@ async function verifyEntitlementSignature(envelope, publicKeyBase64) {
|
|
|
827
978
|
return 'invalid';
|
|
828
979
|
}
|
|
829
980
|
}
|
|
981
|
+
const PUBLIC_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
|
|
982
|
+
/**
|
|
983
|
+
* `invalid` only when the server's current key was checked too (or the envelope carries no
|
|
984
|
+
* signature at all). A mismatch against known keys while the server is unreachable is
|
|
985
|
+
* `unverified`: it may be a rotated key, and no paid access is granted either way.
|
|
986
|
+
*/
|
|
987
|
+
async function verifyWithKeys(envelope, source) {
|
|
988
|
+
if (!envelope.signature || envelope.alg !== 'ed25519')
|
|
989
|
+
return { verdict: 'invalid', key: null };
|
|
990
|
+
let known = [];
|
|
991
|
+
try {
|
|
992
|
+
known = await source.known();
|
|
993
|
+
}
|
|
994
|
+
catch {
|
|
995
|
+
known = [];
|
|
996
|
+
}
|
|
997
|
+
let mismatch = false;
|
|
998
|
+
for (const key of known) {
|
|
999
|
+
const verdict = await verifyEntitlementSignature(envelope, key);
|
|
1000
|
+
if (verdict === 'valid')
|
|
1001
|
+
return { verdict, key };
|
|
1002
|
+
if (verdict === 'invalid')
|
|
1003
|
+
mismatch = true;
|
|
1004
|
+
}
|
|
1005
|
+
let current;
|
|
1006
|
+
try {
|
|
1007
|
+
current = await source.fetchCurrent();
|
|
1008
|
+
}
|
|
1009
|
+
catch {
|
|
1010
|
+
return { verdict: 'unverified', key: null };
|
|
1011
|
+
}
|
|
1012
|
+
if (current && !known.includes(current)) {
|
|
1013
|
+
const verdict = await verifyEntitlementSignature(envelope, current);
|
|
1014
|
+
return { verdict, key: verdict === 'valid' ? current : null };
|
|
1015
|
+
}
|
|
1016
|
+
return { verdict: mismatch ? 'invalid' : 'unverified', key: null };
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
/**
|
|
1020
|
+
* The free trial an application configures on the server (`trialDays`).
|
|
1021
|
+
*
|
|
1022
|
+
* The server starts one clock per installation at its first license read and
|
|
1023
|
+
* signs `{ startedAt, endsAt }` into the entitlement, so the trial comes from
|
|
1024
|
+
* the verified license like paid access does: no start date in extension
|
|
1025
|
+
* storage, nothing a device clock or a storage edit can move. Offline, the
|
|
1026
|
+
* cached license answers for up to 48 hours.
|
|
1027
|
+
*
|
|
1028
|
+
* `trial:ending` / `trial:ended` fire once per installation and trial (the
|
|
1029
|
+
* marker is kept in the SDK's storage), and not while the user has paid
|
|
1030
|
+
* access. Render state from `getTrial()`; the events are one-time notices.
|
|
1031
|
+
*/
|
|
1032
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
1033
|
+
/** Re-check at least daily: long timers are clamped by browsers and lost when a service worker sleeps. */
|
|
1034
|
+
const MAX_TIMER_MS$1 = DAY_MS;
|
|
1035
|
+
/** The trial as of `clock`, or null when the license carries none (or a malformed one). */
|
|
1036
|
+
function trialState(trial, clock) {
|
|
1037
|
+
if (!trial)
|
|
1038
|
+
return null;
|
|
1039
|
+
const startedAt = Date.parse(trial.startedAt);
|
|
1040
|
+
const endsAt = Date.parse(trial.endsAt);
|
|
1041
|
+
if (!Number.isFinite(startedAt) || !Number.isFinite(endsAt))
|
|
1042
|
+
return null;
|
|
1043
|
+
// The server's signed time is a floor: a clock turned back cannot reopen an ended trial.
|
|
1044
|
+
const now = Number.isFinite(clock.issuedAt) ? Math.max(clock.now, clock.issuedAt) : clock.now;
|
|
1045
|
+
const left = endsAt - now;
|
|
1046
|
+
return {
|
|
1047
|
+
active: left > 0 && clock.checked,
|
|
1048
|
+
startedAt: trial.startedAt,
|
|
1049
|
+
endsAt: trial.endsAt,
|
|
1050
|
+
daysLeft: left > 0 ? Math.ceil(left / DAY_MS) : 0,
|
|
1051
|
+
requiresOnlineCheck: left > 0 && !clock.checked,
|
|
1052
|
+
};
|
|
1053
|
+
}
|
|
1054
|
+
/** The feedback form address with `src=trial_end`; null unless it is a plain HTTPS URL. No installation id is added. */
|
|
1055
|
+
function trialFeedbackUrl(raw) {
|
|
1056
|
+
if (!raw)
|
|
1057
|
+
return null;
|
|
1058
|
+
let url;
|
|
1059
|
+
try {
|
|
1060
|
+
url = new URL(raw);
|
|
1061
|
+
}
|
|
1062
|
+
catch {
|
|
1063
|
+
return null;
|
|
1064
|
+
}
|
|
1065
|
+
if (url.protocol !== 'https:' || url.username || url.password)
|
|
1066
|
+
return null;
|
|
1067
|
+
url.searchParams.set('src', 'trial_end');
|
|
1068
|
+
return url.toString();
|
|
1069
|
+
}
|
|
1070
|
+
class TrialNotifier {
|
|
1071
|
+
constructor(options) {
|
|
1072
|
+
this.options = options;
|
|
1073
|
+
this.timer = null;
|
|
1074
|
+
this.running = false;
|
|
1075
|
+
this.pending = Promise.resolve();
|
|
1076
|
+
}
|
|
1077
|
+
start() {
|
|
1078
|
+
this.running = true;
|
|
1079
|
+
void this.evaluate();
|
|
1080
|
+
}
|
|
1081
|
+
stop() {
|
|
1082
|
+
this.running = false;
|
|
1083
|
+
this.clearTimer();
|
|
1084
|
+
}
|
|
1085
|
+
/** Checks the held license; serialized, so two refreshes never send one event twice. */
|
|
1086
|
+
evaluate() {
|
|
1087
|
+
this.pending = this.pending.then(() => this.check()).catch((error) => logger.debug('trial check', error));
|
|
1088
|
+
return this.pending;
|
|
1089
|
+
}
|
|
1090
|
+
async check() {
|
|
1091
|
+
if (!this.running)
|
|
1092
|
+
return;
|
|
1093
|
+
this.clearTimer();
|
|
1094
|
+
const trial = this.options.getTrial();
|
|
1095
|
+
if (!trial)
|
|
1096
|
+
return;
|
|
1097
|
+
const now = this.options.now();
|
|
1098
|
+
const endsAt = Date.parse(trial.endsAt);
|
|
1099
|
+
const endingAt = endsAt - this.options.endingDays * DAY_MS;
|
|
1100
|
+
const event = trial.daysLeft === 0
|
|
1101
|
+
? 'trial:ended'
|
|
1102
|
+
: trial.active && this.options.endingDays > 0 && now >= endingAt
|
|
1103
|
+
? 'trial:ending'
|
|
1104
|
+
: null;
|
|
1105
|
+
if (event && !this.options.hasPaidAccess())
|
|
1106
|
+
await this.send(event, trial);
|
|
1107
|
+
if (!this.running || trial.daysLeft === 0)
|
|
1108
|
+
return;
|
|
1109
|
+
const next = [endingAt, endsAt].find((at) => at > now) ?? endsAt;
|
|
1110
|
+
this.timer = setTimeout(() => {
|
|
1111
|
+
this.timer = null;
|
|
1112
|
+
void this.evaluate();
|
|
1113
|
+
}, Math.max(1000, Math.min(next - now, MAX_TIMER_MS$1)));
|
|
1114
|
+
}
|
|
1115
|
+
async send(event, trial) {
|
|
1116
|
+
const id = `${trial.startedAt}|${trial.endsAt}`;
|
|
1117
|
+
const field = event === 'trial:ended' ? 'ended' : 'ending';
|
|
1118
|
+
const stored = (await this.options.storage.get(this.options.storageKey));
|
|
1119
|
+
const sent = stored && typeof stored === 'object' ? stored : {};
|
|
1120
|
+
if (sent[field] === id || !this.running)
|
|
1121
|
+
return;
|
|
1122
|
+
await this.options.storage.set(this.options.storageKey, { ...sent, [field]: id });
|
|
1123
|
+
this.options.emit(event, trial);
|
|
1124
|
+
}
|
|
1125
|
+
clearTimer() {
|
|
1126
|
+
if (this.timer !== null)
|
|
1127
|
+
clearTimeout(this.timer);
|
|
1128
|
+
this.timer = null;
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
830
1131
|
|
|
831
1132
|
/**
|
|
832
1133
|
* Entitlement cache + refresh.
|
|
@@ -834,13 +1135,18 @@ async function verifyEntitlementSignature(envelope, publicKeyBase64) {
|
|
|
834
1135
|
* The cached envelope is a cache OF the server projection, never a second
|
|
835
1136
|
* source of truth: it is verified when stored and re-verified on load (once
|
|
836
1137
|
* the project's public key is known), served without a round-trip while the
|
|
837
|
-
* TTL holds, served for
|
|
1138
|
+
* TTL holds, served after signed issuance for the signed `offlineSeconds` (48 hours when absent) when the network is down, and expired
|
|
838
1139
|
* locally by `expiresAt`. Background refresh polls at most every 15 minutes
|
|
839
1140
|
* and backs off exponentially on errors.
|
|
840
1141
|
*/
|
|
841
1142
|
const MIN_REFRESH_INTERVAL_MS = 15 * 60 * 1000;
|
|
842
1143
|
const MAX_REFRESH_BACKOFF_MS = 6 * 60 * 60 * 1000;
|
|
1144
|
+
/** Offline allowance when the signed license names none (older servers and caches). */
|
|
843
1145
|
const MAX_OFFLINE_AGE_MS = 48 * 60 * 60 * 1000;
|
|
1146
|
+
/** Ceiling for a signed `offlineSeconds`. */
|
|
1147
|
+
const MAX_SIGNED_OFFLINE_AGE_MS = 366 * 24 * 60 * 60 * 1000;
|
|
1148
|
+
/** `setTimeout` fires at once past this delay. */
|
|
1149
|
+
const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
844
1150
|
// Allow small server/client clock skew without granting more than the signed age limit.
|
|
845
1151
|
const MAX_CLOCK_SKEW_MS = 5 * 60 * 1000;
|
|
846
1152
|
const CACHE_VERSION = 1;
|
|
@@ -859,6 +1165,8 @@ class EntitlementManager {
|
|
|
859
1165
|
this.options = options;
|
|
860
1166
|
this.held = null;
|
|
861
1167
|
this.inflight = null;
|
|
1168
|
+
/** Device clock against the server's at the last license check; null within 5 minutes. */
|
|
1169
|
+
this.clockSkew = null;
|
|
862
1170
|
this.timer = null;
|
|
863
1171
|
this.refreshGeneration = 0;
|
|
864
1172
|
this.deadlineTimer = null;
|
|
@@ -900,8 +1208,10 @@ class EntitlementManager {
|
|
|
900
1208
|
envelope: JSON.parse(JSON.stringify(record.envelope)),
|
|
901
1209
|
fetchedAt: record.fetchedAt,
|
|
902
1210
|
verified: false,
|
|
1211
|
+
key: null,
|
|
903
1212
|
source: this.source === 'mock' ? 'mock' : 'cache',
|
|
904
1213
|
};
|
|
1214
|
+
this.measureClockSkew(record.fetchedAt, Date.parse(record.envelope.payload.issuedAt));
|
|
905
1215
|
this.lastFingerprint = this.fingerprint();
|
|
906
1216
|
return this.snapshot();
|
|
907
1217
|
}
|
|
@@ -912,8 +1222,7 @@ class EntitlementManager {
|
|
|
912
1222
|
if (this.source === 'mock')
|
|
913
1223
|
return;
|
|
914
1224
|
const held = this.held;
|
|
915
|
-
const key = await this.
|
|
916
|
-
const verdict = await verifyEntitlementSignature(held.envelope, key);
|
|
1225
|
+
const { verdict, key } = await verifyWithKeys(held.envelope, this.options.keys);
|
|
917
1226
|
if (held !== this.held)
|
|
918
1227
|
return;
|
|
919
1228
|
if (verdict === 'invalid') {
|
|
@@ -922,19 +1231,39 @@ class EntitlementManager {
|
|
|
922
1231
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Cached entitlement signature is invalid');
|
|
923
1232
|
}
|
|
924
1233
|
held.verified = verdict === 'valid';
|
|
1234
|
+
held.key = key;
|
|
925
1235
|
if (!held.verified) {
|
|
926
1236
|
throw new ExtenshiPayError(ERROR_CODES.VERIFICATION_UNAVAILABLE, 'Entitlement verification requires a trusted key and Ed25519 WebCrypto support');
|
|
927
1237
|
}
|
|
928
1238
|
this.scheduleDeadline();
|
|
929
1239
|
}
|
|
1240
|
+
/** The key the held license was verified with; null when there is none or it is unverified. */
|
|
1241
|
+
get verifiedKey() {
|
|
1242
|
+
return this.held?.verified ? this.held.key : null;
|
|
1243
|
+
}
|
|
930
1244
|
getCached() {
|
|
931
1245
|
return this.held ? this.snapshot() : null;
|
|
932
1246
|
}
|
|
1247
|
+
/** The server trial in the held license; null without one, or while the license is unverified. */
|
|
1248
|
+
getTrial() {
|
|
1249
|
+
const held = this.held;
|
|
1250
|
+
if (!held || (this.source !== 'mock' && !held.verified))
|
|
1251
|
+
return null;
|
|
1252
|
+
const now = this.now();
|
|
1253
|
+
const issuedAt = Date.parse(held.envelope.payload.issuedAt);
|
|
1254
|
+
return trialState(held.envelope.payload.trial, {
|
|
1255
|
+
now,
|
|
1256
|
+
issuedAt,
|
|
1257
|
+
// The same offline rule as paid access (snapshot): the allowance from the signed issue, no clock turned back.
|
|
1258
|
+
checked: this.source === 'mock' ||
|
|
1259
|
+
(now >= held.fetchedAt && now < this.offlineDeadline() && now + MAX_CLOCK_SKEW_MS >= issuedAt),
|
|
1260
|
+
});
|
|
1261
|
+
}
|
|
933
1262
|
isFresh() {
|
|
934
1263
|
return (this.held !== null &&
|
|
935
1264
|
(this.source === 'mock' || (this.held.verified && !this.snapshot().requiresOnlineCheck)) &&
|
|
936
1265
|
this.now() >= this.held.fetchedAt &&
|
|
937
|
-
this.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs,
|
|
1266
|
+
this.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs, this.offlineAgeMs()));
|
|
938
1267
|
}
|
|
939
1268
|
async get(options = {}) {
|
|
940
1269
|
if (!options.force && this.isFresh())
|
|
@@ -949,7 +1278,7 @@ class EntitlementManager {
|
|
|
949
1278
|
logger.debug('serving cached entitlement after refresh failure', err.code);
|
|
950
1279
|
return this.snapshot();
|
|
951
1280
|
}
|
|
952
|
-
return
|
|
1281
|
+
return this.snapshot();
|
|
953
1282
|
}
|
|
954
1283
|
}
|
|
955
1284
|
/** Fetches the projection from the backend, verifies and stores it. */
|
|
@@ -957,7 +1286,8 @@ class EntitlementManager {
|
|
|
957
1286
|
if (!this.inflight) {
|
|
958
1287
|
this.inflight = (async () => {
|
|
959
1288
|
const endUserRef = await this.options.getEndUserRef();
|
|
960
|
-
const
|
|
1289
|
+
const hint = this.options.getTrialStartHint ? await this.options.getTrialStartHint() : null;
|
|
1290
|
+
const envelope = await this.options.api.getEntitlement(endUserRef, hint);
|
|
961
1291
|
return this.accept(envelope, this.source);
|
|
962
1292
|
})().finally(() => {
|
|
963
1293
|
this.inflight = null;
|
|
@@ -979,9 +1309,9 @@ class EntitlementManager {
|
|
|
979
1309
|
if (envelope.payload.endUserRef !== endUserRef) {
|
|
980
1310
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issued for a different endUserRef');
|
|
981
1311
|
}
|
|
982
|
-
const verdict = this.source === 'mock'
|
|
983
|
-
? 'unverified'
|
|
984
|
-
: await
|
|
1312
|
+
const { verdict, key } = this.source === 'mock'
|
|
1313
|
+
? { verdict: 'unverified', key: null }
|
|
1314
|
+
: await verifyWithKeys(envelope, this.options.keys);
|
|
985
1315
|
if (verdict === 'invalid') {
|
|
986
1316
|
await this.discard();
|
|
987
1317
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement signature is invalid');
|
|
@@ -991,15 +1321,19 @@ class EntitlementManager {
|
|
|
991
1321
|
}
|
|
992
1322
|
const fetchedAt = this.now();
|
|
993
1323
|
const issuedAt = Date.parse(envelope.payload.issuedAt);
|
|
1324
|
+
// A verified envelope was signed moments ago: its `issuedAt` is the server's clock.
|
|
1325
|
+
if (this.source !== 'mock')
|
|
1326
|
+
this.measureClockSkew(fetchedAt, issuedAt);
|
|
994
1327
|
if (this.source !== 'mock' && (!Number.isFinite(issuedAt) || issuedAt > fetchedAt + MAX_CLOCK_SKEW_MS)) {
|
|
995
1328
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issuedAt is invalid or in the future');
|
|
996
1329
|
}
|
|
997
|
-
this.held = { envelope, fetchedAt, verified: verdict === 'valid', source };
|
|
1330
|
+
this.held = { envelope, fetchedAt, verified: verdict === 'valid', key, source };
|
|
998
1331
|
const record = { v: CACHE_VERSION, envelope, fetchedAt };
|
|
999
1332
|
await this.options.storage.set(this.storageKey, JSON.parse(JSON.stringify(record)));
|
|
1000
1333
|
this.backoffMs = 0;
|
|
1001
1334
|
this.scheduleDeadline();
|
|
1002
1335
|
this.notifyIfChanged();
|
|
1336
|
+
this.options.onAccepted?.();
|
|
1003
1337
|
return this.snapshot();
|
|
1004
1338
|
}
|
|
1005
1339
|
/** Drain an older installation refresh before changing identity. */
|
|
@@ -1053,7 +1387,7 @@ class EntitlementManager {
|
|
|
1053
1387
|
this.deadlineTimer = null;
|
|
1054
1388
|
this.notifyIfChanged();
|
|
1055
1389
|
this.scheduleDeadline();
|
|
1056
|
-
}, remaining);
|
|
1390
|
+
}, Math.min(remaining, MAX_TIMER_MS));
|
|
1057
1391
|
}
|
|
1058
1392
|
schedule(delayMs) {
|
|
1059
1393
|
const generation = this.refreshGeneration;
|
|
@@ -1074,14 +1408,12 @@ class EntitlementManager {
|
|
|
1074
1408
|
}
|
|
1075
1409
|
}, delayMs);
|
|
1076
1410
|
}
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
return null;
|
|
1084
|
-
}
|
|
1411
|
+
measureClockSkew(local, server) {
|
|
1412
|
+
const ms = local - server;
|
|
1413
|
+
this.clockSkew =
|
|
1414
|
+
Number.isFinite(ms) && Math.abs(ms) > MAX_CLOCK_SKEW_MS
|
|
1415
|
+
? { direction: ms > 0 ? 'ahead' : 'behind', ms: Math.abs(ms) }
|
|
1416
|
+
: null;
|
|
1085
1417
|
}
|
|
1086
1418
|
async discard() {
|
|
1087
1419
|
this.held = null;
|
|
@@ -1091,7 +1423,13 @@ class EntitlementManager {
|
|
|
1091
1423
|
}
|
|
1092
1424
|
fingerprint() {
|
|
1093
1425
|
const state = this.snapshot();
|
|
1094
|
-
return canonicalJson({
|
|
1426
|
+
return canonicalJson({
|
|
1427
|
+
items: state.items,
|
|
1428
|
+
requiresOnlineCheck: state.requiresOnlineCheck,
|
|
1429
|
+
...(state.regionalFreeUntil
|
|
1430
|
+
? { regionalFreeUntil: state.regionalFreeUntil, features: state.features }
|
|
1431
|
+
: {}),
|
|
1432
|
+
});
|
|
1095
1433
|
}
|
|
1096
1434
|
notifyIfChanged() {
|
|
1097
1435
|
const fingerprint = this.fingerprint();
|
|
@@ -1104,16 +1442,31 @@ class EntitlementManager {
|
|
|
1104
1442
|
if (!this.held)
|
|
1105
1443
|
return NaN;
|
|
1106
1444
|
// fetchedAt is untrusted bookkeeping; it may shorten, never extend, a grant.
|
|
1107
|
-
return Math.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) +
|
|
1445
|
+
return (Math.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) + this.offlineAgeMs());
|
|
1446
|
+
}
|
|
1447
|
+
/** The signed allowance of the held license, or 48 hours when it names none. */
|
|
1448
|
+
offlineAgeMs() {
|
|
1449
|
+
const seconds = this.held?.envelope.payload.offlineSeconds;
|
|
1450
|
+
if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0)
|
|
1451
|
+
return MAX_OFFLINE_AGE_MS;
|
|
1452
|
+
return Math.min(seconds * 1000, MAX_SIGNED_OFFLINE_AGE_MS);
|
|
1108
1453
|
}
|
|
1109
1454
|
snapshot() {
|
|
1110
1455
|
if (!this.held)
|
|
1111
|
-
return EMPTY_ENTITLEMENT;
|
|
1456
|
+
return this.clockSkew ? { ...EMPTY_ENTITLEMENT, clockSkew: this.clockSkew } : EMPTY_ENTITLEMENT;
|
|
1112
1457
|
if (this.source !== 'mock' && !this.held.verified) {
|
|
1113
|
-
return {
|
|
1458
|
+
return {
|
|
1459
|
+
...EMPTY_ENTITLEMENT,
|
|
1460
|
+
requiresOnlineCheck: true,
|
|
1461
|
+
clockSkew: this.clockSkew,
|
|
1462
|
+
source: this.held.source,
|
|
1463
|
+
};
|
|
1114
1464
|
}
|
|
1115
|
-
const
|
|
1116
|
-
const
|
|
1465
|
+
const grants = applyLocalExpiry(JSON.parse(JSON.stringify(this.held.envelope.payload.entitlements)), this.now());
|
|
1466
|
+
const regional = grants.find((grant) => grant.sku === PAY_REGIONAL_ACCESS_SKU && grant.status === 'active');
|
|
1467
|
+
const items = grants.filter((grant) => grant.sku !== PAY_REGIONAL_ACCESS_SKU);
|
|
1468
|
+
const hasPaidAccess = grants.some((grant) => grant.sku === PAY_REGIONAL_ACCESS_SKU) ||
|
|
1469
|
+
collectFeatures(items).length > 0 ||
|
|
1117
1470
|
items.some((item) => item.status === 'active' || item.status === 'grace');
|
|
1118
1471
|
const offlineUntil = this.source === 'mock' || !hasPaidAccess ? null : this.offlineDeadline();
|
|
1119
1472
|
const requiresOnlineCheck = offlineUntil !== null &&
|
|
@@ -1123,9 +1476,13 @@ class EntitlementManager {
|
|
|
1123
1476
|
this.now() + MAX_CLOCK_SKEW_MS < Date.parse(this.held.envelope.payload.issuedAt));
|
|
1124
1477
|
return {
|
|
1125
1478
|
items,
|
|
1126
|
-
features: requiresOnlineCheck ? [] : collectFeatures(
|
|
1479
|
+
features: requiresOnlineCheck ? [] : collectFeatures(grants),
|
|
1480
|
+
...(regional?.expiresAt && !requiresOnlineCheck
|
|
1481
|
+
? { regionalFreeUntil: Date.parse(regional.expiresAt) }
|
|
1482
|
+
: {}),
|
|
1127
1483
|
requiresOnlineCheck,
|
|
1128
1484
|
offlineUntil,
|
|
1485
|
+
clockSkew: this.clockSkew,
|
|
1129
1486
|
verified: this.held.verified,
|
|
1130
1487
|
issuedAt: this.held.envelope.payload.issuedAt,
|
|
1131
1488
|
fetchedAt: this.held.fetchedAt,
|
|
@@ -1214,6 +1571,16 @@ class MemoryStorage {
|
|
|
1214
1571
|
this.map.delete(key);
|
|
1215
1572
|
}
|
|
1216
1573
|
}
|
|
1574
|
+
/**
|
|
1575
|
+
* The browser's synced storage (`storage.sync`), or null outside an extension. The SDK keeps
|
|
1576
|
+
* only the trial start there (never `endUserRef`), so devices on one synced account share the
|
|
1577
|
+
* trial. Uninstalling clears it from the account, so it does not survive a reinstall.
|
|
1578
|
+
*/
|
|
1579
|
+
function createSyncStorage() {
|
|
1580
|
+
const g = extensionGlobals();
|
|
1581
|
+
const area = g.chrome?.storage?.sync ?? g.browser?.storage?.sync;
|
|
1582
|
+
return area ? new ExtensionStorage(area) : null;
|
|
1583
|
+
}
|
|
1217
1584
|
function createStorage() {
|
|
1218
1585
|
const g = extensionGlobals();
|
|
1219
1586
|
const area = g.chrome?.storage?.local ?? g.browser?.storage?.local;
|
|
@@ -1270,7 +1637,7 @@ class RecoveryManager {
|
|
|
1270
1637
|
const secret = Array.from(cryptoApi.getRandomValues(new Uint8Array(32)), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
1271
1638
|
const hash = await cryptoApi.subtle.digest('SHA-256', new TextEncoder().encode(secret));
|
|
1272
1639
|
const challenge = Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
1273
|
-
const created = await this.options.api.createRestoreSession(challenge, this.options.locale);
|
|
1640
|
+
const created = await this.options.api.createRestoreSession(challenge, this.options.locale, options.purpose);
|
|
1274
1641
|
if (!Number.isFinite(Date.parse(created.expiresAt)))
|
|
1275
1642
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery expiry');
|
|
1276
1643
|
const pending = { sessionId: created.sessionId, expiresAt: created.expiresAt, claimSecret: secret };
|
|
@@ -1330,8 +1697,9 @@ class RecoveryManager {
|
|
|
1330
1697
|
break;
|
|
1331
1698
|
if (claim.state === 'complete') {
|
|
1332
1699
|
const entitlement = await this.options.onComplete(claim.endUserRef, claim.entitlement);
|
|
1700
|
+
const cloudBackup = await this.options.onStorageGrant?.(claim.storage);
|
|
1333
1701
|
await this.options.storage.remove(this.pendingKey);
|
|
1334
|
-
return { state: 'complete', entitlement };
|
|
1702
|
+
return { state: 'complete', entitlement, ...(cloudBackup ? { cloudBackup } : {}) };
|
|
1335
1703
|
}
|
|
1336
1704
|
if (claim.state !== 'pending')
|
|
1337
1705
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery response');
|
|
@@ -1360,9 +1728,10 @@ class RecoveryManager {
|
|
|
1360
1728
|
const DEFAULT_API_URL = 'https://bff.extenshi.io';
|
|
1361
1729
|
const DEFAULT_CACHE_TTL_MS = 60 * 60 * 1000;
|
|
1362
1730
|
const MAX_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
1731
|
+
const DEFAULT_TRIAL_ENDING_DAYS = 2;
|
|
1363
1732
|
|
|
1364
1733
|
/** Kept in sync with package.json by tests/unit/version.test.ts. */
|
|
1365
|
-
const VERSION = '0.
|
|
1734
|
+
const VERSION = '0.12.0';
|
|
1366
1735
|
|
|
1367
1736
|
/**
|
|
1368
1737
|
* The user's language as the SDK sends it. Kept apart from the paywall
|
|
@@ -1432,7 +1801,7 @@ function resolveConfig(input) {
|
|
|
1432
1801
|
if (!isHttpUrl(apiUrl))
|
|
1433
1802
|
errors.push('apiUrl must be an http(s) URL');
|
|
1434
1803
|
const entitlementPublicKey = input.entitlementPublicKey ?? null;
|
|
1435
|
-
if (entitlementPublicKey !== null &&
|
|
1804
|
+
if (entitlementPublicKey !== null && !PUBLIC_KEY_RE.test(entitlementPublicKey)) {
|
|
1436
1805
|
errors.push('entitlementPublicKey must be a base64-encoded 32-byte Ed25519 public key');
|
|
1437
1806
|
}
|
|
1438
1807
|
const environment = input.environment ?? 'production';
|
|
@@ -1454,6 +1823,9 @@ function resolveConfig(input) {
|
|
|
1454
1823
|
const theme = input.theme ?? {};
|
|
1455
1824
|
if (theme.mode !== undefined && !THEME_MODES.has(theme.mode))
|
|
1456
1825
|
errors.push('theme.mode must be light, dark or auto');
|
|
1826
|
+
const trialEndingDays = input.trialEndingDays ?? DEFAULT_TRIAL_ENDING_DAYS;
|
|
1827
|
+
if (!Number.isInteger(trialEndingDays) || trialEndingDays < 0 || trialEndingDays > 365)
|
|
1828
|
+
errors.push('trialEndingDays must be a whole number of days between 0 and 365');
|
|
1457
1829
|
if (input.mock &&
|
|
1458
1830
|
input.mockData !== undefined &&
|
|
1459
1831
|
(typeof input.mockData !== 'object' || input.mockData === null)) {
|
|
@@ -1474,6 +1846,8 @@ function resolveConfig(input) {
|
|
|
1474
1846
|
mock: input.mock === true,
|
|
1475
1847
|
mockData: input.mock ? (input.mockData ?? {}) : null,
|
|
1476
1848
|
theme,
|
|
1849
|
+
trialEndingDays,
|
|
1850
|
+
syncTrialStart: input.syncTrialStart !== false,
|
|
1477
1851
|
};
|
|
1478
1852
|
}
|
|
1479
1853
|
|
|
@@ -1598,6 +1972,9 @@ const SDK_STRINGS_EN = {
|
|
|
1598
1972
|
pickerDescription: 'Separate purchases can have separate billing profiles. Choose one to manage its subscriptions and payment details.',
|
|
1599
1973
|
pickerFirstRecorded: 'First recorded {date}',
|
|
1600
1974
|
pickerCancel: 'Cancel',
|
|
1975
|
+
trialEndedTitle: 'Your free trial has ended',
|
|
1976
|
+
trialEndedDescription: 'The extension’s tools are paused. Your settings are kept and will be there when you upgrade.',
|
|
1977
|
+
trialEndedFeedback: 'Share feedback',
|
|
1601
1978
|
};
|
|
1602
1979
|
// BEGIN GENERATED TRANSLATIONS
|
|
1603
1980
|
const TRANSLATIONS = {
|
|
@@ -1666,6 +2043,9 @@ const TRANSLATIONS = {
|
|
|
1666
2043
|
pickerDescription: 'Las compras independientes pueden tener perfiles de facturación distintos. Elige uno para gestionar sus suscripciones y datos de pago.',
|
|
1667
2044
|
pickerFirstRecorded: 'Registrado por primera vez el {date}',
|
|
1668
2045
|
pickerCancel: 'Cancelar',
|
|
2046
|
+
trialEndedTitle: 'Tu prueba gratuita ha terminado',
|
|
2047
|
+
trialEndedDescription: 'Las herramientas de la extensión están en pausa. Tu configuración se conserva y la encontrarás igual cuando mejores tu plan.',
|
|
2048
|
+
trialEndedFeedback: 'Enviar comentarios',
|
|
1669
2049
|
},
|
|
1670
2050
|
'pt-BR': {
|
|
1671
2051
|
title: 'Desbloqueie os recursos premium',
|
|
@@ -1732,6 +2112,9 @@ const TRANSLATIONS = {
|
|
|
1732
2112
|
pickerDescription: 'Compras diferentes podem ter perfis de cobrança diferentes. Escolha um perfil para gerenciar as assinaturas e os dados de pagamento vinculados a ele.',
|
|
1733
2113
|
pickerFirstRecorded: 'Registrado pela primeira vez em {date}',
|
|
1734
2114
|
pickerCancel: 'Cancelar',
|
|
2115
|
+
trialEndedTitle: 'Seu teste gratuito terminou',
|
|
2116
|
+
trialEndedDescription: 'As ferramentas da extensão estão pausadas. Suas configurações foram mantidas e estarão lá quando você fizer o upgrade.',
|
|
2117
|
+
trialEndedFeedback: 'Enviar feedback',
|
|
1735
2118
|
},
|
|
1736
2119
|
fr: {
|
|
1737
2120
|
title: 'Débloquez les fonctionnalités premium',
|
|
@@ -1798,6 +2181,9 @@ const TRANSLATIONS = {
|
|
|
1798
2181
|
pickerDescription: 'Des achats distincts peuvent avoir des profils de facturation distincts. Choisissez-en un pour gérer ses abonnements et ses informations de paiement.',
|
|
1799
2182
|
pickerFirstRecorded: 'Enregistré pour la première fois le {date}',
|
|
1800
2183
|
pickerCancel: 'Annuler',
|
|
2184
|
+
trialEndedTitle: 'Votre essai gratuit est terminé',
|
|
2185
|
+
trialEndedDescription: 'Les outils de l’extension sont en pause. Vos paramètres sont conservés et vous les retrouverez après la mise à niveau.',
|
|
2186
|
+
trialEndedFeedback: 'Donner votre avis',
|
|
1801
2187
|
},
|
|
1802
2188
|
de: {
|
|
1803
2189
|
title: 'Premium-Funktionen freischalten',
|
|
@@ -1864,6 +2250,9 @@ const TRANSLATIONS = {
|
|
|
1864
2250
|
pickerDescription: 'Verschiedene Käufe können eigene Abrechnungsprofile haben. Wähle eines aus, um seine Abonnements und Zahlungsdaten zu verwalten.',
|
|
1865
2251
|
pickerFirstRecorded: 'Erstmals erfasst am {date}',
|
|
1866
2252
|
pickerCancel: 'Abbrechen',
|
|
2253
|
+
trialEndedTitle: 'Dein kostenloser Testzeitraum ist abgelaufen',
|
|
2254
|
+
trialEndedDescription: 'Die Funktionen der Erweiterung sind pausiert. Deine Einstellungen bleiben erhalten und sind nach dem Upgrade wieder da.',
|
|
2255
|
+
trialEndedFeedback: 'Feedback geben',
|
|
1867
2256
|
},
|
|
1868
2257
|
it: {
|
|
1869
2258
|
title: 'Sblocca le funzionalità premium',
|
|
@@ -1930,6 +2319,9 @@ const TRANSLATIONS = {
|
|
|
1930
2319
|
pickerDescription: 'Acquisti diversi possono avere profili di fatturazione diversi. Scegline uno per gestirne gli abbonamenti e i dati di pagamento.',
|
|
1931
2320
|
pickerFirstRecorded: 'Registrato per la prima volta il {date}',
|
|
1932
2321
|
pickerCancel: 'Annulla',
|
|
2322
|
+
trialEndedTitle: 'La tua prova gratuita è terminata',
|
|
2323
|
+
trialEndedDescription: 'Gli strumenti dell’estensione sono in pausa. Le tue impostazioni sono conservate e le ritroverai dopo l’upgrade.',
|
|
2324
|
+
trialEndedFeedback: 'Invia un feedback',
|
|
1933
2325
|
},
|
|
1934
2326
|
ru: {
|
|
1935
2327
|
title: 'Откройте доступ к премиум-функциям',
|
|
@@ -1996,6 +2388,9 @@ const TRANSLATIONS = {
|
|
|
1996
2388
|
pickerDescription: 'У разных покупок могут быть разные платёжные профили. Выберите профиль, чтобы управлять его подписками и платёжными данными.',
|
|
1997
2389
|
pickerFirstRecorded: 'Впервые зафиксирован: {date}',
|
|
1998
2390
|
pickerCancel: 'Отмена',
|
|
2391
|
+
trialEndedTitle: 'Бесплатный пробный период закончился',
|
|
2392
|
+
trialEndedDescription: 'Инструменты расширения приостановлены. Ваши настройки сохранены и будут на месте после перехода на премиум.',
|
|
2393
|
+
trialEndedFeedback: 'Оставить отзыв',
|
|
1999
2394
|
},
|
|
2000
2395
|
ja: {
|
|
2001
2396
|
title: 'プレミアム機能をアンロック',
|
|
@@ -2062,6 +2457,9 @@ const TRANSLATIONS = {
|
|
|
2062
2457
|
pickerDescription: '購入ごとに別々の請求プロファイルがある場合があります。サブスクリプションと支払い情報を管理するプロファイルを1つ選択してください。',
|
|
2063
2458
|
pickerFirstRecorded: '初回記録日:{date}',
|
|
2064
2459
|
pickerCancel: 'キャンセル',
|
|
2460
|
+
trialEndedTitle: '無料トライアルが終了しました',
|
|
2461
|
+
trialEndedDescription: '拡張機能のツールは一時停止しています。設定は保存されており、アップグレード後もそのままご利用いただけます。',
|
|
2462
|
+
trialEndedFeedback: 'フィードバックを送信',
|
|
2065
2463
|
},
|
|
2066
2464
|
ko: {
|
|
2067
2465
|
title: '프리미엄 기능 잠금 해제',
|
|
@@ -2128,6 +2526,9 @@ const TRANSLATIONS = {
|
|
|
2128
2526
|
pickerDescription: '구매마다 결제 프로필이 다를 수 있습니다. 구독과 결제 정보를 관리할 프로필을 하나 선택해 주세요.',
|
|
2129
2527
|
pickerFirstRecorded: '최초 기록일: {date}',
|
|
2130
2528
|
pickerCancel: '취소',
|
|
2529
|
+
trialEndedTitle: '무료 체험 기간이 종료되었습니다',
|
|
2530
|
+
trialEndedDescription: '확장 프로그램의 도구가 일시 중지되었습니다. 설정은 그대로 저장되어 있으며 업그레이드하면 다시 사용할 수 있습니다.',
|
|
2531
|
+
trialEndedFeedback: '의견 보내기',
|
|
2131
2532
|
},
|
|
2132
2533
|
'zh-CN': {
|
|
2133
2534
|
title: '解锁高级功能',
|
|
@@ -2194,6 +2595,9 @@ const TRANSLATIONS = {
|
|
|
2194
2595
|
pickerDescription: '不同的购买可以有各自的账单资料。请选择一个,以管理其订阅和付款信息。',
|
|
2195
2596
|
pickerFirstRecorded: '首次记录于 {date}',
|
|
2196
2597
|
pickerCancel: '取消',
|
|
2598
|
+
trialEndedTitle: '免费试用已结束',
|
|
2599
|
+
trialEndedDescription: '扩展程序的工具已暂停。您的设置已保留,升级后即可继续使用。',
|
|
2600
|
+
trialEndedFeedback: '提交反馈',
|
|
2197
2601
|
},
|
|
2198
2602
|
ar: {
|
|
2199
2603
|
title: 'احصل على الميزات المميزة',
|
|
@@ -2260,6 +2664,9 @@ const TRANSLATIONS = {
|
|
|
2260
2664
|
pickerDescription: 'يمكن أن تكون لعمليات الشراء المنفصلة ملفات فوترة منفصلة. اختر ملفًا منها لإدارة اشتراكاته وتفاصيل الدفع الخاصة به.',
|
|
2261
2665
|
pickerFirstRecorded: 'سُجِّل لأول مرة في {date}',
|
|
2262
2666
|
pickerCancel: 'إلغاء',
|
|
2667
|
+
trialEndedTitle: 'انتهت فترتك التجريبية المجانية',
|
|
2668
|
+
trialEndedDescription: 'أدوات الإضافة متوقفة مؤقتًا. إعداداتك محفوظة وستجدها كما هي بعد الترقية.',
|
|
2669
|
+
trialEndedFeedback: 'إرسال ملاحظات',
|
|
2263
2670
|
},
|
|
2264
2671
|
};
|
|
2265
2672
|
// END GENERATED TRANSLATIONS
|
|
@@ -2340,8 +2747,10 @@ function withdrawalWaiverText(serverVersion, locale, seller) {
|
|
|
2340
2747
|
* extends it with `getOffer()` / `showPaywall()`.
|
|
2341
2748
|
*
|
|
2342
2749
|
* Data that leaves the extension: `publishableKey`, `endUserRef`, `sku`,
|
|
2343
|
-
* `locale
|
|
2344
|
-
*
|
|
2750
|
+
* `locale`, checkout session IDs and, with a server trial, the trial start date
|
|
2751
|
+
* the server issued (`trialStartedHint`, kept in storage.sync). Explicit recovery also sends its session ID,
|
|
2752
|
+
* challenge and claim secret (POST body). Email stays on the hosted page. With cloud backup, the
|
|
2753
|
+
* storage token goes only to `/v1/storage` (as a bearer), never in a message to a content script.
|
|
2345
2754
|
*/
|
|
2346
2755
|
/** Server-side offer cache is 5 min; mirror it in memory. */
|
|
2347
2756
|
const OFFER_TTL_MS = 5 * 60 * 1000;
|
|
@@ -2352,12 +2761,30 @@ class ExtenshiPayLite {
|
|
|
2352
2761
|
this.endUserRefPromise = null;
|
|
2353
2762
|
this.offer = null;
|
|
2354
2763
|
this.offerInflight = null;
|
|
2764
|
+
/** The signing key the server returned in this session; never one read from storage. */
|
|
2765
|
+
this.serverKey = null;
|
|
2766
|
+
/** Trust order for license signatures; see payment/signature.ts. */
|
|
2767
|
+
this.keys = {
|
|
2768
|
+
known: async () => {
|
|
2769
|
+
const pinned = this.config.entitlementPublicKey;
|
|
2770
|
+
const offline = pinned ?? (await this.readSavedServerKey());
|
|
2771
|
+
return [...new Set([this.serverKey, offline].filter((key) => !!key))];
|
|
2772
|
+
},
|
|
2773
|
+
fetchCurrent: async () => (await this.fetchOffer(true)).entitlementPublicKey,
|
|
2774
|
+
};
|
|
2355
2775
|
this.readyPromise = null;
|
|
2356
2776
|
this.destroyed = false;
|
|
2357
2777
|
this.config = resolveConfig(config);
|
|
2358
2778
|
logger.configure({ logLevel: this.config.logLevel, debug: this.config.debug });
|
|
2359
2779
|
this.now = deps.now ?? (() => Date.now());
|
|
2360
2780
|
this.storage = deps.storage ?? createStorage();
|
|
2781
|
+
this.openUrl = deps.openUrl;
|
|
2782
|
+
this.syncStorage =
|
|
2783
|
+
!this.config.syncTrialStart || this.config.mock
|
|
2784
|
+
? null
|
|
2785
|
+
: deps.syncStorage === undefined
|
|
2786
|
+
? createSyncStorage()
|
|
2787
|
+
: deps.syncStorage;
|
|
2361
2788
|
const transport = deps.transport ??
|
|
2362
2789
|
(this.config.mock
|
|
2363
2790
|
? new MockTransport(this.config.mockData ?? {})
|
|
@@ -2370,11 +2797,29 @@ class ExtenshiPayLite {
|
|
|
2370
2797
|
cacheTtlMs: this.config.cacheTtlMs,
|
|
2371
2798
|
source: this.config.mock ? 'mock' : 'network',
|
|
2372
2799
|
getEndUserRef: () => this.getEndUserRef(),
|
|
2373
|
-
|
|
2800
|
+
keys: this.keys,
|
|
2374
2801
|
onChange: (entitlement) => this.emitter.emit('entitlement:changed', entitlement),
|
|
2802
|
+
onAccepted: () => {
|
|
2803
|
+
void this.trial.evaluate();
|
|
2804
|
+
void this.rememberTrialStart();
|
|
2805
|
+
},
|
|
2806
|
+
getTrialStartHint: () => this.readTrialStartHint(),
|
|
2375
2807
|
onError: (error) => this.reportError(error),
|
|
2376
2808
|
now: this.now,
|
|
2377
2809
|
});
|
|
2810
|
+
this.trial = new TrialNotifier({
|
|
2811
|
+
storage: this.storage,
|
|
2812
|
+
storageKey: `extenshi-pay:${this.config.publishableKey}:trial-events${this.config.mock ? ':mock' : ''}`,
|
|
2813
|
+
endingDays: this.config.trialEndingDays,
|
|
2814
|
+
getTrial: () => this.entitlements.getTrial(),
|
|
2815
|
+
// A paid license still counts while it waits for an online check: no "trial ended" to a buyer.
|
|
2816
|
+
hasPaidAccess: () => {
|
|
2817
|
+
const license = this.entitlements.getCached();
|
|
2818
|
+
return Boolean(license?.regionalFreeUntil || license?.items.some(isLive));
|
|
2819
|
+
},
|
|
2820
|
+
emit: (event, trial) => this.emitter.emit(event, trial),
|
|
2821
|
+
now: this.now,
|
|
2822
|
+
});
|
|
2378
2823
|
this.checkout = new CheckoutManager({
|
|
2379
2824
|
api: this.api,
|
|
2380
2825
|
storage: this.storage,
|
|
@@ -2388,6 +2833,13 @@ class ExtenshiPayLite {
|
|
|
2388
2833
|
(this.config.mock ? (url) => logger.info('mock checkout (no tab opened)', url) : undefined),
|
|
2389
2834
|
now: this.now,
|
|
2390
2835
|
});
|
|
2836
|
+
this.backup = new CloudBackup({
|
|
2837
|
+
storage: this.storage,
|
|
2838
|
+
publishableKey: this.config.publishableKey,
|
|
2839
|
+
apiUrl: this.config.apiUrl,
|
|
2840
|
+
fetch: deps.fetch,
|
|
2841
|
+
mock: this.config.mock,
|
|
2842
|
+
});
|
|
2391
2843
|
this.recovery = new RecoveryManager({
|
|
2392
2844
|
api: this.api,
|
|
2393
2845
|
locale: this.config.locale,
|
|
@@ -2401,7 +2853,7 @@ class ExtenshiPayLite {
|
|
|
2401
2853
|
envelope.payload.publishableKey !== this.config.publishableKey ||
|
|
2402
2854
|
!Number.isFinite(Date.parse(envelope.payload.issuedAt)) ||
|
|
2403
2855
|
Date.parse(envelope.payload.issuedAt) > this.now() + MAX_CLOCK_SKEW_MS ||
|
|
2404
|
-
(await
|
|
2856
|
+
(await verifyWithKeys(envelope, this.keys)).verdict !== 'valid')
|
|
2405
2857
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Recovery requires a verified entitlement for this installation');
|
|
2406
2858
|
this.entitlements.stopAutoRefresh();
|
|
2407
2859
|
try {
|
|
@@ -2419,6 +2871,7 @@ class ExtenshiPayLite {
|
|
|
2419
2871
|
this.entitlements.startAutoRefresh();
|
|
2420
2872
|
}
|
|
2421
2873
|
},
|
|
2874
|
+
onStorageGrant: (grant) => this.backup.accept(grant),
|
|
2422
2875
|
});
|
|
2423
2876
|
if (config.onError)
|
|
2424
2877
|
this.emitter.on('error', config.onError);
|
|
@@ -2464,8 +2917,11 @@ class ExtenshiPayLite {
|
|
|
2464
2917
|
catch (error) {
|
|
2465
2918
|
this.reportError(error);
|
|
2466
2919
|
}
|
|
2467
|
-
|
|
2920
|
+
void this.confirmSavedServerKey();
|
|
2921
|
+
if (!this.destroyed) {
|
|
2468
2922
|
this.entitlements.startAutoRefresh();
|
|
2923
|
+
this.trial.start();
|
|
2924
|
+
}
|
|
2469
2925
|
}
|
|
2470
2926
|
/** The anonymous, random id this install is known by. */
|
|
2471
2927
|
getEndUserRef() {
|
|
@@ -2486,6 +2942,16 @@ class ExtenshiPayLite {
|
|
|
2486
2942
|
await this.initialize();
|
|
2487
2943
|
return this.entitlements.get(options);
|
|
2488
2944
|
}
|
|
2945
|
+
/**
|
|
2946
|
+
* The free trial the application set on the server, from the verified license, or null when
|
|
2947
|
+
* there is none (or the license could not be verified yet). Answers offline from the cached
|
|
2948
|
+
* license; like paid access, `active` needs a license check within 48 hours. `isPaid()` and
|
|
2949
|
+
* `hasFeature()` do not include the trial: grant trial access with `(await getTrial())?.active`.
|
|
2950
|
+
*/
|
|
2951
|
+
async getTrial(options = {}) {
|
|
2952
|
+
await this.getEntitlement(options);
|
|
2953
|
+
return this.entitlements.getTrial();
|
|
2954
|
+
}
|
|
2489
2955
|
/** True when any active/grace entitlement exists, or the given `sku` is active/grace. */
|
|
2490
2956
|
async isPaid(sku) {
|
|
2491
2957
|
return isEntitled(await this.getEntitlement(), sku);
|
|
@@ -2569,6 +3035,41 @@ class ExtenshiPayLite {
|
|
|
2569
3035
|
throw this.reportError(error);
|
|
2570
3036
|
}
|
|
2571
3037
|
}
|
|
3038
|
+
/**
|
|
3039
|
+
* Turns on the cloud copy of the extension's settings (`@extenshi/storage`): the
|
|
3040
|
+
* hosted restore page shows the storage disclosure and the buyer confirms with
|
|
3041
|
+
* the code from the purchase email. `cloudBackup` in the result says whether it is
|
|
3042
|
+
* on. Buyers only; consent is recorded by the server.
|
|
3043
|
+
*/
|
|
3044
|
+
enableCloudBackup(options = {}) {
|
|
3045
|
+
return this.restorePurchase({ ...options, purpose: 'storage' });
|
|
3046
|
+
}
|
|
3047
|
+
/**
|
|
3048
|
+
* The storage token for `ExtenshiStorage.create({ cloud: { getToken } })`, or null
|
|
3049
|
+
* while cloud backup is off on this installation. Extension pages and background
|
|
3050
|
+
* only: it rejects in a content script, and must never be sent to one.
|
|
3051
|
+
*/
|
|
3052
|
+
async cloudBackupToken() {
|
|
3053
|
+
return this.backup.token();
|
|
3054
|
+
}
|
|
3055
|
+
/** Turns cloud backup off on this installation: revokes its token. The cloud copy stays. */
|
|
3056
|
+
async disableCloudBackup() {
|
|
3057
|
+
try {
|
|
3058
|
+
await this.backup.disable();
|
|
3059
|
+
}
|
|
3060
|
+
catch (error) {
|
|
3061
|
+
throw this.reportError(error);
|
|
3062
|
+
}
|
|
3063
|
+
}
|
|
3064
|
+
/** Deletes the buyer's cloud copy and turns cloud backup off on every installation. */
|
|
3065
|
+
async deleteCloudBackup() {
|
|
3066
|
+
try {
|
|
3067
|
+
await this.backup.delete();
|
|
3068
|
+
}
|
|
3069
|
+
catch (error) {
|
|
3070
|
+
throw this.reportError(error);
|
|
3071
|
+
}
|
|
3072
|
+
}
|
|
2572
3073
|
/** Read-only license view. Entitlements retain cache/signature/offline semantics. */
|
|
2573
3074
|
async getLicenseSummary(options = {}) {
|
|
2574
3075
|
await this.initialize();
|
|
@@ -2638,6 +3139,7 @@ class ExtenshiPayLite {
|
|
|
2638
3139
|
destroy() {
|
|
2639
3140
|
this.destroyed = true;
|
|
2640
3141
|
this.recovery.stop();
|
|
3142
|
+
this.trial.stop();
|
|
2641
3143
|
this.entitlements.stopAutoRefresh();
|
|
2642
3144
|
this.emitter.removeAll();
|
|
2643
3145
|
}
|
|
@@ -2649,8 +3151,9 @@ class ExtenshiPayLite {
|
|
|
2649
3151
|
if (!this.offerInflight) {
|
|
2650
3152
|
this.offerInflight = this.api
|
|
2651
3153
|
.getOffer(this.config.locale)
|
|
2652
|
-
.then((value) => {
|
|
3154
|
+
.then(async (value) => {
|
|
2653
3155
|
this.offer = { value, fetchedAt: this.now() };
|
|
3156
|
+
await this.rememberServerKey(value.entitlementPublicKey);
|
|
2654
3157
|
return value;
|
|
2655
3158
|
})
|
|
2656
3159
|
.finally(() => {
|
|
@@ -2659,8 +3162,88 @@ class ExtenshiPayLite {
|
|
|
2659
3162
|
}
|
|
2660
3163
|
return this.offerInflight;
|
|
2661
3164
|
}
|
|
2662
|
-
|
|
2663
|
-
return this.config.entitlementPublicKey
|
|
3165
|
+
get serverKeyStorageKey() {
|
|
3166
|
+
return `extenshi-pay:${this.config.publishableKey}:entitlementPublicKey`;
|
|
3167
|
+
}
|
|
3168
|
+
async readSavedServerKey() {
|
|
3169
|
+
try {
|
|
3170
|
+
const value = await this.storage.get(this.serverKeyStorageKey);
|
|
3171
|
+
return typeof value === 'string' && PUBLIC_KEY_RE.test(value) ? value : null;
|
|
3172
|
+
}
|
|
3173
|
+
catch {
|
|
3174
|
+
return null;
|
|
3175
|
+
}
|
|
3176
|
+
}
|
|
3177
|
+
/**
|
|
3178
|
+
* Keeps the server's key next to the license cache so a restart with no network can verify it.
|
|
3179
|
+
* Not with a bundled key: that one already covers the restart, and storage stays untrusted.
|
|
3180
|
+
*/
|
|
3181
|
+
async rememberServerKey(key) {
|
|
3182
|
+
if (typeof key !== 'string' || !PUBLIC_KEY_RE.test(key))
|
|
3183
|
+
return;
|
|
3184
|
+
this.serverKey = key;
|
|
3185
|
+
if (this.config.entitlementPublicKey || this.config.mock)
|
|
3186
|
+
return;
|
|
3187
|
+
try {
|
|
3188
|
+
if ((await this.readSavedServerKey()) !== key)
|
|
3189
|
+
await this.storage.set(this.serverKeyStorageKey, key);
|
|
3190
|
+
}
|
|
3191
|
+
catch (error) {
|
|
3192
|
+
logger.debug('signing key not saved', error);
|
|
3193
|
+
}
|
|
3194
|
+
}
|
|
3195
|
+
/**
|
|
3196
|
+
* A license verified with the saved key alone is checked against the server once per start:
|
|
3197
|
+
* when the server's key differs (rotation, or an edited storage) the license is fetched again,
|
|
3198
|
+
* and dropped if it does not verify. Offline, the saved key stands until `offlineUntil`.
|
|
3199
|
+
*/
|
|
3200
|
+
async confirmSavedServerKey() {
|
|
3201
|
+
const used = this.entitlements.verifiedKey;
|
|
3202
|
+
if (this.destroyed || !used || used === this.serverKey || used === this.config.entitlementPublicKey)
|
|
3203
|
+
return;
|
|
3204
|
+
try {
|
|
3205
|
+
if ((await this.fetchOffer()).entitlementPublicKey === used || this.destroyed)
|
|
3206
|
+
return;
|
|
3207
|
+
}
|
|
3208
|
+
catch {
|
|
3209
|
+
return;
|
|
3210
|
+
}
|
|
3211
|
+
try {
|
|
3212
|
+
await this.entitlements.refresh();
|
|
3213
|
+
}
|
|
3214
|
+
catch {
|
|
3215
|
+
await this.entitlements.reverify().catch((error) => this.reportError(error));
|
|
3216
|
+
}
|
|
3217
|
+
}
|
|
3218
|
+
get trialStartKey() {
|
|
3219
|
+
return `extenshi-pay:${this.config.publishableKey}:trialStartedAt`;
|
|
3220
|
+
}
|
|
3221
|
+
/** The synced trial start, or null (none, malformed, or storage.sync unavailable). */
|
|
3222
|
+
async readTrialStartHint() {
|
|
3223
|
+
if (!this.syncStorage)
|
|
3224
|
+
return null;
|
|
3225
|
+
try {
|
|
3226
|
+
const value = await this.syncStorage.get(this.trialStartKey);
|
|
3227
|
+
return typeof value === 'string' && Number.isFinite(Date.parse(value)) ? value : null;
|
|
3228
|
+
}
|
|
3229
|
+
catch {
|
|
3230
|
+
return null;
|
|
3231
|
+
}
|
|
3232
|
+
}
|
|
3233
|
+
/** Syncs the verified trial start, keeping the earliest one seen. Never the installation id. */
|
|
3234
|
+
async rememberTrialStart() {
|
|
3235
|
+
const trial = this.entitlements.getTrial();
|
|
3236
|
+
if (!this.syncStorage || !trial)
|
|
3237
|
+
return;
|
|
3238
|
+
try {
|
|
3239
|
+
const synced = await this.readTrialStartHint();
|
|
3240
|
+
if (synced && Date.parse(synced) <= Date.parse(trial.startedAt))
|
|
3241
|
+
return;
|
|
3242
|
+
await this.syncStorage.set(this.trialStartKey, trial.startedAt);
|
|
3243
|
+
}
|
|
3244
|
+
catch (error) {
|
|
3245
|
+
logger.debug('trial start not synced', error);
|
|
3246
|
+
}
|
|
2664
3247
|
}
|
|
2665
3248
|
reportError(error) {
|
|
2666
3249
|
const err = ExtenshiPayError.from(error);
|
|
@@ -3405,18 +3988,12 @@ class PaywallRenderer {
|
|
|
3405
3988
|
}
|
|
3406
3989
|
if (waiver && waiverBox)
|
|
3407
3990
|
this.mountWaiver(root, doc, waiver.text, waiverBox);
|
|
3408
|
-
|
|
3409
|
-
|
|
3410
|
-
|
|
3411
|
-
|
|
3412
|
-
|
|
3413
|
-
|
|
3414
|
-
button.style.cssText =
|
|
3415
|
-
'display:block;margin:12px auto 0;background:none;border:0;color:inherit;font:inherit;text-decoration:underline;cursor:pointer';
|
|
3416
|
-
button.addEventListener('click', () => this.callbacks.onRestore?.());
|
|
3417
|
-
footer.appendChild(button);
|
|
3418
|
-
}
|
|
3419
|
-
}
|
|
3991
|
+
const onRestore = this.callbacks.onRestore;
|
|
3992
|
+
if (view.recoveryEnabled && onRestore)
|
|
3993
|
+
this.footerLink(root, doc, strings.restorePurchase, onRestore);
|
|
3994
|
+
const onFeedback = this.callbacks.onFeedback;
|
|
3995
|
+
if (view.feedback && onFeedback)
|
|
3996
|
+
this.footerLink(root, doc, view.feedback.label, onFeedback);
|
|
3420
3997
|
const mount = view.mode === 'inline' ? (view.container ?? doc.body) : doc.body;
|
|
3421
3998
|
mount.appendChild(host);
|
|
3422
3999
|
this.host = host;
|
|
@@ -3433,6 +4010,19 @@ class PaywallRenderer {
|
|
|
3433
4010
|
this.host.remove();
|
|
3434
4011
|
this.host = null;
|
|
3435
4012
|
}
|
|
4013
|
+
/** A text button at the end of the footer (no `href`: the SDK opens URLs itself). */
|
|
4014
|
+
footerLink(root, doc, label, onClick) {
|
|
4015
|
+
const footer = root.querySelector('[class*="-footer"], .ep-minimal-actions, .ep-inline-content, .ep-fullscreen-content');
|
|
4016
|
+
if (!footer)
|
|
4017
|
+
return;
|
|
4018
|
+
const button = doc.createElement('button');
|
|
4019
|
+
button.type = 'button';
|
|
4020
|
+
button.textContent = label;
|
|
4021
|
+
button.style.cssText =
|
|
4022
|
+
'display:block;margin:12px auto 0;background:none;border:0;color:inherit;font:inherit;text-decoration:underline;cursor:pointer';
|
|
4023
|
+
button.addEventListener('click', () => onClick());
|
|
4024
|
+
footer.appendChild(button);
|
|
4025
|
+
}
|
|
3436
4026
|
prune(root) {
|
|
3437
4027
|
for (const element of root.querySelectorAll(PRUNE_SELECTOR))
|
|
3438
4028
|
element.remove();
|
|
@@ -3639,7 +4229,31 @@ class ExtenshiPay extends ExtenshiPayLite {
|
|
|
3639
4229
|
* `getOffer()`; if that fails the paywall still renders with checkout disabled.
|
|
3640
4230
|
*/
|
|
3641
4231
|
async showPaywall(options = {}) {
|
|
4232
|
+
return this.present(options, null);
|
|
4233
|
+
}
|
|
4234
|
+
/**
|
|
4235
|
+
* The paywall for a user whose free trial ended, e.g. on `trial:ended`. In the user's
|
|
4236
|
+
* language it says the trial has ended, the tools are paused and the settings are kept,
|
|
4237
|
+
* then shows the plans, "Restore purchase" when recovery is on, and with `feedbackFormUrl`
|
|
4238
|
+
* a feedback button. Resolves like `showPaywall()`. The default text promises the settings
|
|
4239
|
+
* are kept: pass `description` if your extension does not keep them.
|
|
4240
|
+
*/
|
|
4241
|
+
async showTrialEnded(options = {}) {
|
|
4242
|
+
const t = sdkStrings(this.config.locale);
|
|
4243
|
+
const feedbackUrl = trialFeedbackUrl(options.feedbackFormUrl);
|
|
4244
|
+
if (options.feedbackFormUrl !== undefined && !feedbackUrl)
|
|
4245
|
+
this.reportError(new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'feedbackFormUrl must be an https URL without credentials; the feedback button is left out'));
|
|
4246
|
+
const { feedbackFormUrl: _url, feedbackLabel, ...paywall } = options;
|
|
4247
|
+
return this.present({
|
|
4248
|
+
...paywall,
|
|
4249
|
+
title: options.title ?? t.trialEndedTitle,
|
|
4250
|
+
description: options.description ?? t.trialEndedDescription,
|
|
4251
|
+
}, feedbackUrl ? { label: feedbackLabel ?? t.trialEndedFeedback, url: feedbackUrl } : null);
|
|
4252
|
+
}
|
|
4253
|
+
async present(options, feedback) {
|
|
3642
4254
|
await this.initialize();
|
|
4255
|
+
if (this.entitlements.getCached()?.regionalFreeUntil)
|
|
4256
|
+
return false;
|
|
3643
4257
|
let offer = null;
|
|
3644
4258
|
try {
|
|
3645
4259
|
offer = await this.fetchOffer();
|
|
@@ -3665,6 +4279,7 @@ class ExtenshiPay extends ExtenshiPayLite {
|
|
|
3665
4279
|
recoveryEnabled: offer?.recoveryEnabled === true,
|
|
3666
4280
|
seller: offer?.seller ?? null,
|
|
3667
4281
|
withdrawalWaiver: offer?.withdrawalWaiver ?? null,
|
|
4282
|
+
feedback: feedback ? { label: feedback.label } : null,
|
|
3668
4283
|
locale: this.config.locale,
|
|
3669
4284
|
theme: { ...this.config.theme, ...options.theme },
|
|
3670
4285
|
strings: options.strings ?? {},
|
|
@@ -3672,7 +4287,7 @@ class ExtenshiPay extends ExtenshiPayLite {
|
|
|
3672
4287
|
};
|
|
3673
4288
|
this.hidePaywall();
|
|
3674
4289
|
return new Promise((resolve) => {
|
|
3675
|
-
this.paywallSession = { options, resolve };
|
|
4290
|
+
this.paywallSession = { options, resolve, feedbackUrl: feedback?.url ?? null };
|
|
3676
4291
|
try {
|
|
3677
4292
|
this.renderer().show(view);
|
|
3678
4293
|
}
|
|
@@ -3705,6 +4320,7 @@ class ExtenshiPay extends ExtenshiPayLite {
|
|
|
3705
4320
|
onUpgrade: (sku, consent) => void this.handleUpgrade(sku, consent),
|
|
3706
4321
|
onClose: () => this.settlePaywall(false),
|
|
3707
4322
|
onRestore: () => void this.handleRestore(),
|
|
4323
|
+
onFeedback: () => void this.handleFeedback(),
|
|
3708
4324
|
});
|
|
3709
4325
|
}
|
|
3710
4326
|
return this.paywall;
|
|
@@ -3721,6 +4337,17 @@ class ExtenshiPay extends ExtenshiPayLite {
|
|
|
3721
4337
|
/* Reported through the error event; leave the paywall open for retry. */
|
|
3722
4338
|
}
|
|
3723
4339
|
}
|
|
4340
|
+
async handleFeedback() {
|
|
4341
|
+
const url = this.paywallSession?.feedbackUrl;
|
|
4342
|
+
if (!url)
|
|
4343
|
+
return;
|
|
4344
|
+
try {
|
|
4345
|
+
await (this.openUrl ?? openInNewTab)(url);
|
|
4346
|
+
}
|
|
4347
|
+
catch (error) {
|
|
4348
|
+
this.reportError(error);
|
|
4349
|
+
}
|
|
4350
|
+
}
|
|
3724
4351
|
async handleUpgrade(sku, consent) {
|
|
3725
4352
|
if (consent)
|
|
3726
4353
|
this.paywallSession?.options.onUpgrade?.(sku, consent);
|
|
@@ -3753,9 +4380,11 @@ class ExtenshiPay extends ExtenshiPayLite {
|
|
|
3753
4380
|
exports.CHECKOUT_POLL_INTERVAL_MS = CHECKOUT_POLL_INTERVAL_MS;
|
|
3754
4381
|
exports.CHECKOUT_TIMEOUT_MS = CHECKOUT_TIMEOUT_MS;
|
|
3755
4382
|
exports.CheckoutManager = CheckoutManager;
|
|
4383
|
+
exports.CloudBackup = CloudBackup;
|
|
3756
4384
|
exports.DEFAULT_API_URL = DEFAULT_API_URL;
|
|
3757
4385
|
exports.DEFAULT_CACHE_TTL_MS = DEFAULT_CACHE_TTL_MS;
|
|
3758
4386
|
exports.DEFAULT_STRINGS = DEFAULT_STRINGS;
|
|
4387
|
+
exports.DEFAULT_TRIAL_ENDING_DAYS = DEFAULT_TRIAL_ENDING_DAYS;
|
|
3759
4388
|
exports.EMPTY_ENTITLEMENT = EMPTY_ENTITLEMENT;
|
|
3760
4389
|
exports.END_USER_REF_STORAGE_KEY = END_USER_REF_STORAGE_KEY;
|
|
3761
4390
|
exports.ERROR_CODES = ERROR_CODES;
|
|
@@ -3788,11 +4417,14 @@ exports.PAY_OFFER_INTERVALS = PAY_OFFER_INTERVALS;
|
|
|
3788
4417
|
exports.PAY_OFFER_KINDS = PAY_OFFER_KINDS;
|
|
3789
4418
|
exports.PAY_PUBLISHABLE_KEY_HEX_LENGTH = PAY_PUBLISHABLE_KEY_HEX_LENGTH;
|
|
3790
4419
|
exports.PAY_PUBLISHABLE_KEY_PREFIX = PAY_PUBLISHABLE_KEY_PREFIX;
|
|
4420
|
+
exports.PAY_REGIONAL_ACCESS_SKU = PAY_REGIONAL_ACCESS_SKU;
|
|
4421
|
+
exports.PAY_RESTORE_PURPOSES = PAY_RESTORE_PURPOSES;
|
|
3791
4422
|
exports.PAY_SKU_RE = PAY_SKU_RE;
|
|
3792
4423
|
exports.PAY_WITHDRAWAL_WAIVER_VERSION = PAY_WITHDRAWAL_WAIVER_VERSION;
|
|
3793
4424
|
exports.PayApi = PayApi;
|
|
3794
4425
|
exports.PaywallRenderer = PaywallRenderer;
|
|
3795
4426
|
exports.RecoveryManager = RecoveryManager;
|
|
4427
|
+
exports.STORAGE_TOKEN_RE = STORAGE_TOKEN_RE;
|
|
3796
4428
|
exports.TRPC_PATH = TRPC_PATH;
|
|
3797
4429
|
exports.VERSION = VERSION;
|
|
3798
4430
|
exports.WITHDRAWAL_WAIVER_CLASS = WITHDRAWAL_WAIVER_CLASS;
|
|
@@ -3805,6 +4437,7 @@ exports.checkFeatures = checkFeatures;
|
|
|
3805
4437
|
exports.collectFeatures = collectFeatures;
|
|
3806
4438
|
exports.createRecoveryStorage = createRecoveryStorage;
|
|
3807
4439
|
exports.createStorage = createStorage;
|
|
4440
|
+
exports.createSyncStorage = createSyncStorage;
|
|
3808
4441
|
exports.default = ExtenshiPay;
|
|
3809
4442
|
exports.escapeHtml = escapeHtml;
|
|
3810
4443
|
exports.formatPrice = formatPrice;
|