@extenshi/pay 0.9.0 → 0.11.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 +128 -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 +268 -26
- package/dist/core.d.ts +268 -26
- package/dist/core.js +566 -44
- package/dist/core.js.map +1 -1
- package/dist/core.mjs +562 -45
- package/dist/core.mjs.map +1 -1
- package/dist/extenshi-pay-lite.js +555 -44
- 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 +555 -44
- package/dist/extenshi-pay-lite.mjs.map +1 -1
- package/dist/extenshi-pay.cjs.js +670 -57
- 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 +670 -57
- 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 +666 -58
- package/dist/extenshi-pay.mjs.map +1 -1
- package/dist/index.d.mts +285 -26
- package/dist/index.d.ts +285 -26
- package/dist/lite.d.mts +212 -13
- package/dist/lite.d.ts +212 -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 +35 -0
- package/dist/types/contract.d.ts.map +1 -1
- package/dist/types/entitlement.d.ts +37 -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.11.0
|
|
3
3
|
* (c) 2026 Extenshi.io
|
|
4
4
|
* Released under the MIT License.
|
|
5
|
-
* commit
|
|
5
|
+
* commit ed0f776ae9ab7ce6b2c614dbdfe696e9007b0d05 · built by `rollup -c`
|
|
6
6
|
*/
|
|
7
7
|
/**
|
|
8
8
|
* Wire contract between the SDK and catalog-bff `pay.*`.
|
|
@@ -86,6 +86,14 @@ function canonicalJson(value) {
|
|
|
86
86
|
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
87
87
|
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`;
|
|
88
88
|
}
|
|
89
|
+
/**
|
|
90
|
+
* `storage`: the buyer turns on the cloud copy of the extension's settings. The
|
|
91
|
+
* hosted page shows the storage disclosure; the claim records consent. Additive:
|
|
92
|
+
* a session without a purpose is a plain restore.
|
|
93
|
+
*/
|
|
94
|
+
const PAY_RESTORE_PURPOSES = ['restore', 'storage'];
|
|
95
|
+
/** From `shared-types/storage.ts`: `est_` + 32 random bytes, base64url. */
|
|
96
|
+
const STORAGE_TOKEN_RE = /^est_[A-Za-z0-9_-]{43}$/;
|
|
89
97
|
|
|
90
98
|
const ERROR_CODES = {
|
|
91
99
|
INVALID_CONFIG: 'INVALID_CONFIG',
|
|
@@ -157,7 +165,7 @@ async function getOrCreateEndUserRef(storage) {
|
|
|
157
165
|
* developed with no backend: offers and entitlements come from `mockData`, a
|
|
158
166
|
* mock checkout completes after `claimAfterPolls` polls and grants the SKU.
|
|
159
167
|
*/
|
|
160
|
-
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
168
|
+
const DAY_MS$1 = 24 * 60 * 60 * 1000;
|
|
161
169
|
/** Accepts the same optional `withdrawalWaiver` input as the BFF; anything else is no consent. */
|
|
162
170
|
function mockConsent(value) {
|
|
163
171
|
const consent = value;
|
|
@@ -175,6 +183,10 @@ class MockTransport {
|
|
|
175
183
|
this.claimAfterPolls = data.claimAfterPolls ?? 1;
|
|
176
184
|
this.withdrawalWaiver =
|
|
177
185
|
data.withdrawalWaiver === undefined ? { version: PAY_WITHDRAWAL_WAIVER_VERSION } : data.withdrawalWaiver;
|
|
186
|
+
this.seller = data.seller;
|
|
187
|
+
this.trial = null;
|
|
188
|
+
if (data.trial)
|
|
189
|
+
this.setTrial(data.trial.days, data.trial.startedAt);
|
|
178
190
|
}
|
|
179
191
|
async call(procedure, _kind, input) {
|
|
180
192
|
switch (procedure) {
|
|
@@ -196,6 +208,14 @@ class MockTransport {
|
|
|
196
208
|
setEntitlements(items) {
|
|
197
209
|
this.entitlements = [...items];
|
|
198
210
|
}
|
|
211
|
+
/** Previews a server trial of `days` from `startedAt` (default now); `null` removes it. */
|
|
212
|
+
setTrial(days, startedAt = new Date().toISOString()) {
|
|
213
|
+
const start = Date.parse(startedAt);
|
|
214
|
+
this.trial =
|
|
215
|
+
days === null || !Number.isFinite(start)
|
|
216
|
+
? null
|
|
217
|
+
: { startedAt: new Date(start).toISOString(), endsAt: new Date(start + days * DAY_MS$1).toISOString() };
|
|
218
|
+
}
|
|
199
219
|
cancelSession(sessionId) {
|
|
200
220
|
const session = this.sessions.get(sessionId);
|
|
201
221
|
if (session)
|
|
@@ -215,6 +235,7 @@ class MockTransport {
|
|
|
215
235
|
offers: [...this.offers],
|
|
216
236
|
entitlementPublicKey: null,
|
|
217
237
|
withdrawalWaiver: this.withdrawalWaiver ? { ...this.withdrawalWaiver } : null,
|
|
238
|
+
...(this.seller !== undefined && { seller: this.seller ? { ...this.seller } : null }),
|
|
218
239
|
};
|
|
219
240
|
}
|
|
220
241
|
createCheckout(sku, withdrawalWaiver) {
|
|
@@ -252,7 +273,7 @@ class MockTransport {
|
|
|
252
273
|
grant(sku) {
|
|
253
274
|
const offer = this.offers.find((o) => o.sku === sku);
|
|
254
275
|
const expiresAt = offer?.kind === 'subscription'
|
|
255
|
-
? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS).toISOString()
|
|
276
|
+
? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS$1).toISOString()
|
|
256
277
|
: null;
|
|
257
278
|
this.entitlements = [
|
|
258
279
|
...this.entitlements.filter((item) => item.sku !== sku),
|
|
@@ -274,6 +295,7 @@ class MockTransport {
|
|
|
274
295
|
endUserRef,
|
|
275
296
|
entitlements: [...this.entitlements],
|
|
276
297
|
issuedAt: new Date().toISOString(),
|
|
298
|
+
...(this.trial ? { trial: { ...this.trial } } : {}),
|
|
277
299
|
},
|
|
278
300
|
signature: null,
|
|
279
301
|
alg: null,
|
|
@@ -287,12 +309,17 @@ class PayApi {
|
|
|
287
309
|
this.transport = transport;
|
|
288
310
|
this.publishableKey = publishableKey;
|
|
289
311
|
}
|
|
290
|
-
/**
|
|
291
|
-
|
|
312
|
+
/**
|
|
313
|
+
* `locale` opens the hosted recovery page (and its email) in the user's language.
|
|
314
|
+
* `purpose` is sent only for `storage`: a plain restore keeps the request older
|
|
315
|
+
* BFFs know, and their non-strict zod input strips the key anyway.
|
|
316
|
+
*/
|
|
317
|
+
createRestoreSession(claimChallenge, locale, purpose) {
|
|
292
318
|
return this.transport.call('pay.createRestoreSession', 'mutation', {
|
|
293
319
|
publishableKey: this.publishableKey,
|
|
294
320
|
claimChallenge,
|
|
295
321
|
...(locale ? { locale } : {}),
|
|
322
|
+
...(purpose === 'storage' ? { purpose } : {}),
|
|
296
323
|
});
|
|
297
324
|
}
|
|
298
325
|
claimRestoreSession(sessionId, claimSecret) {
|
|
@@ -331,10 +358,12 @@ class PayApi {
|
|
|
331
358
|
endUserRef,
|
|
332
359
|
});
|
|
333
360
|
}
|
|
334
|
-
|
|
361
|
+
/** `trialStartedHint`: the trial start kept in storage.sync; the server only lets it move a start earlier. */
|
|
362
|
+
getEntitlement(endUserRef, trialStartedHint) {
|
|
335
363
|
return this.transport.call('pay.getEntitlement', 'query', {
|
|
336
364
|
publishableKey: this.publishableKey,
|
|
337
365
|
endUserRef,
|
|
366
|
+
...(trialStartedHint ? { trialStartedHint } : {}),
|
|
338
367
|
});
|
|
339
368
|
}
|
|
340
369
|
getPortalUrl(endUserRef, customerId, locale) {
|
|
@@ -732,6 +761,118 @@ var checkout = /*#__PURE__*/Object.freeze({
|
|
|
732
761
|
openInNewTab: openInNewTab
|
|
733
762
|
});
|
|
734
763
|
|
|
764
|
+
/**
|
|
765
|
+
* Cloud copy of the extension's settings (`@extenshi/storage`). Pay owns the
|
|
766
|
+
* token: only a verified restore claim issues it; this module keeps it in the
|
|
767
|
+
* SDK's storage (`storage.local`) and revokes it. `@extenshi/storage` reads it
|
|
768
|
+
* through `cloudBackupToken()`. The token is never logged and never answered to
|
|
769
|
+
* a content script: route those calls to the background.
|
|
770
|
+
*/
|
|
771
|
+
const REQUEST_TIMEOUT_MS = 10000;
|
|
772
|
+
/** True in a content script, where the token must not be handed out. */
|
|
773
|
+
function inContentScript() {
|
|
774
|
+
const g = globalThis;
|
|
775
|
+
return !!(g.chrome?.runtime?.id || g.browser?.runtime?.id) && !(g.chrome?.tabs || g.browser?.tabs);
|
|
776
|
+
}
|
|
777
|
+
class CloudBackup {
|
|
778
|
+
constructor(options) {
|
|
779
|
+
this.options = options;
|
|
780
|
+
this.fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));
|
|
781
|
+
}
|
|
782
|
+
get storageKey() {
|
|
783
|
+
return `extenshi-pay:${this.options.publishableKey}:storageToken`;
|
|
784
|
+
}
|
|
785
|
+
/** Stores or clears the token from a verified claim. Never throws: the licence is already restored. */
|
|
786
|
+
async accept(grant) {
|
|
787
|
+
if (!grant || typeof grant !== 'object')
|
|
788
|
+
return undefined;
|
|
789
|
+
try {
|
|
790
|
+
if (grant.state === 'granted') {
|
|
791
|
+
if (typeof grant.token !== 'string' || !STORAGE_TOKEN_RE.test(grant.token))
|
|
792
|
+
return undefined;
|
|
793
|
+
await this.options.storage.set(this.storageKey, grant.token);
|
|
794
|
+
return 'on';
|
|
795
|
+
}
|
|
796
|
+
if (grant.state === 'unavailable') {
|
|
797
|
+
await this.options.storage.remove(this.storageKey);
|
|
798
|
+
return grant.reason === 'LICENSE_REQUIRED' ? 'license_required' : 'no_consent';
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
catch {
|
|
802
|
+
logger.warn('cloud backup state could not be saved');
|
|
803
|
+
}
|
|
804
|
+
return undefined;
|
|
805
|
+
}
|
|
806
|
+
async token() {
|
|
807
|
+
this.assertTrustedContext();
|
|
808
|
+
const value = await this.options.storage.get(this.storageKey);
|
|
809
|
+
return typeof value === 'string' && STORAGE_TOKEN_RE.test(value) ? value : null;
|
|
810
|
+
}
|
|
811
|
+
/** Revokes this installation's token. A token the server no longer knows (401) is forgotten too. */
|
|
812
|
+
async disable() {
|
|
813
|
+
const token = await this.token();
|
|
814
|
+
if (!token)
|
|
815
|
+
return;
|
|
816
|
+
if (!this.options.mock) {
|
|
817
|
+
const status = await this.request('/v1/storage/grant', token);
|
|
818
|
+
if (status !== 401)
|
|
819
|
+
this.throwUnlessOk(status);
|
|
820
|
+
}
|
|
821
|
+
await this.options.storage.remove(this.storageKey);
|
|
822
|
+
}
|
|
823
|
+
/** Deletes the buyer's cloud copy and turns the backup off on every device. */
|
|
824
|
+
async delete() {
|
|
825
|
+
const token = await this.token();
|
|
826
|
+
if (!token)
|
|
827
|
+
throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Cloud backup is off on this installation; turn it on to delete the cloud copy');
|
|
828
|
+
if (!this.options.mock) {
|
|
829
|
+
const status = await this.request('/v1/storage/data', token);
|
|
830
|
+
if (status === 401) {
|
|
831
|
+
// The server no longer accepts this token, so it is useless here; the copy was not deleted.
|
|
832
|
+
await this.options.storage.remove(this.storageKey);
|
|
833
|
+
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 });
|
|
834
|
+
}
|
|
835
|
+
this.throwUnlessOk(status);
|
|
836
|
+
}
|
|
837
|
+
await this.options.storage.remove(this.storageKey);
|
|
838
|
+
}
|
|
839
|
+
assertTrustedContext() {
|
|
840
|
+
if (inContentScript())
|
|
841
|
+
throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Use cloud backup from an extension page or background context');
|
|
842
|
+
}
|
|
843
|
+
throwUnlessOk(status) {
|
|
844
|
+
if (status >= 200 && status < 300)
|
|
845
|
+
return;
|
|
846
|
+
if (status === 429)
|
|
847
|
+
throw new ExtenshiPayError(ERROR_CODES.RATE_LIMITED, 'Too many requests', { httpStatus: status });
|
|
848
|
+
if (status >= 500)
|
|
849
|
+
throw new ExtenshiPayError(ERROR_CODES.GATEWAY_UNAVAILABLE, `HTTP ${status}`, { httpStatus: status });
|
|
850
|
+
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, `HTTP ${status}`, { httpStatus: status });
|
|
851
|
+
}
|
|
852
|
+
async request(path, token) {
|
|
853
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
|
854
|
+
const timer = controller ? setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS) : null;
|
|
855
|
+
try {
|
|
856
|
+
const response = await this.fetchImpl(`${this.options.apiUrl}${path}`, {
|
|
857
|
+
method: 'DELETE',
|
|
858
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
859
|
+
credentials: 'omit',
|
|
860
|
+
signal: controller?.signal,
|
|
861
|
+
});
|
|
862
|
+
return response.status;
|
|
863
|
+
}
|
|
864
|
+
catch (error) {
|
|
865
|
+
if (controller?.signal.aborted)
|
|
866
|
+
throw new ExtenshiPayError(ERROR_CODES.TIMEOUT, `Request timed out after ${REQUEST_TIMEOUT_MS}ms`);
|
|
867
|
+
throw new ExtenshiPayError(ERROR_CODES.NETWORK_ERROR, 'Network request failed', { cause: error });
|
|
868
|
+
}
|
|
869
|
+
finally {
|
|
870
|
+
if (timer !== null)
|
|
871
|
+
clearTimeout(timer);
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
|
|
735
876
|
/** Pure helpers over the entitlement projection. Features come from the items' `features[]`. */
|
|
736
877
|
const LIVE_STATUSES = new Set(['active', 'grace']);
|
|
737
878
|
function isLive(item) {
|
|
@@ -786,9 +927,17 @@ Object.freeze(EMPTY_ENTITLEMENT.features);
|
|
|
786
927
|
/**
|
|
787
928
|
* Ed25519 verification of the entitlement projection.
|
|
788
929
|
*
|
|
789
|
-
* Tamper resistance, not DRM.
|
|
790
|
-
*
|
|
791
|
-
*
|
|
930
|
+
* Tamper resistance, not DRM. Callers must deny access for both invalid and
|
|
931
|
+
* unverified envelopes outside explicit mocks.
|
|
932
|
+
*
|
|
933
|
+
* Which keys are trusted, in order (`PublicKeySource`, built in core/extenshi-pay.ts):
|
|
934
|
+
* 1. the key the server returned over HTTPS in this session;
|
|
935
|
+
* 2. the bundled `entitlementPublicKey`, when the developer configured one. It pins
|
|
936
|
+
* verification without a round-trip: a key read from extension storage is then never used;
|
|
937
|
+
* 3. without a bundled key, the server key saved in `storage.local` next to the
|
|
938
|
+
* license cache, so a restart with no network can still verify the cache.
|
|
939
|
+
* When none of them verifies an envelope the server is asked for its current key once
|
|
940
|
+
* (a rotated key), and that answer decides.
|
|
792
941
|
*/
|
|
793
942
|
function base64ToBytes(base64) {
|
|
794
943
|
const binary = atob(base64);
|
|
@@ -823,6 +972,156 @@ async function verifyEntitlementSignature(envelope, publicKeyBase64) {
|
|
|
823
972
|
return 'invalid';
|
|
824
973
|
}
|
|
825
974
|
}
|
|
975
|
+
const PUBLIC_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
|
|
976
|
+
/**
|
|
977
|
+
* `invalid` only when the server's current key was checked too (or the envelope carries no
|
|
978
|
+
* signature at all). A mismatch against known keys while the server is unreachable is
|
|
979
|
+
* `unverified`: it may be a rotated key, and no paid access is granted either way.
|
|
980
|
+
*/
|
|
981
|
+
async function verifyWithKeys(envelope, source) {
|
|
982
|
+
if (!envelope.signature || envelope.alg !== 'ed25519')
|
|
983
|
+
return { verdict: 'invalid', key: null };
|
|
984
|
+
let known = [];
|
|
985
|
+
try {
|
|
986
|
+
known = await source.known();
|
|
987
|
+
}
|
|
988
|
+
catch {
|
|
989
|
+
known = [];
|
|
990
|
+
}
|
|
991
|
+
let mismatch = false;
|
|
992
|
+
for (const key of known) {
|
|
993
|
+
const verdict = await verifyEntitlementSignature(envelope, key);
|
|
994
|
+
if (verdict === 'valid')
|
|
995
|
+
return { verdict, key };
|
|
996
|
+
if (verdict === 'invalid')
|
|
997
|
+
mismatch = true;
|
|
998
|
+
}
|
|
999
|
+
let current;
|
|
1000
|
+
try {
|
|
1001
|
+
current = await source.fetchCurrent();
|
|
1002
|
+
}
|
|
1003
|
+
catch {
|
|
1004
|
+
return { verdict: 'unverified', key: null };
|
|
1005
|
+
}
|
|
1006
|
+
if (current && !known.includes(current)) {
|
|
1007
|
+
const verdict = await verifyEntitlementSignature(envelope, current);
|
|
1008
|
+
return { verdict, key: verdict === 'valid' ? current : null };
|
|
1009
|
+
}
|
|
1010
|
+
return { verdict: mismatch ? 'invalid' : 'unverified', key: null };
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
/**
|
|
1014
|
+
* The free trial an application configures on the server (`trialDays`).
|
|
1015
|
+
*
|
|
1016
|
+
* The server starts one clock per installation at its first license read and
|
|
1017
|
+
* signs `{ startedAt, endsAt }` into the entitlement, so the trial comes from
|
|
1018
|
+
* the verified license like paid access does: no start date in extension
|
|
1019
|
+
* storage, nothing a device clock or a storage edit can move. Offline, the
|
|
1020
|
+
* cached license answers for up to 48 hours.
|
|
1021
|
+
*
|
|
1022
|
+
* `trial:ending` / `trial:ended` fire once per installation and trial (the
|
|
1023
|
+
* marker is kept in the SDK's storage), and not while the user has paid
|
|
1024
|
+
* access. Render state from `getTrial()`; the events are one-time notices.
|
|
1025
|
+
*/
|
|
1026
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
1027
|
+
/** Re-check at least daily: long timers are clamped by browsers and lost when a service worker sleeps. */
|
|
1028
|
+
const MAX_TIMER_MS$1 = DAY_MS;
|
|
1029
|
+
/** The trial as of `clock`, or null when the license carries none (or a malformed one). */
|
|
1030
|
+
function trialState(trial, clock) {
|
|
1031
|
+
if (!trial)
|
|
1032
|
+
return null;
|
|
1033
|
+
const startedAt = Date.parse(trial.startedAt);
|
|
1034
|
+
const endsAt = Date.parse(trial.endsAt);
|
|
1035
|
+
if (!Number.isFinite(startedAt) || !Number.isFinite(endsAt))
|
|
1036
|
+
return null;
|
|
1037
|
+
// The server's signed time is a floor: a clock turned back cannot reopen an ended trial.
|
|
1038
|
+
const now = Number.isFinite(clock.issuedAt) ? Math.max(clock.now, clock.issuedAt) : clock.now;
|
|
1039
|
+
const left = endsAt - now;
|
|
1040
|
+
return {
|
|
1041
|
+
active: left > 0 && clock.checked,
|
|
1042
|
+
startedAt: trial.startedAt,
|
|
1043
|
+
endsAt: trial.endsAt,
|
|
1044
|
+
daysLeft: left > 0 ? Math.ceil(left / DAY_MS) : 0,
|
|
1045
|
+
requiresOnlineCheck: left > 0 && !clock.checked,
|
|
1046
|
+
};
|
|
1047
|
+
}
|
|
1048
|
+
/** The feedback form address with `src=trial_end`; null unless it is a plain HTTPS URL. No installation id is added. */
|
|
1049
|
+
function trialFeedbackUrl(raw) {
|
|
1050
|
+
if (!raw)
|
|
1051
|
+
return null;
|
|
1052
|
+
let url;
|
|
1053
|
+
try {
|
|
1054
|
+
url = new URL(raw);
|
|
1055
|
+
}
|
|
1056
|
+
catch {
|
|
1057
|
+
return null;
|
|
1058
|
+
}
|
|
1059
|
+
if (url.protocol !== 'https:' || url.username || url.password)
|
|
1060
|
+
return null;
|
|
1061
|
+
url.searchParams.set('src', 'trial_end');
|
|
1062
|
+
return url.toString();
|
|
1063
|
+
}
|
|
1064
|
+
class TrialNotifier {
|
|
1065
|
+
constructor(options) {
|
|
1066
|
+
this.options = options;
|
|
1067
|
+
this.timer = null;
|
|
1068
|
+
this.running = false;
|
|
1069
|
+
this.pending = Promise.resolve();
|
|
1070
|
+
}
|
|
1071
|
+
start() {
|
|
1072
|
+
this.running = true;
|
|
1073
|
+
void this.evaluate();
|
|
1074
|
+
}
|
|
1075
|
+
stop() {
|
|
1076
|
+
this.running = false;
|
|
1077
|
+
this.clearTimer();
|
|
1078
|
+
}
|
|
1079
|
+
/** Checks the held license; serialized, so two refreshes never send one event twice. */
|
|
1080
|
+
evaluate() {
|
|
1081
|
+
this.pending = this.pending.then(() => this.check()).catch((error) => logger.debug('trial check', error));
|
|
1082
|
+
return this.pending;
|
|
1083
|
+
}
|
|
1084
|
+
async check() {
|
|
1085
|
+
if (!this.running)
|
|
1086
|
+
return;
|
|
1087
|
+
this.clearTimer();
|
|
1088
|
+
const trial = this.options.getTrial();
|
|
1089
|
+
if (!trial)
|
|
1090
|
+
return;
|
|
1091
|
+
const now = this.options.now();
|
|
1092
|
+
const endsAt = Date.parse(trial.endsAt);
|
|
1093
|
+
const endingAt = endsAt - this.options.endingDays * DAY_MS;
|
|
1094
|
+
const event = trial.daysLeft === 0
|
|
1095
|
+
? 'trial:ended'
|
|
1096
|
+
: trial.active && this.options.endingDays > 0 && now >= endingAt
|
|
1097
|
+
? 'trial:ending'
|
|
1098
|
+
: null;
|
|
1099
|
+
if (event && !this.options.hasPaidAccess())
|
|
1100
|
+
await this.send(event, trial);
|
|
1101
|
+
if (!this.running || trial.daysLeft === 0)
|
|
1102
|
+
return;
|
|
1103
|
+
const next = [endingAt, endsAt].find((at) => at > now) ?? endsAt;
|
|
1104
|
+
this.timer = setTimeout(() => {
|
|
1105
|
+
this.timer = null;
|
|
1106
|
+
void this.evaluate();
|
|
1107
|
+
}, Math.max(1000, Math.min(next - now, MAX_TIMER_MS$1)));
|
|
1108
|
+
}
|
|
1109
|
+
async send(event, trial) {
|
|
1110
|
+
const id = `${trial.startedAt}|${trial.endsAt}`;
|
|
1111
|
+
const field = event === 'trial:ended' ? 'ended' : 'ending';
|
|
1112
|
+
const stored = (await this.options.storage.get(this.options.storageKey));
|
|
1113
|
+
const sent = stored && typeof stored === 'object' ? stored : {};
|
|
1114
|
+
if (sent[field] === id || !this.running)
|
|
1115
|
+
return;
|
|
1116
|
+
await this.options.storage.set(this.options.storageKey, { ...sent, [field]: id });
|
|
1117
|
+
this.options.emit(event, trial);
|
|
1118
|
+
}
|
|
1119
|
+
clearTimer() {
|
|
1120
|
+
if (this.timer !== null)
|
|
1121
|
+
clearTimeout(this.timer);
|
|
1122
|
+
this.timer = null;
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
826
1125
|
|
|
827
1126
|
/**
|
|
828
1127
|
* Entitlement cache + refresh.
|
|
@@ -830,13 +1129,18 @@ async function verifyEntitlementSignature(envelope, publicKeyBase64) {
|
|
|
830
1129
|
* The cached envelope is a cache OF the server projection, never a second
|
|
831
1130
|
* source of truth: it is verified when stored and re-verified on load (once
|
|
832
1131
|
* the project's public key is known), served without a round-trip while the
|
|
833
|
-
* TTL holds, served for
|
|
1132
|
+
* TTL holds, served after signed issuance for the signed `offlineSeconds` (48 hours when absent) when the network is down, and expired
|
|
834
1133
|
* locally by `expiresAt`. Background refresh polls at most every 15 minutes
|
|
835
1134
|
* and backs off exponentially on errors.
|
|
836
1135
|
*/
|
|
837
1136
|
const MIN_REFRESH_INTERVAL_MS = 15 * 60 * 1000;
|
|
838
1137
|
const MAX_REFRESH_BACKOFF_MS = 6 * 60 * 60 * 1000;
|
|
1138
|
+
/** Offline allowance when the signed license names none (older servers and caches). */
|
|
839
1139
|
const MAX_OFFLINE_AGE_MS = 48 * 60 * 60 * 1000;
|
|
1140
|
+
/** Ceiling for a signed `offlineSeconds`. */
|
|
1141
|
+
const MAX_SIGNED_OFFLINE_AGE_MS = 366 * 24 * 60 * 60 * 1000;
|
|
1142
|
+
/** `setTimeout` fires at once past this delay. */
|
|
1143
|
+
const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
840
1144
|
// Allow small server/client clock skew without granting more than the signed age limit.
|
|
841
1145
|
const MAX_CLOCK_SKEW_MS = 5 * 60 * 1000;
|
|
842
1146
|
const CACHE_VERSION = 1;
|
|
@@ -855,6 +1159,8 @@ class EntitlementManager {
|
|
|
855
1159
|
this.options = options;
|
|
856
1160
|
this.held = null;
|
|
857
1161
|
this.inflight = null;
|
|
1162
|
+
/** Device clock against the server's at the last license check; null within 5 minutes. */
|
|
1163
|
+
this.clockSkew = null;
|
|
858
1164
|
this.timer = null;
|
|
859
1165
|
this.refreshGeneration = 0;
|
|
860
1166
|
this.deadlineTimer = null;
|
|
@@ -896,8 +1202,10 @@ class EntitlementManager {
|
|
|
896
1202
|
envelope: JSON.parse(JSON.stringify(record.envelope)),
|
|
897
1203
|
fetchedAt: record.fetchedAt,
|
|
898
1204
|
verified: false,
|
|
1205
|
+
key: null,
|
|
899
1206
|
source: this.source === 'mock' ? 'mock' : 'cache',
|
|
900
1207
|
};
|
|
1208
|
+
this.measureClockSkew(record.fetchedAt, Date.parse(record.envelope.payload.issuedAt));
|
|
901
1209
|
this.lastFingerprint = this.fingerprint();
|
|
902
1210
|
return this.snapshot();
|
|
903
1211
|
}
|
|
@@ -908,8 +1216,7 @@ class EntitlementManager {
|
|
|
908
1216
|
if (this.source === 'mock')
|
|
909
1217
|
return;
|
|
910
1218
|
const held = this.held;
|
|
911
|
-
const key = await this.
|
|
912
|
-
const verdict = await verifyEntitlementSignature(held.envelope, key);
|
|
1219
|
+
const { verdict, key } = await verifyWithKeys(held.envelope, this.options.keys);
|
|
913
1220
|
if (held !== this.held)
|
|
914
1221
|
return;
|
|
915
1222
|
if (verdict === 'invalid') {
|
|
@@ -918,19 +1225,39 @@ class EntitlementManager {
|
|
|
918
1225
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Cached entitlement signature is invalid');
|
|
919
1226
|
}
|
|
920
1227
|
held.verified = verdict === 'valid';
|
|
1228
|
+
held.key = key;
|
|
921
1229
|
if (!held.verified) {
|
|
922
1230
|
throw new ExtenshiPayError(ERROR_CODES.VERIFICATION_UNAVAILABLE, 'Entitlement verification requires a trusted key and Ed25519 WebCrypto support');
|
|
923
1231
|
}
|
|
924
1232
|
this.scheduleDeadline();
|
|
925
1233
|
}
|
|
1234
|
+
/** The key the held license was verified with; null when there is none or it is unverified. */
|
|
1235
|
+
get verifiedKey() {
|
|
1236
|
+
return this.held?.verified ? this.held.key : null;
|
|
1237
|
+
}
|
|
926
1238
|
getCached() {
|
|
927
1239
|
return this.held ? this.snapshot() : null;
|
|
928
1240
|
}
|
|
1241
|
+
/** The server trial in the held license; null without one, or while the license is unverified. */
|
|
1242
|
+
getTrial() {
|
|
1243
|
+
const held = this.held;
|
|
1244
|
+
if (!held || (this.source !== 'mock' && !held.verified))
|
|
1245
|
+
return null;
|
|
1246
|
+
const now = this.now();
|
|
1247
|
+
const issuedAt = Date.parse(held.envelope.payload.issuedAt);
|
|
1248
|
+
return trialState(held.envelope.payload.trial, {
|
|
1249
|
+
now,
|
|
1250
|
+
issuedAt,
|
|
1251
|
+
// The same offline rule as paid access (snapshot): the allowance from the signed issue, no clock turned back.
|
|
1252
|
+
checked: this.source === 'mock' ||
|
|
1253
|
+
(now >= held.fetchedAt && now < this.offlineDeadline() && now + MAX_CLOCK_SKEW_MS >= issuedAt),
|
|
1254
|
+
});
|
|
1255
|
+
}
|
|
929
1256
|
isFresh() {
|
|
930
1257
|
return (this.held !== null &&
|
|
931
1258
|
(this.source === 'mock' || (this.held.verified && !this.snapshot().requiresOnlineCheck)) &&
|
|
932
1259
|
this.now() >= this.held.fetchedAt &&
|
|
933
|
-
this.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs,
|
|
1260
|
+
this.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs, this.offlineAgeMs()));
|
|
934
1261
|
}
|
|
935
1262
|
async get(options = {}) {
|
|
936
1263
|
if (!options.force && this.isFresh())
|
|
@@ -945,7 +1272,7 @@ class EntitlementManager {
|
|
|
945
1272
|
logger.debug('serving cached entitlement after refresh failure', err.code);
|
|
946
1273
|
return this.snapshot();
|
|
947
1274
|
}
|
|
948
|
-
return
|
|
1275
|
+
return this.snapshot();
|
|
949
1276
|
}
|
|
950
1277
|
}
|
|
951
1278
|
/** Fetches the projection from the backend, verifies and stores it. */
|
|
@@ -953,7 +1280,8 @@ class EntitlementManager {
|
|
|
953
1280
|
if (!this.inflight) {
|
|
954
1281
|
this.inflight = (async () => {
|
|
955
1282
|
const endUserRef = await this.options.getEndUserRef();
|
|
956
|
-
const
|
|
1283
|
+
const hint = this.options.getTrialStartHint ? await this.options.getTrialStartHint() : null;
|
|
1284
|
+
const envelope = await this.options.api.getEntitlement(endUserRef, hint);
|
|
957
1285
|
return this.accept(envelope, this.source);
|
|
958
1286
|
})().finally(() => {
|
|
959
1287
|
this.inflight = null;
|
|
@@ -975,9 +1303,9 @@ class EntitlementManager {
|
|
|
975
1303
|
if (envelope.payload.endUserRef !== endUserRef) {
|
|
976
1304
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issued for a different endUserRef');
|
|
977
1305
|
}
|
|
978
|
-
const verdict = this.source === 'mock'
|
|
979
|
-
? 'unverified'
|
|
980
|
-
: await
|
|
1306
|
+
const { verdict, key } = this.source === 'mock'
|
|
1307
|
+
? { verdict: 'unverified', key: null }
|
|
1308
|
+
: await verifyWithKeys(envelope, this.options.keys);
|
|
981
1309
|
if (verdict === 'invalid') {
|
|
982
1310
|
await this.discard();
|
|
983
1311
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement signature is invalid');
|
|
@@ -987,15 +1315,19 @@ class EntitlementManager {
|
|
|
987
1315
|
}
|
|
988
1316
|
const fetchedAt = this.now();
|
|
989
1317
|
const issuedAt = Date.parse(envelope.payload.issuedAt);
|
|
1318
|
+
// A verified envelope was signed moments ago: its `issuedAt` is the server's clock.
|
|
1319
|
+
if (this.source !== 'mock')
|
|
1320
|
+
this.measureClockSkew(fetchedAt, issuedAt);
|
|
990
1321
|
if (this.source !== 'mock' && (!Number.isFinite(issuedAt) || issuedAt > fetchedAt + MAX_CLOCK_SKEW_MS)) {
|
|
991
1322
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issuedAt is invalid or in the future');
|
|
992
1323
|
}
|
|
993
|
-
this.held = { envelope, fetchedAt, verified: verdict === 'valid', source };
|
|
1324
|
+
this.held = { envelope, fetchedAt, verified: verdict === 'valid', key, source };
|
|
994
1325
|
const record = { v: CACHE_VERSION, envelope, fetchedAt };
|
|
995
1326
|
await this.options.storage.set(this.storageKey, JSON.parse(JSON.stringify(record)));
|
|
996
1327
|
this.backoffMs = 0;
|
|
997
1328
|
this.scheduleDeadline();
|
|
998
1329
|
this.notifyIfChanged();
|
|
1330
|
+
this.options.onAccepted?.();
|
|
999
1331
|
return this.snapshot();
|
|
1000
1332
|
}
|
|
1001
1333
|
/** Drain an older installation refresh before changing identity. */
|
|
@@ -1049,7 +1381,7 @@ class EntitlementManager {
|
|
|
1049
1381
|
this.deadlineTimer = null;
|
|
1050
1382
|
this.notifyIfChanged();
|
|
1051
1383
|
this.scheduleDeadline();
|
|
1052
|
-
}, remaining);
|
|
1384
|
+
}, Math.min(remaining, MAX_TIMER_MS));
|
|
1053
1385
|
}
|
|
1054
1386
|
schedule(delayMs) {
|
|
1055
1387
|
const generation = this.refreshGeneration;
|
|
@@ -1070,14 +1402,12 @@ class EntitlementManager {
|
|
|
1070
1402
|
}
|
|
1071
1403
|
}, delayMs);
|
|
1072
1404
|
}
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
return null;
|
|
1080
|
-
}
|
|
1405
|
+
measureClockSkew(local, server) {
|
|
1406
|
+
const ms = local - server;
|
|
1407
|
+
this.clockSkew =
|
|
1408
|
+
Number.isFinite(ms) && Math.abs(ms) > MAX_CLOCK_SKEW_MS
|
|
1409
|
+
? { direction: ms > 0 ? 'ahead' : 'behind', ms: Math.abs(ms) }
|
|
1410
|
+
: null;
|
|
1081
1411
|
}
|
|
1082
1412
|
async discard() {
|
|
1083
1413
|
this.held = null;
|
|
@@ -1100,13 +1430,25 @@ class EntitlementManager {
|
|
|
1100
1430
|
if (!this.held)
|
|
1101
1431
|
return NaN;
|
|
1102
1432
|
// 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)) +
|
|
1433
|
+
return (Math.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) + this.offlineAgeMs());
|
|
1434
|
+
}
|
|
1435
|
+
/** The signed allowance of the held license, or 48 hours when it names none. */
|
|
1436
|
+
offlineAgeMs() {
|
|
1437
|
+
const seconds = this.held?.envelope.payload.offlineSeconds;
|
|
1438
|
+
if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0)
|
|
1439
|
+
return MAX_OFFLINE_AGE_MS;
|
|
1440
|
+
return Math.min(seconds * 1000, MAX_SIGNED_OFFLINE_AGE_MS);
|
|
1104
1441
|
}
|
|
1105
1442
|
snapshot() {
|
|
1106
1443
|
if (!this.held)
|
|
1107
|
-
return EMPTY_ENTITLEMENT;
|
|
1444
|
+
return this.clockSkew ? { ...EMPTY_ENTITLEMENT, clockSkew: this.clockSkew } : EMPTY_ENTITLEMENT;
|
|
1108
1445
|
if (this.source !== 'mock' && !this.held.verified) {
|
|
1109
|
-
return {
|
|
1446
|
+
return {
|
|
1447
|
+
...EMPTY_ENTITLEMENT,
|
|
1448
|
+
requiresOnlineCheck: true,
|
|
1449
|
+
clockSkew: this.clockSkew,
|
|
1450
|
+
source: this.held.source,
|
|
1451
|
+
};
|
|
1110
1452
|
}
|
|
1111
1453
|
const items = applyLocalExpiry(JSON.parse(JSON.stringify(this.held.envelope.payload.entitlements)), this.now());
|
|
1112
1454
|
const hasPaidAccess = collectFeatures(items).length > 0 ||
|
|
@@ -1122,6 +1464,7 @@ class EntitlementManager {
|
|
|
1122
1464
|
features: requiresOnlineCheck ? [] : collectFeatures(items),
|
|
1123
1465
|
requiresOnlineCheck,
|
|
1124
1466
|
offlineUntil,
|
|
1467
|
+
clockSkew: this.clockSkew,
|
|
1125
1468
|
verified: this.held.verified,
|
|
1126
1469
|
issuedAt: this.held.envelope.payload.issuedAt,
|
|
1127
1470
|
fetchedAt: this.held.fetchedAt,
|
|
@@ -1210,6 +1553,16 @@ class MemoryStorage {
|
|
|
1210
1553
|
this.map.delete(key);
|
|
1211
1554
|
}
|
|
1212
1555
|
}
|
|
1556
|
+
/**
|
|
1557
|
+
* The browser's synced storage (`storage.sync`), or null outside an extension. The SDK keeps
|
|
1558
|
+
* only the trial start there (never `endUserRef`), so devices on one synced account share the
|
|
1559
|
+
* trial. Uninstalling clears it from the account, so it does not survive a reinstall.
|
|
1560
|
+
*/
|
|
1561
|
+
function createSyncStorage() {
|
|
1562
|
+
const g = extensionGlobals();
|
|
1563
|
+
const area = g.chrome?.storage?.sync ?? g.browser?.storage?.sync;
|
|
1564
|
+
return area ? new ExtensionStorage(area) : null;
|
|
1565
|
+
}
|
|
1213
1566
|
function createStorage() {
|
|
1214
1567
|
const g = extensionGlobals();
|
|
1215
1568
|
const area = g.chrome?.storage?.local ?? g.browser?.storage?.local;
|
|
@@ -1266,7 +1619,7 @@ class RecoveryManager {
|
|
|
1266
1619
|
const secret = Array.from(cryptoApi.getRandomValues(new Uint8Array(32)), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
1267
1620
|
const hash = await cryptoApi.subtle.digest('SHA-256', new TextEncoder().encode(secret));
|
|
1268
1621
|
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);
|
|
1622
|
+
const created = await this.options.api.createRestoreSession(challenge, this.options.locale, options.purpose);
|
|
1270
1623
|
if (!Number.isFinite(Date.parse(created.expiresAt)))
|
|
1271
1624
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery expiry');
|
|
1272
1625
|
const pending = { sessionId: created.sessionId, expiresAt: created.expiresAt, claimSecret: secret };
|
|
@@ -1326,8 +1679,9 @@ class RecoveryManager {
|
|
|
1326
1679
|
break;
|
|
1327
1680
|
if (claim.state === 'complete') {
|
|
1328
1681
|
const entitlement = await this.options.onComplete(claim.endUserRef, claim.entitlement);
|
|
1682
|
+
const cloudBackup = await this.options.onStorageGrant?.(claim.storage);
|
|
1329
1683
|
await this.options.storage.remove(this.pendingKey);
|
|
1330
|
-
return { state: 'complete', entitlement };
|
|
1684
|
+
return { state: 'complete', entitlement, ...(cloudBackup ? { cloudBackup } : {}) };
|
|
1331
1685
|
}
|
|
1332
1686
|
if (claim.state !== 'pending')
|
|
1333
1687
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery response');
|
|
@@ -1356,9 +1710,10 @@ class RecoveryManager {
|
|
|
1356
1710
|
const DEFAULT_API_URL = 'https://bff.extenshi.io';
|
|
1357
1711
|
const DEFAULT_CACHE_TTL_MS = 60 * 60 * 1000;
|
|
1358
1712
|
const MAX_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
1713
|
+
const DEFAULT_TRIAL_ENDING_DAYS = 2;
|
|
1359
1714
|
|
|
1360
1715
|
/** Kept in sync with package.json by tests/unit/version.test.ts. */
|
|
1361
|
-
const VERSION = '0.
|
|
1716
|
+
const VERSION = '0.11.0';
|
|
1362
1717
|
|
|
1363
1718
|
/**
|
|
1364
1719
|
* The user's language as the SDK sends it. Kept apart from the paywall
|
|
@@ -1428,7 +1783,7 @@ function resolveConfig(input) {
|
|
|
1428
1783
|
if (!isHttpUrl(apiUrl))
|
|
1429
1784
|
errors.push('apiUrl must be an http(s) URL');
|
|
1430
1785
|
const entitlementPublicKey = input.entitlementPublicKey ?? null;
|
|
1431
|
-
if (entitlementPublicKey !== null &&
|
|
1786
|
+
if (entitlementPublicKey !== null && !PUBLIC_KEY_RE.test(entitlementPublicKey)) {
|
|
1432
1787
|
errors.push('entitlementPublicKey must be a base64-encoded 32-byte Ed25519 public key');
|
|
1433
1788
|
}
|
|
1434
1789
|
const environment = input.environment ?? 'production';
|
|
@@ -1450,6 +1805,9 @@ function resolveConfig(input) {
|
|
|
1450
1805
|
const theme = input.theme ?? {};
|
|
1451
1806
|
if (theme.mode !== undefined && !THEME_MODES.has(theme.mode))
|
|
1452
1807
|
errors.push('theme.mode must be light, dark or auto');
|
|
1808
|
+
const trialEndingDays = input.trialEndingDays ?? DEFAULT_TRIAL_ENDING_DAYS;
|
|
1809
|
+
if (!Number.isInteger(trialEndingDays) || trialEndingDays < 0 || trialEndingDays > 365)
|
|
1810
|
+
errors.push('trialEndingDays must be a whole number of days between 0 and 365');
|
|
1453
1811
|
if (input.mock &&
|
|
1454
1812
|
input.mockData !== undefined &&
|
|
1455
1813
|
(typeof input.mockData !== 'object' || input.mockData === null)) {
|
|
@@ -1470,6 +1828,8 @@ function resolveConfig(input) {
|
|
|
1470
1828
|
mock: input.mock === true,
|
|
1471
1829
|
mockData: input.mock ? (input.mockData ?? {}) : null,
|
|
1472
1830
|
theme,
|
|
1831
|
+
trialEndingDays,
|
|
1832
|
+
syncTrialStart: input.syncTrialStart !== false,
|
|
1473
1833
|
};
|
|
1474
1834
|
}
|
|
1475
1835
|
|
|
@@ -1594,6 +1954,9 @@ const SDK_STRINGS_EN = {
|
|
|
1594
1954
|
pickerDescription: 'Separate purchases can have separate billing profiles. Choose one to manage its subscriptions and payment details.',
|
|
1595
1955
|
pickerFirstRecorded: 'First recorded {date}',
|
|
1596
1956
|
pickerCancel: 'Cancel',
|
|
1957
|
+
trialEndedTitle: 'Your free trial has ended',
|
|
1958
|
+
trialEndedDescription: 'The extension’s tools are paused. Your settings are kept and will be there when you upgrade.',
|
|
1959
|
+
trialEndedFeedback: 'Share feedback',
|
|
1597
1960
|
};
|
|
1598
1961
|
// BEGIN GENERATED TRANSLATIONS
|
|
1599
1962
|
const TRANSLATIONS = {
|
|
@@ -1662,6 +2025,9 @@ const TRANSLATIONS = {
|
|
|
1662
2025
|
pickerDescription: 'Las compras independientes pueden tener perfiles de facturación distintos. Elige uno para gestionar sus suscripciones y datos de pago.',
|
|
1663
2026
|
pickerFirstRecorded: 'Registrado por primera vez el {date}',
|
|
1664
2027
|
pickerCancel: 'Cancelar',
|
|
2028
|
+
trialEndedTitle: 'Tu prueba gratuita ha terminado',
|
|
2029
|
+
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.',
|
|
2030
|
+
trialEndedFeedback: 'Enviar comentarios',
|
|
1665
2031
|
},
|
|
1666
2032
|
'pt-BR': {
|
|
1667
2033
|
title: 'Desbloqueie os recursos premium',
|
|
@@ -1728,6 +2094,9 @@ const TRANSLATIONS = {
|
|
|
1728
2094
|
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
2095
|
pickerFirstRecorded: 'Registrado pela primeira vez em {date}',
|
|
1730
2096
|
pickerCancel: 'Cancelar',
|
|
2097
|
+
trialEndedTitle: 'Seu teste gratuito terminou',
|
|
2098
|
+
trialEndedDescription: 'As ferramentas da extensão estão pausadas. Suas configurações foram mantidas e estarão lá quando você fizer o upgrade.',
|
|
2099
|
+
trialEndedFeedback: 'Enviar feedback',
|
|
1731
2100
|
},
|
|
1732
2101
|
fr: {
|
|
1733
2102
|
title: 'Débloquez les fonctionnalités premium',
|
|
@@ -1794,6 +2163,9 @@ const TRANSLATIONS = {
|
|
|
1794
2163
|
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
2164
|
pickerFirstRecorded: 'Enregistré pour la première fois le {date}',
|
|
1796
2165
|
pickerCancel: 'Annuler',
|
|
2166
|
+
trialEndedTitle: 'Votre essai gratuit est terminé',
|
|
2167
|
+
trialEndedDescription: 'Les outils de l’extension sont en pause. Vos paramètres sont conservés et vous les retrouverez après la mise à niveau.',
|
|
2168
|
+
trialEndedFeedback: 'Donner votre avis',
|
|
1797
2169
|
},
|
|
1798
2170
|
de: {
|
|
1799
2171
|
title: 'Premium-Funktionen freischalten',
|
|
@@ -1860,6 +2232,9 @@ const TRANSLATIONS = {
|
|
|
1860
2232
|
pickerDescription: 'Verschiedene Käufe können eigene Abrechnungsprofile haben. Wähle eines aus, um seine Abonnements und Zahlungsdaten zu verwalten.',
|
|
1861
2233
|
pickerFirstRecorded: 'Erstmals erfasst am {date}',
|
|
1862
2234
|
pickerCancel: 'Abbrechen',
|
|
2235
|
+
trialEndedTitle: 'Dein kostenloser Testzeitraum ist abgelaufen',
|
|
2236
|
+
trialEndedDescription: 'Die Funktionen der Erweiterung sind pausiert. Deine Einstellungen bleiben erhalten und sind nach dem Upgrade wieder da.',
|
|
2237
|
+
trialEndedFeedback: 'Feedback geben',
|
|
1863
2238
|
},
|
|
1864
2239
|
it: {
|
|
1865
2240
|
title: 'Sblocca le funzionalità premium',
|
|
@@ -1926,6 +2301,9 @@ const TRANSLATIONS = {
|
|
|
1926
2301
|
pickerDescription: 'Acquisti diversi possono avere profili di fatturazione diversi. Scegline uno per gestirne gli abbonamenti e i dati di pagamento.',
|
|
1927
2302
|
pickerFirstRecorded: 'Registrato per la prima volta il {date}',
|
|
1928
2303
|
pickerCancel: 'Annulla',
|
|
2304
|
+
trialEndedTitle: 'La tua prova gratuita è terminata',
|
|
2305
|
+
trialEndedDescription: 'Gli strumenti dell’estensione sono in pausa. Le tue impostazioni sono conservate e le ritroverai dopo l’upgrade.',
|
|
2306
|
+
trialEndedFeedback: 'Invia un feedback',
|
|
1929
2307
|
},
|
|
1930
2308
|
ru: {
|
|
1931
2309
|
title: 'Откройте доступ к премиум-функциям',
|
|
@@ -1992,6 +2370,9 @@ const TRANSLATIONS = {
|
|
|
1992
2370
|
pickerDescription: 'У разных покупок могут быть разные платёжные профили. Выберите профиль, чтобы управлять его подписками и платёжными данными.',
|
|
1993
2371
|
pickerFirstRecorded: 'Впервые зафиксирован: {date}',
|
|
1994
2372
|
pickerCancel: 'Отмена',
|
|
2373
|
+
trialEndedTitle: 'Бесплатный пробный период закончился',
|
|
2374
|
+
trialEndedDescription: 'Инструменты расширения приостановлены. Ваши настройки сохранены и будут на месте после перехода на премиум.',
|
|
2375
|
+
trialEndedFeedback: 'Оставить отзыв',
|
|
1995
2376
|
},
|
|
1996
2377
|
ja: {
|
|
1997
2378
|
title: 'プレミアム機能をアンロック',
|
|
@@ -2058,6 +2439,9 @@ const TRANSLATIONS = {
|
|
|
2058
2439
|
pickerDescription: '購入ごとに別々の請求プロファイルがある場合があります。サブスクリプションと支払い情報を管理するプロファイルを1つ選択してください。',
|
|
2059
2440
|
pickerFirstRecorded: '初回記録日:{date}',
|
|
2060
2441
|
pickerCancel: 'キャンセル',
|
|
2442
|
+
trialEndedTitle: '無料トライアルが終了しました',
|
|
2443
|
+
trialEndedDescription: '拡張機能のツールは一時停止しています。設定は保存されており、アップグレード後もそのままご利用いただけます。',
|
|
2444
|
+
trialEndedFeedback: 'フィードバックを送信',
|
|
2061
2445
|
},
|
|
2062
2446
|
ko: {
|
|
2063
2447
|
title: '프리미엄 기능 잠금 해제',
|
|
@@ -2124,6 +2508,9 @@ const TRANSLATIONS = {
|
|
|
2124
2508
|
pickerDescription: '구매마다 결제 프로필이 다를 수 있습니다. 구독과 결제 정보를 관리할 프로필을 하나 선택해 주세요.',
|
|
2125
2509
|
pickerFirstRecorded: '최초 기록일: {date}',
|
|
2126
2510
|
pickerCancel: '취소',
|
|
2511
|
+
trialEndedTitle: '무료 체험 기간이 종료되었습니다',
|
|
2512
|
+
trialEndedDescription: '확장 프로그램의 도구가 일시 중지되었습니다. 설정은 그대로 저장되어 있으며 업그레이드하면 다시 사용할 수 있습니다.',
|
|
2513
|
+
trialEndedFeedback: '의견 보내기',
|
|
2127
2514
|
},
|
|
2128
2515
|
'zh-CN': {
|
|
2129
2516
|
title: '解锁高级功能',
|
|
@@ -2190,6 +2577,9 @@ const TRANSLATIONS = {
|
|
|
2190
2577
|
pickerDescription: '不同的购买可以有各自的账单资料。请选择一个,以管理其订阅和付款信息。',
|
|
2191
2578
|
pickerFirstRecorded: '首次记录于 {date}',
|
|
2192
2579
|
pickerCancel: '取消',
|
|
2580
|
+
trialEndedTitle: '免费试用已结束',
|
|
2581
|
+
trialEndedDescription: '扩展程序的工具已暂停。您的设置已保留,升级后即可继续使用。',
|
|
2582
|
+
trialEndedFeedback: '提交反馈',
|
|
2193
2583
|
},
|
|
2194
2584
|
ar: {
|
|
2195
2585
|
title: 'احصل على الميزات المميزة',
|
|
@@ -2256,6 +2646,9 @@ const TRANSLATIONS = {
|
|
|
2256
2646
|
pickerDescription: 'يمكن أن تكون لعمليات الشراء المنفصلة ملفات فوترة منفصلة. اختر ملفًا منها لإدارة اشتراكاته وتفاصيل الدفع الخاصة به.',
|
|
2257
2647
|
pickerFirstRecorded: 'سُجِّل لأول مرة في {date}',
|
|
2258
2648
|
pickerCancel: 'إلغاء',
|
|
2649
|
+
trialEndedTitle: 'انتهت فترتك التجريبية المجانية',
|
|
2650
|
+
trialEndedDescription: 'أدوات الإضافة متوقفة مؤقتًا. إعداداتك محفوظة وستجدها كما هي بعد الترقية.',
|
|
2651
|
+
trialEndedFeedback: 'إرسال ملاحظات',
|
|
2259
2652
|
},
|
|
2260
2653
|
};
|
|
2261
2654
|
// END GENERATED TRANSLATIONS
|
|
@@ -2336,8 +2729,10 @@ function withdrawalWaiverText(serverVersion, locale, seller) {
|
|
|
2336
2729
|
* extends it with `getOffer()` / `showPaywall()`.
|
|
2337
2730
|
*
|
|
2338
2731
|
* Data that leaves the extension: `publishableKey`, `endUserRef`, `sku`,
|
|
2339
|
-
* `locale
|
|
2340
|
-
*
|
|
2732
|
+
* `locale`, checkout session IDs and, with a server trial, the trial start date
|
|
2733
|
+
* the server issued (`trialStartedHint`, kept in storage.sync). Explicit recovery also sends its session ID,
|
|
2734
|
+
* challenge and claim secret (POST body). Email stays on the hosted page. With cloud backup, the
|
|
2735
|
+
* storage token goes only to `/v1/storage` (as a bearer), never in a message to a content script.
|
|
2341
2736
|
*/
|
|
2342
2737
|
/** Server-side offer cache is 5 min; mirror it in memory. */
|
|
2343
2738
|
const OFFER_TTL_MS = 5 * 60 * 1000;
|
|
@@ -2348,12 +2743,30 @@ class ExtenshiPayLite {
|
|
|
2348
2743
|
this.endUserRefPromise = null;
|
|
2349
2744
|
this.offer = null;
|
|
2350
2745
|
this.offerInflight = null;
|
|
2746
|
+
/** The signing key the server returned in this session; never one read from storage. */
|
|
2747
|
+
this.serverKey = null;
|
|
2748
|
+
/** Trust order for license signatures; see payment/signature.ts. */
|
|
2749
|
+
this.keys = {
|
|
2750
|
+
known: async () => {
|
|
2751
|
+
const pinned = this.config.entitlementPublicKey;
|
|
2752
|
+
const offline = pinned ?? (await this.readSavedServerKey());
|
|
2753
|
+
return [...new Set([this.serverKey, offline].filter((key) => !!key))];
|
|
2754
|
+
},
|
|
2755
|
+
fetchCurrent: async () => (await this.fetchOffer(true)).entitlementPublicKey,
|
|
2756
|
+
};
|
|
2351
2757
|
this.readyPromise = null;
|
|
2352
2758
|
this.destroyed = false;
|
|
2353
2759
|
this.config = resolveConfig(config);
|
|
2354
2760
|
logger.configure({ logLevel: this.config.logLevel, debug: this.config.debug });
|
|
2355
2761
|
this.now = deps.now ?? (() => Date.now());
|
|
2356
2762
|
this.storage = deps.storage ?? createStorage();
|
|
2763
|
+
this.openUrl = deps.openUrl;
|
|
2764
|
+
this.syncStorage =
|
|
2765
|
+
!this.config.syncTrialStart || this.config.mock
|
|
2766
|
+
? null
|
|
2767
|
+
: deps.syncStorage === undefined
|
|
2768
|
+
? createSyncStorage()
|
|
2769
|
+
: deps.syncStorage;
|
|
2357
2770
|
const transport = deps.transport ??
|
|
2358
2771
|
(this.config.mock
|
|
2359
2772
|
? new MockTransport(this.config.mockData ?? {})
|
|
@@ -2366,11 +2779,26 @@ class ExtenshiPayLite {
|
|
|
2366
2779
|
cacheTtlMs: this.config.cacheTtlMs,
|
|
2367
2780
|
source: this.config.mock ? 'mock' : 'network',
|
|
2368
2781
|
getEndUserRef: () => this.getEndUserRef(),
|
|
2369
|
-
|
|
2782
|
+
keys: this.keys,
|
|
2370
2783
|
onChange: (entitlement) => this.emitter.emit('entitlement:changed', entitlement),
|
|
2784
|
+
onAccepted: () => {
|
|
2785
|
+
void this.trial.evaluate();
|
|
2786
|
+
void this.rememberTrialStart();
|
|
2787
|
+
},
|
|
2788
|
+
getTrialStartHint: () => this.readTrialStartHint(),
|
|
2371
2789
|
onError: (error) => this.reportError(error),
|
|
2372
2790
|
now: this.now,
|
|
2373
2791
|
});
|
|
2792
|
+
this.trial = new TrialNotifier({
|
|
2793
|
+
storage: this.storage,
|
|
2794
|
+
storageKey: `extenshi-pay:${this.config.publishableKey}:trial-events${this.config.mock ? ':mock' : ''}`,
|
|
2795
|
+
endingDays: this.config.trialEndingDays,
|
|
2796
|
+
getTrial: () => this.entitlements.getTrial(),
|
|
2797
|
+
// A paid license still counts while it waits for an online check: no "trial ended" to a buyer.
|
|
2798
|
+
hasPaidAccess: () => (this.entitlements.getCached()?.items ?? []).some(isLive),
|
|
2799
|
+
emit: (event, trial) => this.emitter.emit(event, trial),
|
|
2800
|
+
now: this.now,
|
|
2801
|
+
});
|
|
2374
2802
|
this.checkout = new CheckoutManager({
|
|
2375
2803
|
api: this.api,
|
|
2376
2804
|
storage: this.storage,
|
|
@@ -2384,6 +2812,13 @@ class ExtenshiPayLite {
|
|
|
2384
2812
|
(this.config.mock ? (url) => logger.info('mock checkout (no tab opened)', url) : undefined),
|
|
2385
2813
|
now: this.now,
|
|
2386
2814
|
});
|
|
2815
|
+
this.backup = new CloudBackup({
|
|
2816
|
+
storage: this.storage,
|
|
2817
|
+
publishableKey: this.config.publishableKey,
|
|
2818
|
+
apiUrl: this.config.apiUrl,
|
|
2819
|
+
fetch: deps.fetch,
|
|
2820
|
+
mock: this.config.mock,
|
|
2821
|
+
});
|
|
2387
2822
|
this.recovery = new RecoveryManager({
|
|
2388
2823
|
api: this.api,
|
|
2389
2824
|
locale: this.config.locale,
|
|
@@ -2397,7 +2832,7 @@ class ExtenshiPayLite {
|
|
|
2397
2832
|
envelope.payload.publishableKey !== this.config.publishableKey ||
|
|
2398
2833
|
!Number.isFinite(Date.parse(envelope.payload.issuedAt)) ||
|
|
2399
2834
|
Date.parse(envelope.payload.issuedAt) > this.now() + MAX_CLOCK_SKEW_MS ||
|
|
2400
|
-
(await
|
|
2835
|
+
(await verifyWithKeys(envelope, this.keys)).verdict !== 'valid')
|
|
2401
2836
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Recovery requires a verified entitlement for this installation');
|
|
2402
2837
|
this.entitlements.stopAutoRefresh();
|
|
2403
2838
|
try {
|
|
@@ -2415,6 +2850,7 @@ class ExtenshiPayLite {
|
|
|
2415
2850
|
this.entitlements.startAutoRefresh();
|
|
2416
2851
|
}
|
|
2417
2852
|
},
|
|
2853
|
+
onStorageGrant: (grant) => this.backup.accept(grant),
|
|
2418
2854
|
});
|
|
2419
2855
|
if (config.onError)
|
|
2420
2856
|
this.emitter.on('error', config.onError);
|
|
@@ -2460,8 +2896,11 @@ class ExtenshiPayLite {
|
|
|
2460
2896
|
catch (error) {
|
|
2461
2897
|
this.reportError(error);
|
|
2462
2898
|
}
|
|
2463
|
-
|
|
2899
|
+
void this.confirmSavedServerKey();
|
|
2900
|
+
if (!this.destroyed) {
|
|
2464
2901
|
this.entitlements.startAutoRefresh();
|
|
2902
|
+
this.trial.start();
|
|
2903
|
+
}
|
|
2465
2904
|
}
|
|
2466
2905
|
/** The anonymous, random id this install is known by. */
|
|
2467
2906
|
getEndUserRef() {
|
|
@@ -2482,6 +2921,16 @@ class ExtenshiPayLite {
|
|
|
2482
2921
|
await this.initialize();
|
|
2483
2922
|
return this.entitlements.get(options);
|
|
2484
2923
|
}
|
|
2924
|
+
/**
|
|
2925
|
+
* The free trial the application set on the server, from the verified license, or null when
|
|
2926
|
+
* there is none (or the license could not be verified yet). Answers offline from the cached
|
|
2927
|
+
* license; like paid access, `active` needs a license check within 48 hours. `isPaid()` and
|
|
2928
|
+
* `hasFeature()` do not include the trial: grant trial access with `(await getTrial())?.active`.
|
|
2929
|
+
*/
|
|
2930
|
+
async getTrial(options = {}) {
|
|
2931
|
+
await this.getEntitlement(options);
|
|
2932
|
+
return this.entitlements.getTrial();
|
|
2933
|
+
}
|
|
2485
2934
|
/** True when any active/grace entitlement exists, or the given `sku` is active/grace. */
|
|
2486
2935
|
async isPaid(sku) {
|
|
2487
2936
|
return isEntitled(await this.getEntitlement(), sku);
|
|
@@ -2565,6 +3014,41 @@ class ExtenshiPayLite {
|
|
|
2565
3014
|
throw this.reportError(error);
|
|
2566
3015
|
}
|
|
2567
3016
|
}
|
|
3017
|
+
/**
|
|
3018
|
+
* Turns on the cloud copy of the extension's settings (`@extenshi/storage`): the
|
|
3019
|
+
* hosted restore page shows the storage disclosure and the buyer confirms with
|
|
3020
|
+
* the code from the purchase email. `cloudBackup` in the result says whether it is
|
|
3021
|
+
* on. Buyers only; consent is recorded by the server.
|
|
3022
|
+
*/
|
|
3023
|
+
enableCloudBackup(options = {}) {
|
|
3024
|
+
return this.restorePurchase({ ...options, purpose: 'storage' });
|
|
3025
|
+
}
|
|
3026
|
+
/**
|
|
3027
|
+
* The storage token for `ExtenshiStorage.create({ cloud: { getToken } })`, or null
|
|
3028
|
+
* while cloud backup is off on this installation. Extension pages and background
|
|
3029
|
+
* only: it rejects in a content script, and must never be sent to one.
|
|
3030
|
+
*/
|
|
3031
|
+
async cloudBackupToken() {
|
|
3032
|
+
return this.backup.token();
|
|
3033
|
+
}
|
|
3034
|
+
/** Turns cloud backup off on this installation: revokes its token. The cloud copy stays. */
|
|
3035
|
+
async disableCloudBackup() {
|
|
3036
|
+
try {
|
|
3037
|
+
await this.backup.disable();
|
|
3038
|
+
}
|
|
3039
|
+
catch (error) {
|
|
3040
|
+
throw this.reportError(error);
|
|
3041
|
+
}
|
|
3042
|
+
}
|
|
3043
|
+
/** Deletes the buyer's cloud copy and turns cloud backup off on every installation. */
|
|
3044
|
+
async deleteCloudBackup() {
|
|
3045
|
+
try {
|
|
3046
|
+
await this.backup.delete();
|
|
3047
|
+
}
|
|
3048
|
+
catch (error) {
|
|
3049
|
+
throw this.reportError(error);
|
|
3050
|
+
}
|
|
3051
|
+
}
|
|
2568
3052
|
/** Read-only license view. Entitlements retain cache/signature/offline semantics. */
|
|
2569
3053
|
async getLicenseSummary(options = {}) {
|
|
2570
3054
|
await this.initialize();
|
|
@@ -2634,6 +3118,7 @@ class ExtenshiPayLite {
|
|
|
2634
3118
|
destroy() {
|
|
2635
3119
|
this.destroyed = true;
|
|
2636
3120
|
this.recovery.stop();
|
|
3121
|
+
this.trial.stop();
|
|
2637
3122
|
this.entitlements.stopAutoRefresh();
|
|
2638
3123
|
this.emitter.removeAll();
|
|
2639
3124
|
}
|
|
@@ -2645,8 +3130,9 @@ class ExtenshiPayLite {
|
|
|
2645
3130
|
if (!this.offerInflight) {
|
|
2646
3131
|
this.offerInflight = this.api
|
|
2647
3132
|
.getOffer(this.config.locale)
|
|
2648
|
-
.then((value) => {
|
|
3133
|
+
.then(async (value) => {
|
|
2649
3134
|
this.offer = { value, fetchedAt: this.now() };
|
|
3135
|
+
await this.rememberServerKey(value.entitlementPublicKey);
|
|
2650
3136
|
return value;
|
|
2651
3137
|
})
|
|
2652
3138
|
.finally(() => {
|
|
@@ -2655,8 +3141,88 @@ class ExtenshiPayLite {
|
|
|
2655
3141
|
}
|
|
2656
3142
|
return this.offerInflight;
|
|
2657
3143
|
}
|
|
2658
|
-
|
|
2659
|
-
return this.config.entitlementPublicKey
|
|
3144
|
+
get serverKeyStorageKey() {
|
|
3145
|
+
return `extenshi-pay:${this.config.publishableKey}:entitlementPublicKey`;
|
|
3146
|
+
}
|
|
3147
|
+
async readSavedServerKey() {
|
|
3148
|
+
try {
|
|
3149
|
+
const value = await this.storage.get(this.serverKeyStorageKey);
|
|
3150
|
+
return typeof value === 'string' && PUBLIC_KEY_RE.test(value) ? value : null;
|
|
3151
|
+
}
|
|
3152
|
+
catch {
|
|
3153
|
+
return null;
|
|
3154
|
+
}
|
|
3155
|
+
}
|
|
3156
|
+
/**
|
|
3157
|
+
* Keeps the server's key next to the license cache so a restart with no network can verify it.
|
|
3158
|
+
* Not with a bundled key: that one already covers the restart, and storage stays untrusted.
|
|
3159
|
+
*/
|
|
3160
|
+
async rememberServerKey(key) {
|
|
3161
|
+
if (typeof key !== 'string' || !PUBLIC_KEY_RE.test(key))
|
|
3162
|
+
return;
|
|
3163
|
+
this.serverKey = key;
|
|
3164
|
+
if (this.config.entitlementPublicKey || this.config.mock)
|
|
3165
|
+
return;
|
|
3166
|
+
try {
|
|
3167
|
+
if ((await this.readSavedServerKey()) !== key)
|
|
3168
|
+
await this.storage.set(this.serverKeyStorageKey, key);
|
|
3169
|
+
}
|
|
3170
|
+
catch (error) {
|
|
3171
|
+
logger.debug('signing key not saved', error);
|
|
3172
|
+
}
|
|
3173
|
+
}
|
|
3174
|
+
/**
|
|
3175
|
+
* A license verified with the saved key alone is checked against the server once per start:
|
|
3176
|
+
* when the server's key differs (rotation, or an edited storage) the license is fetched again,
|
|
3177
|
+
* and dropped if it does not verify. Offline, the saved key stands until `offlineUntil`.
|
|
3178
|
+
*/
|
|
3179
|
+
async confirmSavedServerKey() {
|
|
3180
|
+
const used = this.entitlements.verifiedKey;
|
|
3181
|
+
if (this.destroyed || !used || used === this.serverKey || used === this.config.entitlementPublicKey)
|
|
3182
|
+
return;
|
|
3183
|
+
try {
|
|
3184
|
+
if ((await this.fetchOffer()).entitlementPublicKey === used || this.destroyed)
|
|
3185
|
+
return;
|
|
3186
|
+
}
|
|
3187
|
+
catch {
|
|
3188
|
+
return;
|
|
3189
|
+
}
|
|
3190
|
+
try {
|
|
3191
|
+
await this.entitlements.refresh();
|
|
3192
|
+
}
|
|
3193
|
+
catch {
|
|
3194
|
+
await this.entitlements.reverify().catch((error) => this.reportError(error));
|
|
3195
|
+
}
|
|
3196
|
+
}
|
|
3197
|
+
get trialStartKey() {
|
|
3198
|
+
return `extenshi-pay:${this.config.publishableKey}:trialStartedAt`;
|
|
3199
|
+
}
|
|
3200
|
+
/** The synced trial start, or null (none, malformed, or storage.sync unavailable). */
|
|
3201
|
+
async readTrialStartHint() {
|
|
3202
|
+
if (!this.syncStorage)
|
|
3203
|
+
return null;
|
|
3204
|
+
try {
|
|
3205
|
+
const value = await this.syncStorage.get(this.trialStartKey);
|
|
3206
|
+
return typeof value === 'string' && Number.isFinite(Date.parse(value)) ? value : null;
|
|
3207
|
+
}
|
|
3208
|
+
catch {
|
|
3209
|
+
return null;
|
|
3210
|
+
}
|
|
3211
|
+
}
|
|
3212
|
+
/** Syncs the verified trial start, keeping the earliest one seen. Never the installation id. */
|
|
3213
|
+
async rememberTrialStart() {
|
|
3214
|
+
const trial = this.entitlements.getTrial();
|
|
3215
|
+
if (!this.syncStorage || !trial)
|
|
3216
|
+
return;
|
|
3217
|
+
try {
|
|
3218
|
+
const synced = await this.readTrialStartHint();
|
|
3219
|
+
if (synced && Date.parse(synced) <= Date.parse(trial.startedAt))
|
|
3220
|
+
return;
|
|
3221
|
+
await this.syncStorage.set(this.trialStartKey, trial.startedAt);
|
|
3222
|
+
}
|
|
3223
|
+
catch (error) {
|
|
3224
|
+
logger.debug('trial start not synced', error);
|
|
3225
|
+
}
|
|
2660
3226
|
}
|
|
2661
3227
|
reportError(error) {
|
|
2662
3228
|
const err = ExtenshiPayError.from(error);
|
|
@@ -3401,18 +3967,12 @@ class PaywallRenderer {
|
|
|
3401
3967
|
}
|
|
3402
3968
|
if (waiver && waiverBox)
|
|
3403
3969
|
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
|
-
}
|
|
3970
|
+
const onRestore = this.callbacks.onRestore;
|
|
3971
|
+
if (view.recoveryEnabled && onRestore)
|
|
3972
|
+
this.footerLink(root, doc, strings.restorePurchase, onRestore);
|
|
3973
|
+
const onFeedback = this.callbacks.onFeedback;
|
|
3974
|
+
if (view.feedback && onFeedback)
|
|
3975
|
+
this.footerLink(root, doc, view.feedback.label, onFeedback);
|
|
3416
3976
|
const mount = view.mode === 'inline' ? (view.container ?? doc.body) : doc.body;
|
|
3417
3977
|
mount.appendChild(host);
|
|
3418
3978
|
this.host = host;
|
|
@@ -3429,6 +3989,19 @@ class PaywallRenderer {
|
|
|
3429
3989
|
this.host.remove();
|
|
3430
3990
|
this.host = null;
|
|
3431
3991
|
}
|
|
3992
|
+
/** A text button at the end of the footer (no `href`: the SDK opens URLs itself). */
|
|
3993
|
+
footerLink(root, doc, label, onClick) {
|
|
3994
|
+
const footer = root.querySelector('[class*="-footer"], .ep-minimal-actions, .ep-inline-content, .ep-fullscreen-content');
|
|
3995
|
+
if (!footer)
|
|
3996
|
+
return;
|
|
3997
|
+
const button = doc.createElement('button');
|
|
3998
|
+
button.type = 'button';
|
|
3999
|
+
button.textContent = label;
|
|
4000
|
+
button.style.cssText =
|
|
4001
|
+
'display:block;margin:12px auto 0;background:none;border:0;color:inherit;font:inherit;text-decoration:underline;cursor:pointer';
|
|
4002
|
+
button.addEventListener('click', () => onClick());
|
|
4003
|
+
footer.appendChild(button);
|
|
4004
|
+
}
|
|
3432
4005
|
prune(root) {
|
|
3433
4006
|
for (const element of root.querySelectorAll(PRUNE_SELECTOR))
|
|
3434
4007
|
element.remove();
|
|
@@ -3635,6 +4208,28 @@ class ExtenshiPay extends ExtenshiPayLite {
|
|
|
3635
4208
|
* `getOffer()`; if that fails the paywall still renders with checkout disabled.
|
|
3636
4209
|
*/
|
|
3637
4210
|
async showPaywall(options = {}) {
|
|
4211
|
+
return this.present(options, null);
|
|
4212
|
+
}
|
|
4213
|
+
/**
|
|
4214
|
+
* The paywall for a user whose free trial ended, e.g. on `trial:ended`. In the user's
|
|
4215
|
+
* language it says the trial has ended, the tools are paused and the settings are kept,
|
|
4216
|
+
* then shows the plans, "Restore purchase" when recovery is on, and with `feedbackFormUrl`
|
|
4217
|
+
* a feedback button. Resolves like `showPaywall()`. The default text promises the settings
|
|
4218
|
+
* are kept: pass `description` if your extension does not keep them.
|
|
4219
|
+
*/
|
|
4220
|
+
async showTrialEnded(options = {}) {
|
|
4221
|
+
const t = sdkStrings(this.config.locale);
|
|
4222
|
+
const feedbackUrl = trialFeedbackUrl(options.feedbackFormUrl);
|
|
4223
|
+
if (options.feedbackFormUrl !== undefined && !feedbackUrl)
|
|
4224
|
+
this.reportError(new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'feedbackFormUrl must be an https URL without credentials; the feedback button is left out'));
|
|
4225
|
+
const { feedbackFormUrl: _url, feedbackLabel, ...paywall } = options;
|
|
4226
|
+
return this.present({
|
|
4227
|
+
...paywall,
|
|
4228
|
+
title: options.title ?? t.trialEndedTitle,
|
|
4229
|
+
description: options.description ?? t.trialEndedDescription,
|
|
4230
|
+
}, feedbackUrl ? { label: feedbackLabel ?? t.trialEndedFeedback, url: feedbackUrl } : null);
|
|
4231
|
+
}
|
|
4232
|
+
async present(options, feedback) {
|
|
3638
4233
|
await this.initialize();
|
|
3639
4234
|
let offer = null;
|
|
3640
4235
|
try {
|
|
@@ -3661,6 +4256,7 @@ class ExtenshiPay extends ExtenshiPayLite {
|
|
|
3661
4256
|
recoveryEnabled: offer?.recoveryEnabled === true,
|
|
3662
4257
|
seller: offer?.seller ?? null,
|
|
3663
4258
|
withdrawalWaiver: offer?.withdrawalWaiver ?? null,
|
|
4259
|
+
feedback: feedback ? { label: feedback.label } : null,
|
|
3664
4260
|
locale: this.config.locale,
|
|
3665
4261
|
theme: { ...this.config.theme, ...options.theme },
|
|
3666
4262
|
strings: options.strings ?? {},
|
|
@@ -3668,7 +4264,7 @@ class ExtenshiPay extends ExtenshiPayLite {
|
|
|
3668
4264
|
};
|
|
3669
4265
|
this.hidePaywall();
|
|
3670
4266
|
return new Promise((resolve) => {
|
|
3671
|
-
this.paywallSession = { options, resolve };
|
|
4267
|
+
this.paywallSession = { options, resolve, feedbackUrl: feedback?.url ?? null };
|
|
3672
4268
|
try {
|
|
3673
4269
|
this.renderer().show(view);
|
|
3674
4270
|
}
|
|
@@ -3701,6 +4297,7 @@ class ExtenshiPay extends ExtenshiPayLite {
|
|
|
3701
4297
|
onUpgrade: (sku, consent) => void this.handleUpgrade(sku, consent),
|
|
3702
4298
|
onClose: () => this.settlePaywall(false),
|
|
3703
4299
|
onRestore: () => void this.handleRestore(),
|
|
4300
|
+
onFeedback: () => void this.handleFeedback(),
|
|
3704
4301
|
});
|
|
3705
4302
|
}
|
|
3706
4303
|
return this.paywall;
|
|
@@ -3717,6 +4314,17 @@ class ExtenshiPay extends ExtenshiPayLite {
|
|
|
3717
4314
|
/* Reported through the error event; leave the paywall open for retry. */
|
|
3718
4315
|
}
|
|
3719
4316
|
}
|
|
4317
|
+
async handleFeedback() {
|
|
4318
|
+
const url = this.paywallSession?.feedbackUrl;
|
|
4319
|
+
if (!url)
|
|
4320
|
+
return;
|
|
4321
|
+
try {
|
|
4322
|
+
await (this.openUrl ?? openInNewTab)(url);
|
|
4323
|
+
}
|
|
4324
|
+
catch (error) {
|
|
4325
|
+
this.reportError(error);
|
|
4326
|
+
}
|
|
4327
|
+
}
|
|
3720
4328
|
async handleUpgrade(sku, consent) {
|
|
3721
4329
|
if (consent)
|
|
3722
4330
|
this.paywallSession?.options.onUpgrade?.(sku, consent);
|
|
@@ -3746,5 +4354,5 @@ class ExtenshiPay extends ExtenshiPayLite {
|
|
|
3746
4354
|
|
|
3747
4355
|
// Full SDK entry point: core + paywall UI.
|
|
3748
4356
|
|
|
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 };
|
|
4357
|
+
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_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
4358
|
//# sourceMappingURL=extenshi-pay.mjs.map
|