@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.mjs
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
|
/**
|
|
8
8
|
* Wire contract between the SDK and catalog-bff `pay.*`.
|
|
@@ -46,6 +46,8 @@ const PAY_SKU_RE = /^[a-z0-9][a-z0-9_-]{1,39}$/;
|
|
|
46
46
|
* none — never had it
|
|
47
47
|
*/
|
|
48
48
|
const PAY_ENTITLEMENT_STATUSES = ['active', 'grace', 'expired', 'none'];
|
|
49
|
+
// Outside the seller SKU grammar. Issued only in a signed projection, never in the sales ledger.
|
|
50
|
+
const PAY_REGIONAL_ACCESS_SKU = '@regional-free';
|
|
49
51
|
/**
|
|
50
52
|
* Version of the buyer-facing withdrawal waiver text the paywall shows (EU/EEA
|
|
51
53
|
* digital content, Directive 2011/83/EU art. 16(m); UK CCR 2013 reg. 37). The
|
|
@@ -86,6 +88,14 @@ function canonicalJson(value) {
|
|
|
86
88
|
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
87
89
|
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`;
|
|
88
90
|
}
|
|
91
|
+
/**
|
|
92
|
+
* `storage`: the buyer turns on the cloud copy of the extension's settings. The
|
|
93
|
+
* hosted page shows the storage disclosure; the claim records consent. Additive:
|
|
94
|
+
* a session without a purpose is a plain restore.
|
|
95
|
+
*/
|
|
96
|
+
const PAY_RESTORE_PURPOSES = ['restore', 'storage'];
|
|
97
|
+
/** From `shared-types/storage.ts`: `est_` + 32 random bytes, base64url. */
|
|
98
|
+
const STORAGE_TOKEN_RE = /^est_[A-Za-z0-9_-]{43}$/;
|
|
89
99
|
|
|
90
100
|
const ERROR_CODES = {
|
|
91
101
|
INVALID_CONFIG: 'INVALID_CONFIG',
|
|
@@ -157,7 +167,7 @@ async function getOrCreateEndUserRef(storage) {
|
|
|
157
167
|
* developed with no backend: offers and entitlements come from `mockData`, a
|
|
158
168
|
* mock checkout completes after `claimAfterPolls` polls and grants the SKU.
|
|
159
169
|
*/
|
|
160
|
-
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
170
|
+
const DAY_MS$1 = 24 * 60 * 60 * 1000;
|
|
161
171
|
/** Accepts the same optional `withdrawalWaiver` input as the BFF; anything else is no consent. */
|
|
162
172
|
function mockConsent(value) {
|
|
163
173
|
const consent = value;
|
|
@@ -175,6 +185,10 @@ class MockTransport {
|
|
|
175
185
|
this.claimAfterPolls = data.claimAfterPolls ?? 1;
|
|
176
186
|
this.withdrawalWaiver =
|
|
177
187
|
data.withdrawalWaiver === undefined ? { version: PAY_WITHDRAWAL_WAIVER_VERSION } : data.withdrawalWaiver;
|
|
188
|
+
this.seller = data.seller;
|
|
189
|
+
this.trial = null;
|
|
190
|
+
if (data.trial)
|
|
191
|
+
this.setTrial(data.trial.days, data.trial.startedAt);
|
|
178
192
|
}
|
|
179
193
|
async call(procedure, _kind, input) {
|
|
180
194
|
switch (procedure) {
|
|
@@ -196,6 +210,14 @@ class MockTransport {
|
|
|
196
210
|
setEntitlements(items) {
|
|
197
211
|
this.entitlements = [...items];
|
|
198
212
|
}
|
|
213
|
+
/** Previews a server trial of `days` from `startedAt` (default now); `null` removes it. */
|
|
214
|
+
setTrial(days, startedAt = new Date().toISOString()) {
|
|
215
|
+
const start = Date.parse(startedAt);
|
|
216
|
+
this.trial =
|
|
217
|
+
days === null || !Number.isFinite(start)
|
|
218
|
+
? null
|
|
219
|
+
: { startedAt: new Date(start).toISOString(), endsAt: new Date(start + days * DAY_MS$1).toISOString() };
|
|
220
|
+
}
|
|
199
221
|
cancelSession(sessionId) {
|
|
200
222
|
const session = this.sessions.get(sessionId);
|
|
201
223
|
if (session)
|
|
@@ -215,6 +237,7 @@ class MockTransport {
|
|
|
215
237
|
offers: [...this.offers],
|
|
216
238
|
entitlementPublicKey: null,
|
|
217
239
|
withdrawalWaiver: this.withdrawalWaiver ? { ...this.withdrawalWaiver } : null,
|
|
240
|
+
...(this.seller !== undefined && { seller: this.seller ? { ...this.seller } : null }),
|
|
218
241
|
};
|
|
219
242
|
}
|
|
220
243
|
createCheckout(sku, withdrawalWaiver) {
|
|
@@ -252,7 +275,7 @@ class MockTransport {
|
|
|
252
275
|
grant(sku) {
|
|
253
276
|
const offer = this.offers.find((o) => o.sku === sku);
|
|
254
277
|
const expiresAt = offer?.kind === 'subscription'
|
|
255
|
-
? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS).toISOString()
|
|
278
|
+
? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS$1).toISOString()
|
|
256
279
|
: null;
|
|
257
280
|
this.entitlements = [
|
|
258
281
|
...this.entitlements.filter((item) => item.sku !== sku),
|
|
@@ -274,6 +297,7 @@ class MockTransport {
|
|
|
274
297
|
endUserRef,
|
|
275
298
|
entitlements: [...this.entitlements],
|
|
276
299
|
issuedAt: new Date().toISOString(),
|
|
300
|
+
...(this.trial ? { trial: { ...this.trial } } : {}),
|
|
277
301
|
},
|
|
278
302
|
signature: null,
|
|
279
303
|
alg: null,
|
|
@@ -287,12 +311,17 @@ class PayApi {
|
|
|
287
311
|
this.transport = transport;
|
|
288
312
|
this.publishableKey = publishableKey;
|
|
289
313
|
}
|
|
290
|
-
/**
|
|
291
|
-
|
|
314
|
+
/**
|
|
315
|
+
* `locale` opens the hosted recovery page (and its email) in the user's language.
|
|
316
|
+
* `purpose` is sent only for `storage`: a plain restore keeps the request older
|
|
317
|
+
* BFFs know, and their non-strict zod input strips the key anyway.
|
|
318
|
+
*/
|
|
319
|
+
createRestoreSession(claimChallenge, locale, purpose) {
|
|
292
320
|
return this.transport.call('pay.createRestoreSession', 'mutation', {
|
|
293
321
|
publishableKey: this.publishableKey,
|
|
294
322
|
claimChallenge,
|
|
295
323
|
...(locale ? { locale } : {}),
|
|
324
|
+
...(purpose === 'storage' ? { purpose } : {}),
|
|
296
325
|
});
|
|
297
326
|
}
|
|
298
327
|
claimRestoreSession(sessionId, claimSecret) {
|
|
@@ -331,10 +360,12 @@ class PayApi {
|
|
|
331
360
|
endUserRef,
|
|
332
361
|
});
|
|
333
362
|
}
|
|
334
|
-
|
|
363
|
+
/** `trialStartedHint`: the trial start kept in storage.sync; the server only lets it move a start earlier. */
|
|
364
|
+
getEntitlement(endUserRef, trialStartedHint) {
|
|
335
365
|
return this.transport.call('pay.getEntitlement', 'query', {
|
|
336
366
|
publishableKey: this.publishableKey,
|
|
337
367
|
endUserRef,
|
|
368
|
+
...(trialStartedHint ? { trialStartedHint } : {}),
|
|
338
369
|
});
|
|
339
370
|
}
|
|
340
371
|
getPortalUrl(endUserRef, customerId, locale) {
|
|
@@ -732,6 +763,118 @@ var checkout = /*#__PURE__*/Object.freeze({
|
|
|
732
763
|
openInNewTab: openInNewTab
|
|
733
764
|
});
|
|
734
765
|
|
|
766
|
+
/**
|
|
767
|
+
* Cloud copy of the extension's settings (`@extenshi/storage`). Pay owns the
|
|
768
|
+
* token: only a verified restore claim issues it; this module keeps it in the
|
|
769
|
+
* SDK's storage (`storage.local`) and revokes it. `@extenshi/storage` reads it
|
|
770
|
+
* through `cloudBackupToken()`. The token is never logged and never answered to
|
|
771
|
+
* a content script: route those calls to the background.
|
|
772
|
+
*/
|
|
773
|
+
const REQUEST_TIMEOUT_MS = 10000;
|
|
774
|
+
/** True in a content script, where the token must not be handed out. */
|
|
775
|
+
function inContentScript() {
|
|
776
|
+
const g = globalThis;
|
|
777
|
+
return !!(g.chrome?.runtime?.id || g.browser?.runtime?.id) && !(g.chrome?.tabs || g.browser?.tabs);
|
|
778
|
+
}
|
|
779
|
+
class CloudBackup {
|
|
780
|
+
constructor(options) {
|
|
781
|
+
this.options = options;
|
|
782
|
+
this.fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));
|
|
783
|
+
}
|
|
784
|
+
get storageKey() {
|
|
785
|
+
return `extenshi-pay:${this.options.publishableKey}:storageToken`;
|
|
786
|
+
}
|
|
787
|
+
/** Stores or clears the token from a verified claim. Never throws: the licence is already restored. */
|
|
788
|
+
async accept(grant) {
|
|
789
|
+
if (!grant || typeof grant !== 'object')
|
|
790
|
+
return undefined;
|
|
791
|
+
try {
|
|
792
|
+
if (grant.state === 'granted') {
|
|
793
|
+
if (typeof grant.token !== 'string' || !STORAGE_TOKEN_RE.test(grant.token))
|
|
794
|
+
return undefined;
|
|
795
|
+
await this.options.storage.set(this.storageKey, grant.token);
|
|
796
|
+
return 'on';
|
|
797
|
+
}
|
|
798
|
+
if (grant.state === 'unavailable') {
|
|
799
|
+
await this.options.storage.remove(this.storageKey);
|
|
800
|
+
return grant.reason === 'LICENSE_REQUIRED' ? 'license_required' : 'no_consent';
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
catch {
|
|
804
|
+
logger.warn('cloud backup state could not be saved');
|
|
805
|
+
}
|
|
806
|
+
return undefined;
|
|
807
|
+
}
|
|
808
|
+
async token() {
|
|
809
|
+
this.assertTrustedContext();
|
|
810
|
+
const value = await this.options.storage.get(this.storageKey);
|
|
811
|
+
return typeof value === 'string' && STORAGE_TOKEN_RE.test(value) ? value : null;
|
|
812
|
+
}
|
|
813
|
+
/** Revokes this installation's token. A token the server no longer knows (401) is forgotten too. */
|
|
814
|
+
async disable() {
|
|
815
|
+
const token = await this.token();
|
|
816
|
+
if (!token)
|
|
817
|
+
return;
|
|
818
|
+
if (!this.options.mock) {
|
|
819
|
+
const status = await this.request('/v1/storage/grant', token);
|
|
820
|
+
if (status !== 401)
|
|
821
|
+
this.throwUnlessOk(status);
|
|
822
|
+
}
|
|
823
|
+
await this.options.storage.remove(this.storageKey);
|
|
824
|
+
}
|
|
825
|
+
/** Deletes the buyer's cloud copy and turns the backup off on every device. */
|
|
826
|
+
async delete() {
|
|
827
|
+
const token = await this.token();
|
|
828
|
+
if (!token)
|
|
829
|
+
throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Cloud backup is off on this installation; turn it on to delete the cloud copy');
|
|
830
|
+
if (!this.options.mock) {
|
|
831
|
+
const status = await this.request('/v1/storage/data', token);
|
|
832
|
+
if (status === 401) {
|
|
833
|
+
// The server no longer accepts this token, so it is useless here; the copy was not deleted.
|
|
834
|
+
await this.options.storage.remove(this.storageKey);
|
|
835
|
+
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 });
|
|
836
|
+
}
|
|
837
|
+
this.throwUnlessOk(status);
|
|
838
|
+
}
|
|
839
|
+
await this.options.storage.remove(this.storageKey);
|
|
840
|
+
}
|
|
841
|
+
assertTrustedContext() {
|
|
842
|
+
if (inContentScript())
|
|
843
|
+
throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Use cloud backup from an extension page or background context');
|
|
844
|
+
}
|
|
845
|
+
throwUnlessOk(status) {
|
|
846
|
+
if (status >= 200 && status < 300)
|
|
847
|
+
return;
|
|
848
|
+
if (status === 429)
|
|
849
|
+
throw new ExtenshiPayError(ERROR_CODES.RATE_LIMITED, 'Too many requests', { httpStatus: status });
|
|
850
|
+
if (status >= 500)
|
|
851
|
+
throw new ExtenshiPayError(ERROR_CODES.GATEWAY_UNAVAILABLE, `HTTP ${status}`, { httpStatus: status });
|
|
852
|
+
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, `HTTP ${status}`, { httpStatus: status });
|
|
853
|
+
}
|
|
854
|
+
async request(path, token) {
|
|
855
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
|
856
|
+
const timer = controller ? setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS) : null;
|
|
857
|
+
try {
|
|
858
|
+
const response = await this.fetchImpl(`${this.options.apiUrl}${path}`, {
|
|
859
|
+
method: 'DELETE',
|
|
860
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
861
|
+
credentials: 'omit',
|
|
862
|
+
signal: controller?.signal,
|
|
863
|
+
});
|
|
864
|
+
return response.status;
|
|
865
|
+
}
|
|
866
|
+
catch (error) {
|
|
867
|
+
if (controller?.signal.aborted)
|
|
868
|
+
throw new ExtenshiPayError(ERROR_CODES.TIMEOUT, `Request timed out after ${REQUEST_TIMEOUT_MS}ms`);
|
|
869
|
+
throw new ExtenshiPayError(ERROR_CODES.NETWORK_ERROR, 'Network request failed', { cause: error });
|
|
870
|
+
}
|
|
871
|
+
finally {
|
|
872
|
+
if (timer !== null)
|
|
873
|
+
clearTimeout(timer);
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
|
|
735
878
|
/** Pure helpers over the entitlement projection. Features come from the items' `features[]`. */
|
|
736
879
|
const LIVE_STATUSES = new Set(['active', 'grace']);
|
|
737
880
|
function isLive(item) {
|
|
@@ -786,9 +929,17 @@ Object.freeze(EMPTY_ENTITLEMENT.features);
|
|
|
786
929
|
/**
|
|
787
930
|
* Ed25519 verification of the entitlement projection.
|
|
788
931
|
*
|
|
789
|
-
* Tamper resistance, not DRM.
|
|
790
|
-
*
|
|
791
|
-
*
|
|
932
|
+
* Tamper resistance, not DRM. Callers must deny access for both invalid and
|
|
933
|
+
* unverified envelopes outside explicit mocks.
|
|
934
|
+
*
|
|
935
|
+
* Which keys are trusted, in order (`PublicKeySource`, built in core/extenshi-pay.ts):
|
|
936
|
+
* 1. the key the server returned over HTTPS in this session;
|
|
937
|
+
* 2. the bundled `entitlementPublicKey`, when the developer configured one. It pins
|
|
938
|
+
* verification without a round-trip: a key read from extension storage is then never used;
|
|
939
|
+
* 3. without a bundled key, the server key saved in `storage.local` next to the
|
|
940
|
+
* license cache, so a restart with no network can still verify the cache.
|
|
941
|
+
* When none of them verifies an envelope the server is asked for its current key once
|
|
942
|
+
* (a rotated key), and that answer decides.
|
|
792
943
|
*/
|
|
793
944
|
function base64ToBytes(base64) {
|
|
794
945
|
const binary = atob(base64);
|
|
@@ -823,6 +974,156 @@ async function verifyEntitlementSignature(envelope, publicKeyBase64) {
|
|
|
823
974
|
return 'invalid';
|
|
824
975
|
}
|
|
825
976
|
}
|
|
977
|
+
const PUBLIC_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
|
|
978
|
+
/**
|
|
979
|
+
* `invalid` only when the server's current key was checked too (or the envelope carries no
|
|
980
|
+
* signature at all). A mismatch against known keys while the server is unreachable is
|
|
981
|
+
* `unverified`: it may be a rotated key, and no paid access is granted either way.
|
|
982
|
+
*/
|
|
983
|
+
async function verifyWithKeys(envelope, source) {
|
|
984
|
+
if (!envelope.signature || envelope.alg !== 'ed25519')
|
|
985
|
+
return { verdict: 'invalid', key: null };
|
|
986
|
+
let known = [];
|
|
987
|
+
try {
|
|
988
|
+
known = await source.known();
|
|
989
|
+
}
|
|
990
|
+
catch {
|
|
991
|
+
known = [];
|
|
992
|
+
}
|
|
993
|
+
let mismatch = false;
|
|
994
|
+
for (const key of known) {
|
|
995
|
+
const verdict = await verifyEntitlementSignature(envelope, key);
|
|
996
|
+
if (verdict === 'valid')
|
|
997
|
+
return { verdict, key };
|
|
998
|
+
if (verdict === 'invalid')
|
|
999
|
+
mismatch = true;
|
|
1000
|
+
}
|
|
1001
|
+
let current;
|
|
1002
|
+
try {
|
|
1003
|
+
current = await source.fetchCurrent();
|
|
1004
|
+
}
|
|
1005
|
+
catch {
|
|
1006
|
+
return { verdict: 'unverified', key: null };
|
|
1007
|
+
}
|
|
1008
|
+
if (current && !known.includes(current)) {
|
|
1009
|
+
const verdict = await verifyEntitlementSignature(envelope, current);
|
|
1010
|
+
return { verdict, key: verdict === 'valid' ? current : null };
|
|
1011
|
+
}
|
|
1012
|
+
return { verdict: mismatch ? 'invalid' : 'unverified', key: null };
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
/**
|
|
1016
|
+
* The free trial an application configures on the server (`trialDays`).
|
|
1017
|
+
*
|
|
1018
|
+
* The server starts one clock per installation at its first license read and
|
|
1019
|
+
* signs `{ startedAt, endsAt }` into the entitlement, so the trial comes from
|
|
1020
|
+
* the verified license like paid access does: no start date in extension
|
|
1021
|
+
* storage, nothing a device clock or a storage edit can move. Offline, the
|
|
1022
|
+
* cached license answers for up to 48 hours.
|
|
1023
|
+
*
|
|
1024
|
+
* `trial:ending` / `trial:ended` fire once per installation and trial (the
|
|
1025
|
+
* marker is kept in the SDK's storage), and not while the user has paid
|
|
1026
|
+
* access. Render state from `getTrial()`; the events are one-time notices.
|
|
1027
|
+
*/
|
|
1028
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
1029
|
+
/** Re-check at least daily: long timers are clamped by browsers and lost when a service worker sleeps. */
|
|
1030
|
+
const MAX_TIMER_MS$1 = DAY_MS;
|
|
1031
|
+
/** The trial as of `clock`, or null when the license carries none (or a malformed one). */
|
|
1032
|
+
function trialState(trial, clock) {
|
|
1033
|
+
if (!trial)
|
|
1034
|
+
return null;
|
|
1035
|
+
const startedAt = Date.parse(trial.startedAt);
|
|
1036
|
+
const endsAt = Date.parse(trial.endsAt);
|
|
1037
|
+
if (!Number.isFinite(startedAt) || !Number.isFinite(endsAt))
|
|
1038
|
+
return null;
|
|
1039
|
+
// The server's signed time is a floor: a clock turned back cannot reopen an ended trial.
|
|
1040
|
+
const now = Number.isFinite(clock.issuedAt) ? Math.max(clock.now, clock.issuedAt) : clock.now;
|
|
1041
|
+
const left = endsAt - now;
|
|
1042
|
+
return {
|
|
1043
|
+
active: left > 0 && clock.checked,
|
|
1044
|
+
startedAt: trial.startedAt,
|
|
1045
|
+
endsAt: trial.endsAt,
|
|
1046
|
+
daysLeft: left > 0 ? Math.ceil(left / DAY_MS) : 0,
|
|
1047
|
+
requiresOnlineCheck: left > 0 && !clock.checked,
|
|
1048
|
+
};
|
|
1049
|
+
}
|
|
1050
|
+
/** The feedback form address with `src=trial_end`; null unless it is a plain HTTPS URL. No installation id is added. */
|
|
1051
|
+
function trialFeedbackUrl(raw) {
|
|
1052
|
+
if (!raw)
|
|
1053
|
+
return null;
|
|
1054
|
+
let url;
|
|
1055
|
+
try {
|
|
1056
|
+
url = new URL(raw);
|
|
1057
|
+
}
|
|
1058
|
+
catch {
|
|
1059
|
+
return null;
|
|
1060
|
+
}
|
|
1061
|
+
if (url.protocol !== 'https:' || url.username || url.password)
|
|
1062
|
+
return null;
|
|
1063
|
+
url.searchParams.set('src', 'trial_end');
|
|
1064
|
+
return url.toString();
|
|
1065
|
+
}
|
|
1066
|
+
class TrialNotifier {
|
|
1067
|
+
constructor(options) {
|
|
1068
|
+
this.options = options;
|
|
1069
|
+
this.timer = null;
|
|
1070
|
+
this.running = false;
|
|
1071
|
+
this.pending = Promise.resolve();
|
|
1072
|
+
}
|
|
1073
|
+
start() {
|
|
1074
|
+
this.running = true;
|
|
1075
|
+
void this.evaluate();
|
|
1076
|
+
}
|
|
1077
|
+
stop() {
|
|
1078
|
+
this.running = false;
|
|
1079
|
+
this.clearTimer();
|
|
1080
|
+
}
|
|
1081
|
+
/** Checks the held license; serialized, so two refreshes never send one event twice. */
|
|
1082
|
+
evaluate() {
|
|
1083
|
+
this.pending = this.pending.then(() => this.check()).catch((error) => logger.debug('trial check', error));
|
|
1084
|
+
return this.pending;
|
|
1085
|
+
}
|
|
1086
|
+
async check() {
|
|
1087
|
+
if (!this.running)
|
|
1088
|
+
return;
|
|
1089
|
+
this.clearTimer();
|
|
1090
|
+
const trial = this.options.getTrial();
|
|
1091
|
+
if (!trial)
|
|
1092
|
+
return;
|
|
1093
|
+
const now = this.options.now();
|
|
1094
|
+
const endsAt = Date.parse(trial.endsAt);
|
|
1095
|
+
const endingAt = endsAt - this.options.endingDays * DAY_MS;
|
|
1096
|
+
const event = trial.daysLeft === 0
|
|
1097
|
+
? 'trial:ended'
|
|
1098
|
+
: trial.active && this.options.endingDays > 0 && now >= endingAt
|
|
1099
|
+
? 'trial:ending'
|
|
1100
|
+
: null;
|
|
1101
|
+
if (event && !this.options.hasPaidAccess())
|
|
1102
|
+
await this.send(event, trial);
|
|
1103
|
+
if (!this.running || trial.daysLeft === 0)
|
|
1104
|
+
return;
|
|
1105
|
+
const next = [endingAt, endsAt].find((at) => at > now) ?? endsAt;
|
|
1106
|
+
this.timer = setTimeout(() => {
|
|
1107
|
+
this.timer = null;
|
|
1108
|
+
void this.evaluate();
|
|
1109
|
+
}, Math.max(1000, Math.min(next - now, MAX_TIMER_MS$1)));
|
|
1110
|
+
}
|
|
1111
|
+
async send(event, trial) {
|
|
1112
|
+
const id = `${trial.startedAt}|${trial.endsAt}`;
|
|
1113
|
+
const field = event === 'trial:ended' ? 'ended' : 'ending';
|
|
1114
|
+
const stored = (await this.options.storage.get(this.options.storageKey));
|
|
1115
|
+
const sent = stored && typeof stored === 'object' ? stored : {};
|
|
1116
|
+
if (sent[field] === id || !this.running)
|
|
1117
|
+
return;
|
|
1118
|
+
await this.options.storage.set(this.options.storageKey, { ...sent, [field]: id });
|
|
1119
|
+
this.options.emit(event, trial);
|
|
1120
|
+
}
|
|
1121
|
+
clearTimer() {
|
|
1122
|
+
if (this.timer !== null)
|
|
1123
|
+
clearTimeout(this.timer);
|
|
1124
|
+
this.timer = null;
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
826
1127
|
|
|
827
1128
|
/**
|
|
828
1129
|
* Entitlement cache + refresh.
|
|
@@ -830,13 +1131,18 @@ async function verifyEntitlementSignature(envelope, publicKeyBase64) {
|
|
|
830
1131
|
* The cached envelope is a cache OF the server projection, never a second
|
|
831
1132
|
* source of truth: it is verified when stored and re-verified on load (once
|
|
832
1133
|
* the project's public key is known), served without a round-trip while the
|
|
833
|
-
* TTL holds, served for
|
|
1134
|
+
* TTL holds, served after signed issuance for the signed `offlineSeconds` (48 hours when absent) when the network is down, and expired
|
|
834
1135
|
* locally by `expiresAt`. Background refresh polls at most every 15 minutes
|
|
835
1136
|
* and backs off exponentially on errors.
|
|
836
1137
|
*/
|
|
837
1138
|
const MIN_REFRESH_INTERVAL_MS = 15 * 60 * 1000;
|
|
838
1139
|
const MAX_REFRESH_BACKOFF_MS = 6 * 60 * 60 * 1000;
|
|
1140
|
+
/** Offline allowance when the signed license names none (older servers and caches). */
|
|
839
1141
|
const MAX_OFFLINE_AGE_MS = 48 * 60 * 60 * 1000;
|
|
1142
|
+
/** Ceiling for a signed `offlineSeconds`. */
|
|
1143
|
+
const MAX_SIGNED_OFFLINE_AGE_MS = 366 * 24 * 60 * 60 * 1000;
|
|
1144
|
+
/** `setTimeout` fires at once past this delay. */
|
|
1145
|
+
const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
840
1146
|
// Allow small server/client clock skew without granting more than the signed age limit.
|
|
841
1147
|
const MAX_CLOCK_SKEW_MS = 5 * 60 * 1000;
|
|
842
1148
|
const CACHE_VERSION = 1;
|
|
@@ -855,6 +1161,8 @@ class EntitlementManager {
|
|
|
855
1161
|
this.options = options;
|
|
856
1162
|
this.held = null;
|
|
857
1163
|
this.inflight = null;
|
|
1164
|
+
/** Device clock against the server's at the last license check; null within 5 minutes. */
|
|
1165
|
+
this.clockSkew = null;
|
|
858
1166
|
this.timer = null;
|
|
859
1167
|
this.refreshGeneration = 0;
|
|
860
1168
|
this.deadlineTimer = null;
|
|
@@ -896,8 +1204,10 @@ class EntitlementManager {
|
|
|
896
1204
|
envelope: JSON.parse(JSON.stringify(record.envelope)),
|
|
897
1205
|
fetchedAt: record.fetchedAt,
|
|
898
1206
|
verified: false,
|
|
1207
|
+
key: null,
|
|
899
1208
|
source: this.source === 'mock' ? 'mock' : 'cache',
|
|
900
1209
|
};
|
|
1210
|
+
this.measureClockSkew(record.fetchedAt, Date.parse(record.envelope.payload.issuedAt));
|
|
901
1211
|
this.lastFingerprint = this.fingerprint();
|
|
902
1212
|
return this.snapshot();
|
|
903
1213
|
}
|
|
@@ -908,8 +1218,7 @@ class EntitlementManager {
|
|
|
908
1218
|
if (this.source === 'mock')
|
|
909
1219
|
return;
|
|
910
1220
|
const held = this.held;
|
|
911
|
-
const key = await this.
|
|
912
|
-
const verdict = await verifyEntitlementSignature(held.envelope, key);
|
|
1221
|
+
const { verdict, key } = await verifyWithKeys(held.envelope, this.options.keys);
|
|
913
1222
|
if (held !== this.held)
|
|
914
1223
|
return;
|
|
915
1224
|
if (verdict === 'invalid') {
|
|
@@ -918,19 +1227,39 @@ class EntitlementManager {
|
|
|
918
1227
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Cached entitlement signature is invalid');
|
|
919
1228
|
}
|
|
920
1229
|
held.verified = verdict === 'valid';
|
|
1230
|
+
held.key = key;
|
|
921
1231
|
if (!held.verified) {
|
|
922
1232
|
throw new ExtenshiPayError(ERROR_CODES.VERIFICATION_UNAVAILABLE, 'Entitlement verification requires a trusted key and Ed25519 WebCrypto support');
|
|
923
1233
|
}
|
|
924
1234
|
this.scheduleDeadline();
|
|
925
1235
|
}
|
|
1236
|
+
/** The key the held license was verified with; null when there is none or it is unverified. */
|
|
1237
|
+
get verifiedKey() {
|
|
1238
|
+
return this.held?.verified ? this.held.key : null;
|
|
1239
|
+
}
|
|
926
1240
|
getCached() {
|
|
927
1241
|
return this.held ? this.snapshot() : null;
|
|
928
1242
|
}
|
|
1243
|
+
/** The server trial in the held license; null without one, or while the license is unverified. */
|
|
1244
|
+
getTrial() {
|
|
1245
|
+
const held = this.held;
|
|
1246
|
+
if (!held || (this.source !== 'mock' && !held.verified))
|
|
1247
|
+
return null;
|
|
1248
|
+
const now = this.now();
|
|
1249
|
+
const issuedAt = Date.parse(held.envelope.payload.issuedAt);
|
|
1250
|
+
return trialState(held.envelope.payload.trial, {
|
|
1251
|
+
now,
|
|
1252
|
+
issuedAt,
|
|
1253
|
+
// The same offline rule as paid access (snapshot): the allowance from the signed issue, no clock turned back.
|
|
1254
|
+
checked: this.source === 'mock' ||
|
|
1255
|
+
(now >= held.fetchedAt && now < this.offlineDeadline() && now + MAX_CLOCK_SKEW_MS >= issuedAt),
|
|
1256
|
+
});
|
|
1257
|
+
}
|
|
929
1258
|
isFresh() {
|
|
930
1259
|
return (this.held !== null &&
|
|
931
1260
|
(this.source === 'mock' || (this.held.verified && !this.snapshot().requiresOnlineCheck)) &&
|
|
932
1261
|
this.now() >= this.held.fetchedAt &&
|
|
933
|
-
this.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs,
|
|
1262
|
+
this.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs, this.offlineAgeMs()));
|
|
934
1263
|
}
|
|
935
1264
|
async get(options = {}) {
|
|
936
1265
|
if (!options.force && this.isFresh())
|
|
@@ -945,7 +1274,7 @@ class EntitlementManager {
|
|
|
945
1274
|
logger.debug('serving cached entitlement after refresh failure', err.code);
|
|
946
1275
|
return this.snapshot();
|
|
947
1276
|
}
|
|
948
|
-
return
|
|
1277
|
+
return this.snapshot();
|
|
949
1278
|
}
|
|
950
1279
|
}
|
|
951
1280
|
/** Fetches the projection from the backend, verifies and stores it. */
|
|
@@ -953,7 +1282,8 @@ class EntitlementManager {
|
|
|
953
1282
|
if (!this.inflight) {
|
|
954
1283
|
this.inflight = (async () => {
|
|
955
1284
|
const endUserRef = await this.options.getEndUserRef();
|
|
956
|
-
const
|
|
1285
|
+
const hint = this.options.getTrialStartHint ? await this.options.getTrialStartHint() : null;
|
|
1286
|
+
const envelope = await this.options.api.getEntitlement(endUserRef, hint);
|
|
957
1287
|
return this.accept(envelope, this.source);
|
|
958
1288
|
})().finally(() => {
|
|
959
1289
|
this.inflight = null;
|
|
@@ -975,9 +1305,9 @@ class EntitlementManager {
|
|
|
975
1305
|
if (envelope.payload.endUserRef !== endUserRef) {
|
|
976
1306
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issued for a different endUserRef');
|
|
977
1307
|
}
|
|
978
|
-
const verdict = this.source === 'mock'
|
|
979
|
-
? 'unverified'
|
|
980
|
-
: await
|
|
1308
|
+
const { verdict, key } = this.source === 'mock'
|
|
1309
|
+
? { verdict: 'unverified', key: null }
|
|
1310
|
+
: await verifyWithKeys(envelope, this.options.keys);
|
|
981
1311
|
if (verdict === 'invalid') {
|
|
982
1312
|
await this.discard();
|
|
983
1313
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement signature is invalid');
|
|
@@ -987,15 +1317,19 @@ class EntitlementManager {
|
|
|
987
1317
|
}
|
|
988
1318
|
const fetchedAt = this.now();
|
|
989
1319
|
const issuedAt = Date.parse(envelope.payload.issuedAt);
|
|
1320
|
+
// A verified envelope was signed moments ago: its `issuedAt` is the server's clock.
|
|
1321
|
+
if (this.source !== 'mock')
|
|
1322
|
+
this.measureClockSkew(fetchedAt, issuedAt);
|
|
990
1323
|
if (this.source !== 'mock' && (!Number.isFinite(issuedAt) || issuedAt > fetchedAt + MAX_CLOCK_SKEW_MS)) {
|
|
991
1324
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issuedAt is invalid or in the future');
|
|
992
1325
|
}
|
|
993
|
-
this.held = { envelope, fetchedAt, verified: verdict === 'valid', source };
|
|
1326
|
+
this.held = { envelope, fetchedAt, verified: verdict === 'valid', key, source };
|
|
994
1327
|
const record = { v: CACHE_VERSION, envelope, fetchedAt };
|
|
995
1328
|
await this.options.storage.set(this.storageKey, JSON.parse(JSON.stringify(record)));
|
|
996
1329
|
this.backoffMs = 0;
|
|
997
1330
|
this.scheduleDeadline();
|
|
998
1331
|
this.notifyIfChanged();
|
|
1332
|
+
this.options.onAccepted?.();
|
|
999
1333
|
return this.snapshot();
|
|
1000
1334
|
}
|
|
1001
1335
|
/** Drain an older installation refresh before changing identity. */
|
|
@@ -1049,7 +1383,7 @@ class EntitlementManager {
|
|
|
1049
1383
|
this.deadlineTimer = null;
|
|
1050
1384
|
this.notifyIfChanged();
|
|
1051
1385
|
this.scheduleDeadline();
|
|
1052
|
-
}, remaining);
|
|
1386
|
+
}, Math.min(remaining, MAX_TIMER_MS));
|
|
1053
1387
|
}
|
|
1054
1388
|
schedule(delayMs) {
|
|
1055
1389
|
const generation = this.refreshGeneration;
|
|
@@ -1070,14 +1404,12 @@ class EntitlementManager {
|
|
|
1070
1404
|
}
|
|
1071
1405
|
}, delayMs);
|
|
1072
1406
|
}
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
return null;
|
|
1080
|
-
}
|
|
1407
|
+
measureClockSkew(local, server) {
|
|
1408
|
+
const ms = local - server;
|
|
1409
|
+
this.clockSkew =
|
|
1410
|
+
Number.isFinite(ms) && Math.abs(ms) > MAX_CLOCK_SKEW_MS
|
|
1411
|
+
? { direction: ms > 0 ? 'ahead' : 'behind', ms: Math.abs(ms) }
|
|
1412
|
+
: null;
|
|
1081
1413
|
}
|
|
1082
1414
|
async discard() {
|
|
1083
1415
|
this.held = null;
|
|
@@ -1087,7 +1419,13 @@ class EntitlementManager {
|
|
|
1087
1419
|
}
|
|
1088
1420
|
fingerprint() {
|
|
1089
1421
|
const state = this.snapshot();
|
|
1090
|
-
return canonicalJson({
|
|
1422
|
+
return canonicalJson({
|
|
1423
|
+
items: state.items,
|
|
1424
|
+
requiresOnlineCheck: state.requiresOnlineCheck,
|
|
1425
|
+
...(state.regionalFreeUntil
|
|
1426
|
+
? { regionalFreeUntil: state.regionalFreeUntil, features: state.features }
|
|
1427
|
+
: {}),
|
|
1428
|
+
});
|
|
1091
1429
|
}
|
|
1092
1430
|
notifyIfChanged() {
|
|
1093
1431
|
const fingerprint = this.fingerprint();
|
|
@@ -1100,16 +1438,31 @@ class EntitlementManager {
|
|
|
1100
1438
|
if (!this.held)
|
|
1101
1439
|
return NaN;
|
|
1102
1440
|
// fetchedAt is untrusted bookkeeping; it may shorten, never extend, a grant.
|
|
1103
|
-
return Math.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) +
|
|
1441
|
+
return (Math.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) + this.offlineAgeMs());
|
|
1442
|
+
}
|
|
1443
|
+
/** The signed allowance of the held license, or 48 hours when it names none. */
|
|
1444
|
+
offlineAgeMs() {
|
|
1445
|
+
const seconds = this.held?.envelope.payload.offlineSeconds;
|
|
1446
|
+
if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0)
|
|
1447
|
+
return MAX_OFFLINE_AGE_MS;
|
|
1448
|
+
return Math.min(seconds * 1000, MAX_SIGNED_OFFLINE_AGE_MS);
|
|
1104
1449
|
}
|
|
1105
1450
|
snapshot() {
|
|
1106
1451
|
if (!this.held)
|
|
1107
|
-
return EMPTY_ENTITLEMENT;
|
|
1452
|
+
return this.clockSkew ? { ...EMPTY_ENTITLEMENT, clockSkew: this.clockSkew } : EMPTY_ENTITLEMENT;
|
|
1108
1453
|
if (this.source !== 'mock' && !this.held.verified) {
|
|
1109
|
-
return {
|
|
1454
|
+
return {
|
|
1455
|
+
...EMPTY_ENTITLEMENT,
|
|
1456
|
+
requiresOnlineCheck: true,
|
|
1457
|
+
clockSkew: this.clockSkew,
|
|
1458
|
+
source: this.held.source,
|
|
1459
|
+
};
|
|
1110
1460
|
}
|
|
1111
|
-
const
|
|
1112
|
-
const
|
|
1461
|
+
const grants = applyLocalExpiry(JSON.parse(JSON.stringify(this.held.envelope.payload.entitlements)), this.now());
|
|
1462
|
+
const regional = grants.find((grant) => grant.sku === PAY_REGIONAL_ACCESS_SKU && grant.status === 'active');
|
|
1463
|
+
const items = grants.filter((grant) => grant.sku !== PAY_REGIONAL_ACCESS_SKU);
|
|
1464
|
+
const hasPaidAccess = grants.some((grant) => grant.sku === PAY_REGIONAL_ACCESS_SKU) ||
|
|
1465
|
+
collectFeatures(items).length > 0 ||
|
|
1113
1466
|
items.some((item) => item.status === 'active' || item.status === 'grace');
|
|
1114
1467
|
const offlineUntil = this.source === 'mock' || !hasPaidAccess ? null : this.offlineDeadline();
|
|
1115
1468
|
const requiresOnlineCheck = offlineUntil !== null &&
|
|
@@ -1119,9 +1472,13 @@ class EntitlementManager {
|
|
|
1119
1472
|
this.now() + MAX_CLOCK_SKEW_MS < Date.parse(this.held.envelope.payload.issuedAt));
|
|
1120
1473
|
return {
|
|
1121
1474
|
items,
|
|
1122
|
-
features: requiresOnlineCheck ? [] : collectFeatures(
|
|
1475
|
+
features: requiresOnlineCheck ? [] : collectFeatures(grants),
|
|
1476
|
+
...(regional?.expiresAt && !requiresOnlineCheck
|
|
1477
|
+
? { regionalFreeUntil: Date.parse(regional.expiresAt) }
|
|
1478
|
+
: {}),
|
|
1123
1479
|
requiresOnlineCheck,
|
|
1124
1480
|
offlineUntil,
|
|
1481
|
+
clockSkew: this.clockSkew,
|
|
1125
1482
|
verified: this.held.verified,
|
|
1126
1483
|
issuedAt: this.held.envelope.payload.issuedAt,
|
|
1127
1484
|
fetchedAt: this.held.fetchedAt,
|
|
@@ -1210,6 +1567,16 @@ class MemoryStorage {
|
|
|
1210
1567
|
this.map.delete(key);
|
|
1211
1568
|
}
|
|
1212
1569
|
}
|
|
1570
|
+
/**
|
|
1571
|
+
* The browser's synced storage (`storage.sync`), or null outside an extension. The SDK keeps
|
|
1572
|
+
* only the trial start there (never `endUserRef`), so devices on one synced account share the
|
|
1573
|
+
* trial. Uninstalling clears it from the account, so it does not survive a reinstall.
|
|
1574
|
+
*/
|
|
1575
|
+
function createSyncStorage() {
|
|
1576
|
+
const g = extensionGlobals();
|
|
1577
|
+
const area = g.chrome?.storage?.sync ?? g.browser?.storage?.sync;
|
|
1578
|
+
return area ? new ExtensionStorage(area) : null;
|
|
1579
|
+
}
|
|
1213
1580
|
function createStorage() {
|
|
1214
1581
|
const g = extensionGlobals();
|
|
1215
1582
|
const area = g.chrome?.storage?.local ?? g.browser?.storage?.local;
|
|
@@ -1266,7 +1633,7 @@ class RecoveryManager {
|
|
|
1266
1633
|
const secret = Array.from(cryptoApi.getRandomValues(new Uint8Array(32)), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
1267
1634
|
const hash = await cryptoApi.subtle.digest('SHA-256', new TextEncoder().encode(secret));
|
|
1268
1635
|
const challenge = Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
1269
|
-
const created = await this.options.api.createRestoreSession(challenge, this.options.locale);
|
|
1636
|
+
const created = await this.options.api.createRestoreSession(challenge, this.options.locale, options.purpose);
|
|
1270
1637
|
if (!Number.isFinite(Date.parse(created.expiresAt)))
|
|
1271
1638
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery expiry');
|
|
1272
1639
|
const pending = { sessionId: created.sessionId, expiresAt: created.expiresAt, claimSecret: secret };
|
|
@@ -1326,8 +1693,9 @@ class RecoveryManager {
|
|
|
1326
1693
|
break;
|
|
1327
1694
|
if (claim.state === 'complete') {
|
|
1328
1695
|
const entitlement = await this.options.onComplete(claim.endUserRef, claim.entitlement);
|
|
1696
|
+
const cloudBackup = await this.options.onStorageGrant?.(claim.storage);
|
|
1329
1697
|
await this.options.storage.remove(this.pendingKey);
|
|
1330
|
-
return { state: 'complete', entitlement };
|
|
1698
|
+
return { state: 'complete', entitlement, ...(cloudBackup ? { cloudBackup } : {}) };
|
|
1331
1699
|
}
|
|
1332
1700
|
if (claim.state !== 'pending')
|
|
1333
1701
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery response');
|
|
@@ -1356,9 +1724,10 @@ class RecoveryManager {
|
|
|
1356
1724
|
const DEFAULT_API_URL = 'https://bff.extenshi.io';
|
|
1357
1725
|
const DEFAULT_CACHE_TTL_MS = 60 * 60 * 1000;
|
|
1358
1726
|
const MAX_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
1727
|
+
const DEFAULT_TRIAL_ENDING_DAYS = 2;
|
|
1359
1728
|
|
|
1360
1729
|
/** Kept in sync with package.json by tests/unit/version.test.ts. */
|
|
1361
|
-
const VERSION = '0.
|
|
1730
|
+
const VERSION = '0.12.0';
|
|
1362
1731
|
|
|
1363
1732
|
/**
|
|
1364
1733
|
* The user's language as the SDK sends it. Kept apart from the paywall
|
|
@@ -1428,7 +1797,7 @@ function resolveConfig(input) {
|
|
|
1428
1797
|
if (!isHttpUrl(apiUrl))
|
|
1429
1798
|
errors.push('apiUrl must be an http(s) URL');
|
|
1430
1799
|
const entitlementPublicKey = input.entitlementPublicKey ?? null;
|
|
1431
|
-
if (entitlementPublicKey !== null &&
|
|
1800
|
+
if (entitlementPublicKey !== null && !PUBLIC_KEY_RE.test(entitlementPublicKey)) {
|
|
1432
1801
|
errors.push('entitlementPublicKey must be a base64-encoded 32-byte Ed25519 public key');
|
|
1433
1802
|
}
|
|
1434
1803
|
const environment = input.environment ?? 'production';
|
|
@@ -1450,6 +1819,9 @@ function resolveConfig(input) {
|
|
|
1450
1819
|
const theme = input.theme ?? {};
|
|
1451
1820
|
if (theme.mode !== undefined && !THEME_MODES.has(theme.mode))
|
|
1452
1821
|
errors.push('theme.mode must be light, dark or auto');
|
|
1822
|
+
const trialEndingDays = input.trialEndingDays ?? DEFAULT_TRIAL_ENDING_DAYS;
|
|
1823
|
+
if (!Number.isInteger(trialEndingDays) || trialEndingDays < 0 || trialEndingDays > 365)
|
|
1824
|
+
errors.push('trialEndingDays must be a whole number of days between 0 and 365');
|
|
1453
1825
|
if (input.mock &&
|
|
1454
1826
|
input.mockData !== undefined &&
|
|
1455
1827
|
(typeof input.mockData !== 'object' || input.mockData === null)) {
|
|
@@ -1470,6 +1842,8 @@ function resolveConfig(input) {
|
|
|
1470
1842
|
mock: input.mock === true,
|
|
1471
1843
|
mockData: input.mock ? (input.mockData ?? {}) : null,
|
|
1472
1844
|
theme,
|
|
1845
|
+
trialEndingDays,
|
|
1846
|
+
syncTrialStart: input.syncTrialStart !== false,
|
|
1473
1847
|
};
|
|
1474
1848
|
}
|
|
1475
1849
|
|
|
@@ -1594,6 +1968,9 @@ const SDK_STRINGS_EN = {
|
|
|
1594
1968
|
pickerDescription: 'Separate purchases can have separate billing profiles. Choose one to manage its subscriptions and payment details.',
|
|
1595
1969
|
pickerFirstRecorded: 'First recorded {date}',
|
|
1596
1970
|
pickerCancel: 'Cancel',
|
|
1971
|
+
trialEndedTitle: 'Your free trial has ended',
|
|
1972
|
+
trialEndedDescription: 'The extension’s tools are paused. Your settings are kept and will be there when you upgrade.',
|
|
1973
|
+
trialEndedFeedback: 'Share feedback',
|
|
1597
1974
|
};
|
|
1598
1975
|
// BEGIN GENERATED TRANSLATIONS
|
|
1599
1976
|
const TRANSLATIONS = {
|
|
@@ -1662,6 +2039,9 @@ const TRANSLATIONS = {
|
|
|
1662
2039
|
pickerDescription: 'Las compras independientes pueden tener perfiles de facturación distintos. Elige uno para gestionar sus suscripciones y datos de pago.',
|
|
1663
2040
|
pickerFirstRecorded: 'Registrado por primera vez el {date}',
|
|
1664
2041
|
pickerCancel: 'Cancelar',
|
|
2042
|
+
trialEndedTitle: 'Tu prueba gratuita ha terminado',
|
|
2043
|
+
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.',
|
|
2044
|
+
trialEndedFeedback: 'Enviar comentarios',
|
|
1665
2045
|
},
|
|
1666
2046
|
'pt-BR': {
|
|
1667
2047
|
title: 'Desbloqueie os recursos premium',
|
|
@@ -1728,6 +2108,9 @@ const TRANSLATIONS = {
|
|
|
1728
2108
|
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.',
|
|
1729
2109
|
pickerFirstRecorded: 'Registrado pela primeira vez em {date}',
|
|
1730
2110
|
pickerCancel: 'Cancelar',
|
|
2111
|
+
trialEndedTitle: 'Seu teste gratuito terminou',
|
|
2112
|
+
trialEndedDescription: 'As ferramentas da extensão estão pausadas. Suas configurações foram mantidas e estarão lá quando você fizer o upgrade.',
|
|
2113
|
+
trialEndedFeedback: 'Enviar feedback',
|
|
1731
2114
|
},
|
|
1732
2115
|
fr: {
|
|
1733
2116
|
title: 'Débloquez les fonctionnalités premium',
|
|
@@ -1794,6 +2177,9 @@ const TRANSLATIONS = {
|
|
|
1794
2177
|
pickerDescription: 'Des achats distincts peuvent avoir des profils de facturation distincts. Choisissez-en un pour gérer ses abonnements et ses informations de paiement.',
|
|
1795
2178
|
pickerFirstRecorded: 'Enregistré pour la première fois le {date}',
|
|
1796
2179
|
pickerCancel: 'Annuler',
|
|
2180
|
+
trialEndedTitle: 'Votre essai gratuit est terminé',
|
|
2181
|
+
trialEndedDescription: 'Les outils de l’extension sont en pause. Vos paramètres sont conservés et vous les retrouverez après la mise à niveau.',
|
|
2182
|
+
trialEndedFeedback: 'Donner votre avis',
|
|
1797
2183
|
},
|
|
1798
2184
|
de: {
|
|
1799
2185
|
title: 'Premium-Funktionen freischalten',
|
|
@@ -1860,6 +2246,9 @@ const TRANSLATIONS = {
|
|
|
1860
2246
|
pickerDescription: 'Verschiedene Käufe können eigene Abrechnungsprofile haben. Wähle eines aus, um seine Abonnements und Zahlungsdaten zu verwalten.',
|
|
1861
2247
|
pickerFirstRecorded: 'Erstmals erfasst am {date}',
|
|
1862
2248
|
pickerCancel: 'Abbrechen',
|
|
2249
|
+
trialEndedTitle: 'Dein kostenloser Testzeitraum ist abgelaufen',
|
|
2250
|
+
trialEndedDescription: 'Die Funktionen der Erweiterung sind pausiert. Deine Einstellungen bleiben erhalten und sind nach dem Upgrade wieder da.',
|
|
2251
|
+
trialEndedFeedback: 'Feedback geben',
|
|
1863
2252
|
},
|
|
1864
2253
|
it: {
|
|
1865
2254
|
title: 'Sblocca le funzionalità premium',
|
|
@@ -1926,6 +2315,9 @@ const TRANSLATIONS = {
|
|
|
1926
2315
|
pickerDescription: 'Acquisti diversi possono avere profili di fatturazione diversi. Scegline uno per gestirne gli abbonamenti e i dati di pagamento.',
|
|
1927
2316
|
pickerFirstRecorded: 'Registrato per la prima volta il {date}',
|
|
1928
2317
|
pickerCancel: 'Annulla',
|
|
2318
|
+
trialEndedTitle: 'La tua prova gratuita è terminata',
|
|
2319
|
+
trialEndedDescription: 'Gli strumenti dell’estensione sono in pausa. Le tue impostazioni sono conservate e le ritroverai dopo l’upgrade.',
|
|
2320
|
+
trialEndedFeedback: 'Invia un feedback',
|
|
1929
2321
|
},
|
|
1930
2322
|
ru: {
|
|
1931
2323
|
title: 'Откройте доступ к премиум-функциям',
|
|
@@ -1992,6 +2384,9 @@ const TRANSLATIONS = {
|
|
|
1992
2384
|
pickerDescription: 'У разных покупок могут быть разные платёжные профили. Выберите профиль, чтобы управлять его подписками и платёжными данными.',
|
|
1993
2385
|
pickerFirstRecorded: 'Впервые зафиксирован: {date}',
|
|
1994
2386
|
pickerCancel: 'Отмена',
|
|
2387
|
+
trialEndedTitle: 'Бесплатный пробный период закончился',
|
|
2388
|
+
trialEndedDescription: 'Инструменты расширения приостановлены. Ваши настройки сохранены и будут на месте после перехода на премиум.',
|
|
2389
|
+
trialEndedFeedback: 'Оставить отзыв',
|
|
1995
2390
|
},
|
|
1996
2391
|
ja: {
|
|
1997
2392
|
title: 'プレミアム機能をアンロック',
|
|
@@ -2058,6 +2453,9 @@ const TRANSLATIONS = {
|
|
|
2058
2453
|
pickerDescription: '購入ごとに別々の請求プロファイルがある場合があります。サブスクリプションと支払い情報を管理するプロファイルを1つ選択してください。',
|
|
2059
2454
|
pickerFirstRecorded: '初回記録日:{date}',
|
|
2060
2455
|
pickerCancel: 'キャンセル',
|
|
2456
|
+
trialEndedTitle: '無料トライアルが終了しました',
|
|
2457
|
+
trialEndedDescription: '拡張機能のツールは一時停止しています。設定は保存されており、アップグレード後もそのままご利用いただけます。',
|
|
2458
|
+
trialEndedFeedback: 'フィードバックを送信',
|
|
2061
2459
|
},
|
|
2062
2460
|
ko: {
|
|
2063
2461
|
title: '프리미엄 기능 잠금 해제',
|
|
@@ -2124,6 +2522,9 @@ const TRANSLATIONS = {
|
|
|
2124
2522
|
pickerDescription: '구매마다 결제 프로필이 다를 수 있습니다. 구독과 결제 정보를 관리할 프로필을 하나 선택해 주세요.',
|
|
2125
2523
|
pickerFirstRecorded: '최초 기록일: {date}',
|
|
2126
2524
|
pickerCancel: '취소',
|
|
2525
|
+
trialEndedTitle: '무료 체험 기간이 종료되었습니다',
|
|
2526
|
+
trialEndedDescription: '확장 프로그램의 도구가 일시 중지되었습니다. 설정은 그대로 저장되어 있으며 업그레이드하면 다시 사용할 수 있습니다.',
|
|
2527
|
+
trialEndedFeedback: '의견 보내기',
|
|
2127
2528
|
},
|
|
2128
2529
|
'zh-CN': {
|
|
2129
2530
|
title: '解锁高级功能',
|
|
@@ -2190,6 +2591,9 @@ const TRANSLATIONS = {
|
|
|
2190
2591
|
pickerDescription: '不同的购买可以有各自的账单资料。请选择一个,以管理其订阅和付款信息。',
|
|
2191
2592
|
pickerFirstRecorded: '首次记录于 {date}',
|
|
2192
2593
|
pickerCancel: '取消',
|
|
2594
|
+
trialEndedTitle: '免费试用已结束',
|
|
2595
|
+
trialEndedDescription: '扩展程序的工具已暂停。您的设置已保留,升级后即可继续使用。',
|
|
2596
|
+
trialEndedFeedback: '提交反馈',
|
|
2193
2597
|
},
|
|
2194
2598
|
ar: {
|
|
2195
2599
|
title: 'احصل على الميزات المميزة',
|
|
@@ -2256,6 +2660,9 @@ const TRANSLATIONS = {
|
|
|
2256
2660
|
pickerDescription: 'يمكن أن تكون لعمليات الشراء المنفصلة ملفات فوترة منفصلة. اختر ملفًا منها لإدارة اشتراكاته وتفاصيل الدفع الخاصة به.',
|
|
2257
2661
|
pickerFirstRecorded: 'سُجِّل لأول مرة في {date}',
|
|
2258
2662
|
pickerCancel: 'إلغاء',
|
|
2663
|
+
trialEndedTitle: 'انتهت فترتك التجريبية المجانية',
|
|
2664
|
+
trialEndedDescription: 'أدوات الإضافة متوقفة مؤقتًا. إعداداتك محفوظة وستجدها كما هي بعد الترقية.',
|
|
2665
|
+
trialEndedFeedback: 'إرسال ملاحظات',
|
|
2259
2666
|
},
|
|
2260
2667
|
};
|
|
2261
2668
|
// END GENERATED TRANSLATIONS
|
|
@@ -2336,8 +2743,10 @@ function withdrawalWaiverText(serverVersion, locale, seller) {
|
|
|
2336
2743
|
* extends it with `getOffer()` / `showPaywall()`.
|
|
2337
2744
|
*
|
|
2338
2745
|
* Data that leaves the extension: `publishableKey`, `endUserRef`, `sku`,
|
|
2339
|
-
* `locale
|
|
2340
|
-
*
|
|
2746
|
+
* `locale`, checkout session IDs and, with a server trial, the trial start date
|
|
2747
|
+
* the server issued (`trialStartedHint`, kept in storage.sync). Explicit recovery also sends its session ID,
|
|
2748
|
+
* challenge and claim secret (POST body). Email stays on the hosted page. With cloud backup, the
|
|
2749
|
+
* storage token goes only to `/v1/storage` (as a bearer), never in a message to a content script.
|
|
2341
2750
|
*/
|
|
2342
2751
|
/** Server-side offer cache is 5 min; mirror it in memory. */
|
|
2343
2752
|
const OFFER_TTL_MS = 5 * 60 * 1000;
|
|
@@ -2348,12 +2757,30 @@ class ExtenshiPayLite {
|
|
|
2348
2757
|
this.endUserRefPromise = null;
|
|
2349
2758
|
this.offer = null;
|
|
2350
2759
|
this.offerInflight = null;
|
|
2760
|
+
/** The signing key the server returned in this session; never one read from storage. */
|
|
2761
|
+
this.serverKey = null;
|
|
2762
|
+
/** Trust order for license signatures; see payment/signature.ts. */
|
|
2763
|
+
this.keys = {
|
|
2764
|
+
known: async () => {
|
|
2765
|
+
const pinned = this.config.entitlementPublicKey;
|
|
2766
|
+
const offline = pinned ?? (await this.readSavedServerKey());
|
|
2767
|
+
return [...new Set([this.serverKey, offline].filter((key) => !!key))];
|
|
2768
|
+
},
|
|
2769
|
+
fetchCurrent: async () => (await this.fetchOffer(true)).entitlementPublicKey,
|
|
2770
|
+
};
|
|
2351
2771
|
this.readyPromise = null;
|
|
2352
2772
|
this.destroyed = false;
|
|
2353
2773
|
this.config = resolveConfig(config);
|
|
2354
2774
|
logger.configure({ logLevel: this.config.logLevel, debug: this.config.debug });
|
|
2355
2775
|
this.now = deps.now ?? (() => Date.now());
|
|
2356
2776
|
this.storage = deps.storage ?? createStorage();
|
|
2777
|
+
this.openUrl = deps.openUrl;
|
|
2778
|
+
this.syncStorage =
|
|
2779
|
+
!this.config.syncTrialStart || this.config.mock
|
|
2780
|
+
? null
|
|
2781
|
+
: deps.syncStorage === undefined
|
|
2782
|
+
? createSyncStorage()
|
|
2783
|
+
: deps.syncStorage;
|
|
2357
2784
|
const transport = deps.transport ??
|
|
2358
2785
|
(this.config.mock
|
|
2359
2786
|
? new MockTransport(this.config.mockData ?? {})
|
|
@@ -2366,11 +2793,29 @@ class ExtenshiPayLite {
|
|
|
2366
2793
|
cacheTtlMs: this.config.cacheTtlMs,
|
|
2367
2794
|
source: this.config.mock ? 'mock' : 'network',
|
|
2368
2795
|
getEndUserRef: () => this.getEndUserRef(),
|
|
2369
|
-
|
|
2796
|
+
keys: this.keys,
|
|
2370
2797
|
onChange: (entitlement) => this.emitter.emit('entitlement:changed', entitlement),
|
|
2798
|
+
onAccepted: () => {
|
|
2799
|
+
void this.trial.evaluate();
|
|
2800
|
+
void this.rememberTrialStart();
|
|
2801
|
+
},
|
|
2802
|
+
getTrialStartHint: () => this.readTrialStartHint(),
|
|
2371
2803
|
onError: (error) => this.reportError(error),
|
|
2372
2804
|
now: this.now,
|
|
2373
2805
|
});
|
|
2806
|
+
this.trial = new TrialNotifier({
|
|
2807
|
+
storage: this.storage,
|
|
2808
|
+
storageKey: `extenshi-pay:${this.config.publishableKey}:trial-events${this.config.mock ? ':mock' : ''}`,
|
|
2809
|
+
endingDays: this.config.trialEndingDays,
|
|
2810
|
+
getTrial: () => this.entitlements.getTrial(),
|
|
2811
|
+
// A paid license still counts while it waits for an online check: no "trial ended" to a buyer.
|
|
2812
|
+
hasPaidAccess: () => {
|
|
2813
|
+
const license = this.entitlements.getCached();
|
|
2814
|
+
return Boolean(license?.regionalFreeUntil || license?.items.some(isLive));
|
|
2815
|
+
},
|
|
2816
|
+
emit: (event, trial) => this.emitter.emit(event, trial),
|
|
2817
|
+
now: this.now,
|
|
2818
|
+
});
|
|
2374
2819
|
this.checkout = new CheckoutManager({
|
|
2375
2820
|
api: this.api,
|
|
2376
2821
|
storage: this.storage,
|
|
@@ -2384,6 +2829,13 @@ class ExtenshiPayLite {
|
|
|
2384
2829
|
(this.config.mock ? (url) => logger.info('mock checkout (no tab opened)', url) : undefined),
|
|
2385
2830
|
now: this.now,
|
|
2386
2831
|
});
|
|
2832
|
+
this.backup = new CloudBackup({
|
|
2833
|
+
storage: this.storage,
|
|
2834
|
+
publishableKey: this.config.publishableKey,
|
|
2835
|
+
apiUrl: this.config.apiUrl,
|
|
2836
|
+
fetch: deps.fetch,
|
|
2837
|
+
mock: this.config.mock,
|
|
2838
|
+
});
|
|
2387
2839
|
this.recovery = new RecoveryManager({
|
|
2388
2840
|
api: this.api,
|
|
2389
2841
|
locale: this.config.locale,
|
|
@@ -2397,7 +2849,7 @@ class ExtenshiPayLite {
|
|
|
2397
2849
|
envelope.payload.publishableKey !== this.config.publishableKey ||
|
|
2398
2850
|
!Number.isFinite(Date.parse(envelope.payload.issuedAt)) ||
|
|
2399
2851
|
Date.parse(envelope.payload.issuedAt) > this.now() + MAX_CLOCK_SKEW_MS ||
|
|
2400
|
-
(await
|
|
2852
|
+
(await verifyWithKeys(envelope, this.keys)).verdict !== 'valid')
|
|
2401
2853
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Recovery requires a verified entitlement for this installation');
|
|
2402
2854
|
this.entitlements.stopAutoRefresh();
|
|
2403
2855
|
try {
|
|
@@ -2415,6 +2867,7 @@ class ExtenshiPayLite {
|
|
|
2415
2867
|
this.entitlements.startAutoRefresh();
|
|
2416
2868
|
}
|
|
2417
2869
|
},
|
|
2870
|
+
onStorageGrant: (grant) => this.backup.accept(grant),
|
|
2418
2871
|
});
|
|
2419
2872
|
if (config.onError)
|
|
2420
2873
|
this.emitter.on('error', config.onError);
|
|
@@ -2460,8 +2913,11 @@ class ExtenshiPayLite {
|
|
|
2460
2913
|
catch (error) {
|
|
2461
2914
|
this.reportError(error);
|
|
2462
2915
|
}
|
|
2463
|
-
|
|
2916
|
+
void this.confirmSavedServerKey();
|
|
2917
|
+
if (!this.destroyed) {
|
|
2464
2918
|
this.entitlements.startAutoRefresh();
|
|
2919
|
+
this.trial.start();
|
|
2920
|
+
}
|
|
2465
2921
|
}
|
|
2466
2922
|
/** The anonymous, random id this install is known by. */
|
|
2467
2923
|
getEndUserRef() {
|
|
@@ -2482,6 +2938,16 @@ class ExtenshiPayLite {
|
|
|
2482
2938
|
await this.initialize();
|
|
2483
2939
|
return this.entitlements.get(options);
|
|
2484
2940
|
}
|
|
2941
|
+
/**
|
|
2942
|
+
* The free trial the application set on the server, from the verified license, or null when
|
|
2943
|
+
* there is none (or the license could not be verified yet). Answers offline from the cached
|
|
2944
|
+
* license; like paid access, `active` needs a license check within 48 hours. `isPaid()` and
|
|
2945
|
+
* `hasFeature()` do not include the trial: grant trial access with `(await getTrial())?.active`.
|
|
2946
|
+
*/
|
|
2947
|
+
async getTrial(options = {}) {
|
|
2948
|
+
await this.getEntitlement(options);
|
|
2949
|
+
return this.entitlements.getTrial();
|
|
2950
|
+
}
|
|
2485
2951
|
/** True when any active/grace entitlement exists, or the given `sku` is active/grace. */
|
|
2486
2952
|
async isPaid(sku) {
|
|
2487
2953
|
return isEntitled(await this.getEntitlement(), sku);
|
|
@@ -2565,6 +3031,41 @@ class ExtenshiPayLite {
|
|
|
2565
3031
|
throw this.reportError(error);
|
|
2566
3032
|
}
|
|
2567
3033
|
}
|
|
3034
|
+
/**
|
|
3035
|
+
* Turns on the cloud copy of the extension's settings (`@extenshi/storage`): the
|
|
3036
|
+
* hosted restore page shows the storage disclosure and the buyer confirms with
|
|
3037
|
+
* the code from the purchase email. `cloudBackup` in the result says whether it is
|
|
3038
|
+
* on. Buyers only; consent is recorded by the server.
|
|
3039
|
+
*/
|
|
3040
|
+
enableCloudBackup(options = {}) {
|
|
3041
|
+
return this.restorePurchase({ ...options, purpose: 'storage' });
|
|
3042
|
+
}
|
|
3043
|
+
/**
|
|
3044
|
+
* The storage token for `ExtenshiStorage.create({ cloud: { getToken } })`, or null
|
|
3045
|
+
* while cloud backup is off on this installation. Extension pages and background
|
|
3046
|
+
* only: it rejects in a content script, and must never be sent to one.
|
|
3047
|
+
*/
|
|
3048
|
+
async cloudBackupToken() {
|
|
3049
|
+
return this.backup.token();
|
|
3050
|
+
}
|
|
3051
|
+
/** Turns cloud backup off on this installation: revokes its token. The cloud copy stays. */
|
|
3052
|
+
async disableCloudBackup() {
|
|
3053
|
+
try {
|
|
3054
|
+
await this.backup.disable();
|
|
3055
|
+
}
|
|
3056
|
+
catch (error) {
|
|
3057
|
+
throw this.reportError(error);
|
|
3058
|
+
}
|
|
3059
|
+
}
|
|
3060
|
+
/** Deletes the buyer's cloud copy and turns cloud backup off on every installation. */
|
|
3061
|
+
async deleteCloudBackup() {
|
|
3062
|
+
try {
|
|
3063
|
+
await this.backup.delete();
|
|
3064
|
+
}
|
|
3065
|
+
catch (error) {
|
|
3066
|
+
throw this.reportError(error);
|
|
3067
|
+
}
|
|
3068
|
+
}
|
|
2568
3069
|
/** Read-only license view. Entitlements retain cache/signature/offline semantics. */
|
|
2569
3070
|
async getLicenseSummary(options = {}) {
|
|
2570
3071
|
await this.initialize();
|
|
@@ -2634,6 +3135,7 @@ class ExtenshiPayLite {
|
|
|
2634
3135
|
destroy() {
|
|
2635
3136
|
this.destroyed = true;
|
|
2636
3137
|
this.recovery.stop();
|
|
3138
|
+
this.trial.stop();
|
|
2637
3139
|
this.entitlements.stopAutoRefresh();
|
|
2638
3140
|
this.emitter.removeAll();
|
|
2639
3141
|
}
|
|
@@ -2645,8 +3147,9 @@ class ExtenshiPayLite {
|
|
|
2645
3147
|
if (!this.offerInflight) {
|
|
2646
3148
|
this.offerInflight = this.api
|
|
2647
3149
|
.getOffer(this.config.locale)
|
|
2648
|
-
.then((value) => {
|
|
3150
|
+
.then(async (value) => {
|
|
2649
3151
|
this.offer = { value, fetchedAt: this.now() };
|
|
3152
|
+
await this.rememberServerKey(value.entitlementPublicKey);
|
|
2650
3153
|
return value;
|
|
2651
3154
|
})
|
|
2652
3155
|
.finally(() => {
|
|
@@ -2655,8 +3158,88 @@ class ExtenshiPayLite {
|
|
|
2655
3158
|
}
|
|
2656
3159
|
return this.offerInflight;
|
|
2657
3160
|
}
|
|
2658
|
-
|
|
2659
|
-
return this.config.entitlementPublicKey
|
|
3161
|
+
get serverKeyStorageKey() {
|
|
3162
|
+
return `extenshi-pay:${this.config.publishableKey}:entitlementPublicKey`;
|
|
3163
|
+
}
|
|
3164
|
+
async readSavedServerKey() {
|
|
3165
|
+
try {
|
|
3166
|
+
const value = await this.storage.get(this.serverKeyStorageKey);
|
|
3167
|
+
return typeof value === 'string' && PUBLIC_KEY_RE.test(value) ? value : null;
|
|
3168
|
+
}
|
|
3169
|
+
catch {
|
|
3170
|
+
return null;
|
|
3171
|
+
}
|
|
3172
|
+
}
|
|
3173
|
+
/**
|
|
3174
|
+
* Keeps the server's key next to the license cache so a restart with no network can verify it.
|
|
3175
|
+
* Not with a bundled key: that one already covers the restart, and storage stays untrusted.
|
|
3176
|
+
*/
|
|
3177
|
+
async rememberServerKey(key) {
|
|
3178
|
+
if (typeof key !== 'string' || !PUBLIC_KEY_RE.test(key))
|
|
3179
|
+
return;
|
|
3180
|
+
this.serverKey = key;
|
|
3181
|
+
if (this.config.entitlementPublicKey || this.config.mock)
|
|
3182
|
+
return;
|
|
3183
|
+
try {
|
|
3184
|
+
if ((await this.readSavedServerKey()) !== key)
|
|
3185
|
+
await this.storage.set(this.serverKeyStorageKey, key);
|
|
3186
|
+
}
|
|
3187
|
+
catch (error) {
|
|
3188
|
+
logger.debug('signing key not saved', error);
|
|
3189
|
+
}
|
|
3190
|
+
}
|
|
3191
|
+
/**
|
|
3192
|
+
* A license verified with the saved key alone is checked against the server once per start:
|
|
3193
|
+
* when the server's key differs (rotation, or an edited storage) the license is fetched again,
|
|
3194
|
+
* and dropped if it does not verify. Offline, the saved key stands until `offlineUntil`.
|
|
3195
|
+
*/
|
|
3196
|
+
async confirmSavedServerKey() {
|
|
3197
|
+
const used = this.entitlements.verifiedKey;
|
|
3198
|
+
if (this.destroyed || !used || used === this.serverKey || used === this.config.entitlementPublicKey)
|
|
3199
|
+
return;
|
|
3200
|
+
try {
|
|
3201
|
+
if ((await this.fetchOffer()).entitlementPublicKey === used || this.destroyed)
|
|
3202
|
+
return;
|
|
3203
|
+
}
|
|
3204
|
+
catch {
|
|
3205
|
+
return;
|
|
3206
|
+
}
|
|
3207
|
+
try {
|
|
3208
|
+
await this.entitlements.refresh();
|
|
3209
|
+
}
|
|
3210
|
+
catch {
|
|
3211
|
+
await this.entitlements.reverify().catch((error) => this.reportError(error));
|
|
3212
|
+
}
|
|
3213
|
+
}
|
|
3214
|
+
get trialStartKey() {
|
|
3215
|
+
return `extenshi-pay:${this.config.publishableKey}:trialStartedAt`;
|
|
3216
|
+
}
|
|
3217
|
+
/** The synced trial start, or null (none, malformed, or storage.sync unavailable). */
|
|
3218
|
+
async readTrialStartHint() {
|
|
3219
|
+
if (!this.syncStorage)
|
|
3220
|
+
return null;
|
|
3221
|
+
try {
|
|
3222
|
+
const value = await this.syncStorage.get(this.trialStartKey);
|
|
3223
|
+
return typeof value === 'string' && Number.isFinite(Date.parse(value)) ? value : null;
|
|
3224
|
+
}
|
|
3225
|
+
catch {
|
|
3226
|
+
return null;
|
|
3227
|
+
}
|
|
3228
|
+
}
|
|
3229
|
+
/** Syncs the verified trial start, keeping the earliest one seen. Never the installation id. */
|
|
3230
|
+
async rememberTrialStart() {
|
|
3231
|
+
const trial = this.entitlements.getTrial();
|
|
3232
|
+
if (!this.syncStorage || !trial)
|
|
3233
|
+
return;
|
|
3234
|
+
try {
|
|
3235
|
+
const synced = await this.readTrialStartHint();
|
|
3236
|
+
if (synced && Date.parse(synced) <= Date.parse(trial.startedAt))
|
|
3237
|
+
return;
|
|
3238
|
+
await this.syncStorage.set(this.trialStartKey, trial.startedAt);
|
|
3239
|
+
}
|
|
3240
|
+
catch (error) {
|
|
3241
|
+
logger.debug('trial start not synced', error);
|
|
3242
|
+
}
|
|
2660
3243
|
}
|
|
2661
3244
|
reportError(error) {
|
|
2662
3245
|
const err = ExtenshiPayError.from(error);
|
|
@@ -3401,18 +3984,12 @@ class PaywallRenderer {
|
|
|
3401
3984
|
}
|
|
3402
3985
|
if (waiver && waiverBox)
|
|
3403
3986
|
this.mountWaiver(root, doc, waiver.text, waiverBox);
|
|
3404
|
-
|
|
3405
|
-
|
|
3406
|
-
|
|
3407
|
-
|
|
3408
|
-
|
|
3409
|
-
|
|
3410
|
-
button.style.cssText =
|
|
3411
|
-
'display:block;margin:12px auto 0;background:none;border:0;color:inherit;font:inherit;text-decoration:underline;cursor:pointer';
|
|
3412
|
-
button.addEventListener('click', () => this.callbacks.onRestore?.());
|
|
3413
|
-
footer.appendChild(button);
|
|
3414
|
-
}
|
|
3415
|
-
}
|
|
3987
|
+
const onRestore = this.callbacks.onRestore;
|
|
3988
|
+
if (view.recoveryEnabled && onRestore)
|
|
3989
|
+
this.footerLink(root, doc, strings.restorePurchase, onRestore);
|
|
3990
|
+
const onFeedback = this.callbacks.onFeedback;
|
|
3991
|
+
if (view.feedback && onFeedback)
|
|
3992
|
+
this.footerLink(root, doc, view.feedback.label, onFeedback);
|
|
3416
3993
|
const mount = view.mode === 'inline' ? (view.container ?? doc.body) : doc.body;
|
|
3417
3994
|
mount.appendChild(host);
|
|
3418
3995
|
this.host = host;
|
|
@@ -3429,6 +4006,19 @@ class PaywallRenderer {
|
|
|
3429
4006
|
this.host.remove();
|
|
3430
4007
|
this.host = null;
|
|
3431
4008
|
}
|
|
4009
|
+
/** A text button at the end of the footer (no `href`: the SDK opens URLs itself). */
|
|
4010
|
+
footerLink(root, doc, label, onClick) {
|
|
4011
|
+
const footer = root.querySelector('[class*="-footer"], .ep-minimal-actions, .ep-inline-content, .ep-fullscreen-content');
|
|
4012
|
+
if (!footer)
|
|
4013
|
+
return;
|
|
4014
|
+
const button = doc.createElement('button');
|
|
4015
|
+
button.type = 'button';
|
|
4016
|
+
button.textContent = label;
|
|
4017
|
+
button.style.cssText =
|
|
4018
|
+
'display:block;margin:12px auto 0;background:none;border:0;color:inherit;font:inherit;text-decoration:underline;cursor:pointer';
|
|
4019
|
+
button.addEventListener('click', () => onClick());
|
|
4020
|
+
footer.appendChild(button);
|
|
4021
|
+
}
|
|
3432
4022
|
prune(root) {
|
|
3433
4023
|
for (const element of root.querySelectorAll(PRUNE_SELECTOR))
|
|
3434
4024
|
element.remove();
|
|
@@ -3635,7 +4225,31 @@ class ExtenshiPay extends ExtenshiPayLite {
|
|
|
3635
4225
|
* `getOffer()`; if that fails the paywall still renders with checkout disabled.
|
|
3636
4226
|
*/
|
|
3637
4227
|
async showPaywall(options = {}) {
|
|
4228
|
+
return this.present(options, null);
|
|
4229
|
+
}
|
|
4230
|
+
/**
|
|
4231
|
+
* The paywall for a user whose free trial ended, e.g. on `trial:ended`. In the user's
|
|
4232
|
+
* language it says the trial has ended, the tools are paused and the settings are kept,
|
|
4233
|
+
* then shows the plans, "Restore purchase" when recovery is on, and with `feedbackFormUrl`
|
|
4234
|
+
* a feedback button. Resolves like `showPaywall()`. The default text promises the settings
|
|
4235
|
+
* are kept: pass `description` if your extension does not keep them.
|
|
4236
|
+
*/
|
|
4237
|
+
async showTrialEnded(options = {}) {
|
|
4238
|
+
const t = sdkStrings(this.config.locale);
|
|
4239
|
+
const feedbackUrl = trialFeedbackUrl(options.feedbackFormUrl);
|
|
4240
|
+
if (options.feedbackFormUrl !== undefined && !feedbackUrl)
|
|
4241
|
+
this.reportError(new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'feedbackFormUrl must be an https URL without credentials; the feedback button is left out'));
|
|
4242
|
+
const { feedbackFormUrl: _url, feedbackLabel, ...paywall } = options;
|
|
4243
|
+
return this.present({
|
|
4244
|
+
...paywall,
|
|
4245
|
+
title: options.title ?? t.trialEndedTitle,
|
|
4246
|
+
description: options.description ?? t.trialEndedDescription,
|
|
4247
|
+
}, feedbackUrl ? { label: feedbackLabel ?? t.trialEndedFeedback, url: feedbackUrl } : null);
|
|
4248
|
+
}
|
|
4249
|
+
async present(options, feedback) {
|
|
3638
4250
|
await this.initialize();
|
|
4251
|
+
if (this.entitlements.getCached()?.regionalFreeUntil)
|
|
4252
|
+
return false;
|
|
3639
4253
|
let offer = null;
|
|
3640
4254
|
try {
|
|
3641
4255
|
offer = await this.fetchOffer();
|
|
@@ -3661,6 +4275,7 @@ class ExtenshiPay extends ExtenshiPayLite {
|
|
|
3661
4275
|
recoveryEnabled: offer?.recoveryEnabled === true,
|
|
3662
4276
|
seller: offer?.seller ?? null,
|
|
3663
4277
|
withdrawalWaiver: offer?.withdrawalWaiver ?? null,
|
|
4278
|
+
feedback: feedback ? { label: feedback.label } : null,
|
|
3664
4279
|
locale: this.config.locale,
|
|
3665
4280
|
theme: { ...this.config.theme, ...options.theme },
|
|
3666
4281
|
strings: options.strings ?? {},
|
|
@@ -3668,7 +4283,7 @@ class ExtenshiPay extends ExtenshiPayLite {
|
|
|
3668
4283
|
};
|
|
3669
4284
|
this.hidePaywall();
|
|
3670
4285
|
return new Promise((resolve) => {
|
|
3671
|
-
this.paywallSession = { options, resolve };
|
|
4286
|
+
this.paywallSession = { options, resolve, feedbackUrl: feedback?.url ?? null };
|
|
3672
4287
|
try {
|
|
3673
4288
|
this.renderer().show(view);
|
|
3674
4289
|
}
|
|
@@ -3701,6 +4316,7 @@ class ExtenshiPay extends ExtenshiPayLite {
|
|
|
3701
4316
|
onUpgrade: (sku, consent) => void this.handleUpgrade(sku, consent),
|
|
3702
4317
|
onClose: () => this.settlePaywall(false),
|
|
3703
4318
|
onRestore: () => void this.handleRestore(),
|
|
4319
|
+
onFeedback: () => void this.handleFeedback(),
|
|
3704
4320
|
});
|
|
3705
4321
|
}
|
|
3706
4322
|
return this.paywall;
|
|
@@ -3717,6 +4333,17 @@ class ExtenshiPay extends ExtenshiPayLite {
|
|
|
3717
4333
|
/* Reported through the error event; leave the paywall open for retry. */
|
|
3718
4334
|
}
|
|
3719
4335
|
}
|
|
4336
|
+
async handleFeedback() {
|
|
4337
|
+
const url = this.paywallSession?.feedbackUrl;
|
|
4338
|
+
if (!url)
|
|
4339
|
+
return;
|
|
4340
|
+
try {
|
|
4341
|
+
await (this.openUrl ?? openInNewTab)(url);
|
|
4342
|
+
}
|
|
4343
|
+
catch (error) {
|
|
4344
|
+
this.reportError(error);
|
|
4345
|
+
}
|
|
4346
|
+
}
|
|
3720
4347
|
async handleUpgrade(sku, consent) {
|
|
3721
4348
|
if (consent)
|
|
3722
4349
|
this.paywallSession?.options.onUpgrade?.(sku, consent);
|
|
@@ -3746,5 +4373,5 @@ class ExtenshiPay extends ExtenshiPayLite {
|
|
|
3746
4373
|
|
|
3747
4374
|
// Full SDK entry point: core + paywall UI.
|
|
3748
4375
|
|
|
3749
|
-
export { CHECKOUT_POLL_INTERVAL_MS, CHECKOUT_TIMEOUT_MS, CheckoutManager, DEFAULT_API_URL, DEFAULT_CACHE_TTL_MS, DEFAULT_STRINGS, EMPTY_ENTITLEMENT, END_USER_REF_STORAGE_KEY, ERROR_CODES, EntitlementManager, EventEmitter, ExtenshiPay, ExtenshiPayError, ExtenshiPayLite, ExtensionStorage, HttpTransport, LOCALE_RE, LocalStorageAdapter, Logger, MAX_CACHE_TTL_MS, MAX_REFRESH_BACKOFF_MS, MIN_REFRESH_INTERVAL_MS, MemoryStorage, MockTransport, PAYWALL_HOST_CLASS, PAYWALL_MODES, PAYWALL_SHARED_CSS, PAYWALL_TEMPLATES, PAY_CONTRACT_VERSION, PAY_CURRENCIES, PAY_END_USER_REF_RE, PAY_ENTITLEMENT_STATUSES, PAY_ERRORS, PAY_GATEWAYS, PAY_OFFER_INTERVALS, PAY_OFFER_KINDS, PAY_PUBLISHABLE_KEY_HEX_LENGTH, PAY_PUBLISHABLE_KEY_PREFIX, PAY_SKU_RE, PAY_WITHDRAWAL_WAIVER_VERSION, PayApi, PaywallRenderer, RecoveryManager, TRPC_PATH, VERSION, WITHDRAWAL_WAIVER_CLASS, WITHDRAWAL_WAIVER_TEXTS, applyLocalExpiry, base64ToBytes, buildContent, canonicalJson, checkFeatures, collectFeatures, createRecoveryStorage, createStorage, ExtenshiPay as default, escapeHtml, formatPrice, getOrCreateEndUserRef, hasFeature, isEntitled, isLive, isPayPublishableKey, logger, mintEndUserRef, openInNewTab, periodLabel, resolveConfig, resolveThemeMode, substitute, themeCss, trpcErrorToPayError, verifyEntitlementSignature, withdrawalWaiverText };
|
|
4376
|
+
export { CHECKOUT_POLL_INTERVAL_MS, CHECKOUT_TIMEOUT_MS, CheckoutManager, CloudBackup, DEFAULT_API_URL, DEFAULT_CACHE_TTL_MS, DEFAULT_STRINGS, DEFAULT_TRIAL_ENDING_DAYS, EMPTY_ENTITLEMENT, END_USER_REF_STORAGE_KEY, ERROR_CODES, EntitlementManager, EventEmitter, ExtenshiPay, ExtenshiPayError, ExtenshiPayLite, ExtensionStorage, HttpTransport, LOCALE_RE, LocalStorageAdapter, Logger, MAX_CACHE_TTL_MS, MAX_REFRESH_BACKOFF_MS, MIN_REFRESH_INTERVAL_MS, MemoryStorage, MockTransport, PAYWALL_HOST_CLASS, PAYWALL_MODES, PAYWALL_SHARED_CSS, PAYWALL_TEMPLATES, PAY_CONTRACT_VERSION, PAY_CURRENCIES, PAY_END_USER_REF_RE, PAY_ENTITLEMENT_STATUSES, PAY_ERRORS, PAY_GATEWAYS, PAY_OFFER_INTERVALS, PAY_OFFER_KINDS, PAY_PUBLISHABLE_KEY_HEX_LENGTH, PAY_PUBLISHABLE_KEY_PREFIX, PAY_REGIONAL_ACCESS_SKU, PAY_RESTORE_PURPOSES, PAY_SKU_RE, PAY_WITHDRAWAL_WAIVER_VERSION, PayApi, PaywallRenderer, RecoveryManager, STORAGE_TOKEN_RE, TRPC_PATH, VERSION, WITHDRAWAL_WAIVER_CLASS, WITHDRAWAL_WAIVER_TEXTS, applyLocalExpiry, base64ToBytes, buildContent, canonicalJson, checkFeatures, collectFeatures, createRecoveryStorage, createStorage, createSyncStorage, ExtenshiPay as default, escapeHtml, formatPrice, getOrCreateEndUserRef, hasFeature, isEntitled, isLive, isPayPublishableKey, logger, mintEndUserRef, openInNewTab, periodLabel, resolveConfig, resolveThemeMode, substitute, themeCss, trpcErrorToPayError, verifyEntitlementSignature, withdrawalWaiverText };
|
|
3750
4377
|
//# sourceMappingURL=extenshi-pay.mjs.map
|