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